Skip to content

sync(test): merge main into test for app#2049 preview verification - #884

Merged
sweetmantech merged 16 commits into
testfrom
sync/test-from-main-2048
Sep 1, 2026
Merged

sweetmantech merged 16 commits into
testfrom
sync/test-from-main-2048

Conversation

@sweetmantech

@sweetmantech sweetmantech commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Routine test sync, same shape as api#880.

app previews call test-recoup-api, not production, so app#2049 cannot be preview-verified until the project endpoints are on this branch. Before this merge test was 15 commits behind main and contained none of them — every /api/projects/* request from an app preview would have 404'd.

Brings in the four merged PRs from app#2048:

api#881 collaborator access guard, GET /api/projects/{id}, GET .../tasks/{taskId}
api#882 task create, update, delete
api#883 task comments, read and post
plus the regenerated types/database.types.ts for the four project tables

Checked rather than assumed

The merge was clean, but a clean merge is not a working one — api#883 merged main without a git conflict and still broke the build, because api#881 had changed a function signature and deleted a type underneath it. So:

  • tsc --noEmit → 0 errors in lib/projects, lib/supabase/project* and app/api/projects. Total error count is 377, matching the pre-existing baseline in test files.
  • No conflicts, and the diff is additive: the merge creates the project routes, handlers and supabase libs, and changes nothing that was already on test.

Merging this unblocks preview verification of app#2049.

🤖 Generated with Claude Code

https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i


Summary by cubic

Syncs main into test so app previews can reach the project endpoints. Before this, test was 15 commits behind main and had none of them, so every /api/projects/* request from an app preview — which calls test-recoup-api — would 404, blocking preview verification of app#2049.

Verified rather than assumed

  • A clean merge was not taken as a working one: api#883 merged main without a git conflict and still broke the build because an earlier PR changed a function signature underneath it.
  • tsc --noEmit shows 0 errors in the project paths, matching the pre-existing baseline.
  • The diff is purely additive: the four merged PRs for app#2048 plus regenerated types/database.types.ts, changing nothing already on test.

Written for commit f25fbbd. Summary will update on new commits.

Review in cubic

sweetmantech and others added 16 commits September 1, 2026 10:39
…app#2048)

GET /api/projects/{projectId} returns a project with its tasks oldest first,
each carrying a comment_count, plus the project's collaborators.
GET /api/projects/{projectId}/tasks/{taskId} returns one task with its comment
feed.

requireProjectAccess is the gate every endpoint in this issue shares. It
resolves the caller with the existing getAuthenticatedAccountId, so a Recoup
API key and a Privy access token both work on the same Bearer header, then
requires a project_collaborators row. No row is a 404, never a 403: a 403
tells the caller the project id is real, and these ids travel in links.

hasProjectAccess denies on a lookup failure rather than throwing. Treating a
database error as access would turn one bad minute into a disclosure.

Comment counts are one grouped read rather than a count per task, so the
project page does not scale calls with the length of the timeline.

Contract: recoupable/docs#326. Tables: recoupable/database#68.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BTaK5sDuryYsQG5W56mR5n
POST /api/projects/{projectId}/tasks, plus PATCH and DELETE on a single task.
This is what makes a project seedable at all: with no project-creation
endpoint, tasks are authored over the API from Claude Code.

Completion moves only through PATCH's `completed` boolean. toTaskUpdates
stamps completed_at from the server clock and completed_by from the
authenticated account, and the validator does not accept either field from the
caller — so who closed an item, and when, is never the client's word for it.

An empty PATCH body is a 400 rather than a no-op 200: silently succeeding on a
body that changes nothing hides a broken client.

Both ids are matched on every write, so a task id from another project cannot
be updated or deleted through a project the caller does collaborate on.

Contract: recoupable/docs#326. Tables: recoupable/database#68.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BTaK5sDuryYsQG5W56mR5n
GET and POST /api/projects/{projectId}/tasks/{taskId}/comments. This is the
thread that replaces the email chain: a client comments on the task itself and
we answer in the same place.

Comments are append-only plain text. No edit, no delete, no markdown, no
mentions, no attachments — each is a real feature with real edge cases and none
is needed to replace an email thread.

The author is the authenticated account, never a field in the body, so a
comment cannot be posted as someone else.

Both handlers confirm the task belongs to the project before touching its
comments, so a task id from elsewhere cannot be read or written through a
project the caller does collaborate on.

The validator mirrors the column's 4000-character CHECK rather than trusting
it: a 400 naming the field beats a 500 from a constraint violation.

Contract: recoupable/docs#326. Tables: recoupable/database#68.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BTaK5sDuryYsQG5W56mR5n
database#68 merged, so `projects`, `project_tasks`, `project_collaborators`
and `project_task_comments` now exist on prod. Without them in the generated
types every Supabase call in this PR fails to compile — `TS2344: Type
'"project_tasks"' does not satisfy the constraint` and the `never` cascades
that follow — which is what has kept the preview build red.

Generated from project godremdqwajrwazhbrue and formatted with the repo's
prettier config, so it is byte-identical to `pnpm update-types` output.
Purely additive: +151/-0, the four new tables and nothing else.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i
Preview verification of this PR turned up a real defect. `GET
/api/projects/{projectId}/tasks/nope` answered **500**, because a non-UUID
segment reaches Postgres as `invalid input syntax for type uuid`, throws out
of selectProjectTask, and lands in the handler's catch. The contract
(recoupable/docs#326) documents a 400 there, and app#2049's task page renders
`notFound()` off a 404 — a 500 breaks that path with a server error for what
is only a mistyped link.

Mirrors getMusicGenerationHandler: `z.string().uuid().safeParse` on each path
segment before auth or any database call. A 400 discloses nothing — it says
the id is not an id, not whether a project by that id exists — so the
404-never-403 property is untouched.

`projectId` was already answering 404 rather than 500, but only by accident:
hasProjectAccess swallows its lookup error and denies. Both segments now fail
the same, explicit way.

Tests written red first and reproduce the live 500 (`expected 500 to be 400`)
before the guard lands.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i
cubic flagged the zod-parse-plus-errorResponse block as duplicated verbatim
across getProjectHandler once and getProjectTaskHandler twice. Valid, and it
gets worse rather than better: api#882 and api#883 add five more endpoints on
these same two path segments, so the copy count was on its way to eight.

Extracted to lib/projects/requireUuidParam.ts — one exported function per
file, per the house rule — returning the 400 response or null. The status
code, the message wording and the placement before auth now have one
definition to change.

No behaviour change: the same three cases still answer
400 `<name> must be a valid UUID`, and the handler tests that were written
red against the original 500 still pass unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i
…f the supabase lib, no hand-written row types

Four review comments, all applied.

**SRP: requirements move out of the handlers into a validate function.**
Both handlers were running the requirement checks inline. Each endpoint now
has one validate function that calls the requirement functions in the order
they need — validateProjectRequest and validateProjectTaskRequest — and the
handler makes a single call. Mirrors the validate* convention the neighbouring
endpoints already use.

The 400 tests move with their subject: they were asserting on the handlers,
and the behaviour they cover now lives in the validate functions, so they test
those directly. A third case pins the both-malformed ordering.

**KISS/SRP: counting logic leaves the supabase lib.**
countProjectTaskComments was doing a read and a reduce inside
lib/supabase/. The supabase file is now selectProjectTaskCommentTaskIds and
does nothing but select; the reduce lives in
lib/projects/countProjectTaskComments.ts.

**YAGNI: no hand-written row types.**
selectProjectTaskComments declared a ProjectTaskCommentRow interface and cast
to it with `as unknown as`. The generated database types already infer the
joined shape, `accounts(name)` included — verified against tsc rather than
assumed — so the interface and the cast are both gone. The mappers derive
their parameter type from the select instead, which cannot drift from the
query the way a hand-written copy can.

selectProjectCollaborators carried the identical interface-and-cast pair and
gets the same treatment; leaving it would have left the same defect one file
away from the one flagged.

No behaviour change intended in any of it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i
The previous commit left two near-identical selects in the same folder —
selectProjectTaskComments for one task's feed and
selectProjectTaskCommentTaskIds for the counting read. Two functions against
one table, differing only in the columns and whether the filter took one id or
many.

Now one: selectProjectTaskComments(taskIds). The task page passes a
single-element list, the project page passes the whole timeline, and
countProjectTaskComments reduces what comes back.

Tradeoff, stated rather than hidden: the counting path now fetches the full
comment rows and the accounts(name) join where it previously fetched only
task_id. Same one query, more columns. For a client status page whose comment
volume is a handful per task, the second file was the larger cost.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i
feat(projects): collaborator access guard and the two project reads (app#2048)
…00 on a malformed id

Two things, one change.

**SRP (review comment).** All three handlers ran the requirements inline —
requireProjectAccess, then a separate body parse and validate. Each now makes
one call: validateCreateProjectTaskRequest and
validateUpdateProjectTaskRequest resolve access and body together and hand back
{ accountId, body }; DELETE has no body, so its whole requirement is the shared
validateProjectTaskRequest that api#881 already ships. Order inside is access
before body, so an unauthorised caller never learns whether their body would
have been accepted.

The zod body validators stay their own files and keep their tests; the Request
functions call them. Named *Request rather than *Body because they now settle
more than the body, and a name that says Body while doing an access check
would mislead the next reader.

**A 500 preview verification caught.** PATCH and DELETE with a non-UUID taskId
returned 500, exactly the defect fixed in api#881 — these handlers predated
that fix and never picked it up. Routing them through the api#881 validators
brings the requireUuidParam guard with it, so both now return the documented
400. POST with a non-UUID projectId was answering 404 by accident, via
hasProjectAccess swallowing its lookup error; it is now an explicit 400 too.

Tests written red first against the missing modules.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i
feat(projects): task create, update and delete (app#2048)
… handler

The `main` merge into this branch was clean textually and broken semantically:
git had no conflict to report, but api#881 changed the API underneath these
files and the branch kept calling the old one. Two failures, both caught by
`tsc` and both red on the Vercel build:

1. `insertProjectTaskComment` imported `ProjectTaskCommentRow` from
   `selectProjectTaskComments`. api#881 deleted that hand-written type in
   favour of the inferred one — `TS2305: Module has no exported member`.
2. `getProjectCommentsHandler` called `selectProjectTaskComments(taskId)`.
   api#883 collapsed that function to take a list — `TS2345: Argument of type
   'string' is not assignable to parameter of type 'string[]'`. Worse than a
   type error if it had compiled: a bare string reaching `.in()` does not
   filter the way a caller would expect.

Both now follow main: the insert returns the inferred row, and the read passes
`[taskId]`.

**SRP (review comment).** Both handlers ran `requireProjectAccess` inline.
`POST` now makes one call to `validateCreateProjectCommentRequest`, which
returns `{ accountId, body }`; `GET` has no body, so its whole requirement is
the shared `validateProjectTaskRequest` from api#881. Access resolves before
the body, so an unauthorised caller never learns whether their body would have
been accepted.

That also fixes a 500 this PR would have shipped: a non-UUID `taskId` reached
Postgres, the same defect api#881 and api#882 each had to fix. Routing through
those validators brings the `requireUuidParam` guard with it.

Test written red first against the missing module.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i
feat(projects): task comments, read and post (app#2048)
@vercel

vercel Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Sep 1, 2026 6:56pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 45 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Team

Run ID: 347d69ee-ec13-4026-953c-3c0eacfa4395

📥 Commits

Reviewing files that changed from the base of the PR and between 5ace056 and f25fbbd.

⛔ Files ignored due to path filters (11)
  • lib/projects/__tests__/hasProjectAccess.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/requireUuidParam.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/toTaskUpdates.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/validateCreateProjectCommentBody.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/validateProjectRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/validateProjectTaskRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/projects/__tests__/validateUpdateProjectTaskRequest.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • types/database.types.ts is excluded by none and included by none
📒 Files selected for processing (37)
  • app/api/projects/[projectId]/route.ts
  • app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts
  • app/api/projects/[projectId]/tasks/[taskId]/route.ts
  • app/api/projects/[projectId]/tasks/route.ts
  • lib/projects/countProjectTaskComments.ts
  • lib/projects/createProjectCommentHandler.ts
  • lib/projects/createProjectTaskHandler.ts
  • lib/projects/deleteProjectTaskHandler.ts
  • lib/projects/getProjectCommentsHandler.ts
  • lib/projects/getProjectHandler.ts
  • lib/projects/getProjectTaskHandler.ts
  • lib/projects/hasProjectAccess.ts
  • lib/projects/requireProjectAccess.ts
  • lib/projects/requireUuidParam.ts
  • lib/projects/toProjectCollaborator.ts
  • lib/projects/toProjectComment.ts
  • lib/projects/toProjectTask.ts
  • lib/projects/toTaskUpdates.ts
  • lib/projects/updateProjectTaskHandler.ts
  • lib/projects/validateCreateProjectCommentBody.ts
  • lib/projects/validateCreateProjectCommentRequest.ts
  • lib/projects/validateCreateProjectTaskBody.ts
  • lib/projects/validateCreateProjectTaskRequest.ts
  • lib/projects/validateProjectRequest.ts
  • lib/projects/validateProjectTaskRequest.ts
  • lib/projects/validateUpdateProjectTaskBody.ts
  • lib/projects/validateUpdateProjectTaskRequest.ts
  • lib/supabase/project_collaborators/selectProjectCollaborator.ts
  • lib/supabase/project_collaborators/selectProjectCollaborators.ts
  • lib/supabase/project_task_comments/insertProjectTaskComment.ts
  • lib/supabase/project_task_comments/selectProjectTaskComments.ts
  • lib/supabase/project_tasks/deleteProjectTask.ts
  • lib/supabase/project_tasks/insertProjectTask.ts
  • lib/supabase/project_tasks/selectProjectTask.ts
  • lib/supabase/project_tasks/selectProjectTasks.ts
  • lib/supabase/project_tasks/updateProjectTask.ts
  • lib/supabase/projects/selectProject.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

14 issues found across 48 files

Confidence score: 2/5

  • lib/supabase/project_tasks/updateProjectTask.ts allows project_id or id from updates to alter the row selected by the scope filters, creating a risk of moving or renaming the wrong task — restrict updates to mutable task fields.
  • Both task validators accept calendar-invalid dates such as 2026-02-31, while validateCreateProjectTaskBody can also pass nonexistent assignee UUIDs to a foreign-key write; these cases can produce 500s instead of documented 400 responses — validate calendar dates and referenced accounts before database writes.
  • lib/projects/validateCreateProjectCommentBody.ts returns missing_fields: [] for malformed JSON and rejects long astral-Unicode comments based on UTF-16 length despite the database limit; align the malformed-body envelope and count code points for consistent validation.
  • Coverage remains weak around the new DELETE handler and comment/task validation error envelopes in lib/projects/deleteProjectTaskHandler.ts and the listed test files, so status-code, authorization, and response-shape regressions could go undetected — add assertions for the documented outcomes and failure paths.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/projects/__tests__/validateCreateProjectCommentBody.test.ts">

<violation number="1" location="lib/projects/__tests__/validateCreateProjectCommentBody.test.ts:16">
P2: The three error-path cases only assert `toBeInstanceOf(NextResponse)`, so a regression that breaks the documented `{status:"error", error, missing_fields}` envelope (e.g. wrong status code or dropped fields) would still pass. Assert the parsed envelope for each 400 case: `status: "error"`, `missing_fields: ["body"]`, and a string `error`, matching the sibling validator tests in this directory.</violation>
</file>

<file name="lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts">

<violation number="1" location="lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts:19">
P3: The test title claims the malformed-projectId 400 is returned before the body is read, but the body sent ({title:'x'}) is valid, so the test cannot detect a reordering — it passes even if the implementation parses the body first. To actually guard this ordering, send a body that would fail validation (e.g. {}) and assert the projectId 400 envelope still wins.</violation>
</file>

<file name="lib/projects/deleteProjectTaskHandler.ts">

<violation number="1" location="lib/projects/deleteProjectTaskHandler.ts:19">
P3: Add handler tests before merging this new DELETE endpoint. Without coverage for authorization failures, successful deletion, missing tasks, and database exceptions, changes can regress its status codes or response envelope unnoticed.</violation>
</file>

<file name="lib/supabase/project_tasks/updateProjectTask.ts">

<violation number="1" location="lib/supabase/project_tasks/updateProjectTask.ts:13">
P2: When a caller includes `project_id` or `id` in `updates`, this helper moves or renames the row that matched the scope filters. Restrict `updates` to mutable task fields so the project and task identities cannot be changed through this scoped update.</violation>
</file>

<file name="lib/projects/validateUpdateProjectTaskBody.ts">

<violation number="1" location="lib/projects/validateUpdateProjectTaskBody.ts:11">
P2: Calendar-invalid values such as `2026-02-31` pass this validator even though the field is documented as a date. Validate the parsed month/day combination before forwarding `due_date`, so invalid dates return 400 instead of being persisted or reaching the database as a 500.</violation>
</file>

<file name="lib/projects/getProjectCommentsHandler.ts">

<violation number="1" location="lib/projects/getProjectCommentsHandler.ts:18">
P3: When either path segment is malformed, `validateProjectTaskRequest` returns 400 before auth, but this `@returns` contract omits 400. Document the 400 response so the handler contract matches runtime behavior.</violation>
</file>

<file name="lib/projects/validateCreateProjectCommentBody.ts">

<violation number="1" location="lib/projects/validateCreateProjectCommentBody.ts:13">
P2: Comments containing more than 2,000 astral Unicode characters are rejected even though the database allows up to 4,000 characters. Replace the UTF-16-based `.max` check with a code-point count so validation matches `length(body)`.</violation>

<violation number="2" location="lib/projects/validateCreateProjectCommentBody.ts:37">
P2: When `request.json()` fails, `validateCreateProjectCommentRequest` passes `null` here, so the 400 includes `missing_fields: []`. Return the generic malformed-JSON envelope without `missing_fields` instead of treating the absence of a parsed body as a field error.

(Based on your team's feedback about validator error envelopes.) [B414E1B-DB44-465F-B577-8FF7-EC584B81D675]</violation>
</file>

<file name="lib/projects/__tests__/validateProjectTaskRequest.test.ts">

<violation number="1" location="lib/projects/__tests__/validateProjectTaskRequest.test.ts:23">
P3: The "names projectId when both segments are malformed" case asserts only the error body and never the HTTP status, unlike the two sibling tests in this file that also assert `status: 400`. Add the `toMatchObject({ status: 400 })` assertion so the both-malformed path verifies the status the validator actually returns.</violation>
</file>

<file name="lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts">

<violation number="1" location="lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts:6">
P3: The tests cover only the two malformed-UUID 400s; the success path and the invalid-body 400 path of `validateCreateProjectCommentRequest` are untested. Because the mock returns `undefined` for `requireProjectAccess`, a success-path test added as-is would silently return `{ accountId: undefined, body }` instead of failing. Mock `requireProjectAccess` to resolve an account id and add tests for the success path and the invalid-body 400.</violation>
</file>

<file name="lib/projects/countProjectTaskComments.ts">

<violation number="1" location="lib/projects/countProjectTaskComments.ts:12">
P3: Counting comments downloads the full comment rows — including each comment's `body` and its author-account join (see `selectProjectTaskComments`, which selects `id, task_id, account_id, body, created_at, accounts(name)`) — just to increment a counter. Use a lightweight exact-count query (e.g. `.select("task_id", { count: "exact", head: true }).in("task_id", taskIds)`) so the project page doesn't transfer every comment's text and author rows to count them.</violation>
</file>

<file name="lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts">

<violation number="1" location="lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts:13">
P3: These 400 error-path tests assert only `toBeInstanceOf(NextResponse)`, so they would still pass if the validator regressed to returning a 500 or dropped the error envelope. Assert the 400 status and the `{ status: "error", error: string }` fields (and `missing_fields` where parsed) that `validateUpdateProjectTaskBody` is documented to return, matching the repository's validator-test convention.</violation>
</file>

<file name="lib/projects/validateCreateProjectTaskBody.ts">

<violation number="1" location="lib/projects/validateCreateProjectTaskBody.ts:10">
P2: Dates like `2026-02-31` pass this regex and then reach the database, producing a 500 instead of the documented 400 validation response. Keep the format check but also validate the calendar date in both task schemas.</violation>

<violation number="2" location="lib/projects/validateCreateProjectTaskBody.ts:12">
P2: A well-formed UUID for a nonexistent account passes this check, then violates the `assignee_account_id` foreign key and returns 500. Validate the referenced account before both writes or translate that constraint failure to a 400.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant App as App Preview Client
    participant API as test-recoup-api
    participant Route as Next.js Project Route
    participant Validate as Request Validation
    participant Auth as Auth Context
    participant DB as Supabase Database

    Note over App,DB: Project API runtime on the test environment
    App->>API: OPTIONS /api/projects/... with CORS headers
    API->>Route: Route preflight request
    Route-->>App: 204 + CORS headers

    App->>API: Project request with x-api-key or Authorization: Bearer
    API->>Route: Dispatch project endpoint and path parameters
    Route->>Validate: Validate UUID path parameters
    alt Invalid projectId or taskId
        Validate-->>API: 400 invalid UUID
        API-->>App: 400 error response
    else Valid path parameters
        Validate->>Auth: Resolve account from API key or Privy token
        alt Missing or invalid credentials
            Auth-->>API: 401 unauthenticated
            API-->>App: 401 error response
        else Authenticated account
            Auth->>DB: Check project_collaborators(projectId, accountId)
            alt No collaborator row or access lookup failure
                DB-->>Auth: No access or database error
                Auth-->>API: 404 project not found
                API-->>App: 404 error response
            else Collaborator access granted
                Auth-->>Validate: accountId
                Validate->>API: Validated request and account context

                alt GET /api/projects/{projectId}
                    API->>DB: Read project
                    API->>DB: Read project tasks and collaborators
                    API->>DB: Read task comments for comment counts
                    DB-->>API: Project aggregate data
                    API-->>App: 200 project, tasks, collaborators, comment counts
                else GET /api/projects/{projectId}/tasks/{taskId}
                    API->>DB: Read task scoped to project
                    API->>DB: Read task comments and project collaborators
                    DB-->>API: Task detail data
                    API-->>App: 200 task, comments, collaborators
                else GET /.../comments
                    API->>DB: Confirm task belongs to project
                    API->>DB: Read task comments oldest first
                    DB-->>API: Comment feed
                    API-->>App: 200 comments
                else POST /api/projects/{projectId}/tasks
                    API->>Validate: Parse and validate task body
                    alt Invalid task body
                        Validate-->>API: 400 validation error
                        API-->>App: 400 error response
                    else Valid task body
                        API->>DB: Insert project_tasks row
                        DB-->>API: Created task
                        API-->>App: 201 task
                    end
                else POST /.../comments
                    API->>Validate: Parse, trim, and validate comment body
                    alt Invalid or oversized comment
                        Validate-->>API: 400 validation error
                        API-->>App: 400 error response
                    else Valid comment body
                        API->>DB: Confirm task belongs to project
                        API->>DB: Insert project_task_comments row with accountId
                        DB-->>API: Created comment with author data
                        API-->>App: 201 comment
                    end
                else PATCH /.../tasks/{taskId}
                    API->>Validate: Parse and validate task update
                    API->>API: Map completed flag to server timestamp and accountId
                    API->>DB: Update task scoped to project and task
                    DB-->>API: Updated task
                    API-->>App: 200 updated task
                else DELETE /.../tasks/{taskId}
                    API->>DB: Delete task scoped to project and task
                    DB-->>API: Deleted task and cascaded comments
                    API-->>App: 200 deleted task id
                end
            end
        end
    end

    Note over API,DB: Database failures return 500 for authorized operations and access checks fail closed as 404
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

});

it("rejects whitespace only, which the database CHECK would also reject", () => {
expect(validateCreateProjectCommentBody({ body: " " })).toBeInstanceOf(NextResponse);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The three error-path cases only assert toBeInstanceOf(NextResponse), so a regression that breaks the documented {status:"error", error, missing_fields} envelope (e.g. wrong status code or dropped fields) would still pass. Assert the parsed envelope for each 400 case: status: "error", missing_fields: ["body"], and a string error, matching the sibling validator tests in this directory.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/__tests__/validateCreateProjectCommentBody.test.ts, line 16:

<comment>The three error-path cases only assert `toBeInstanceOf(NextResponse)`, so a regression that breaks the documented `{status:"error", error, missing_fields}` envelope (e.g. wrong status code or dropped fields) would still pass. Assert the parsed envelope for each 400 case: `status: "error"`, `missing_fields: ["body"]`, and a string `error`, matching the sibling validator tests in this directory.</comment>

<file context>
@@ -0,0 +1,32 @@
+  });
+
+  it("rejects whitespace only, which the database CHECK would also reject", () => {
+    expect(validateCreateProjectCommentBody({ body: "   " })).toBeInstanceOf(NextResponse);
+  });
+
</file context>

export async function updateProjectTask(
projectId: string,
taskId: string,
updates: TablesUpdate<"project_tasks">,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When a caller includes project_id or id in updates, this helper moves or renames the row that matched the scope filters. Restrict updates to mutable task fields so the project and task identities cannot be changed through this scoped update.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/supabase/project_tasks/updateProjectTask.ts, line 13:

<comment>When a caller includes `project_id` or `id` in `updates`, this helper moves or renames the row that matched the scope filters. Restrict `updates` to mutable task fields so the project and task identities cannot be changed through this scoped update.</comment>

<file context>
@@ -0,0 +1,25 @@
+export async function updateProjectTask(
+  projectId: string,
+  taskId: string,
+  updates: TablesUpdate<"project_tasks">,
+): Promise<Tables<"project_tasks"> | null> {
+  const { data, error } = await supabase
</file context>
Suggested change
updates: TablesUpdate<"project_tasks">,
updates: Omit<TablesUpdate<"project_tasks">, "id" | "project_id" | "created_at" | "updated_at">,

description: z.string().trim().nullish(),
due_date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "due_date must be a YYYY-MM-DD date")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Calendar-invalid values such as 2026-02-31 pass this validator even though the field is documented as a date. Validate the parsed month/day combination before forwarding due_date, so invalid dates return 400 instead of being persisted or reaching the database as a 500.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/validateUpdateProjectTaskBody.ts, line 11:

<comment>Calendar-invalid values such as `2026-02-31` pass this validator even though the field is documented as a date. Validate the parsed month/day combination before forwarding `due_date`, so invalid dates return 400 instead of being persisted or reaching the database as a 500.</comment>

<file context>
@@ -0,0 +1,50 @@
+    description: z.string().trim().nullish(),
+    due_date: z
+      .string()
+      .regex(/^\d{4}-\d{2}-\d{2}$/, "due_date must be a YYYY-MM-DD date")
+      .nullish(),
+    assignee_account_id: z.string().uuid("assignee_account_id must be a valid UUID").nullish(),
</file context>

return NextResponse.json(
{
status: "error",
missing_fields: firstError.path,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When request.json() fails, validateCreateProjectCommentRequest passes null here, so the 400 includes missing_fields: []. Return the generic malformed-JSON envelope without missing_fields instead of treating the absence of a parsed body as a field error.

(Based on your team's feedback about validator error envelopes.) [B414E1B-DB44-465F-B577-8FF7-EC584B81D675]

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/validateCreateProjectCommentBody.ts, line 37:

<comment>When `request.json()` fails, `validateCreateProjectCommentRequest` passes `null` here, so the 400 includes `missing_fields: []`. Return the generic malformed-JSON envelope without `missing_fields` instead of treating the absence of a parsed body as a field error.

(Based on your team's feedback about validator error envelopes.) [B414E1B-DB44-465F-B577-8FF7-EC584B81D675]</comment>

<file context>
@@ -0,0 +1,45 @@
+    return NextResponse.json(
+      {
+        status: "error",
+        missing_fields: firstError.path,
+        error: firstError.message,
+      },
</file context>

.string({ message: "body is required" })
.trim()
.min(1, "body cannot be empty")
.max(COMMENT_MAX_LENGTH, `body cannot exceed ${COMMENT_MAX_LENGTH} characters`),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Comments containing more than 2,000 astral Unicode characters are rejected even though the database allows up to 4,000 characters. Replace the UTF-16-based .max check with a code-point count so validation matches length(body).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/validateCreateProjectCommentBody.ts, line 13:

<comment>Comments containing more than 2,000 astral Unicode characters are rejected even though the database allows up to 4,000 characters. Replace the UTF-16-based `.max` check with a code-point count so validation matches `length(body)`.</comment>

<file context>
@@ -0,0 +1,45 @@
+    .string({ message: "body is required" })
+    .trim()
+    .min(1, "body cannot be empty")
+    .max(COMMENT_MAX_LENGTH, `body cannot exceed ${COMMENT_MAX_LENGTH} characters`),
+});
+
</file context>
Suggested change
.max(COMMENT_MAX_LENGTH, `body cannot exceed ${COMMENT_MAX_LENGTH} characters`),
.refine(
value => [...value].length <= COMMENT_MAX_LENGTH,
`body cannot exceed ${COMMENT_MAX_LENGTH} characters`,
),

* @param request - The incoming request.
* @param projectId - The project the task belongs to.
* @param taskId - The task whose comments to read.
* @returns 200 with the comments, 401, 404 or 500.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: When either path segment is malformed, validateProjectTaskRequest returns 400 before auth, but this @returns contract omits 400. Document the 400 response so the handler contract matches runtime behavior.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/getProjectCommentsHandler.ts, line 18:

<comment>When either path segment is malformed, `validateProjectTaskRequest` returns 400 before auth, but this `@returns` contract omits 400. Document the 400 response so the handler contract matches runtime behavior.</comment>

<file context>
@@ -0,0 +1,41 @@
+ * @param request - The incoming request.
+ * @param projectId - The project the task belongs to.
+ * @param taskId - The task whose comments to read.
+ * @returns 200 with the comments, 401, 404 or 500.
+ */
+export async function getProjectCommentsHandler(
</file context>
Suggested change
* @returns 200 with the comments, 401, 404 or 500.
* @returns 200 with the comments, 400, 401, 404 or 500.

const result = await validateProjectTaskRequest(new NextRequest(url), "not-a-uuid", TASK_ID);

expect(result).toMatchObject({ status: 400 });
await expect(body(result)).resolves.toEqual({

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The "names projectId when both segments are malformed" case asserts only the error body and never the HTTP status, unlike the two sibling tests in this file that also assert status: 400. Add the toMatchObject({ status: 400 }) assertion so the both-malformed path verifies the status the validator actually returns.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/__tests__/validateProjectTaskRequest.test.ts, line 23:

<comment>The "names projectId when both segments are malformed" case asserts only the error body and never the HTTP status, unlike the two sibling tests in this file that also assert `status: 400`. Add the `toMatchObject({ status: 400 })` assertion so the both-malformed path verifies the status the validator actually returns.</comment>

<file context>
@@ -0,0 +1,48 @@
+    const result = await validateProjectTaskRequest(new NextRequest(url), "not-a-uuid", TASK_ID);
+
+    expect(result).toMatchObject({ status: 400 });
+    await expect(body(result)).resolves.toEqual({
+      status: "error",
+      error: "projectId must be a valid UUID",
</file context>

import { validateCreateProjectCommentRequest } from "@/lib/projects/validateCreateProjectCommentRequest";

vi.mock("@/lib/supabase/serverClient", () => ({ default: {} }));
vi.mock("@/lib/projects/requireProjectAccess", () => ({

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The tests cover only the two malformed-UUID 400s; the success path and the invalid-body 400 path of validateCreateProjectCommentRequest are untested. Because the mock returns undefined for requireProjectAccess, a success-path test added as-is would silently return { accountId: undefined, body } instead of failing. Mock requireProjectAccess to resolve an account id and add tests for the success path and the invalid-body 400.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts, line 6:

<comment>The tests cover only the two malformed-UUID 400s; the success path and the invalid-body 400 path of `validateCreateProjectCommentRequest` are untested. Because the mock returns `undefined` for `requireProjectAccess`, a success-path test added as-is would silently return `{ accountId: undefined, body }` instead of failing. Mock `requireProjectAccess` to resolve an account id and add tests for the success path and the invalid-body 400.</comment>

<file context>
@@ -0,0 +1,49 @@
+import { validateCreateProjectCommentRequest } from "@/lib/projects/validateCreateProjectCommentRequest";
+
+vi.mock("@/lib/supabase/serverClient", () => ({ default: {} }));
+vi.mock("@/lib/projects/requireProjectAccess", () => ({
+  requireProjectAccess: vi.fn(),
+}));
</file context>

export async function countProjectTaskComments(taskIds: string[]): Promise<Record<string, number>> {
if (!taskIds.length) return {};

const comments = await selectProjectTaskComments(taskIds);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Counting comments downloads the full comment rows — including each comment's body and its author-account join (see selectProjectTaskComments, which selects id, task_id, account_id, body, created_at, accounts(name)) — just to increment a counter. Use a lightweight exact-count query (e.g. .select("task_id", { count: "exact", head: true }).in("task_id", taskIds)) so the project page doesn't transfer every comment's text and author rows to count them.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/countProjectTaskComments.ts, line 12:

<comment>Counting comments downloads the full comment rows — including each comment's `body` and its author-account join (see `selectProjectTaskComments`, which selects `id, task_id, account_id, body, created_at, accounts(name)`) — just to increment a counter. Use a lightweight exact-count query (e.g. `.select("task_id", { count: "exact", head: true }).in("task_id", taskIds)`) so the project page doesn't transfer every comment's text and author rows to count them.</comment>

<file context>
@@ -0,0 +1,18 @@
+export async function countProjectTaskComments(taskIds: string[]): Promise<Record<string, number>> {
+  if (!taskIds.length) return {};
+
+  const comments = await selectProjectTaskComments(taskIds);
+
+  return comments.reduce<Record<string, number>>((counts, comment) => {
</file context>

});

it("rejects an empty body rather than treating it as a no-op success", () => {
expect(validateUpdateProjectTaskBody({})).toBeInstanceOf(NextResponse);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: These 400 error-path tests assert only toBeInstanceOf(NextResponse), so they would still pass if the validator regressed to returning a 500 or dropped the error envelope. Assert the 400 status and the { status: "error", error: string } fields (and missing_fields where parsed) that validateUpdateProjectTaskBody is documented to return, matching the repository's validator-test convention.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts, line 13:

<comment>These 400 error-path tests assert only `toBeInstanceOf(NextResponse)`, so they would still pass if the validator regressed to returning a 500 or dropped the error envelope. Assert the 400 status and the `{ status: "error", error: string }` fields (and `missing_fields` where parsed) that `validateUpdateProjectTaskBody` is documented to return, matching the repository's validator-test convention.</comment>

<file context>
@@ -0,0 +1,36 @@
+  });
+
+  it("rejects an empty body rather than treating it as a no-op success", () => {
+    expect(validateUpdateProjectTaskBody({})).toBeInstanceOf(NextResponse);
+  });
+
</file context>

This branch was successfully deployed

1 active deployment
Preview — f25fbbdf Deployed Sep 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant