Skip to content

Fix confirmed merged-PR review findings and stage atomic milestone repair - #3638

Closed
BigSimmo wants to merge 33 commits into
mainfrom
fix/merged-pr-review-20261018
Closed

BigSimmo wants to merge 33 commits into
mainfrom
fix/merged-pr-review-20261018

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

User description

Summary

Investigate the 30 open findings in the supplied merged-PR review and repair confirmed local mechanisms. The issue-by-issue evidence and remaining limitations are in docs/audit/2026-10-18-merged-pr-resolution.md.

Fix cited-source recovery authority, generation-safe metadata and summary reads, upload replay cleanup, queue rollback fences, batched dashboard actions, worker timeouts, Teaching request sharing and post-write freshness, booking withdrawal races, EPA rotation dates, source provenance, shell/Git isolation, and ledger identity/correction handling. Withdraw unverifiable CET claims and the stale lithium attestation without granting clinical approval.

An atomic CME/registrar milestone RPC is included as a draft database proposal. This PR is not merge-ready. Merge only after explicit owner approval for this specific database change and an approved window, migration sealing, pinned schema replay/drift regeneration, and the applicable acceptance evidence. Merging the migration to main automatically applies it to the live clinical database.

Two independent adversarial reviewers found and verified corrections for stale Teaching reads, metadata pagination, obsolete metadata test contracts and residual claims attributed to the withdrawn CET citation. Preserve the newer main accessibility and worker-claim fixes through a fresh-base rebase. Resolve the later schema append conflict by merging main 57b2cd052 (#3636), retaining its entire legacy-claim repair before the draft milestone function.

Areas touched: Knowledge and records, Personal practice, Source intake and indexing, Clinical reference content, Answer engine, Delivery and assurance, App experience, Data platform and access, Prototypes

RAG impact: behaviour change — canary pair not run; live before/after provider evaluation requires separate explicit owner authorization. Recovery now requires evidence from exact cited chunks/documents and preserves low confidence; metadata admission is stricter. No relevance comparator changes.

Verification

  • Independent source review and bounded correction review completed; confirmed findings corrected.

  • Earlier focused baseline suite: 855 passed in 32 files, with overlapping follow-up suites recorded in the audit. These are historical local results, not hosted CI or production acceptance.

  • Correction suite: 61 passed in eight files before the final CET/EPA assertions; subsequent broader evidence is recorded below.

  • Local PostgreSQL/PGlite: 13 transaction/ownership/rollback scenarios passed, plus successful service-role create/update/delete with RLS enabled and equivalent repository grants/policies. This is not full Supabase-chain or multi-session proof.

  • Complete PR-local gate: blocked; see final evidence below.

  • Hosted CI on the first synchronized head: Cloud source contracts, Secret Scan, SAST and Cloud platform smoke passed. The native Windows 2025 bootstrap job passed Git Bash path, donor-copy and hook-installation fixtures. This is not Desktop GUI or device acceptance. Main CI status is recorded below.

  • Full unit run on 193f7be7b: 32,330 passed, 24 failed, 2 skipped / 1,986 files. Twenty-one fixture/contract failures were corrected and independently reviewed: targeted rerun 496 passed / 4 budget expectations failed, followed by 10/10 budget tests passed; complete Teaching/current-manifest run 2,169 passed in 77 files. These overlapping runs are separate evidence, not an invented green full-suite rerun.

  • Fresh repository lint (zero warnings) and complete typecheck passed after the corrections. Offline RAG fixture/adversarial contracts, medication data, function grants, owner scope, calculator content, ledger discipline, snapshot freshness and diff integrity passed. Diff integrity: 828 → 856 cases in 33 changed test files.

  • Three draft database unit failures remain: two sealing assertions and stale drift-manifest freshness. verify:pr-local passes its static stages through migration-role validation, then correctly stops at unsealed migration immutability; the remaining offline checks above were run separately.

  • Production build passed: optimized webpack compilation, generated-route TypeScript, 2,047 generated pages and client-bundle secret-surface check. Temporary build snapshot restored.

Measured metadata query counts are answer 12 → 16, search core 10 → 12, and search route 15 → 19: each unstamped metadata RPC becomes batched labels, stamped summaries and admitted parent reads. Successful-result, exact table-shape and equal one/five-document assertions remain; live latency is unverified.

Conflict resolution preserves application/worker/script source byte-for-byte from the build-verified head. Protected database manifests exactly match latest main; the draft remains unsealed. No applied migration was edited.

Publication exception: use only the repository's documented SKIP_DRIFT_GUARD=1 override to publish this blocked draft. No schema hash is forged; required CI and merge requirements remain unchanged. The existing unstamped RPC is recorded as intentionally unused pending owner-approved database retirement, without a dummy caller or deployed-function deletion.

Verification not run: live provider canary pair, hosted database queries/mutations, physical-device acceptance and clinical/legal/cultural sign-off. UI verification not run: browser execution is blocked by the browser CDN's HTTP 403 policy denial. Pinned Supabase replay/drift generation is blocked by Docker-daemon image-extraction storage exhaustion; no cached image remains. No gate, tolerance, historical hash or clinical approval was weakened to hide these limitations.

CI scope: change-scope classification, Static PR checks and the PR required aggregate, plus configured policy/safety checks. Coverage, build, database replay and browser lanes have draft/event/success conditions and may remain deferred; missing or skipped checks are not passing evidence.

Hosted static checks exposed a stale current-catalogue manifest fixture. Regenerated it from the current sources: 1,081 IDs preserved, 205 therapy lineage digests changed, and all content hashes, governance and eligibility unchanged. Independent review confirmed the correction; 216 site-content/ownership cases in 17 files and the exact static/synthetic freshness commands passed. Frozen database seeds and synthetic release-evidence receipts were preserved. Synthetic freshness is not live database proof.

Risk and rollout

  • Risk: cross-subsystem clinical-source, owner-access, ingestion and transaction changes. Database proposal remains unsealed and the drift manifest is stale against it; this prevents a readiness claim. All source-review holds remain.
  • Rollback: revert the application changes before release; any database rollback is a separately approved forward migration, never an edit to applied migration history.
  • Provider or production effects: branch publication and configured GitHub automation only. No merge, auto-merge, production deployment, live database mutation, provider evaluation or provider configuration change is authorized or performed by this work.

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use
  • No patient-identifiable document workflow was introduced or expanded without explicit governance approval
  • Supabase target remains PsychSift Production (sjrfecxgysukkwxsowpy)
  • Service-role keys and private document access remain server-only
  • Demo/synthetic content remains clearly separated from real clinical sources
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative
  • Deployment classification/TGA SaMD impact was checked when clinical decision-support behavior changed

Deployment classification/TGA SaMD assessment and clinical activation approval remain outstanding. No regulatory or clinical acceptance is inferred from synthetic tests or source review.

Notes

PS-003 scroll acceptance, PS-008 durable per-device/cross-instance alert delivery and PS-029 ambiguous PDF table continuations remain open. Native Windows bootstrap fixture proof passed hosted CI; Desktop GUI/forwarding acceptance and broader historical provenance remain incomplete. PS-062 corrections are immutable queued requests; canonical ledger reconciliation requires its separate serialized workflow. The PR is not merge-ready while the database and acceptance gates above are incomplete. It was created as a draft; GitHub later showed an external ready-for-review state change, which this session did not perform or reverse.

CI observation on the first synchronized head: Static PR checks failed the stale catalogue fixture described above; the correction passes the exact commands locally. The run was subsequently cancelled after another run was queued for that head. Container app/worker builds and provider-free smoke/runtime checks passed before cancellation; the overall container job is not claimed passing. New-head CI remains pending observation.


Summary by cubic

Fixes the confirmed findings from the 2026-10-18 merged-PR review across cited-source recovery, generation-safe metadata reads, upload replay cleanup, queue rollback fences, batched dashboard actions, worker timeouts, Teaching request sharing and post-write freshness, booking withdrawal races, EPA rotation dates, source provenance, shell/Git isolation, ledger reopen identity, and the stale lithium attestation. The branch incorporates newer main fixes through a merge; shell/Git isolation now comes from main's merged agent-policy delivery, and the mangled ingestion-enqueue.ts merge was repaired. The content-addressed therapy assets were regenerated so only the narrowed CET record's sources, references and notes differ, and the current catalogue manifest fixture was regenerated to match (all 1,081 content hashes, governance fields, and eligibility values preserved; CET stays excluded). No clinical approval is implied.

Behavior changes

  • RAG recovery fails closed when the exact cited chunks and documents carry no retrieval signals, preserving low confidence; unstamped metadata RPCs are replaced with batched labels, stamped summaries, and admitted parent reads, with committed-generation chunks sorting ahead of legacy rows so the read cap is not filled by stale chunks (answer/search/search-route query counts pinned at 16/12/19, live latency unverified). The quarantine runbook now requires returned sources — or zero chunks — before offline mode can be lifted, since citation omission alone does not prove exclusion.
  • Teaching submit/remind buttons stay focusable with aria-disabled and guard the click; successful writes reset in-flight shared GETs so a refresh cannot join a stale read.
  • Supervisor booking withdrawal is an optimistic update fenced on open status and timestamp so concurrent bookings survive; bulk reindex sends 10-document batches and reports succeeded/failed counts, keeping partial totals visible when a later batch fails even if the follow-up refresh rejects (a warning is appended instead); worker Supabase timeout default rises to 240s to cover the data plane while control-plane RPCs keep 30s.
  • Queue rollbacks are fenced on the stored updated_at timestamp read back after the write, so a stale rollback matches zero rows once an overlapping update re-stamps the row.
  • Setup aborts with an explicit prerequisite error when GNU timeout is missing, checked once in the parent shell so npm is never reinstalled on a false probe; setup and smoke scripts drop inherited GIT_* environment; ledger reopen rejects a short ID when any row with that display id belongs to a different ULID; EPA attainment counts only inside the current rotation; NICE citation detection trusts explicit authority over prose keywords; CET efficacy claims are narrowed to exclude the unidentified 2025 review.

Migration

  • Adds the mutate_owner_training_milestone database proposal, sealed with owner approval for this PR; merging would still apply it to the live clinical database and requires an approved window and regenerated schema replay/drift, so the PR is not merge-ready.
  • The retired unstamped metadata RPC stays in SQL as intentionally unused pending owner-approved removal.

Written for commit 013a81d. Summary will update on new commits.

View guided diff Turn on auto-fix

Summary by CodeRabbit

  • Bug Fixes
    • Bulk document reindexing now processes large selections in batches and provides clearer progress and recovery when a batch fails.
    • Teaching assessment and reminder actions remain keyboard-accessible when unavailable, with safeguards to prevent invalid submissions.
    • Training records now count dated EPA achievements only within the current rotation.
    • Document summaries and labels now exclude staged or outdated metadata, and answers are less likely to overstate confidence.
  • Content Updates
    • Therapy guidance was revised to remove claims awaiting source verification and clarify that cue exposure therapy is a selective adjunct, not a default first-line treatment.

CodeAnt-AI Description

Restore source-grounded answers and protect concurrent clinical workflows

What Changed

  • Related-document summaries and labels now come only from indexed documents in the caller’s access scope and committed index generation. Answer recovery relies on evidence from the cited source and retains low confidence when the query is not supported.
  • Teaching reads refresh after successful saves and uploads. Incomplete assessment actions remain keyboard-focusable but cannot be activated.
  • Bulk reindexing submits up to 10 documents at a time, reports partial results, and refreshes work already queued if a later batch fails.
  • Queue rollbacks, booking withdrawals, and upload-replay cleanup now preserve newer or already-committed changes during concurrent requests.
  • EPA completions count only within the current rotation and through today. Worker database deadlines now accommodate longer data operations.
  • Removed CET claims attributed to an unverifiable review and withdrew the stale lithium attestation. Citations are no longer labeled NICE solely because their text mentions NICE.
  • Adds a proposed atomic operation for mirrored training milestones; the database migration remains a draft pending owner approval.

Impact

✅ Fewer unsupported clinical answers
✅ Fewer overwritten bookings and queued updates
✅ Fewer long-running indexing timeouts

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Joshua Simpson added 7 commits October 18, 2026 06:22
Measure metadata safety cost: each former RPC becomes batched labels, stamped summaries and admitted parent reads. Pin answer/search/search-route at16/12/19, preserving successful results, exact traffic shape and no per-document scaling. Retain frozen manifests and applied migrations.
@coderabbitai

coderabbitai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

This pull request records review and governance updates and changes workflows across uploads, indexing, metadata retrieval, training records, Teaching interactions, RAG recovery, therapy evidence, worker timeouts, and cloud setup. It adds related tests and updates documentation and data records.

Changes: Governance records and runbooks

Layer / File(s) Summary
Review receipts and provenance
data/repo-awareness-snapshot.json, docs/audit/*, docs/branch-review-records/*
Adds audit and review records for findings, corrections, checks, and remaining acceptance boundaries.
Issue status and incident procedures
docs/decisions/*, docs/governance-incident-runbooks.md, docs/organisation/*, docs/outstanding-issues-inbox/*, scripts/list-database-skills.mjs, tests/organisation-instruction-guards.test.ts
Updates issue and inbox status records, incident procedures, service names, a retired-rule match, and repository path and collision records.

Cloud setup and Git isolation

Layer / File(s) Summary
Git isolation and bounded probes
scripts/check-cloud-platform-smoke.mjs, scripts/setup-codex-cloud.sh, tests/cloud-platform-smoke.test.ts, tests/codex-cloud-policy-harness.test.ts, tests/codex-cloud-setup.test.ts, tests/fixtures/empty.gitconfig
Isolates Git configuration for bootstrap commands, adds bounded runtime-version checks, and moves environment-variable unsets earlier in generated profiles. Tests cover Git isolation, probe failures, and profile sourcing.

Upload, queue, and booking consistency

Layer / File(s) Summary
Upload replay and bulk reindex
src/app/api/upload/route.ts, src/components/clinical-dashboard/use-dashboard-bulk-actions.ts, tests/clinical-dashboard-bulk-actions.dom.test.tsx, tests/upload-duplicate-cleanup-ledger.test.ts
Upload replay releases the intended path as superseded relative to the committed path. Bulk reindex submits batches of 10, tracks results, and refreshes after successful work.
Document queue rollback fence
src/lib/ingestion-enqueue.ts, src/lib/supabase/database.types.ts, supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql, supabase/schema.sql, tests/ingestion-enqueue.test.ts, tests/ingestion-quality-route.test.ts
Adds a database-generated mutation identifier and uses the returned value to constrain rollback updates.
Concurrent booking withdrawal
src/lib/teaching/assessments/supervisor-bookings.ts, tests/work-bookings-concurrent-withdrawal.test.ts, docs/organisation/systems/personal-practice.json
Constrains withdrawal updates by the slot’s status and previously read timestamp. Tests check both concurrent and non-concurrent overlap cases.

Issue ledger identity

Layer / File(s) Summary
Reopen identity validation
scripts/ledger-inbox.mjs, tests/ledger-inbox.test.ts
Rejects reopen requests when the supplied display ID belongs to a different issue than the target ULID. For a known ULID, request targeting uses the existing row ID.

Training milestones and EPA dates

Layer / File(s) Summary
Atomic milestone and registrar updates
src/lib/cme/training-repository.ts, src/lib/supabase/database.types.ts, supabase/migrations/20261018075500_atomic_training_milestone_mirror.sql, supabase/schema.sql, tests/cme-training-registrar-milestones.test.ts
Adds an owner-scoped RPC for milestone create, update, and delete, and routes synchronized repository writes through it.
EPA attainment date filtering
src/lib/cme/training-assessments.ts, tests/cme-training-registrar-milestones.test.ts
Retains undated EPA records and filters dated attainments by the current rotation, today, and rotation end date using Perth dates.

Teaching client and assessment controls

Layer / File(s) Summary
Shared reads and write invalidation
src/lib/teaching/client.ts, tests/teaching-client.test.ts, tests/helpers/teaching-fixtures.ts, tests/teaching-depth-pages.dom.test.tsx
Shares Teaching GET requests and resets shared reads after successful writes. Tests cover caller cancellation and fresh reads after writes.
Accessible assessment controls
src/components/teaching/assessments/*, tests/teaching-assessments-epa-answers.dom.test.tsx, tests/teaching-assessments-extras.dom.test.tsx
Keeps selected blocked controls focusable with ARIA disabled state and guards actions against invalid or unavailable states.

Document metadata retrieval

Layer / File(s) Summary
Scoped metadata reads
src/lib/document-enrichment.ts, tests/helpers/document-metadata-fixture.ts, tests/document-enrichment*.test.ts, tests/private-access-routes.test.ts, tests/rag-round-trip-budget.test.ts, tests/search*-round-trip-budget.test.ts, tests/supabase-function-callers.test.ts
Replaces related-metadata RPC reads with paged table reads. It filters by access scope and committed generation, checks cancellation and query errors, and updates retrieval round-trip expectations.
Generation-aware chunk selection
src/lib/rag/rag-document-summary-context.ts, tests/rag-document-summary.test.ts
Includes null-generation chunks as well as chunks matching the committed generation.

Citation-backed answer recovery

Layer / File(s) Summary
Cited signal validation
src/lib/rag/rag-answer-quality-gate.ts, src/lib/rag/rag-cited-recovery-support.ts, tests/rag-answer-fallback.test.ts, tests/source-backed-recovery-cross-reference.test.ts
Requires recovery signals to come from sources matching both the cited chunk and document IDs. Recovery no longer raises low confidence to medium.

Therapy source classification and evidence

Layer / File(s) Summary
NICE citation classification
src/lib/therapy-source-governance.ts, src/components/therapy-compass/record/source-provenance.tsx, tests/therapy-source-governance.test.ts
Adds a shared NICE citation check and uses it to select NICE guideline metadata or generic source metadata.
CET evidence corrections
src/data/therapies-index.json, src/data/therapies-source.json, src/data/therapy-catalogue-assets.ts, src/lib/site-content/site-content-change-owners.json, tests/therapy-source-governance.test.ts, tests/site-content-sync.test.ts
Removes claims attributed to an unverified 2025 review, retains qualified descriptions based on the 2017 meta-analysis, and updates catalogue references and related tests.

Sign-off records and queue

Layer / File(s) Summary
Rule gates and source attestation
src/lib/developer-area/sign-off-queue.ts, src/data/source-acquisitions.json, tests/sign-off-queue.test.ts, tests/sign-off-today.test.ts, tests/developer-sign-off-page.dom.test.tsx, tests/owner-sign-off-today.dom.test.tsx
Uses rule gate results and signer metadata to determine signed status. Withdraws a source attestation and updates sign-off queue counts.

Worker database deadlines

Layer / File(s) Summary
Timeout defaults and RPC signals
worker/behavior.ts, worker/main.ts, docs/worker-deploy-runbook.md, tests/worker-control-plane-timeouts.test.ts
Raises the default Supabase timeout, resolves the shared timeout from plane deadlines, and selects abort signals by RPC name.

Priority: ⬇️ Low

Estimated code review effort: 5 (Critical) | ~90 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant TrainingRepository
  participant MilestoneRpc
  participant CmeAndRegistrarTables
  TrainingRepository->>MilestoneRpc: Send milestone operation and registrar fields
  MilestoneRpc->>CmeAndRegistrarTables: Apply owner-scoped create, update, or delete
  MilestoneRpc-->>TrainingRepository: Return result or mutation error
Loading
sequenceDiagram
  participant SearchOrAnswerPath
  participant FetchRelatedDocumentMetadata
  participant SupabaseMetadataTables
  SearchOrAnswerPath->>FetchRelatedDocumentMetadata: Request metadata for document IDs and access scope
  FetchRelatedDocumentMetadata->>SupabaseMetadataTables: Read paged labels, summaries, and indexed documents
  SupabaseMetadataTables-->>FetchRelatedDocumentMetadata: Return rows for scope and generation checks
  FetchRelatedDocumentMetadata-->>SearchOrAnswerPath: Return admitted labels and summaries
Loading

Suggested reviewers: claude

Merge Risk: 🟠 High · up to 16883

Several source-recovery and booking paths retain correctness risks, and migration verification is incomplete. Resolve these issues and the queue rollback failure before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 39.62% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 53 functions across 50 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly summarizes the main changes: fixing confirmed merged-PR findings and staging the atomic milestone repair.
Description check Passed The description follows the required template and documents the summary, verification evidence, risks, rollback, production effects, limitations, and outstanding approval gates. It clearly states that…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description follows the required template and documents the summary, verification evidence, risks, rollback, production effects, limitations, and outstanding approval gates. It clearly states that the PR is not merge-ready.

Full details: Docstring Coverage

Explanation

Docstring coverage is 39.62% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 53 functions across 50 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches: 💡 2
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@supabase

supabase Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Updates to Preview Branch (fix/merged-pr-review-20261018) ↗︎

Deployments Status Updated
Database ✅ Sun, 18 Oct 2026 10:38:55 UTC
Services ✅ Sun, 18 Oct 2026 10:38:55 UTC
APIs ✅ Sun, 18 Oct 2026 10:38:55 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations ✅ Sun, 18 Oct 2026 10:38:56 UTC
Migrations ✅ Sun, 18 Oct 2026 10:38:58 UTC
Seeding ✅ Sun, 18 Oct 2026 10:39:00 UTC
Edge Functions ✅ Sun, 18 Oct 2026 10:39:02 UTC

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

Comment thread scripts/setup-codex-cloud.sh Resolved
gitar-bot[bot]
gitar-bot Bot previously approved these changes Oct 18, 2026

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Gitar has auto-approved this PR (configure)

gitar-bot[bot]
gitar-bot Bot previously approved these changes Oct 18, 2026

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Gitar has auto-approved this PR (configure)

@codeant-ai

codeant-ai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

🏁 CodeAnt Quality Gate Results

Commit: e51796cf
Scan Time: 2026-10-18 09:52:02 UTC

✅ Overall Status: PASSED

Quality Gate Details

Quality Gate Status Details
Secrets ✅ PASSED 0 secrets found
Duplicate Code ✅ PASSED 0.0% duplicated
SAST ✅ PASSED No security issues
Bugs ✅ PASSED Rating B: 3 bugs (3 medium)
IAC ✅ PASSED Rating S: No issues

View Full Results

Joshua Simpson added 2 commits October 18, 2026 07:09
Regenerate the current catalogue fixture after the content-addressed therapy asset changes. Preserve all1081content hashes, governance fields and eligibility values; keep CET excluded. Frozen epoch-zero SQL and synthetic release evidence remain unchanged.
@BigSimmo
BigSimmo marked this pull request as ready for review October 18, 2026 07:15

@greptile-apps greptile-apps 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.

BigSimmo has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@BigSimmo
BigSimmo enabled auto-merge (squash) October 18, 2026 07:15
@codeant-ai

codeant-ai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Incremental review completed e51796c Oct 18, 2026 · 09:44 09:51
✅ Incremental review completed 168837d Oct 18, 2026 · 08:19 08:24
✅ Reviewed your PR 0094b90 Oct 18, 2026 · 07:15 07:23

@codeant-ai

codeant-ai Bot commented Oct 18, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-18T07:20:29.820051Z 0094b90 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@claude

claude Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 2s —— View job


I'll analyze this and get back to you.

@codeant-ai codeant-ai Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files label Oct 18, 2026
@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Repair confirmed review findings and draft atomic milestone writes

🐞 Bug fix 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Tightens cited-answer recovery, metadata admission, ingestion rollback, Teaching freshness,
 booking races, and worker deadlines.
• Corrects clinical provenance, ledger claims, operator guidance, and accessibility; adds focused
 regression coverage.
• Drafts atomic CME milestone writes; database approval, migration sealing, and replay remain merge
 blockers.
Diagram

graph TD
  A["Review findings"] --> B["Source repairs"] --> C["Regression tests"] --> D["Audit handoff"]
  B --> E["Metadata admission"] --> F[("Document records")]
  B --> G["CME repository"] --> H["Milestone RPC"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Separate the database proposal
  • ➕ Prevents source fixes from implicitly authorizing a live migration.
  • ➕ Allows dedicated owner approval, sealing, and replay.
  • ➖ Requires coordinated rollout because the application now calls the RPC.
  • ➖ May require temporarily gating the repository change.

Recommendation: Do not merge while the migration is unapproved, unsealed, and unreplayed. Prefer a separately approved database rollout coordinated with application activation; retain a combined PR only after all stated database and acceptance gates pass.

Files changed (83) +1704 / -459

Bug fix (27) +443 / -237
check-cloud-platform-smoke.mjsIsolate Git environment in smoke checks +9/-2

Isolate Git environment in smoke checks

• Drops inherited Git selectors and supplies an isolated config to mutating children.

scripts/check-cloud-platform-smoke.mjs

ledger-inbox.mjsFence ledger identity collisions +9/-2

Fence ledger identity collisions

• Rejects reopen IDs owned by another ULID and resolves full-ULID targets to actual row IDs.

scripts/ledger-inbox.mjs

list-database-skills.mjsDerive reviewed-twin diagnostic +1/-1

Derive reviewed-twin diagnostic

• Reports permitted skill-name twins from the configured set.

scripts/list-database-skills.mjs

setup-codex-cloud.shScrub secrets and bound probes +26/-21

Scrub secrets and bound probes

• Removes inherited provider variables before nvm and rejects missing or unsuccessful bounded version probes.

scripts/setup-codex-cloud.sh

route.tsRetry cleanup on durable upload replay +13/-0

Retry cleanup on durable upload replay

• Releases a superseded intended path using the committed admission path before returning replay.

src/app/api/upload/route.ts

use-dashboard-bulk-actions.tsBatch dashboard reindex requests +35/-20

Batch dashboard reindex requests

• Submits groups of at most ten, totals results, and refreshes earlier successes after a later failure.

src/components/clinical-dashboard/use-dashboard-bulk-actions.ts

assessments-assessor.tsxKeep blocked EPA submission focusable +0/-1

Keep blocked EPA submission focusable

• Removes native disabling while preserving the accessible blocked state and submission guard.

src/components/teaching/assessments/assessments-assessor.tsx

assessments-inbox.tsxKeep blocked feedback send focusable +3/-2

Keep blocked feedback send focusable

• Exposes the reason to keyboard users while guarding incomplete sends.

src/components/teaching/assessments/assessments-inbox.tsx

assessments-term-overview.tsxExpose blocked reminder reasons +9/-5

Expose blocked reminder reasons

• Keeps reminder controls focusable and prevents invalid individual or bulk sends.

src/components/teaching/assessments/assessments-term-overview.tsx

source-provenance.tsxUse authority-aware NICE classification +2/-3

Use authority-aware NICE classification

• Replaces broad text matching with the shared citation predicate.

src/components/therapy-compass/record/source-provenance.tsx

source-acquisitions.jsonWithdraw stale lithium attestation +2/-5

Withdraw stale lithium attestation

• Removes the obsolete signature, marks the candidate unverified, and requires genuine re-review.

src/data/source-acquisitions.json

therapies-index.jsonRemove unsupported indexed CET claims +2/-2

Remove unsupported indexed CET claims

• Drops efficacy statements attributed to an unidentified 2025 review.

src/data/therapies-index.json

therapies-source.jsonWithdraw unverifiable CET citation +11/-11

Withdraw unverifiable CET citation

• Removes its trial counts and attributed efficacy conclusions while retaining needs-review status.

src/data/therapies-source.json

training-assessments.tsLimit EPA credit to current rotation +14/-2

Limit EPA credit to current rotation

• Uses work-zone dates and keeps undated records in progress.

src/lib/cme/training-assessments.ts

training-repository.tsUse atomic production milestone mutation +49/-0

Use atomic production milestone mutation

• Routes create, update, and delete through one RPC without falling back after failure.

src/lib/cme/training-repository.ts

sign-off-queue.tsApply runtime Today sign-off gates +11/-22

Apply runtime Today sign-off gates

• Uses fatigue, CPD, and MHA gates rather than weaker ledger-only classification.

src/lib/developer-area/sign-off-queue.ts

document-enrichment.tsPage and admit generation-safe metadata +55/-91

Page and admit generation-safe metadata

• Replaces unstamped RPC results with paged labels, summaries, and indexed parents, enforcing access and generation fences.

src/lib/document-enrichment.ts

ingestion-enqueue.tsUse stored queue timestamp for rollback +8/-4

Use stored queue timestamp for rollback

• Reads the trigger-adjusted timestamp and uses it to fence compensation.

src/lib/ingestion-enqueue.ts

rag-answer-quality-gate.tsRestrict cited-answer recovery +5/-32

Restrict cited-answer recovery

• Requires cited support, retains low confidence, and drops unmatched citations on quality failure.

src/lib/rag/rag-answer-quality-gate.ts

rag-cited-recovery-support.tsCheck exact cited evidence +45/-0

Check exact cited evidence

• Validates retrieval and required-term signals against matching cited chunk/document pairs.

src/lib/rag/rag-cited-recovery-support.ts

rag-document-summary-context.tsInclude legacy chunks before cap +1/-1

Include legacy chunks before cap

• Queries NULL and committed generations together before ordering and limiting.

src/lib/rag/rag-document-summary-context.ts

supervisor-bookings.tsFence availability withdrawal +2/-0

Fence availability withdrawal

• Withdraws only slots whose original open status and timestamp still match.

src/lib/teaching/assessments/supervisor-bookings.ts

client.tsShare reads and invalidate after writes +12/-4

Share reads and invalidate after writes

• Coalesces identical account-aware GETs and prevents post-write refreshes joining older reads.

src/lib/teaching/client.ts

therapy-source-governance.tsHonor explicit NICE authority +12/-0

Honor explicit NICE authority

• Avoids promoting PubMed or other citations that merely mention NICE.

src/lib/therapy-source-governance.ts

20261018055300_atomic_training_milestone_mirror.sqlDraft transactional milestone RPC +71/-0

Draft transactional milestone RPC

• Defines service-role-only owner-scoped CME/registrar mutations with serialization and rollback. This unsealed proposal would apply to the live database on merge.

supabase/migrations/20261018055300_atomic_training_milestone_mirror.sql

behavior.tsCover worker budgets with transport cap +8/-2

Cover worker budgets with transport cap

• Defaults the shared Supabase timeout to at least configured control/data deadlines.

worker/behavior.ts

main.tsSelect deadline by RPC class +28/-4

Select deadline by RPC class

• Uses data-plane deadlines for image and terminal writes and control deadlines for control RPCs.

worker/main.ts

Tests (36) +938 / -178
clinical-dashboard-bulk-actions.dom.test.tsxTest dashboard batching +54/-0

Test dashboard batching

• Covers selection sizes and refreshing earlier queued work after failure.

tests/clinical-dashboard-bulk-actions.dom.test.tsx

cloud-platform-smoke.test.tsTest Git isolation +19/-1

Test Git isolation

• Injects Git redirection and verifies the caller index survives.

tests/cloud-platform-smoke.test.ts

cme-training-registrar-milestones.test.tsTest atomic writes and rotation dates +69/-1

Test atomic writes and rotation dates

• Checks RPC-only production mutations and EPA boundary cases.

tests/cme-training-registrar-milestones.test.ts

codex-cloud-policy-harness.test.tsTest secret scrub and fixture shim +36/-1

Test secret scrub and fixture shim

• Checks nvm sees no inherited provider names and binds synthetic Git on Windows.

tests/codex-cloud-policy-harness.test.ts

codex-cloud-setup.test.tsTest portable bounded probes +36/-2

Test portable bounded probes

• Uses a real Git fixture and tests failed, missing-timeout, and timed-out probes.

tests/codex-cloud-setup.test.ts

developer-sign-off-page.dom.test.tsxAdjust signable count +1/-1

Adjust signable count

• Reflects the withdrawn lithium attestation.

tests/developer-sign-off-page.dom.test.tsx

document-enrichment-retrieval-scope.test.tsTest scoped paged admission +94/-95

Test scoped paged admission

• Replaces retired RPC assertions with owner/public, cancellation, error, and multi-page controls.

tests/document-enrichment-retrieval-scope.test.ts

document-enrichment-visual-counts.test.tsAdapt visual-count metadata fixtures +24/-26

Adapt visual-count metadata fixtures

• Retains opt-in visual counts and cancellation checks under source-row reads.

tests/document-enrichment-visual-counts.test.ts

document-enrichment.test.tsReject staged summaries +17/-2

Reject staged summaries

• Confirms successful RPC fixtures cannot bypass committed source-row generations.

tests/document-enrichment.test.ts

empty.gitconfigAdd portable Git fixture +1/-0

Add portable Git fixture

• Provides an isolated configuration file instead of a platform-dependent null device.

tests/fixtures/empty.gitconfig

document-metadata-fixture.tsModel metadata query statements +85/-0

Model metadata query statements

• Applies scope filters, ordering, row caps, cancellation, and errors before filtering results.

tests/helpers/document-metadata-fixture.ts

teaching-fixtures.tsReset shared reads between tests +2/-0

Reset shared reads between tests

• Clears GET sharing state when setting up the Teaching clock.

tests/helpers/teaching-fixtures.ts

ingestion-enqueue.test.tsTest trigger-aware rollback +72/-2

Test trigger-aware rollback

• Models returned timestamps, collisions, and intervening writes.

tests/ingestion-enqueue.test.ts

ingestion-quality-route.test.tsAssert stored compensation fence +9/-1

Assert stored compensation fence

• Verifies route fixtures return and use the database timestamp.

tests/ingestion-quality-route.test.ts

ledger-inbox.test.tsTest reopen ID collisions +11/-0

Test reopen ID collisions

• Rejects another issue's short display ID even with a supplied ULID.

tests/ledger-inbox.test.ts

organisation-instruction-guards.test.tsSeparate current and retired therapy holds +9/-0

Separate current and retired therapy holds

• Allows pending owner review but rejects missing-reference rationale.

tests/organisation-instruction-guards.test.ts

owner-sign-off-today.dom.test.tsxAdjust owner signature totals +2/-2

Adjust owner signature totals

• Accounts for the withdrawn lithium signature.

tests/owner-sign-off-today.dom.test.tsx

private-access-routes.test.tsAdmit parents in search fixtures +6/-0

Admit parents in search fixtures

• Supplies indexed document rows required by metadata admission.

tests/private-access-routes.test.ts

rag-answer-fallback.test.tsExpect low-confidence recovery +12/-1

Expect low-confidence recovery

• Extends query fakes and preserves low confidence in the asserted answer.

tests/rag-answer-fallback.test.ts

rag-document-summary.test.tsTest legacy-generation query +3/-1

Test legacy-generation query

• Asserts NULL and committed chunks are selected together.

tests/rag-document-summary.test.ts

rag-round-trip-budget.test.tsPin answer metadata cost +25/-3

Pin answer metadata cost

• Pins 16 round trips and non-per-document batched reads.

tests/rag-round-trip-budget.test.ts

search-round-trip-budget.test.tsPin search metadata cost +10/-3

Pin search metadata cost

• Pins 12 calls and the source-row traffic shape.

tests/search-round-trip-budget.test.ts

search-route-round-trip-budget.test.tsPin route metadata cost +14/-5

Pin route metadata cost

• Pins 19 calls and the batched metadata breakdown.

tests/search-route-round-trip-budget.test.ts

sign-off-queue.test.tsTest runtime gate classification +30/-8

Test runtime gate classification

• Rejects stale, unauthorized, or future sign-offs and revises totals.

tests/sign-off-queue.test.ts

sign-off-today.test.tsList lithium for genuine review +7/-1

List lithium for genuine review

• Adds the unverified candidate to expected source sign-off work.

tests/sign-off-today.test.ts

site-content-sync.test.tsUse current-source test manifests +30/-11

Use current-source test manifests

• Generates temporary CLI-planning manifests while preserving frozen historical fixtures.

tests/site-content-sync.test.ts

source-backed-recovery-cross-reference.test.tsTest cited-only recovery +68/-2

Test cited-only recovery

• Covers uncited signals, absent sources, required signals, and low confidence.

tests/source-backed-recovery-cross-reference.test.ts

supabase-function-callers.test.tsRecord retired metadata caller +3/-0

Record retired metadata caller

• Marks the deployed unstamped metadata RPC intentionally uncalled pending approved retirement.

tests/supabase-function-callers.test.ts

teaching-assessments-epa-answers.dom.test.tsxTest focusable blocked EPA submit +7/-1

Test focusable blocked EPA submit

• Checks accessible explanation and blocked activation.

tests/teaching-assessments-epa-answers.dom.test.tsx

teaching-assessments-extras.dom.test.tsxTest focusable blocked actions +19/-4

Test focusable blocked actions

• Covers feedback and reminder reasons and activation guards.

tests/teaching-assessments-extras.dom.test.tsx

teaching-client.test.tsTest sharing and post-write freshness +51/-0

Test sharing and post-write freshness

• Checks independent cancellation and fresh GETs after each write form.

tests/teaching-client.test.ts

teaching-depth-pages.dom.test.tsxIsolate depth-page GETs +2/-0

Isolate depth-page GETs

• Resets shared transport before each test.

tests/teaching-depth-pages.dom.test.tsx

therapy-source-governance.test.tsGuard CET and NICE provenance +27/-0

Guard CET and NICE provenance

• Checks excluded 2025 claims and mixed-authority classification.

tests/therapy-source-governance.test.ts

upload-duplicate-cleanup-ledger.test.tsGuard replay cleanup ordering +12/-2

Guard replay cleanup ordering

• Checks committed-path cleanup precedes replay response.

tests/upload-duplicate-cleanup-ledger.test.ts

work-bookings-concurrent-withdrawal.test.tsSimulate booking during withdrawal +68/-0

Simulate booking during withdrawal

• Verifies a new booking survives while unchanged open slots withdraw.

tests/work-bookings-concurrent-withdrawal.test.ts

worker-control-plane-timeouts.test.tsPin worker transport budgets +3/-2

Pin worker transport budgets

• Checks the cap covers data deadlines unless explicitly overridden.

tests/worker-control-plane-timeouts.test.ts

Documentation (13) +242 / -41
repo-awareness-snapshot.jsonRecord audit and review provenance +29/-0

Record audit and review provenance

• Catalogues the audit and adds review and historical provenance-correction entries.

data/repo-awareness-snapshot.json

2026-10-18-merged-pr-resolution.mdDocument findings and merge blockers +103/-0

Document findings and merge blockers

• Records 30 finding dispositions, repairs, evidence, adversarial corrections, and outstanding database, clinical, browser, and provider acceptance.

docs/audit/2026-10-18-merged-pr-resolution.md

837eb3931dd62dd05a2ac276fb997a16d9d73ce4ed7bada001cb3bef680a2632.record.mdRecord bounded correction review +1/-0

Record bounded correction review

• Captures reviewer acceptance and focused evidence without claiming a green full rerun.

docs/branch-review-records/837eb3931dd62dd05a2ac276fb997a16d9d73ce4ed7bada001cb3bef680a2632.record.md

8ab59556f1b1143dbcea904e06017be7f65d6937573e0412b1d874a1744360c2.record.mdRecord adversarial source review +1/-0

Record adversarial source review

• Documents Teaching, metadata, and CET corrections and remaining acceptance boundaries.

docs/branch-review-records/8ab59556f1b1143dbcea904e06017be7f65d6937573e0412b1d874a1744360c2.record.md

e2c104cc7dff402a6ff932a489e08f2d3f2bb4f33a3a4af98f30357f5e95995e.record.mdAppend historical branch correction +1/-0

Append historical branch correction

• Corrects PR #3570 branch provenance without rewriting its immutable receipt.

docs/branch-review-records/e2c104cc7dff402a6ff932a489e08f2d3f2bb4f33a3a4af98f30357f5e95995e.record.md

2026-10-17-wfydv6-stays-open-until-sign-off.mdClarify pending ledger reconciliation +4/-3

Clarify pending ledger reconciliation

• States the WFYDV6 reopen and duplicate fold-back are queued, not completed.

docs/decisions/2026-10-17-wfydv6-stays-open-until-sign-off.md

governance-incident-runbooks.mdAlign incident commands with current contracts +33/-38

Align incident commands with current contracts

• Uses the current feedback table, transactional source-review RPC, governance metadata, and Railway service names.

docs/governance-incident-runbooks.md

14e2a5cd-4d1e-4c1b-8b85-f5e573fb6be7.jsonCancel shorter specifier correction +10/-0

Cancel shorter specifier correction

• Queues cancellation in favor of a history-preserving update.

docs/outstanding-issues-inbox/14e2a5cd-4d1e-4c1b-8b85-f5e573fb6be7.json

2f15ec99-d824-4c5c-99e2-0801f58522d7.jsonQueue initial specifier correction +13/-0

Queue initial specifier correction

• Records the reset DID sign-off and 515 pending items; a subsequent request supersedes it.

docs/outstanding-issues-inbox/2f15ec99-d824-4c5c-99e2-0801f58522d7.json

3d33317d-4a51-4a3f-ac76-5a85aa0c036e.jsonQueue therapy issue reopen +16/-0

Queue therapy issue reopen

• Requests fingerprinted reopening because 26 therapy reviews were reset.

docs/outstanding-issues-inbox/3d33317d-4a51-4a3f-ac76-5a85aa0c036e.json

82706397-5f18-49eb-904d-a308e9251b07.jsonPreserve specifier history in correction +13/-0

Preserve specifier history in correction

• Queues corrected DID and pending counts while retaining superseded worklist detail.

docs/outstanding-issues-inbox/82706397-5f18-49eb-904d-a308e9251b07.json

95bba750-da9d-4dc3-babd-36264d71cdc4.jsonCancel ineffective archived update +10/-0

Cancel ineffective archived update

• Supersedes a non-outcome archive update with a reopen request.

docs/outstanding-issues-inbox/95bba750-da9d-4dc3-babd-36264d71cdc4.json

worker-deploy-runbook.mdExplain worker database deadlines +8/-0

Explain worker database deadlines

• Documents control/data budgets, the shared cap, and explicit override behavior.

docs/worker-deploy-runbook.md

Other (7) +81 / -3
retired-rules.jsonNarrow obsolete wake-therapy rule +1/-1

Narrow obsolete wake-therapy rule

• Detects the retired missing-references rationale without rejecting the current owner-review hold.

docs/organisation/retired-rules.json

knowledge.jsonRegister Git fixture +1/-0

Register Git fixture

• Catalogues the isolated Git configuration fixture.

docs/organisation/systems/knowledge.json

personal-practice.jsonRegister booking concurrency tests +1/-0

Register booking concurrency tests

• Includes concurrent withdrawal coverage in the system inventory.

docs/organisation/systems/personal-practice.json

therapy-catalogue-assets.tsReference regenerated therapy asset +1/-1

Reference regenerated therapy asset

• Updates the content-addressed full-catalogue filename.

src/data/therapy-catalogue-assets.ts

site-content-change-owners.jsonTrack regenerated therapy asset +1/-1

Track regenerated therapy asset

• Replaces the old asset hash in the ownership inventory.

src/lib/site-content/site-content-change-owners.json

database.types.tsType draft milestone RPC +4/-0

Type draft milestone RPC

• Adds its arguments and JSON return contract.

src/lib/supabase/database.types.ts

schema.sqlMirror proposed milestone RPC +72/-0

Mirror proposed milestone RPC

• Appends the draft function and grant after newer main schema changes; replay and drift checks remain outstanding.

supabase/schema.sql

@qodo-code-review

qodo-code-review Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

No findings for this group


Remediation recommended

No findings for this group


Informational

No findings for this group

Grey Divider


Resolved findings

1. Operators may restore unsafe retrieval ✓ Resolved
Description
The runbook accepts a staging probe whose citations omit the quarantined document as evidence that
retrieval excludes it. A retrieved chunk can be supplied to answer generation without being cited,
so this check can pass while the source remains available to the model.
Code

docs/governance-incident-runbooks.md[86]

+   Before lifting `RAG_PROVIDER_MODE=offline`, require retrieval evidence rather than the containment setting itself: `chunk_count` above must be `0`, or the restored retrieval path must be shown to exclude the quarantined `document_id` (for example, a non-offline staging probe whose citations omit it). An `/api/ask` probe made while offline, or reading the Railway variable, only confirms the temporary containment. To read that one setting, print only it (`railway variables --service PsychSift --kv | grep '^RAG_PROVIDER_MODE='`), never the whole service environment, which contains credentials.
Relevance

●●● Strong

Recent runbook and RAG precedents accept tightening evidence requirements when documentation can
overstate retrieval safety.

PR-#3522
PR-#2832

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed instruction proposes citation omission as proof of exclusion, but answer construction
assigns all retrieved results to sources independently of the model-selected citations.

docs/governance-incident-runbooks.md[75-86]
src/lib/rag/rag.ts[2071-2088]
src/lib/rag/rag.ts[621-648]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A probe that omits a source from answer citations does not establish that retrieval excluded the source.
## Fix Focus Areas
- docs/governance-incident-runbooks.md[75-86]
## Recommended Fix
Remove citation omission as a containment example. Require inspection of raw retrieval candidates across the restored retrieval path, or the documented zero-chunk condition, before lifting offline mode.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Existing public sources block migration ⊘ Outdated
Description
The mutation_id backfill updates every existing document, but guard_australian_source_activation
treats a change to that column as an unauthorized change to an Australian public document. If the
database contains an Australian public document, its update raises an exception and aborts the
migration; the newly installed mutation trigger would also make later approved publication updates
fail the same comparison.
Code

supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[R4-6]

+update public.documents
+set mutation_id = gen_random_uuid()
+where mutation_id is null;
Relevance

●●● Strong

Accepted migration precedents flag backfill-trigger conflicts and require preflight, locking, or
safe ordering to prevent deployment failure.

PR-#3111
PR-#2547
PR-#2407

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The existing AFTER UPDATE guard runs for every document update. For an ownerless australian_public
row, it compares old and new rows while excluding several generated fields but not mutation_id,
then raises on any difference. The new backfill necessarily changes that field, and the new BEFORE
UPDATE trigger changes it on subsequent updates too.

supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[1-10]
supabase/migrations/20260822123000_govern_australian_source_activation.sql[128-145]
supabase/migrations/20260822123000_govern_australian_source_activation.sql[180-201]
supabase/migrations/20260822123000_govern_australian_source_activation.sql[255-260]
supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[12-26]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The document backfill and subsequent updates change `mutation_id`, which the existing Australian public-source activation guard compares as immutable state. Populated databases with Australian public documents cannot apply the migration, and later publication updates also fail.

## Fix Focus Areas
- supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[4-6]
- supabase/migrations/20260822123000_govern_australian_source_activation.sql[137-144]
- supabase/migrations/20260822123000_govern_australian_source_activation.sql[180-201]
- supabase/schema.sql[9977-10035]

## Recommended Fix
In the new migration, update the guard function before the backfill so its same-scope and activation comparisons exclude the database-managed `mutation_id`; make the equivalent change to the schema mirror without altering the historical migration. Verify migration replay with an existing approved Australian public document and a subsequent approved publication transition.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Queued-work counts vanish on refresh error ✓ Resolved
Description
bulkReindexSelected constructs a partial-result status after an earlier batch succeeds and a later
batch fails, but its subsequent refresh can replace that status with a generic error. When the
dashboard refresh rejects because of a network failure, users lose the succeeded, failed, and
not-queued counts needed to understand what to retry.
Code

src/components/clinical-dashboard/use-dashboard-bulk-actions.ts[R82-85]

+        setBulkActionStatus(
+          submitted > 0
+            ? `${message} (bulk reindex: ${succeeded} succeeded; ${failed} failed; ${selectedDocumentIds.length - submitted} not queued).`
+            : message,
Relevance

●●● Strong

A recent dashboard precedent accepted preserving failure visibility when library refreshes reject,
closely matching this partial-result loss.

PR-#3563

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new catch branch records partial totals, while the refresh catch replaces them. The dashboard
refresh implementation rethrows outright request failures, making the replacement reachable.

src/components/clinical-dashboard/use-dashboard-bulk-actions.ts[78-96]
src/components/clinical-dashboard/use-dashboard-library-data.ts[416-424]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A failed refresh overwrites the new partial-batch result with a generic error even though earlier batches remain queued.
## Fix Focus Areas
- src/components/clinical-dashboard/use-dashboard-bulk-actions.ts[80-96]
- tests/clinical-dashboard-bulk-actions.dom.test.tsx[45-55]
## Recommended Fix
Keep the batch counts in the status if refresh fails, appending a distinct refresh warning if needed. Add a test where the second batch fails and refresh also rejects.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View resolved (4)
4. An empty retrieval scope returns public metadata ✓ Resolved
Description
fetchRelatedDocumentMetadata admits public-corpus documents whenever the access scope has no
owner, without checking includePublic. Passing the supported { includePublic: false } scope
therefore returns those documents’ labels and summaries, although that scope matches no documents.
Code

src/lib/document-enrichment.ts[R1109-1110]

+  } else {
+    documentsQuery = documentsQuery.is("owner_id", null).eq("metadata->>public_corpus", "true");
Relevance

●●● Strong

Recent metadata reviews accepted stricter admission and owner-scoped filtering when fallback reads
could expose stale or unauthorized metadata.

PR-#3596

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The scope resolver preserves an explicitly supplied scope, and the owner-matching contract admits
ownerless rows only when includePublic is true. The new document query instead admits indexed
public-corpus rows in its no-owner branch regardless of that flag; their metadata then passes the
parent-admission filters.

src/lib/owner-scope.ts[22-38]
src/lib/document-enrichment.ts[1098-1132]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An ownerless retrieval scope with `includePublic: false` must not return public document metadata.

## Fix Focus Areas
- src/lib/document-enrichment.ts[1098-1115]
- src/lib/owner-scope.ts[22-38]

## Recommended Fix
Return no metadata when the resolved scope has neither an owner nor public access, or otherwise prevent the document admission query from matching rows. Add a regression using an explicit empty scope and an indexed public document.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Missing timeout triggers global installs with no clear error ✓ Resolved
Description
probe_version calls bounded_probe "$1" --version 2>/dev/null. That redirect also hides the
stderr message fail prints when GNU timeout is missing ("GNU timeout is required…"), and fail
only returns 1. On a host without timeout, install_npm_cli and the npm check treat that status
as a version mismatch and run npm install --global anyway. They then stop with the misleading
"<tool> version probe failed." message, so the operator never sees the prerequisite to fix.
Code

scripts/setup-codex-cloud.sh[R191-195]

+probe_version() {
+  local output
+  output="$(bounded_probe "$1" --version 2>/dev/null)" || return $?
+  printf '%s\n' "$output" | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' | head -n 1
+}
Relevance

●●● Strong

Recent setup reviews accepted clearer prerequisite errors and correct handling of failed or
timed-out version probes.

PR-#3604

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
fail writes to stderr and returns 1; it does not exit (lines 9-12). Inside probe_version, the
2>/dev/null covers the whole bounded_probe call, so that message is thrown away. The || in
install_npm_cli and in the npm check sends execution into the install branch. The new test calls
bounded_probe directly rather than through probe_version, so it never catches the hidden
message.

scripts/setup-codex-cloud.sh[9-12]
scripts/setup-codex-cloud.sh[184-207]
scripts/setup-codex-cloud.sh[231-234]
tests/codex-cloud-setup.test.ts[1922-1927]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`probe_version` sends `bounded_probe` stderr to /dev/null, which hides the "GNU timeout is required" error. The non-zero status then looks like a version mismatch, so setup runs `npm install --global` before failing with a misleading message.

## Fix Focus Areas
- scripts/setup-codex-cloud.sh[184-207]
- scripts/setup-codex-cloud.sh[231-234]

## Recommended Fix
Check that `timeout` exists once, early in setup, and call `fail` (then exit) if it is missing; or do that check inside `probe_version` before the redirected call. Apply `2>/dev/null` only to the probed tool's output, e.g. `timeout -k 5s 30s "$1" --version 2>/dev/null`, not to the whole function. Add a test that runs `install_npm_cli` without `timeout` and asserts the prerequisite message appears and `npm install` is not called.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. CET evidence implies missing reviews ✓ Resolved
Description
sourceNotes still says that multiple reviews establish efficacy across substance use disorders,
although the revised reference names only one meta-analysis in alcohol use disorder. After the
unidentified 2025 review is removed, the same broader claim remains in the evidence notes,
references, and displayed source citation.
Code

src/data/therapies-source.json[3949]

+    "sourceNotes": "Systematic reviews and meta-analyses of Cue Exposure Therapy in substance use disorders (Mellentin et al., 2017 meta-analysis in alcohol use disorder) find mixed and modest efficacy overall, supporting selective adjunctive use in cue-reactive alcohol use disorder rather than routine standalone first-line SUD psychotherapy. (PubMed) These references were added on 17 October 2026 from clinical guidelines and peer-reviewed literature; they were not part of the original import. Bibliography correction 18 October 2026 (PS-051): the unidentified 2025 review is excluded pending verification of its authors, title and stable identifier. The efficacy conclusions and trial count attributed to that review have also been withdrawn. This record still requires clinical source checking and evidence appraisal.",
Relevance

●●● Strong

The PR explicitly withdraws unverifiable CET claims; provenance-focused reviews accept narrowing
unsupported evidence and correcting source records.

PR-#2827
PR-#3412

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The source-governance skill requires checking citation provenance and conservative treatment of
absent sources. The changed text excludes the unidentified 2025 review but continues to present a
multi-review, cross-substance conclusion while naming only the 2017 alcohol-use meta-analysis.

src/data/therapies-source.json[3949-3949]
src/data/therapies-source.json[3966-3968]
src/data/therapies-source.json[3991-3995]
Skill: source-governance

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The CET citation text still attributes a cross-substance, multi-review efficacy conclusion to a reference list that now identifies only an alcohol-use meta-analysis.

## Fix Focus Areas
- src/data/therapies-source.json[3949-3949]
- src/data/therapies-source.json[3966-3968]
- src/data/therapies-source.json[3994-3994]

## Recommended Fix
Replace the plural and cross-substance evidence attribution with a statement limited to what the identified 2017 alcohol-use source supports. Align the repeated citation fields, then regenerate the catalogue artifacts through the repository's normal process.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. A queue rollback can overwrite a newer update ✓ Resolved
Description
enqueueDocumentReindexJob uses the returned updated_at as its rollback fence, but the document
trigger replaces that value with transaction-start now(), which is not a unique mutation token. If
overlapping updates receive the same timestamp and a job-insert collision is followed by removal of
the competing job, the rollback can match and restore stale document state over the later update.
Code

src/lib/ingestion-enqueue.ts[128]

+        .eq("updated_at", storedFence);
Relevance

● Weak

A directly matching review rejected the same updated_at rollback-fence concern after examining the
trigger behavior.

PR-#3596

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The queue update now reads the trigger-produced timestamp, and the collision path uses that
timestamp as its sole mutation fence. The attached trigger unconditionally writes now() to
documents.updated_at; an equal timestamp cannot distinguish two updates to the same owner's row.

src/lib/ingestion-enqueue.ts[78-91]
src/lib/ingestion-enqueue.ts[105-129]
supabase/schema.sql[914-920]
supabase/schema.sql[1077-1080]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The trigger-produced timestamp used by queue compensation does not uniquely identify the update being rolled back.

## Fix Focus Areas
- src/lib/ingestion-enqueue.ts[78-84]
- src/lib/ingestion-enqueue.ts[105-129]
- supabase/schema.sql[914-920]

## Recommended Fix
Use a database-preserved unique mutation token or revision for the conditional rollback instead of `updated_at`. Exercise a collision path in which a later document update has the same trigger timestamp and verify that compensation leaves it intact.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
❌ Tickets: failed to load — Ticket collection could not establish complete evidence
✅ Compliance rules (platform): 9 rules
✅ Cross-repo context — repo relationships
Review mode: Auto: ⚖️ Balanced: Comparison failure: full PR diff.
✅ Fix-loop round: fix loop

Grey Divider

Tip of the day
💡 Did you know, you can move or hide resolved findings to focus on what still needs action

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 21c8653 ⚖️ Balanced

Results up to commit 0094b90 🧠 Deep


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required

No findings for this group


Remediation recommended

No findings for this group


Informational

No findings for this group


Resolved findings

1. An empty retrieval scope returns public metadata ✓ Resolved
Description
fetchRelatedDocumentMetadata admits public-corpus documents whenever the access scope has no
owner, without checking includePublic. Passing the supported { includePublic: false } scope
therefore returns those documents’ labels and summaries, although that scope matches no documents.
Code

src/lib/document-enrichment.ts[R1109-1110]

+  } else {
+    documentsQuery = documentsQuery.is("owner_id", null).eq("metadata->>public_corpus", "true");
Relevance

●●● Strong

Recent metadata reviews accepted stricter admission and owner-scoped filtering when fallback reads
could expose stale or unauthorized metadata.

PR-#3596

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The scope resolver preserves an explicitly supplied scope, and the owner-matching contract admits
ownerless rows only when includePublic is true. The new document query instead admits indexed
public-corpus rows in its no-owner branch regardless of that flag; their metadata then passes the
parent-admission filters.

src/lib/owner-scope.ts[22-38]
src/lib/document-enrichment.ts[1098-1132]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An ownerless retrieval scope with `includePublic: false` must not return public document metadata.

## Fix Focus Areas
- src/lib/document-enrichment.ts[1098-1115]
- src/lib/owner-scope.ts[22-38]

## Recommended Fix
Return no metadata when the resolved scope has neither an owner nor public access, or otherwise prevent the document admission query from matching rows. Add a regression using an explicit empty scope and an indexed public document.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Missing timeout triggers global installs with no clear error ✓ Resolved
Description
probe_version calls bounded_probe "$1" --version 2>/dev/null. That redirect also hides the
stderr message fail prints when GNU timeout is missing ("GNU timeout is required…"), and fail
only returns 1. On a host without timeout, install_npm_cli and the npm check treat that status
as a version mismatch and run npm install --global anyway. They then stop with the misleading
"<tool> version probe failed." message, so the operator never sees the prerequisite to fix.
Code

scripts/setup-codex-cloud.sh[R191-195]

+probe_version() {
+  local output
+  output="$(bounded_probe "$1" --version 2>/dev/null)" || return $?
+  printf '%s\n' "$output" | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' | head -n 1
+}
Relevance

●●● Strong

Recent setup reviews accepted clearer prerequisite errors and correct handling of failed or
timed-out version probes.

PR-#3604

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
fail writes to stderr and returns 1; it does not exit (lines 9-12). Inside probe_version, the
2>/dev/null covers the whole bounded_probe call, so that message is thrown away. The || in
install_npm_cli and in the npm check sends execution into the install branch. The new test calls
bounded_probe directly rather than through probe_version, so it never catches the hidden
message.

scripts/setup-codex-cloud.sh[9-12]
scripts/setup-codex-cloud.sh[184-207]
scripts/setup-codex-cloud.sh[231-234]
tests/codex-cloud-setup.test.ts[1922-1927]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`probe_version` sends `bounded_probe` stderr to /dev/null, which hides the "GNU timeout is required" error. The non-zero status then looks like a version mismatch, so setup runs `npm install --global` before failing with a misleading message.

## Fix Focus Areas
- scripts/setup-codex-cloud.sh[184-207]
- scripts/setup-codex-cloud.sh[231-234]

## Recommended Fix
Check that `timeout` exists once, early in setup, and call `fail` (then exit) if it is missing; or do that check inside `probe_version` before the redirected call. Apply `2>/dev/null` only to the probed tool's output, e.g. `timeout -k 5s 30s "$1" --version 2>/dev/null`, not to the whole function. Add a test that runs `install_npm_cli` without `timeout` and asserts the prerequisite message appears and `npm install` is not called.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. CET evidence implies missing reviews ✓ Resolved
Description
sourceNotes still says that multiple reviews establish efficacy across substance use disorders,
although the revised reference names only one meta-analysis in alcohol use disorder. After the
unidentified 2025 review is removed, the same broader claim remains in the evidence notes,
references, and displayed source citation.
Code

src/data/therapies-source.json[3949]

+    "sourceNotes": "Systematic reviews and meta-analyses of Cue Exposure Therapy in substance use disorders (Mellentin et al., 2017 meta-analysis in alcohol use disorder) find mixed and modest efficacy overall, supporting selective adjunctive use in cue-reactive alcohol use disorder rather than routine standalone first-line SUD psychotherapy. (PubMed) These references were added on 17 October 2026 from clinical guidelines and peer-reviewed literature; they were not part of the original import. Bibliography correction 18 October 2026 (PS-051): the unidentified 2025 review is excluded pending verification of its authors, title and stable identifier. The efficacy conclusions and trial count attributed to that review have also been withdrawn. This record still requires clinical source checking and evidence appraisal.",
Relevance

●●● Strong

The PR explicitly withdraws unverifiable CET claims; provenance-focused reviews accept narrowing
unsupported evidence and correcting source records.

PR-#2827
PR-#3412

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The source-governance skill requires checking citation provenance and conservative treatment of
absent sources. The changed text excludes the unidentified 2025 review but continues to present a
multi-review, cross-substance conclusion while naming only the 2017 alcohol-use meta-analysis.

src/data/therapies-source.json[3949-3949]
src/data/therapies-source.json[3966-3968]
src/data/therapies-source.json[3991-3995]
Skill: source-governance

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The CET citation text still attributes a cross-substance, multi-review efficacy conclusion to a reference list that now identifies only an alcohol-use meta-analysis.

## Fix Focus Areas
- src/data/therapies-source.json[3949-3949]
- src/data/therapies-source.json[3966-3968]
- src/data/therapies-source.json[3994-3994]

## Recommended Fix
Replace the plural and cross-substance evidence attribution with a statement limited to what the identified 2017 alcohol-use source supports. Align the repeated citation fields, then regenerate the catalogue artifacts through the repository's normal process.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View resolved (1)
4. A queue rollback can overwrite a newer update ✓ Resolved
Description
enqueueDocumentReindexJob uses the returned updated_at as its rollback fence, but the document
trigger replaces that value with transaction-start now(), which is not a unique mutation token. If
overlapping updates receive the same timestamp and a job-insert collision is followed by removal of
the competing job, the rollback can match and restore stale document state over the later update.
Code

src/lib/ingestion-enqueue.ts[128]

+        .eq("updated_at", storedFence);
Relevance

● Weak

A directly matching review rejected the same updated_at rollback-fence concern after examining the
trigger behavior.

PR-#3596

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The queue update now reads the trigger-produced timestamp, and the collision path uses that
timestamp as its sole mutation fence. The attached trigger unconditionally writes now() to
documents.updated_at; an equal timestamp cannot distinguish two updates to the same owner's row.

src/lib/ingestion-enqueue.ts[78-91]
src/lib/ingestion-enqueue.ts[105-129]
supabase/schema.sql[914-920]
supabase/schema.sql[1077-1080]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The trigger-produced timestamp used by queue compensation does not uniquely identify the update being rolled back.

## Fix Focus Areas
- src/lib/ingestion-enqueue.ts[78-84]
- src/lib/ingestion-enqueue.ts[105-129]
- supabase/schema.sql[914-920]

## Recommended Fix
Use a database-preserved unique mutation token or revision for the conditional rollback instead of `updated_at`. Exercise a collision path in which a later document update has the same trigger timestamp and verify that compensation leaves it intact.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 129a877 ⏭️ Skipped


No changes from previous review

Results up to commit 168837d ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required

No findings for this group


Remediation recommended

No findings for this group


Informational

No findings for this group


Resolved findings

1. Existing public sources block migration ⊘ Outdated
Description
The mutation_id backfill updates every existing document, but guard_australian_source_activation
treats a change to that column as an unauthorized change to an Australian public document. If the
database contains an Australian public document, its update raises an exception and aborts the
migration; the newly installed mutation trigger would also make later approved publication updates
fail the same comparison.
Code

supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[R4-6]

+update public.documents
+set mutation_id = gen_random_uuid()
+where mutation_id is null;
Relevance

●●● Strong

Accepted migration precedents flag backfill-trigger conflicts and require preflight, locking, or
safe ordering to prevent deployment failure.

PR-#3111
PR-#2547
PR-#2407

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The existing AFTER UPDATE guard runs for every document update. For an ownerless australian_public
row, it compares old and new rows while excluding several generated fields but not mutation_id,
then raises on any difference. The new backfill necessarily changes that field, and the new BEFORE
UPDATE trigger changes it on subsequent updates too.

supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[1-10]
supabase/migrations/20260822123000_govern_australian_source_activation.sql[128-145]
supabase/migrations/20260822123000_govern_australian_source_activation.sql[180-201]
supabase/migrations/20260822123000_govern_australian_source_activation.sql[255-260]
supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[12-26]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The document backfill and subsequent updates change `mutation_id`, which the existing Australian public-source activation guard compares as immutable state. Populated databases with Australian public documents cannot apply the migration, and later publication updates also fail.

## Fix Focus Areas
- supabase/migrations/20261018100000_fence_document_queue_rollbacks.sql[4-6]
- supabase/migrations/20260822123000_govern_australian_source_activation.sql[137-144]
- supabase/migrations/20260822123000_govern_australian_source_activation.sql[180-201]
- supabase/schema.sql[9977-10035]

## Recommended Fix
In the new migration, update the guard function before the backfill so its same-scope and activation comparisons exclude the database-managed `mutation_id`; make the equivalent change to the schema mirror without altering the historical migration. Verify migration replay with an existing approved Australian public document and a subsequent approved publication transition.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 3ffca93 ⚖️ Balanced


No changes from previous review

Results up to commit 1a85865 ⚖️ Balanced


No changes from previous review

Results up to commit 8ac5410 ⚖️ Balanced


No changes from previous review

Results up to commit e51796c ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required

No findings for this group


Remediation recommended

No findings for this group


Informational

No findings for this group


Resolved findings

1. Operators may restore unsafe retrieval ✓ Resolved
Description
The runbook accepts a staging probe whose citations omit the quarantined document as evidence that
retrieval excludes it. A retrieved chunk can be supplied to answer generation without being cited,
so this check can pass while the source remains available to the model.
Code

docs/governance-incident-runbooks.md[86]

+   Before lifting `RAG_PROVIDER_MODE=offline`, require retrieval evidence rather than the containment setting itself: `chunk_count` above must be `0`, or the restored retrieval path must be shown to exclude the quarantined `document_id` (for example, a non-offline staging probe whose citations omit it). An `/api/ask` probe made while offline, or reading the Railway variable, only confirms the temporary containment. To read that one setting, print only it (`railway variables --service PsychSift --kv | grep '^RAG_PROVIDER_MODE='`), never the whole service environment, which contains credentials.
Relevance

●●● Strong

Recent runbook and RAG precedents accept tightening evidence requirements when documentation can
overstate retrieval safety.

PR-#3522
PR-#2832

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed instruction proposes citation omission as proof of exclusion, but answer construction
assigns all retrieved results to sources independently of the model-selected citations.

docs/governance-incident-runbooks.md[75-86]
src/lib/rag/rag.ts[2071-2088]
src/lib/rag/rag.ts[621-648]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A probe that omits a source from answer citations does not establish that retrieval excluded the source.
## Fix Focus Areas
- docs/governance-incident-runbooks.md[75-86]
## Recommended Fix
Remove citation omission as a containment example. Require inspection of raw retrieval candidates across the restored retrieval path, or the documented zero-chunk condition, before lifting offline mode.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Queued-work counts vanish on refresh error ✓ Resolved
Description
bulkReindexSelected constructs a partial-result status after an earlier batch succeeds and a later
batch fails, but its subsequent refresh can replace that status with a generic error. When the
dashboard refresh rejects because of a network failure, users lose the succeeded, failed, and
not-queued counts needed to understand what to retry.
Code

src/components/clinical-dashboard/use-dashboard-bulk-actions.ts[R82-85]

+        setBulkActionStatus(
+          submitted > 0
+            ? `${message} (bulk reindex: ${succeeded} succeeded; ${failed} failed; ${selectedDocumentIds.length - submitted} not queued).`
+            : message,
Relevance

●●● Strong

A recent dashboard precedent accepted preserving failure visibility when library refreshes reject,
closely matching this partial-result loss.

PR-#3563

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new catch branch records partial totals, while the refresh catch replaces them. The dashboard
refresh implementation rethrows outright request failures, making the replacement reachable.

src/components/clinical-dashboard/use-dashboard-bulk-actions.ts[78-96]
src/components/clinical-dashboard/use-dashboard-library-data.ts[416-424]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A failed refresh overwrites the new partial-batch result with a generic error even though earlier batches remain queued.
## Fix Focus Areas
- src/components/clinical-dashboard/use-dashboard-bulk-actions.ts[80-96]
- tests/clinical-dashboard-bulk-actions.dom.test.tsx[45-55]
## Recommended Fix
Keep the batch counts in the status if refresh fails, appending a distinct refresh warning if needed. Add a test where the second batch fails and refresh also rejects.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread src/lib/document-enrichment.ts Resolved
Comment thread scripts/setup-codex-cloud.sh Resolved
Comment thread src/data/therapies-source.json Resolved

Copy link
Copy Markdown
Owner Author

Acknowledged. This Claude session has stopped pushing to fix/merged-pr-review-20261018 and will not touch the CET text or the mutation_id migration. My last push there was 1a85865b2. I'll leave the reverts to you and will re-check the branch state before doing anything further on it.

Note for whoever lands the reverts: if the mutation_id migration is removed, src/lib/ingestion-enqueue.ts (which now fences rollbacks on mutation_id), src/lib/supabase/database.types.ts, and tests/ingestion-enqueue.test.ts / tests/ingestion-quality-route.test.ts need to be reverted together with it, or the enqueue code will throw "Queue update returned no database mutation fence."


Generated by Claude Code

gitar-bot[bot]
gitar-bot Bot previously approved these changes Oct 18, 2026

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Gitar has auto-approved this PR (configure)

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 8ac5410

@BigSimmo
BigSimmo disabled auto-merge October 18, 2026 09:07
Resolve the two Cloud fixture test conflicts in favour of main's isolated Git
config and runBash helper (from the merged agent-policy delivery), which
covers the same Git isolation this branch added.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V2VWJXoHMnr3XnAhrREN8V
gitar-bot[bot]
gitar-bot Bot previously approved these changes Oct 18, 2026

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Gitar has auto-approved this PR (configure)

Comment thread docs/governance-incident-runbooks.md Resolved
@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit e51796c

…rned sources

- Bulk reindex: when a later batch fails and the dashboard refresh also
  rejects, keep the succeeded/failed/not-queued totals and append a refresh
  warning instead of replacing them with a generic error. New test.
- Governance runbook: citation omission is not proof a quarantined document
  was excluded from retrieval, because retrieved results reach answer
  generation as sources whether or not they are cited. Require the returned
  sources (or zero chunks) before lifting offline mode.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V2VWJXoHMnr3XnAhrREN8V
gitar-bot[bot]
gitar-bot Bot previously approved these changes Oct 18, 2026

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Gitar has auto-approved this PR (configure)

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 21c8653

Owner approved sealing 20261018075500_atomic_training_milestone_mirror.sql for PR 3638.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V2VWJXoHMnr3XnAhrREN8V

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Gitar has auto-approved this PR (configure)

@gitar-bot

gitar-bot Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor
CI failed: The PR policy check failed because two bot-authored commits (by qodo-code-review[bot]) touched protected Supabase, backend SQL, and clinical paths, which require human authorship and owner review; the incomplete Clinical Governance Preflight was advisory only.

Overview

One unique failure pattern was found across 34 analyzed logs for commit 013a81d. The PR policy gate in the merged-PR workflow failed on a single blocking condition: bot-authored commits touching protected paths. The assessment is that this is change-related and requires a human to re-author the affected changes.

Failures

Bot-authored commits touch protected paths (confidence: high)

  • Type: configuration
  • Affected jobs: 117653592398
  • Related to change: yes
  • Root cause: Commits 955e943 and c02f718, authored by qodo-code-review[bot], modify protected paths (src/lib/document-enrichment.ts, src/lib/supabase/database.types.ts, a Supabase migration, and supabase/schema.sql). The policy requires protected-path changes to come from human-authored commits with owner review. The incomplete Clinical Governance Preflight warning (6/7 items evidenced) is advisory only and did not cause the failure.
  • Suggested fix: Remove or rewrite the bot-authored commits from PR history, reintroduce the needed changes in human-authored commits, obtain the required owner review, and rerun the policy check. No action is needed on the advisory preflight warning to clear this failure.

Summary

  • Change-related failures: 1 failure (bot-authored commits touching protected Supabase, backend SQL, and clinical paths).
  • Infrastructure/flaky failures: None identified.
  • Recommended action: Re-author the protected-path changes by hand in human-authored commits, get owner review, and rerun the PR policy check. Note that the migration-history edit to supabase/applied-migration-hashes.json shown in the diff stats is a separate concern from the bot-authored commit block and should be verified against the trusted base.
Code Review ✅ Approved 2 closed / 2 findings

🔴 High risk · The atomic CME/registrar milestone migration changes clinical-record writes; a faulty owner-scoped transaction could corrupt or misattribute training records.

Fixes the missing GNU timeout error path so setup aborts with an explicit prerequisite error instead of silently installing npm globally, and repairs the leftover code fragment that made ingestion-enqueue.ts unparseable. No open issues remain.

✅ 2 closed
✅ Edge Case: Missing-timeout error is swallowed and npm still installs globally

📄 scripts/setup-codex-cloud.sh:183-195 📄 scripts/setup-codex-cloud.sh:202-206 📄 scripts/setup-codex-cloud.sh:231-234
When GNU timeout is absent, bounded_probe calls fail, which prints to stderr and returns 1. That happens inside $(bounded_probe "$1" --version 2>/dev/null) in probe_version, so the stderr redirect hides the "GNU timeout is required" message. The non-zero exit only marks the probe as failed. At line 231 the caller treats that failure as a version mismatch and runs npm install --global npm@…. install_npm_cli then does the same for npx. Setup finally stops with the misleading "npx version probe failed" after it has already changed the global npm installation. Check for timeout once before any probe and fail at that point, or stop redirecting stderr for the precondition check.

✅ Bug: Leftover code fragment after function makes ingestion-enqueue.ts unparseable

📄 src/lib/ingestion-enqueue.ts:136-143
This commit left a duplicated tail after enqueueDocumentReindexJob closes at line 136. Lines 137-143 (erFilter(rollback);, then stray }, return { outcome: "already_active" }; and throw new Error(jobError.message);) sit at module scope. That is a TypeScript syntax error, so typecheck, build and every importer of src/lib/ingestion-enqueue.ts (the reindex enqueue paths) will fail. It looks like a bad edit or merge splice. Delete lines 137-143 so the file ends at the function's closing brace on line 136.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Approved

For more verification details, comment gitar display:verbose.

Tip

Comment Gitar fix CI or enable auto-apply: gitar auto-apply:on

Options

Auto-apply is off → Gitar will not commit updates to this branch.
Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Auto-apply Compact
gitar auto-apply:on         
gitar display:verbose         

Important

Your trial ends in 3 days — upgrade now to keep code review, CI analysis, auto-apply, custom automations, and more.

Was this helpful? React with 👍 / 👎 | Gitar

Copy link
Copy Markdown
Owner Author

Superseded by #3652: a clean one-commit rebuild with identical final code (head 013a81de8 merged with current main). The owner chose this because qodo-code-review[bot] commits in this PR's history fail the bot-authored-sensitive-commits PR policy, and history rewrites are banned. The five open review threads here (CET timing fields, cited-recovery title signals, fatigue review date, supervisor slot race) still apply to #3652. The branch is kept.


Generated by Claude Code

@BigSimmo BigSimmo closed this Oct 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🔴 Large blast radius size:XXL This PR changes 1000+ lines, ignoring generated files 🕐 40+ Minutes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants