Skip to content

refactor: harden RAG and dashboard boundaries#457

Merged
BigSimmo merged 3 commits into
mainfrom
codex/architecture-review-integration
Jul 10, 2026
Merged

refactor: harden RAG and dashboard boundaries#457
BigSimmo merged 3 commits into
mainfrom
codex/architecture-review-integration

Conversation

@BigSimmo

Copy link
Copy Markdown
Owner

Summary

  • Break RAG runtime cycles into shared contracts and pure policy modules.
  • Bound owner-scoped caches and keep server/provider environment modules out of the client graph.
  • Restore effective lazy boundaries, avoid duplicate dashboard subscriptions, and stabilize search context values.
  • Move shared local-server utilities into runtime-owned source and update architecture/deployment documentation.

Why

The architecture reviews found repeatable cycle, cache-growth, client/server-boundary, lazy-loading, and duplicate-subscription risks. This branch replays the reviewed fixes onto the current main tree without altering the already-merged PR verification or Codex autofix work.

Areas touched

RAG orchestration and cache modules, dashboard/evidence components, local-server helpers, architecture documentation, and focused architecture tests.

Verification

  • npm run check:runtime — passed
  • npm run check:github-actions — passed
  • npm run sitemap:check — passed
  • npm run lint — passed
  • npm run typecheck — passed
  • Focused Vitest — 24 passed
  • Full Vitest with --testTimeout=30000 — 1,433 passed, 1 skipped
  • git diff --check — passed

Not run

Browser/UI checks, provider-backed Supabase/OpenAI checks, release gates, and deployment were not run. They remain outside the local/offline verification boundary.

Risk and governance

This touches clinical RAG internals but does not change provider credentials, database schema, production data, or deployment configuration. The existing fail-closed clinical tests remain green. The main residual risk is browser-level behavior around the dashboard lazy-loading/subscription changes.

@supabase

supabase Bot commented Jul 10, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The changes reorganize dashboard contracts and clinical-output rendering, extract RAG contracts and answer helpers, bound retrieval caches, centralize local-server utilities, add dependency-boundary tests, and update architecture, deployment, and review documentation.

Changes

Dashboard UI and client boundaries

Layer / File(s) Summary
Dashboard contracts and client environment
src/components/clinical-dashboard/dashboard-contracts.ts, src/lib/client-env.ts, src/components/ClinicalDashboard.tsx, src/components/DocumentViewer.tsx
Dashboard constants and types move into shared contracts, while client components use NEXT_PUBLIC_* environment helpers.
Clinical output helpers and rendering
src/components/clinical-dashboard/clinical-output-helpers.tsx, src/components/clinical-dashboard/evidence-panels.tsx, src/components/clinical-dashboard/output-panel.tsx
Clinical detail processing, view controls, and evidence-map rendering move into reusable helpers and re-exports.
Route-aware dashboard dispatch
src/components/clinical-dashboard/global-mockup-search-shell.tsx, src/components/clinical-dashboard/dashboard-nav.tsx
Dashboard and application-launcher workspaces are dynamically loaded, with route decisions handled by the global shell.
Dashboard context and admin wiring
src/components/ClinicalDashboard.tsx, src/components/clinical-dashboard/document-admin.tsx
Command-scope context is memoized, the Tools count uses catalog records, and admin types/labels are relocated or added.

RAG contracts, helpers, and caching

Layer / File(s) Summary
RAG contracts and query policies
src/lib/rag-contracts.ts, src/lib/rag-query-guard.ts
Retrieval contracts, telemetry, plan selection, and unsupported-query guards are added.
RAG answer-support utilities
src/lib/rag-answer-support.ts
Shared confidence, fallback, memory-card, evidence, indexing-quality, and ranking helpers are introduced.
RAG orchestration extraction
src/lib/rag.ts, src/lib/rag-extractive-answer.ts
Answer and query-guard implementations are moved behind dedicated modules and re-exported.
Bounded retrieval caches
src/lib/bounded-ttl-cache.ts, src/lib/rag-cache.ts, src/lib/rag-retrieval-variants.ts, tests/bounded-ttl-cache.test.ts
TTL cleanup and maximum-entry eviction are centralized and applied to retrieval caches with tests.

Architecture validation and local infrastructure

Layer / File(s) Summary
Shared local-server identity
src/lib/local-server-utils.mjs, src/lib/local-project-guard.ts, scripts/*.mjs, scripts/playwright-base-url.ts
Deterministic project IDs and ports are centralized under src/lib, and script imports are redirected there.
Runtime boundary validation
tests/architecture-boundaries.test.ts
AST-based dependency analysis checks runtime cycles, client isolation, scripts coupling, and static/dynamic import collisions.
Architecture and deployment records
docs/codebase-index.md, docs/deployment-architecture.md, docs/branch-review-ledger.md
Architecture mappings, staging and container validation rules, and review records are updated.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant GlobalMockupSearchShellClient
  participant ClinicalDashboard
  participant GlobalMockupStandaloneSearchShellClient
  GlobalMockupSearchShellClient->>GlobalMockupSearchShellClient: derive route and search state
  GlobalMockupSearchShellClient->>ClinicalDashboard: lazy-load and render dashboard
  GlobalMockupSearchShellClient->>GlobalMockupStandaloneSearchShellClient: render standalone shell for excluded routes
Loading

Caution

Pre-merge checks failed

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

  • Ignore

❌ Failed checks (1 error, 2 warnings)

Check name Status Explanation Resolution
Verification Claims ❌ Error Verification bullets say “Focused Vitest — 24 passed” and “Full Vitest… — 1,433 passed, 1 skipped” without explicit commands. Rewrite each verification claim as Ran <exact command>: passed or Not run: <reason>, especially the focused/full Vitest entries.
Description check ⚠️ Warning The description covers summary and verification, but it omits the required Clinical Governance Preflight and Notes sections. Add the template’s Clinical Governance Preflight checklist and a Notes section, and format Verification as the required checkboxes.
Docstring Coverage ⚠️ Warning Docstring coverage is 22.73% which is insufficient. The required threshold is 70.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (8 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately reflects the main boundary-hardening refactor.
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 secrets or disallowed artifacts were added; the PR only changes docs/source/tests, and the only config templates are safe (.npmrc engine-strict only, .env.example placeholders).
Risky Git Or Deployment Actions ✅ Passed Touched docs/workflows only describe safe rollout/rollback; no force-push, hard reset, branch deletion, destructive clean, or unsafe deployment guidance was added.
Supabase Project And Schema Safety ✅ Passed No migrations/env examples changed; diff only tightens staging project validation in docs, and code enforces explicit distinct staging refs with fail-closed checks.
Runtime And Package Manager Integrity ✅ Passed No package.json, lockfile, .npmrc, .nvmrc, or .node-version changes; repo still declares npm@11.17.0, Node 24.x, and engine-strict=true, with no legacy/force install flags introduced.
Api Route Failure Handling ✅ Passed The actual diff only reformats docs/branch-review-ledger.md; no API route, server action, RAG, search, ingestion, or provider code changed.
✨ 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/architecture-review-integration
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch codex/architecture-review-integration

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

coderabbitai[bot]
coderabbitai Bot previously requested changes Jul 10, 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: 3

🤖 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 `@src/lib/local-server-utils.mjs`:
- Around line 7-8: Update normalizeProjectRoot to preserve case on
case-sensitive filesystems and leave POSIX backslashes unchanged; only normalize
separators and lowercase when running on a case-insensitive host. Add
platform-aware tests covering distinct roots’ generated project IDs and stable
ports to ensure they do not collide.

In `@tests/architecture-boundaries.test.ts`:
- Around line 145-153: Update the cycle detection logic in the strongly
connected component traversal to retain singleton components when the file has a
runtime self-import, instead of only pushing components with length greater than
one. Use the existing graph/runtime-edge data to distinguish genuine self-import
cycles from ordinary single-file components before appending to cycles.
- Around line 73-80: Broaden the dynamic-import handling in the visit function
to accept statically resolvable imports with an optional second options argument
and no-substitution template literals, while still rejecting non-static
expressions; add each resolved module specifier to dynamicImports so runtime
graph and boundary checks include these edges.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

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: c67e82d3-7741-48dc-977e-69a226eda800

📥 Commits

Reviewing files that changed from the base of the PR and between 01f2cee and a9bfec3.

📒 Files selected for processing (31)
  • docs/branch-review-ledger.md
  • docs/codebase-index.md
  • docs/deployment-architecture.md
  • scripts/deployment-boot-smoke.mjs
  • scripts/dev-free-port.mjs
  • scripts/ensure-local-server.mjs
  • scripts/guard-next-build.mjs
  • scripts/playwright-base-url.ts
  • scripts/run-playwright.mjs
  • src/components/ClinicalDashboard.tsx
  • src/components/DocumentViewer.tsx
  • src/components/clinical-dashboard/clinical-output-helpers.tsx
  • src/components/clinical-dashboard/dashboard-contracts.ts
  • src/components/clinical-dashboard/dashboard-nav.tsx
  • src/components/clinical-dashboard/document-admin.tsx
  • src/components/clinical-dashboard/evidence-panels.tsx
  • src/components/clinical-dashboard/global-mockup-search-shell.tsx
  • src/components/clinical-dashboard/output-panel.tsx
  • src/lib/bounded-ttl-cache.ts
  • src/lib/client-env.ts
  • src/lib/local-project-guard.ts
  • src/lib/local-server-utils.mjs
  • src/lib/rag-answer-support.ts
  • src/lib/rag-cache.ts
  • src/lib/rag-contracts.ts
  • src/lib/rag-extractive-answer.ts
  • src/lib/rag-query-guard.ts
  • src/lib/rag-retrieval-variants.ts
  • src/lib/rag.ts
  • tests/architecture-boundaries.test.ts
  • tests/bounded-ttl-cache.test.ts

@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

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

🤖 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 `@src/lib/local-server-utils.mjs`:
- Around line 7-8: Update normalizeProjectRoot to preserve case on
case-sensitive filesystems and leave POSIX backslashes unchanged; only normalize
separators and lowercase when running on a case-insensitive host. Add
platform-aware tests covering distinct roots’ generated project IDs and stable
ports to ensure they do not collide.

In `@tests/architecture-boundaries.test.ts`:
- Around line 145-153: Update the cycle detection logic in the strongly
connected component traversal to retain singleton components when the file has a
runtime self-import, instead of only pushing components with length greater than
one. Use the existing graph/runtime-edge data to distinguish genuine self-import
cycles from ordinary single-file components before appending to cycles.
- Around line 73-80: Broaden the dynamic-import handling in the visit function
to accept statically resolvable imports with an optional second options argument
and no-substitution template literals, while still rejecting non-static
expressions; add each resolved module specifier to dynamicImports so runtime
graph and boundary checks include these edges.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

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: c67e82d3-7741-48dc-977e-69a226eda800

📥 Commits

Reviewing files that changed from the base of the PR and between 01f2cee and a9bfec3.

📒 Files selected for processing (31)
  • docs/branch-review-ledger.md
  • docs/codebase-index.md
  • docs/deployment-architecture.md
  • scripts/deployment-boot-smoke.mjs
  • scripts/dev-free-port.mjs
  • scripts/ensure-local-server.mjs
  • scripts/guard-next-build.mjs
  • scripts/playwright-base-url.ts
  • scripts/run-playwright.mjs
  • src/components/ClinicalDashboard.tsx
  • src/components/DocumentViewer.tsx
  • src/components/clinical-dashboard/clinical-output-helpers.tsx
  • src/components/clinical-dashboard/dashboard-contracts.ts
  • src/components/clinical-dashboard/dashboard-nav.tsx
  • src/components/clinical-dashboard/document-admin.tsx
  • src/components/clinical-dashboard/evidence-panels.tsx
  • src/components/clinical-dashboard/global-mockup-search-shell.tsx
  • src/components/clinical-dashboard/output-panel.tsx
  • src/lib/bounded-ttl-cache.ts
  • src/lib/client-env.ts
  • src/lib/local-project-guard.ts
  • src/lib/local-server-utils.mjs
  • src/lib/rag-answer-support.ts
  • src/lib/rag-cache.ts
  • src/lib/rag-contracts.ts
  • src/lib/rag-extractive-answer.ts
  • src/lib/rag-query-guard.ts
  • src/lib/rag-retrieval-variants.ts
  • src/lib/rag.ts
  • tests/architecture-boundaries.test.ts
  • tests/bounded-ttl-cache.test.ts
🛑 Comments failed to post (3)
src/lib/local-server-utils.mjs (1)

7-8: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve path semantics on case-sensitive systems.

normalizeProjectRoot lowercases every path and rewrites backslashes even on POSIX. Distinct roots such as /work/App and /work/app can therefore receive the same project ID and stable port; ensure-local-server.mjs may then treat another project's server as the requested one. Lowercase only where the host filesystem is case-insensitive, and do not reinterpret POSIX backslashes.

Proposed direction
-import crypto from "node:crypto";
+import crypto from "node:crypto";
+import { resolve } from "node:path";

 export function normalizeProjectRoot(projectRoot) {
-  return projectRoot.replaceAll("\\", "/").toLowerCase();
+  const resolvedRoot = resolve(projectRoot);
+  return process.platform === "win32"
+    ? resolvedRoot.replaceAll("\\", "/").toLowerCase()
+    : resolvedRoot;
 }

Add platform-aware collision tests for the generated project ID and port.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

import crypto from "node:crypto";
import { resolve } from "node:path";

export function normalizeProjectRoot(projectRoot) {
  const resolvedRoot = resolve(projectRoot);
  return process.platform === "win32"
    ? resolvedRoot.replaceAll("\\", "/").toLowerCase()
    : resolvedRoot;
}
🤖 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/local-server-utils.mjs` around lines 7 - 8, Update
normalizeProjectRoot to preserve case on case-sensitive filesystems and leave
POSIX backslashes unchanged; only normalize separators and lowercase when
running on a case-insensitive host. Add platform-aware tests covering distinct
roots’ generated project IDs and stable ports to ensure they do not collide.
tests/architecture-boundaries.test.ts (2)

73-80: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP --glob '*.{ts,tsx,js,jsx,mjs}' 'import\s*\([^)]*,|import\s*\(`[^$`]*`\s*\)' src worker

Repository: BigSimmo/Database

Length of output: 1986


Broaden dynamic-import detection. The parser only accepts import("literal") with exactly one argument, so it misses statically resolvable import("literal", options) and no-substitution template literals. Those edges never reach the runtime graph or boundary check.

🤖 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/architecture-boundaries.test.ts` around lines 73 - 80, Broaden the
dynamic-import handling in the visit function to accept statically resolvable
imports with an optional second options argument and no-substitution template
literals, while still rejecting non-static expressions; add each resolved module
specifier to dynamicImports so runtime graph and boundary checks include these
edges.

145-153: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Count self-imports as runtime cycles.

A strongly connected component containing one file is currently discarded, so a module that imports itself passes the “no runtime import cycles” test.

Proposed fix
-    if (component.length > 1) cycles.push(component);
+    const hasSelfCycle = graph.get(file)?.includes(file) ?? false;
+    if (component.length > 1 || hasSelfCycle) cycles.push(component);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if (lowLinks.get(file) !== indexes.get(file)) return;
    const component: string[] = [];
    let current: string;
    do {
      current = stack.pop()!;
      onStack.delete(current);
      component.push(current);
    } while (current !== file);
    const hasSelfCycle = graph.get(file)?.includes(file) ?? false;
    if (component.length > 1 || hasSelfCycle) cycles.push(component);
🤖 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/architecture-boundaries.test.ts` around lines 145 - 153, Update the
cycle detection logic in the strongly connected component traversal to retain
singleton components when the file has a runtime self-import, instead of only
pushing components with length greater than one. Use the existing
graph/runtime-edge data to distinguish genuine self-import cycles from ordinary
single-file components before appending to cycles.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found.

@BigSimmo
BigSimmo enabled auto-merge (squash) July 10, 2026 19:29
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found.

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