Skip to content

feat(rag): remediate clinical retrieval and safety#553

Merged
BigSimmo merged 9 commits into
mainfrom
codex/rag-remediation
Jul 13, 2026
Merged

feat(rag): remediate clinical retrieval and safety#553
BigSimmo merged 9 commits into
mainfrom
codex/rag-remediation

Conversation

@BigSimmo

Copy link
Copy Markdown
Owner

Summary

  • harden deep-memory ownership with producer-scoped transactional generations and fail-closed containment
  • add owner-plus-public retrieval scope, clinical value semantics, comparison/claim provenance, and safer source governance
  • enforce answer-log minimisation, anonymous-cache privacy, upload admission controls, privacy notices, canonical table copy parity, and offline quality metrics
  • include three prepared but unexecuted migrations; no live provider, migration, backfill, or deployment action was performed

Verification

  • npm run verify:pr-local — passed before the final one-commit main sync: 1,890 tests, production build (634 pages), client secret scan, offline RAG 263/263
  • npm run verify:ui — full aggregate was not rerun; targeted changed-surface Chromium checks passed 12/12 during implementation
  • npm run verify:release — not run; provider/release workflows remain approval-gated
  • npm run eval:rag:offline — latest exact merge commit: 21 files, 264/264
  • npm run eval:retrieval:quality — not run; requires live/provider credentials
  • npm run eval:rag -- --limit 15 + npm run eval:quality -- --rag-only — not run; provider-backed
  • npm run check:production-readiness — static production-like readiness passed during implementation with nonfunctional placeholders and no provider calls
  • npm run check:deployment-readiness — no deployment requested
  • npm run verify:cheap — latest exact merge commit: 207 files passed, 1 skipped; 1,901 tests passed, 1 skipped
  • npm run drift:manifest — scratch Postgres schema replay passed; live drift was not contacted

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 Clinical KB Database (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 requires governance review before rollout

Notes

  • /privacy content and point-of-entry notices are explicitly draft and governance-review-required.
  • Historical answer cleanup, retrieval RPC rollout, and producer-scoped artifact migration are committed but unexecuted.
  • Anonymous PHI-bearing answers are deliberately neither cached nor coalesced, superseding the original public-coalescing acceptance item.

BigSimmo added 3 commits July 13, 2026 14:13
# Conflicts:
#	.env.example
#	docs/privacy-impact-assessment.md
#	docs/site-map.md
#	scripts/compare-retrieval-eval.ts
#	scripts/eval-quality.ts
#	src/app/api/documents/[id]/reindex/route.ts
#	src/app/api/documents/bulk/reindex/route.ts
#	src/app/api/upload/route.ts
#	src/app/privacy/page.tsx
#	src/components/mode-home-template.tsx
#	src/lib/answer-render-policy.ts
#	src/lib/answer-verification.ts
#	src/lib/env.ts
#	src/lib/rag-cache.ts
#	src/lib/rag-extractive-answer.ts
#	src/lib/rag.ts
#	supabase/drift-manifest.json
#	supabase/schema.sql
#	tests/answer-render-policy.test.ts
#	tests/rag-answer-fallback.test.ts
#	tests/rag-offline-answer.test.ts
# Conflicts:
#	docs/privacy-impact-assessment.md
#	src/lib/answer-render-policy.ts
@supabase

supabase Bot commented Jul 13, 2026

Copy link
Copy Markdown

Updates to Preview Branch (codex/rag-remediation) ↗︎

Deployments Status Updated
Database Mon, 13 Jul 2026 07:39:17 UTC
Services Mon, 13 Jul 2026 07:39:17 UTC
APIs Mon, 13 Jul 2026 07:39:17 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 Mon, 13 Jul 2026 07:39:20 UTC
Migrations Mon, 13 Jul 2026 07:39:25 UTC
Seeding Mon, 13 Jul 2026 07:39:29 UTC
Edge Functions Mon, 13 Jul 2026 07:39:30 UTC

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

@BigSimmo
BigSimmo enabled auto-merge (squash) July 13, 2026 07:03
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added privacy reminders and links to the search and document-upload interfaces.
    • Added canonical clinical table displays with source links, caveats, accessibility support, and copy functionality.
    • Added structured comparison answers for multi-document clinical evidence, including agreement, conflict, and missing-evidence states.
    • Added stronger clinical-value verification and claim-support assessments for safer answer confidence and warnings.
    • Added upload size, concurrency, cancellation, and cleanup safeguards.
  • Documentation

    • Updated privacy information and site-map descriptions to clarify draft status and data handling.

Walkthrough

This PR adds access-scoped retrieval, versioned RPC fallbacks, deterministic comparison and claim-support enforcement, producer-scoped deep-memory commits, upload admission controls, privacy notices, and expanded retrieval/offline evaluation metrics with corresponding tests.

Changes

RAG platform and governance

Layer / File(s) Summary
Evaluation and offline contracts
scripts/eval-*.ts, scripts/eval-rag-offline.mjs, scripts/rag-offline-contract.mjs, scripts/fixtures/*
Retrieval signal metrics and validated offline contract-suite definitions are added to evaluation output and preflight execution.
Access-scoped retrieval and RPC rollout
src/lib/owner-scope.ts, src/lib/rag.ts, src/lib/rag-cache.ts, src/lib/search-scope.ts, src/lib/document-enrichment.ts, supabase/migrations/20260713020000_owner_plus_public_retrieval.sql
Owner-plus-public retrieval is represented by RetrievalAccessScope, propagated through caches and hydration, and supported by versioned RPC wrappers with legacy fallbacks.
Answer evidence and comparison flow
src/lib/rag-claim-support.ts, src/lib/rag-comparison.ts, src/lib/answer-render-policy.ts, src/lib/answer-verification.ts, src/lib/rag-routing.ts
Answers gain claim/evidence assessment, deterministic comparison matrices, canonical clinical tables, provenance-aware citations, and clinical value atom verification.
Deep-memory generation control
src/lib/deep-memory.ts, supabase/migrations/20260713030000_producer_scoped_deep_memory.sql, supabase/schema.sql
Deep-memory writes use producer-scoped staging and atomic commit validation, with ownership checks and generation metadata.
Upload and privacy surfaces
src/lib/upload-admission.ts, src/app/api/upload/route.ts, src/components/privacy-input-notice.tsx, src/app/privacy/page.tsx, src/components/clinical-dashboard/*
Uploads enforce content-length, concurrency, byte-budget, and cancellation checks; privacy warnings are shown before answer input and document upload.
Validation coverage
tests/*
Tests cover retrieval scope, RPC rollout, comparisons, evidence enforcement, upload admission, privacy UI, deep-memory transactions, answer rendering, and updated route behavior.

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

Possibly related PRs


Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Verification Claims ❌ Error FAIL: The PR description says generic checks “passed” (e.g. “cheap verification” and “Chromium checks passed 12/12”) without naming exact commands/results. Rewrite those claims to name the exact command/check and result, e.g. npm run verify:cheap: passed or npm run verify:ui: not run — reason; avoid umbrella “checks passed” wording.
Docstring Coverage ⚠️ Warning Docstring coverage is 17.32% which is insufficient. The required threshold is 70.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (9 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately reflects the PR’s main focus on clinical retrieval and safety hardening.
Description check ✅ Passed The description follows the template well and includes summary, verification, governance, and notes sections.
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.
Generated And Sensitive Files ✅ Passed No committed secrets or local artifacts found; the diff is source/docs/tests/migrations plus a safe .env.example and intentional Supabase schema/drift outputs.
Risky Git Or Deployment Actions ✅ Passed PASS: The PR only adds additive retrieval SQL wrappers and a test; no force-push, reset, destructive cleanup, or deployment instructions are introduced.
Supabase Project And Schema Safety ✅ Passed No stale Supabase refs found; .env.example and docs use the live sjrfecxgysukkwxsowpy project, and the SQL changes are review-gated/additive with no live execution.
Runtime And Package Manager Integrity ✅ Passed No package/runtime files changed; package.json still pins npm@11.17.0 and Node 24.x, and .npmrc keeps engine-strict=true with no new force/legacy install flags.
Api Route Failure Handling ✅ Passed Routes validate input and changed RAG/search/upload paths have explicit catch/fallback branches for auth, provider, RPC, and admission failures.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/rag-remediation
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch codex/rag-remediation

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

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a3eacb22b4

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread supabase/migrations/20260713030000_producer_scoped_deep_memory.sql Outdated
Comment thread src/lib/rag-cache.ts
@BigSimmo

Copy link
Copy Markdown
Owner Author

@codex fix all comments and failing CI tests

@chatgpt-codex-connector

Copy link
Copy Markdown

Summary

Git / PR

  • Committed changes on the current branch: 23ab2b0 fix: address rag remediation PR feedback.
  • Created a pull request with title: fix: address rag remediation PR feedback.

Testing

  • git diff --check
  • node <<'NODE' ... NODE static assertions for the Supabase lexical fallback, legacy local-worker allowlist, and cache-key matcher update.
  • ⚠️ npm test -- --run tests/rag-cache-utils.test.ts tests/deep-memory-transaction-sql.test.ts — could not run because this workspace is missing node_modules/vitest/vitest.mjs.

View task →

coderabbitai[bot]
coderabbitai Bot previously requested changes Jul 13, 2026

@coderabbitai coderabbitai 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.

Actionable comments posted: 4

🧹 Nitpick comments (4)
tests/ui-smoke.spec.ts (1)

750-782: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

openUploadSurface lost the click-retry resilience of the old openUploadDrawer helper.

The click at line 759 fires once with no retry; .poll() (761-769) only re-checks visibility afterward and doesn't re-click if the first click didn't register. The old helper wrapped click+visibility in toPass({ timeout: 8_000 }), retrying the whole action. This is a step back in flake-resistance for a helper used across multiple new smoke tests gating the UI check.

♻️ Proposed fix to restore click-retry resilience
 async function openUploadSurface(page: Page) {
   const uploadButton = page.getByRole("button", { name: /Upload document/i });
   const uploadDialog = page.getByRole("dialog", { name: "Upload and indexing" });
   const inlineUploadPanel = page.getByRole("tabpanel", { name: "Upload", exact: true });
   const visibleUploadTab = page
     .locator('[role="tab"]:visible')
     .filter({ hasText: /^Upload\b/ })
     .first();
   await expect(uploadButton).toBeVisible();
-  await uploadButton.click();
-
-  await expect
-    .poll(async () => {
-      return (
-        (await uploadDialog.isVisible().catch(() => false)) ||
-        (await inlineUploadPanel.isVisible().catch(() => false)) ||
-        (await visibleUploadTab.isVisible().catch(() => false))
-      );
-    })
-    .toBe(true);
+  await expect(async () => {
+    if (
+      (await uploadDialog.isVisible().catch(() => false)) ||
+      (await inlineUploadPanel.isVisible().catch(() => false)) ||
+      (await visibleUploadTab.isVisible().catch(() => false))
+    ) {
+      return;
+    }
+    await uploadButton.click();
+    await expect
+      .poll(async () =>
+        (await uploadDialog.isVisible().catch(() => false)) ||
+        (await inlineUploadPanel.isVisible().catch(() => false)) ||
+        (await visibleUploadTab.isVisible().catch(() => false)),
+      )
+      .toBe(true);
+  }).toPass({ timeout: 8_000 });
As per path instructions, "When fixing review findings, make the smallest clear, scoped, low-risk, testable change."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/ui-smoke.spec.ts` around lines 750 - 782, Restore click-retry behavior
in openUploadSurface by retrying the uploadButton click together with the
dialog/panel visibility assertion, using the existing bounded retry pattern from
openUploadDrawer. Ensure each retry performs a fresh click before checking all
supported upload surfaces, while preserving the current dialog and inline-panel
selection logic.

Source: Path instructions

src/app/api/upload/route.ts (1)

109-141: 🩺 Stability & Availability | 🔵 Trivial

Fail-closed rate limiting removes upload availability fallback.

allowInMemoryFallbackOnUnavailable: false means an outage in the rate-limit backing store will now hard-block all uploads (503/limited) instead of degrading to an in-memory fallback. This is consistent with the PR's fail-closed containment goal, but it's a meaningful availability trade-off worth explicit monitoring/alerting on the rate-limit store's health so an outage there doesn't silently become "uploads are down."

The admission-lease acquisition/release pairing (releaseAdmission set right after acquireUploadAdmission, unconditionally released in finally) is correctly leak-proof across all the new assertUploadNotAborted throw points.

Also applies to: 362-364

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/upload/route.ts` around lines 109 - 141, Keep the fail-closed
rate-limit configuration in the upload handler by retaining
allowInMemoryFallbackOnUnavailable: false in consumeSubjectApiRateLimit, and add
explicit monitoring or alerting for rate-limit backing-store health and failures
so an outage causing upload unavailability is visible. Preserve the existing
acquireUploadAdmission/releaseAdmission pairing and abort checks.
src/lib/upload-admission.ts (1)

5-8: 🩺 Stability & Availability | 🔵 Trivial

Per-process admission state won't enforce limits across instances.

The controller keeps active/bytes on globalThis, so concurrency and byte ceilings are enforced per Node process only. Under serverless/multi-instance deployment each instance admits up to the full limit independently, so aggregate load can exceed maxConcurrent/maxBytes. If this is intended as a best-effort per-instance shed, a brief comment stating that assumption would help; a shared store (e.g. Redis/DB counter) is needed for a global guarantee.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/upload-admission.ts` around lines 5 - 8, Clarify the scope of the
state used by the upload admission controller around AdmissionState and the
globalThis-backed state: document that active/byte limits are best-effort and
enforced per Node process or instance. If global enforcement is required,
replace this in-memory global state with atomic shared-store counters,
preserving the maxConcurrent and maxBytes admission semantics across instances.
supabase/migrations/20260713010000_clear_historical_rag_query_answers.sql (1)

3-5: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider batching this backfill for large tables.

The single UPDATE ... WHERE answer is not null rewrites every affected row in one transaction, which can hold locks and bloat WAL on a large rag_queries table. For the reviewed migration run, consider batching by primary key (e.g. loop over LIMIT-sized id windows) to keep transactions short. The WHERE answer is not null guard is good — it already skips already-cleared rows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/migrations/20260713010000_clear_historical_rag_query_answers.sql`
around lines 3 - 5, Batch the historical update on public.rag_queries instead of
rewriting all non-null answers in one transaction. Iterate through primary-key
windows using a bounded batch size, updating only rows where answer is not null,
and commit each batch while preserving the existing guard.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/privacy-impact-assessment.md`:
- Around line 45-53: The PIA-3 status terminology is inconsistent across the
document. Standardize all PIA-3 references in the gap table, gap-register
header, Recommendation, and surrounding discussion on one status term,
preferably “Mitigated,” without changing the underlying assessment.

In `@src/lib/rag-claim-support.ts`:
- Around line 265-273: Update isBoundedEvidenceGapSegment so that, after
excluding segments containing clinical value atoms or matching
clinicalRecommendationPattern, non-claim segments return true instead of falling
through to false. Preserve the existing true results for the exact normalized
“no evidence found” matches and the false result for clinical content.

In `@tests/deep-memory.test.ts`:
- Around line 696-737: Update the delete mock in the test’s supabase.from
implementation to record each delete operation in operations, including its
table name and staged/non-staged scope as needed by the existing assertion. Keep
the current cleanup assertion unchanged so unintended non-staged deletes are
detected rather than passing vacuously.

In `@tests/retrieval-access-scope.test.ts`:
- Around line 77-92: Update the mock RPC branch for
"match_document_chunks_hybrid_v2" in the test to return Supabase’s
missing-function response shape: data: null with an error containing the
PGRST202 code. Keep the fallback RPC response and expected ordering unchanged so
callVersionedRetrievalRpc exercises the real fallback path.

---

Nitpick comments:
In `@src/app/api/upload/route.ts`:
- Around line 109-141: Keep the fail-closed rate-limit configuration in the
upload handler by retaining allowInMemoryFallbackOnUnavailable: false in
consumeSubjectApiRateLimit, and add explicit monitoring or alerting for
rate-limit backing-store health and failures so an outage causing upload
unavailability is visible. Preserve the existing
acquireUploadAdmission/releaseAdmission pairing and abort checks.

In `@src/lib/upload-admission.ts`:
- Around line 5-8: Clarify the scope of the state used by the upload admission
controller around AdmissionState and the globalThis-backed state: document that
active/byte limits are best-effort and enforced per Node process or instance. If
global enforcement is required, replace this in-memory global state with atomic
shared-store counters, preserving the maxConcurrent and maxBytes admission
semantics across instances.

In `@supabase/migrations/20260713010000_clear_historical_rag_query_answers.sql`:
- Around line 3-5: Batch the historical update on public.rag_queries instead of
rewriting all non-null answers in one transaction. Iterate through primary-key
windows using a bounded batch size, updating only rows where answer is not null,
and commit each batch while preserving the existing guard.

In `@tests/ui-smoke.spec.ts`:
- Around line 750-782: Restore click-retry behavior in openUploadSurface by
retrying the uploadButton click together with the dialog/panel visibility
assertion, using the existing bounded retry pattern from openUploadDrawer.
Ensure each retry performs a fresh click before checking all supported upload
surfaces, while preserving the current dialog and inline-panel selection logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d8530dbb-83d0-4991-b526-a3a833101324

📥 Commits

Reviewing files that changed from the base of the PR and between 3f739cd and a3eacb2.

📒 Files selected for processing (82)
  • .env.example
  • docs/privacy-impact-assessment.md
  • docs/site-map.md
  • scripts/compare-retrieval-eval.ts
  • scripts/eval-quality.ts
  • scripts/eval-rag-offline.mjs
  • scripts/eval-retrieval.ts
  • scripts/fixtures/rag-offline-contract-tests.json
  • scripts/generate-site-map.ts
  • scripts/rag-offline-contract.mjs
  • src/app/api/answer/route.ts
  • src/app/api/answer/stream/route.ts
  • src/app/api/search/route.ts
  • src/app/api/upload/route.ts
  • src/app/globals.css
  • src/app/privacy/page.tsx
  • src/components/AccessibleTable.tsx
  • src/components/clinical-dashboard/DocumentManagerPanel.tsx
  • src/components/clinical-dashboard/answer-result-surface.tsx
  • src/components/clinical-dashboard/master-search-header.tsx
  • src/components/clinical-dashboard/visual-evidence.tsx
  • src/components/privacy-input-notice.tsx
  • src/lib/answer-render-policy.ts
  • src/lib/answer-verification.ts
  • src/lib/citations.ts
  • src/lib/clinical-search.ts
  • src/lib/corpus-grounding.ts
  • src/lib/cross-document-synthesis.ts
  • src/lib/deep-memory.ts
  • src/lib/demo-data.ts
  • src/lib/document-enrichment.ts
  • src/lib/env.ts
  • src/lib/evidence.ts
  • src/lib/owner-scope.ts
  • src/lib/rag-cache.ts
  • src/lib/rag-claim-support.ts
  • src/lib/rag-comparison.ts
  • src/lib/rag-contracts.ts
  • src/lib/rag-extractive-answer.ts
  • src/lib/rag-quote-verification.ts
  • src/lib/rag-retrieval-variants.ts
  • src/lib/rag-routing.ts
  • src/lib/rag.ts
  • src/lib/retrieval-rpc-rollout.ts
  • src/lib/search-scope.ts
  • src/lib/supabase/database.types.ts
  • src/lib/types.ts
  • src/lib/upload-admission.ts
  • supabase/drift-manifest.json
  • supabase/migrations/20260713010000_clear_historical_rag_query_answers.sql
  • supabase/migrations/20260713020000_owner_plus_public_retrieval.sql
  • supabase/migrations/20260713030000_producer_scoped_deep_memory.sql
  • supabase/schema.sql
  • tests/answer-render-policy.test.ts
  • tests/answer-verification.test.ts
  • tests/canonical-answer-table.test.ts
  • tests/clinical-search.test.ts
  • tests/corpus-grounding.test.ts
  • tests/cross-document-synthesis.test.ts
  • tests/deep-memory-transaction-sql.test.ts
  • tests/deep-memory.test.ts
  • tests/document-enrichment-retrieval-scope.test.ts
  • tests/eval-quality.test.ts
  • tests/eval-retrieval.test.ts
  • tests/owner-scope.test.ts
  • tests/privacy-ui.test.ts
  • tests/privacy.test.ts
  • tests/private-access-routes.test.ts
  • tests/private-rag-access.test.ts
  • tests/rag-answer-fallback.test.ts
  • tests/rag-claim-support.test.ts
  • tests/rag-comparison.test.ts
  • tests/rag-offline-answer.test.ts
  • tests/rag-offline-contract.test.ts
  • tests/rag-routing.test.ts
  • tests/retrieval-access-scope.test.ts
  • tests/retrieval-hydration-scope.test.ts
  • tests/retrieval-owner-filter-guard.test.ts
  • tests/retrieval-rpc-rollout.test.ts
  • tests/search-scope.test.ts
  • tests/ui-smoke.spec.ts
  • tests/upload-admission.test.ts

Comment thread docs/privacy-impact-assessment.md
Comment thread src/lib/rag-claim-support.ts
Comment thread tests/deep-memory.test.ts
Comment thread tests/retrieval-access-scope.test.ts
@BigSimmo

Copy link
Copy Markdown
Owner Author

Final review disposition:

  • Fixed all six actionable inline findings in f9e00d5 and cec1e5d; replied to and resolved each thread.
  • Also restored bounded click retries for the upload UI helper and documented the upload limiter as per-process best-effort load shedding in 4f60686.
  • Kept fail-closed upload rate limiting unchanged. A deployment alert requires observability/provider configuration outside this code-only remediation and is not being invented here.
  • Kept the historical answer-null migration approval-gated and unexecuted as planned. Looping batches inside a normal Supabase migration would still run in one transaction and would not deliver the suggested short-transaction benefit; operational backfill strategy remains a deployment decision.

Local validation: verify:cheap passed (207 files, 1905 tests; one file/test skipped), focused review suites passed, TypeScript passed, and scratch Postgres schema replay passed.

@BigSimmo
BigSimmo dismissed coderabbitai[bot]’s stale review July 13, 2026 07:37

All actionable findings were fixed, tested, replied to, and their review threads resolved. Remaining review-body nitpicks were either implemented or explicitly dispositioned in the PR.

@BigSimmo
BigSimmo merged commit c0a7cef into main Jul 13, 2026
13 of 15 checks passed

@coderabbitai coderabbitai 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/privacy-impact-assessment.md (1)

439-441: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not overstate automated purge coverage.

This paragraph calls automated purge part of the existing strong posture, while the assessment documents that rag_query_misses has no purge and expired rag_response_cache rows can persist until overwrite or manual invalidation. Reword this claim to avoid implying complete retention coverage.

Suggested wording
- The data-at-rest security posture (Sydney residency, RLS, private storage, query hashing, automated purge) is already strong and should be highlighted
+ The data-at-rest controls are strong for covered tables (Sydney residency, RLS, private storage, query hashing, and existing purge jobs), but retention gaps remain for `rag_query_misses` and expired `rag_response_cache` rows
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/privacy-impact-assessment.md` around lines 439 - 441, Revise the PIA-5
residual data-handling documentation to avoid presenting automated purge as
comprehensive retention coverage. Acknowledge that rag_query_misses lacks purge
and expired rag_response_cache rows may persist until overwrite or manual
invalidation, while retaining the other documented security controls.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@docs/privacy-impact-assessment.md`:
- Around line 439-441: Revise the PIA-5 residual data-handling documentation to
avoid presenting automated purge as comprehensive retention coverage.
Acknowledge that rag_query_misses lacks purge and expired rag_response_cache
rows may persist until overwrite or manual invalidation, while retaining the
other documented security controls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 004d458e-956d-4ff7-8338-00c762f177e2

📥 Commits

Reviewing files that changed from the base of the PR and between 7c8da13 and 18cf01f.

📒 Files selected for processing (16)
  • docs/privacy-impact-assessment.md
  • src/components/clinical-dashboard/master-search-header.tsx
  • src/lib/deep-memory.ts
  • src/lib/rag-cache-utils.ts
  • src/lib/rag-claim-support.ts
  • src/lib/upload-admission.ts
  • supabase/drift-manifest.json
  • supabase/migrations/20260713020000_owner_plus_public_retrieval.sql
  • supabase/migrations/20260713030000_producer_scoped_deep_memory.sql
  • supabase/schema.sql
  • tests/deep-memory-transaction-sql.test.ts
  • tests/deep-memory.test.ts
  • tests/rag-cache-utils.test.ts
  • tests/rag-claim-support.test.ts
  • tests/retrieval-access-scope.test.ts
  • tests/ui-smoke.spec.ts
🚧 Files skipped from review as they are similar to previous changes (13)
  • tests/deep-memory-transaction-sql.test.ts
  • src/lib/upload-admission.ts
  • src/components/clinical-dashboard/master-search-header.tsx
  • supabase/migrations/20260713030000_producer_scoped_deep_memory.sql
  • src/lib/rag-claim-support.ts
  • tests/retrieval-access-scope.test.ts
  • supabase/drift-manifest.json
  • tests/deep-memory.test.ts
  • tests/ui-smoke.spec.ts
  • tests/rag-claim-support.test.ts
  • supabase/schema.sql
  • src/lib/deep-memory.ts
  • supabase/migrations/20260713020000_owner_plus_public_retrieval.sql

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4f60686d13

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +155 to +156
const evidenceDimensions = safetyDimensions(evidence);
return [...safetyDimensions(claim)].every((dimension) => evidenceDimensions.has(dimension));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Verify safety polarity before accepting cited support

When a high-risk safety claim uses wording outside actionPolarity() (for example, Drug A is safe in pregnancy) this check only verifies that the cited source mentions the same safety dimension. A source saying Drug A is unsafe in pregnancy has the same pregnancy dimension, no clinical value atom, and enough topic overlap, so sourceSupportsClaim() can mark the opposite claim as directly supported and the high-risk evidence-gap gate will not fire. Add directional safety-state handling (safe/unsafe, risk/no risk, required/not required, etc.) before treating same-dimension evidence as compatible.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant