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

Closed
BI
25d ago
+1973-672

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.

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.