Skip to content

fix(platform): repair review access retargeting - #4396

Merged
yannickmonney merged 11 commits into
mainfrom
fix/repair-review-access
Oct 13, 2026
Merged

yannickmonney merged 11 commits into
mainfrom
fix/repair-review-access

Conversation

@yannickmonney

Copy link
Copy Markdown
Contributor

Repair pending review retargeting after access loss. Pending recipients are discovered from approval metadata and designations, removed designations are cleared across task statuses, and all edit-losing role transitions revalidate reviews.

Verified with focused review and member tests, oxlint, oxfmt, and diff checks.

Closes #3789

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent exact-head verdict (Codex #9): REQUEST CHANGES on 9e440ab. I am not Codex #5. This head is a complete replacement for #4387: its first parent is 0e510af, so it stands on main without #4387. #4396 should survive; close #4387 after this replacement is corrected.

Findings:

  1. P1 — invalid SQL: the designation-clearing UPDATE references team_ids, team_id, and shared_with_team_ids without joining or qualifying app.projects. PostgreSQL will fail, so member removal/role changes fail transactionally. The team-route test reproduces a 500 through the new tx.unsafe path.
  2. P2 — recipients remain incomplete: discovery only checks requestedFor / typed user metadata, missing all live recipient shapes and creator fallback. Required stale and not-yet-in-review designation clearing is not proven.
  3. P2 — role changes incomplete: only member/disabled destinations revalidate. Admin to editor/developer on a restricted project can lose canEdit and retain the review.
  4. P2 — team removal unconditionally excludes: an editor eligible through another team, or owner/admin, is rerouted unnecessarily.
  5. P2 — archived reviews can fan out actionable notifications: archive state is not loaded and silent is not passed.
  6. P2 — transaction/CAS scope is unsafe: unlocked scan and unguarded metadata updates can race decisions/reviewer changes; fan-out is not conditional on a successful change.

No required regression tests ship (creator fallback, stale designation, not-yet-in-review designation, every edit-losing role change). No system retarget audit row is written. PostgreSQL proof remains required for array SQL, locks/CAS, isolation, and notification idempotency.

Verification, exact head, one worker (/opt/node/bin/node): targeted tests 85 passed, 1 failed (team route 500); parent team suite 16/16. Scoped type-aware oxlint fails reviews.ts:590 unsafe TaskRow assertion. Scoped oxfmt and git diff --check pass. PostgreSQL/integration not run.

CI is pending/stalled under githubstatus incident 3q1yb5m7ltvb; no rerun/cancel. This is the requested fallback for TALE-244 and TALE-359 (3729d02a-eb44-42b2-a68e-1bec2cebbcd6); task connector unavailable. Cross-linking #4387. No push, merge, close, rerun, or status change performed.

@yannickmonney

yannickmonney commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Independent exact-head re-review (Codex #9; not Codex #5) at 33aeff1: REQUEST CHANGES.

Blocking findings remain:

  1. P1 SQL still fails. PROJECT_TEAM_IDS_SQL is unqualified and the chained replacements produce identifiers such as p.p.team_ids and shared_with_p.p.team_ids. PostgreSQL rejects this. The existing team-removal regression still returns HTTP 500 (98 passed, 1 failed); the fake transaction also reports tx.unsafe is not a function before SQL execution.
  2. P2 role/team eligibility remains wrong. The helper unconditionally clears reviewer_user_id for every matching user; it does not establish that the user lost edit eligibility. An admin/editor or a user still eligible through another team is rerouted/excluded.
  3. P2 concurrency/CAS remains incomplete. The scan locks task rows, but approval rows are read without FOR UPDATE; updates only guard status = pending and do not condition on the scanned recipient/review identity.
  4. P2 recipient discovery is only partially repaired. No regression tests cover stale designation, not-yet-in-review designation, or every creator fallback; no test files are in the PR.
  5. The bulk helper emits realtime hints but no system retarget audit row for each changed review.
  6. Scoped type-aware checking reports TS2740 at reviews.ts:507: RetargetTask is passed to resolveHumanReviewer, which still requires TaskRow.

Verification: focused server tests with one worker: 98 passed, 1 failed (backend/domains/teams/routes.test.ts, expected 200, got 500). Oxfmt and git diff --check pass. Scoped type-aware oxlint/type-check fails as above. PostgreSQL backend:integration was not run, so array SQL, locking/CAS, isolation, and notification idempotency remain unproven. CI is pending/stalled under githubstatus incident 3q1yb5m7ltvb; I did not rerun it.

This is also the exact-head fallback verdict for TALE-244 and TALE-359 (3729d02a-eb44-42b2-a68e-1bec2cebbcd6). No push, merge, close, rerun, or status change.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-938: diagnosis and repair handoff for #4396

Investigated as Codex #4, distinct from author Codex #5. Exact source: 33aeff17a338f06a18a5347a0312424fb8fd2c4a. Diagnostic only; no implementation, branch push, database startup, CI rerun or merge. Scope: inspect SQL, transaction fake, erasure precedent, and propose reviewable changes. All line references below refer to this commit.

New evidence and root cause

backend/core/lib/audience.ts:140–145 defines the unqualified legacy-compatible audience CASE expression. backend/domains/tasks/reviews.ts:581,605 applies three substring replacements. The first replaces team_ids even inside shared_with_team_ids; the second replaces team_id inside the already qualified p.team_ids. The result is:

CASE WHEN cardinality(p.p.team_ids) > 0 THEN p.p.team_ids
ELSE array_remove(ARRAY[p.team_id] || shared_with_p.p.team_ids, NULL) END

The final replacement cannot repair the shared column because its original name no longer exists. Both candidate SELECT and designation UPDATE contain this defect; correcting only the UPDATE is insufficient. sql-reproduction.json records a deterministic reproduction extracted from the exact commit, with both corruption assertions passing. This is source-level proof, not PostgreSQL execution proof.

The 500 in backend/domains/teams/routes.test.ts:445–479 has a separate earlier cause: fakeSql at lines 78–94 implements only a callable template tag and begin. Its serializable mock at lines 46–48 passes that same tag as tx. The new real helper is reached after DELETE (teams/routes.ts:376–381), evaluates tx.unsafe at reviews.ts:581, and throws before the fake tag records the SELECT. Therefore the reported fake-test 500 does not independently demonstrate a PostgreSQL parser error. Adding a no-op unsafe mock would conceal rather than prove SQL correctness. That test also expects DELETE to be the only write (lines 452–454), so leaving an unconditional bulk UPDATE makes its next failure predictable even after adding unsafe.

Additional source findings: candidate metadata matching at reviews.ts:589–590 ignores typed-recipient precedence (taskReviewRecipientOf, lines 275–284); an agent review with a stale requestedFor mirror can match discovery. Equality at line 510 compares only requestedFor, so a changed typed human recipient with an unchanged mirror can escape repair. Both should use the canonical recipient semantics.

Existing implementation to reuse, with limits

backend/domains/erasure/service.ts:1225–1297 unions designation and waiting-review task IDs; clears a designation with user/org CAS and RETURNING; loads the task in a serializable transaction; rechecks the pending workflow-free review still addressed to the subject; excludes that subject from creator fallback; suppresses actionable notifications for archived tasks; emits a transactional hint. review-handover.integration.ts supplies existing real-database handover fixtures. Erasure always removes routing to its subject, whereas team/role loss must first establish loss of canEdit. Do not copy erasure's failure fallback/pseudonymization into membership handling. The existing shared retarget helper itself lacks approval locks/CAS, so the erasure precedent is not proof that every concurrency requirement is already satisfied.

Exact repair plan

All paths below are under services/platform/.

  1. reviews.ts:559–606: replace string rewriting and unconditional bulk UPDATE with one parameterized candidate SELECT joining app.tasks t to app.projects p on project and org. Select the project audience explicitly:

    CASE WHEN cardinality(p.team_ids) > 0 THEN p.team_ids
      ELSE array_remove(ARRAY[p.team_id] || p.shared_with_team_ids, NULL)
    END AS "projectTeamIds"

    Use a CTE/subquery to reuse that selected audience for the optional team overlap filter, with ${teamIds}::text[]. Match designations across all task statuses and pending workflow-free human recipients, respecting typed reviewer precedence; include legacy requestedFor only when the typed field is absent. Keep FOR UPDATE OF t on the outer task join and deterministic task ordering. Preserve legacy fallback semantics; do not use only p.team_ids while older-image writes remain supported. Qualified CASE precedent: backend/db/migrations/0109_team_audience.sql:35–41; tagged qualified team-array predicate precedent: backend/core/lib/audience.ts:185–186. No dynamic SQL or identifier replacement is needed.

  2. reviews.ts:607–618: for each locked candidate call existing reviewerEligibility (lines 118–139) against the selected audience and current member/team state, AFTER the mutation. If eligible, retain designation and pending recipient, with no audit/bell/hint. If not eligible, clear only that user's designation using task id + org + reviewer_user_id CAS and RETURNING (modeled on erasure lines 1225–1230); preserve another user's newer designation. Revalidate only human approvals still addressed to the affected user. Exclusion from fallback is justified only after this eligibility result. Keep archived routing/subscription changes silent. Remove the unconditional bulk UPDATE and emit hints only on an actual designation or approval change.

  3. reviews.ts:243–250,478–489,507: narrow resolveHumanReviewer's argument to the actual fields it reads (projectId, organizationId, reviewerUserId, createdBy, createdByType), using a shared Pick type; do not cast RetargetTask to TaskRow. Qualify and org-scope the project lookup. Inline a tagged audience CASE in this lookup too if removing unsafe from the route's execution graph, or use an established typed fragment with a proper fragment-aware fake.

  4. reviews.ts:90–98,501–526: add a dedicated mutation reader for org/task-scoped, pending, workflow-free approvals ordered consistently and FOR UPDATE, with an explicit tagged column list. Keep read-only consumers unlocked. Hold task lock before approval locks; inspect decision/reviewer mutation paths for the same order. Capture approval id, source run/round, canonical recipient, and scanned metadata. Update with org/resource/task/approval id, pending status, wf_execution_id IS NULL, and null-safe scanned metadata CAS (metadata IS NOT DISTINCT FROM ${tx.json(...)} with proper SQL NULL handling); full metadata equality includes recipient and review-source identity without another SQL copy of recipient parsing. Use RETURNING id. A lost CAS causes no dismissal, subscription, notification, audit or hint. Decide whether to reload or skip through the existing transaction retry contract. Compare recipient via sameRecipient/taskReviewRecipientOf rather than requestedFor alone. Preserve agent-owned and workflow-era approvals.

  5. reviews.ts:527–550 and audit precedent 924–939: only after RETURNING confirms a changed human review, dismiss the old request, subscribe the new reviewer, and notify unless silent. Write one task.review_retargeted audit row in the same transaction, using actorType system and actorId system when no human actor is supplied (existing system convention in retention/service.ts and connector_credentials/service.ts). Include previous/new recipient, approval id, run/round and cause (membership removed, role changed, team removed). Keep in-place approval id unless a separately reviewed requirement calls for minting. Audit a move to no eligible recipient too. Replaying an unchanged recipient must produce zero additional audit/notification rows. Thread a cause through bulk-helper args/callers; preserve human designation-change actor attribution. Return a changed result to gate hints rather than reporting every scanned task as changed.

  6. Callers: retain after-mutation calls at members/service.ts:330–333,449–454 and teams/routes.ts:376–381; thread cause only. Every actual role transition is already covered at this head. The repair belongs in per-project eligibility, not a new destination-role whitelist.

  7. Route fake, routes.test.ts:78–94,445–479: keep the real helper in the route regression. With explicit tagged SQL and zero affected tasks, assert a successful removal records the candidate read and no designation UPDATE; keep DELETE-only expectation. For affected-task tests extend the fake deliberately for member/team reads, json and RETURNING semantics; do not add unsafe merely to make the old malformed expression invisible. Existing review tests already provide richer fakes that can be reused. The route's successful response is unit proof only.

Required regression matrix and gates

  • backend/domains/teams/routes.test.ts: removal succeeds with no affected reviews; affected losing-editor handover is atomic with team removal; admin/owner retains; editor eligible through another team retains; team-scoped filter excludes unrelated projects; legacy audience fallback is preserved.
  • backend/domains/tasks/reviews.retarget.test.ts (new bulk-helper describe): stale designation without open approval; designated task not yet in_review; creator recipient without designation; task creator and project creator independently eligible/ineligible; no fallback candidate; typed human metadata, absent-typed legacy mirror, inconsistent mirror, typed null and captured agent; archived silent routing; other org untouched; decided/workflow rows untouched; changed recipient gets one system audit, repeat gets none; failed CAS produces no side effects.
  • backend/domains/members/service.test.ts and existing member/route suites: member deletion/disabled/member role loss, restricted-project admin→editor/developer loss, eligible editor/developer transitions and other-team access retained. Keep last-admin refusal unchanged.
  • Existing reviews.member.test.ts, reviews.routing.test.ts, service.reviewer.test.ts, erasure service.lifecycle.test.ts: shared-helper compatibility and creator exclusion. Update task spec/manual automation reference only where guarantees need clarification, following repository contract.
  • Local repair gates: focused Vitest server files with one worker, scoped oxlint including type-aware checking, scoped oxfmt and diff checks. Verify resolveHumanReviewer call no longer produces TS2740. No whole platform suite, workspace tsc or full check in this 4 GiB sandbox.
  • Named-permit PostgreSQL gate: actual query parse/execution with canonical and legacy arrays (including empty arrays), tenant isolation, concurrent review decision/reassignment versus removal, lock order and serialization retries, recipient/source CAS, atomic rollback and duplicate notification/audit prevention under replay. Extend existing erasure/review-handover.integration.ts/task review integration harness, not an ad-hoc database. Unit doubles cannot prove these properties.

Handoff and permit request

A documented new diagnosis now exists, but it does not constitute repair approval or PASS. Dispatch a fresh ordinary repair to the author only after the TALE-244 handoff is recorded, under unchanged guards and distinct review. No optional minimal patch was made: SQL-only repair would leave eligibility, CAS, audit and type failures open.

Requested permit text for TALE-357: “TALE-938 / #4396 needs a named heavy PostgreSQL integration permit for the repaired head. Requested operator: Codex #4, independent of author Codex #5; manager to explicitly grant the slot and execution window. Scope: qualified project audience arrays, task/approval lock ordering, scanned-recipient/source CAS, isolation, rollback, and notification/audit idempotency using the repository integration harness. No database has been started; no heavy work will begin before the named grant.”

Posting blocker: workspace_status returned status unavailable, blocker not_granted. Per tool instructions it was not blindly retried; task_get/find/comment shapes were not available. Consequently TALE-244, TALE-359 (3729d02a-eb44-42b2-a68e-1bec2cebbcd6) and TALE-357 could not be read/commented from this run. Deliver this document to those cards; #4396 receives the diagnosis directly through GitHub. This run's final report is posted back to TALE-938 by the task runner.

Verification performed: exact-head Git source inspection; deterministic SQL-expansion assertions both passed. The previously reported 98-pass/1-fail result and TS2740 are reviewer evidence, not tests rerun here. No code changed, so implementation test/lint/type gates and PR creation are not applicable to this diagnostic deliverable. PostgreSQL proof remains pending permit and repaired head.

The retarget helper the PR added could not run: its audience filter
rewrote PROJECT_TEAM_IDS_SQL by string replacement and produced
p.p.team_ids, it passed a partial task where a full TaskRow is required
(Type check), and it broke the team-removal route test (TEAM-R7). It also
moved every review of a person the moment a role changed or a team was
left, even when they could still edit the project.

Rewrite it around the one routing rule, reviewerEligibility:

- find the tasks that name the person as reviewer (any status) and the
  tasks whose open human review is addressed to them, by two bound reads
  instead of a join with rewritten identifiers;
- leave a project alone where the person can still edit it (an admin
  role, another team in either audience spelling), checked once per
  project against the state the door just wrote;
- otherwise lock the task row, re-read it and its review, clear the
  designation, and move the review through the chain a cleared
  designation takes (task creator, project creator), never back to the
  person, asking the new reviewer impersonally and nobody for an archived
  task;
- write one task.review_retargeted audit row (actor system, the cause in
  its metadata) and one hint per changed task.

Run it from the removal cascade, so SCIM's delete and the sign-in
handler's hook are covered with the members door, and run the team
removal under the serializable wrapper so a concurrent decision or
reviewer change retries instead of leaving a stale hand-over.

TASK-R39 states the rule in the tasks spec.
checkReviewAccessLoss runs the real doors on fresh organizations:
removing a member and changing a role through the members service, and
leaving a team through the removal's own statements. It proves what a
fake transaction cannot:

- other organizations, decided reviews, agent reviews and workflow-era
  rows keep what they had, while the designation of a task whose review
  is decided is cleared;
- the audience decides eligibility in both spellings, canonical and the
  legacy pair the previous image writes: one of two teams that reach a
  project keeps the review, the last one moves it;
- an admin made an editor keeps an organization-wide project and loses a
  team project they are not in, Developer keeps everything and Disabled
  moves everything;
- each changed task has one system audit row naming the cause and one
  hint, the new reviewer is asked once, nobody for an archived task;
- a reviewer change or a decision committed while the hand-over holds its
  read is kept, the serializable door runs again, and the role change
  still lands.

The erasure lane's barrier helpers are exported and take the statement to
pause before, so this lane pauses ahead of the lock its hand-over takes.
TASK-F93 asks a person to watch a waiting review move across two live
boards and the bell when its reviewer is lowered to Member, removed, or
taken off the only team that reaches the project. The coverage row names
what the unit tests and the real-Postgres lane own, and what still does
not hand reviews on (SCIM role updates, SSO role reconciliation, a deleted
team, an edited project audience).
The task guide says who keeps a review (only someone who can edit the
project) and where it goes when they lose that access: removal, a role
without edit access, or leaving the last team that reaches the project.
The members guide says removal, and Disabled, hand waiting reviews on.
English, German and French together.
@yannickmonney
yannickmonney force-pushed the fix/repair-review-access branch from 33aeff1 to d79bbbf Compare October 13, 2026 11:01
The removal cascade and the role door called the review hand-over of the
tasks domain directly. auth/membership.ts and the members service sit in
the low-level layer that the sign-in code reaches, so that static import
pulled the tasks, collaboration and governance modules into the CLI's
type-check program (render_layout.ts and crawl_action.ts do not compile
there), into the CLI's closure guards and into the UI suites' hashed
inputs. Three required checks failed on the pull request.

membership.ts now owns a setter-style hook, the way the corpus health hook
is installed: the cascade and the role door run it in their own
transaction after the write, and installReviewHandoverHook (tasks/reviews)
puts the hand-over behind it. The boot sequence and the integration
harness install it. A guard holds the layer free of the tasks domain and
holds both install sites. The team door stays a direct call: it is outside
that layer.
TASK-F93 went to the batched agent runs box that landed first; the hand-over box is TASK-F94.
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Pushed three changes on top of the rebase, during the branch cleanup of 2026-10-13. Why it was red: Type check, Unit (workspaces) and Unit (platform 2/2) failed for one reason. auth/membership.ts (and the role door in domains/members/service.ts) imported the tasks domain's hand-over statically, and those modules sit in the low-level layer the sign-in code reaches. That pulled the tasks, collaboration and governance modules into the CLI's TypeScript program (render_layout.ts and crawl_action.ts do not compile there), into the CLI's closure guards and into the UI suites' hashed inputs. The fix: membership.ts owns a setter-style hook, the way the corpus health hook is installed. The removal cascade and the role door run it in their own transaction after the write, installReviewHandoverHook (in tasks/reviews.ts) puts the hand-over behind it, and main.ts and the integration harness install it. A new guard holds both low-level modules free of the tasks domain and holds both install sites; the team door stays a direct call because it is outside that layer. Also: the hand-over's manual box is now TASK-F94 (TASK-F93 went to the batched-runs box that landed first). Verified locally on this head merged with current main: the CLI typecheck and its closure guards (12 of 12), the platform typecheck, all 23 guard files, knip, lint:manual, 156 test files of the auth, members, tasks, teams, scim and i18n areas, and 129 of 129 real-Postgres checks across checkReviewAccessLoss, checkErasureReviewHandoverRaces, checkScim and the agent lanes.

The draft-etag merge left the body textarea's onChange on three lines;
oxfmt keeps it on one, so the Format check failed on main.
@yannickmonney
yannickmonney added this pull request to the merge queue Oct 13, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 13, 2026
@yannickmonney
yannickmonney added this pull request to the merge queue Oct 13, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 13, 2026
@yannickmonney
yannickmonney merged commit f1bbf05 into main Oct 13, 2026
@yannickmonney
yannickmonney deleted the fix/repair-review-access branch October 13, 2026 19:51
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.

bug(platform): a waiting task review stays with a reviewer who was removed or lost edit access

1 participant