Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4f03aef
test(eval): add force-embedding flag + 10 vector-exercising golden cases
BigSimmo Jul 3, 2026
a17fa3f
test(eval): harden force-embedding flag and vector-path eval guards
BigSimmo Jul 5, 2026
9400841
test: add deep public access and production scope checks
BigSimmo Jul 5, 2026
a382754
refactor(ui): remove duplicate visual-evidence code from ClinicalDash…
BigSimmo Jul 5, 2026
2748e6e
fix: allow anonymous setup-status on production deployments
BigSimmo Jul 5, 2026
8ab57af
merge: consolidate force-embedding eval hardening into platform fixes…
BigSimmo Jul 5, 2026
a93b5b9
fix: harden public production access across API, UI, and rate limits
BigSimmo Jul 5, 2026
90fde2d
test: fix unused param lint in document search rate-limit mock
BigSimmo Jul 5, 2026
650d26c
fix(rag): scope anonymous retrieval to public documents via owner sen…
BigSimmo Jul 5, 2026
c331802
fix(access): complete forms fallback, signed-url hardening, upload guard
BigSimmo Jul 5, 2026
8981761
feat(db): promote locally reviewed documents to public corpus for ano…
BigSimmo Jul 5, 2026
85f247a
test: stabilize scope-sources stress flow via answer options menu
BigSimmo Jul 5, 2026
d9c9084
fix(access): complete public retrieval scope and production access ha…
BigSimmo Jul 5, 2026
e474d03
fix: allow anonymous setup-status on production for mobile access
BigSimmo Jul 5, 2026
2bad3a3
Merge pull request #277 from BigSimmo/cursor/hotfix-setup-status-c40b
BigSimmo Jul 5, 2026
7217a8e
merge: reconcile content-access rollout with main hotfix
BigSimmo Jul 5, 2026
3a1cf9c
Auto-hide answer support chips when content sits below on mobile
BigSimmo Jul 5, 2026
8eccda8
Remove Evidence-based and All sources chips from answer footer
BigSimmo Jul 5, 2026
5d86c8f
test: open answer scope via + menu using Scope label
BigSimmo Jul 5, 2026
7a0166d
chore: add answer bar screenshot capture script for chip removal QA
BigSimmo Jul 5, 2026
4a22a59
fix: resolve six PR bug-detection findings
cursoragent Jul 5, 2026
52d0f9c
fix(db): use valid dollar-quoting in retrieval_owner_matches migration
BigSimmo Jul 5, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"reindex:cleanup-staged": "tsx scripts/cleanup-abandoned-reindex-generations.ts",
"supabase:recovery-status": "tsx scripts/supabase-recovery-status.ts",
"promote:query-misses": "tsx scripts/promote-query-misses.ts",
"promote:public-documents": "tsx scripts/promote-public-documents.ts",
"eval:rag": "node scripts/run-eval-safe.mjs scripts/eval-rag.ts",
"eval:answer-quality": "node scripts/run-eval-safe.mjs scripts/eval-answer-quality.ts",
"eval:quality": "node scripts/run-eval-safe.mjs scripts/eval-quality.ts",
Expand Down
90 changes: 90 additions & 0 deletions scripts/capture-answer-bar-screenshot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { chromium } from "playwright";
import { demoAnswer, demoDocuments } from "../src/lib/demo-data";

const baseUrl = process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:4298";
const outDir = join(process.cwd(), "scratch", "screenshots");
const outPath = join(outDir, "answer-bar-after-chip-removal.png");
const outBottomPath = join(outDir, "answer-bar-bottom-after-chip-removal.png");

const readySetupChecks = [
{ id: "env", label: ".env.local configured", status: "ready", detail: "Test environment ready." },
{ id: "project", label: "Clinical KB Database target", status: "ready", detail: "Test Supabase project ready." },
{ id: "schema", label: "supabase/schema.sql applied", status: "ready", detail: "Test schema ready." },
{ id: "search", label: "Search RPC and vector indexes", status: "ready", detail: "Test search schema ready." },
{ id: "openai", label: "OpenAI API key available", status: "ready", detail: "Test OpenAI ready." },
{ id: "worker", label: "npm run worker running", status: "unknown", detail: "Worker not required." },
];

async function mockDemoApi(page) {
await page.route("**/api/setup-status**", async (route) => {
await route.fulfill({ json: { demoMode: true, checks: readySetupChecks } });
});
await page.route(/\/api\/documents(?:\?.*)?$/, async (route) => {
await route.fulfill({
json: {
documents: demoDocuments,
demoMode: true,
pagination: {
limit: 150,
offset: 0,
total: demoDocuments.length,
nextOffset: demoDocuments.length,
hasMore: false,
},
},
});
});
await page.route(/\/api\/ingestion\/(jobs|batches|quality)(?:\?.*)?$/, async (route) => {
await route.fulfill({ json: { jobs: [], batches: [], items: [], demoMode: true } });
});
await page.route(/\/api\/answer(?:\/stream)?(?:\?.*)?$/, async (route) => {
const body = route.request().postDataJSON();
const payload = { ...demoAnswer(body?.query ?? "clozapine monitoring"), demoMode: true };
if (route.request().url().includes("/stream")) {
await route.fulfill({
body: [
`event: progress\ndata: ${JSON.stringify({ stage: "retrieving", message: "Searching indexed documents." })}`,
`event: final\ndata: ${JSON.stringify(payload)}`,
"",
].join("\n\n"),
contentType: "text/event-stream; charset=utf-8",
});
return;
}
await route.fulfill({ json: payload });
});
}

async function main() {
mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 390, height: 820 } });
await mockDemoApi(page);
await page.goto(`${baseUrl}/`, { waitUntil: "domcontentloaded" });
await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => undefined);

const input = page.locator('[data-testid="global-search-input"]:visible').first();
await input.waitFor({ state: "visible", timeout: 30000 });
await input.fill("clozapine monitoring");
await page.locator('[aria-label="Generate source-backed answer"]:visible').first().click();
await page.getByTestId("plain-answer-response").waitFor({ timeout: 30000 });
await page.waitForTimeout(600);

const chipCount = await page.locator(".answer-footer-search-chip:visible").count();
if (chipCount > 0) {
throw new Error(`Expected 0 footer chips in answer mode, found ${chipCount}.`);
}

await page.screenshot({ path: outPath, fullPage: false });
await page.locator("form.answer-footer-search-edge").first().screenshot({ path: outBottomPath });
console.log(outPath);
console.log(outBottomPath);
await browser.close();
}

main().catch((error) => {
console.error(error);
process.exit(1);
});
4 changes: 0 additions & 4 deletions scripts/capture-chrome-parity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,6 @@ const selectorGroups: Array<{ key: string; selector: string; pseudo?: string }>
{ key: "composer-pill-children", selector: 'form:has([data-testid="global-search-input"]) > div > *' },
{ key: "composer-input", selector: '[data-testid="global-search-input"]', pseudo: "::placeholder" },
{ key: "composer-buttons", selector: 'form:has([data-testid="global-search-input"]) button' },
{ key: "evidence-chip", selector: 'button[aria-label="Open evidence-backed answer sources"]' },
{ key: "evidence-chip-icon", selector: 'button[aria-label="Open evidence-backed answer sources"] svg' },
{ key: "scope-chip", selector: 'button[aria-label="Open source scope"]' },
{ key: "scope-chip-icon", selector: 'button[aria-label="Open source scope"] svg' },
{ key: "viewer-header", selector: "main header, body > div > header", pseudo: "::after" },
{ key: "viewer-composer", selector: 'form:has(input[placeholder^="Search or answer"])' },
{ key: "viewer-composer-children", selector: 'form:has(input[placeholder^="Search or answer"]) > *' },
Expand Down
16 changes: 15 additions & 1 deletion scripts/eval-quality.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type EvalQualityArgs = {
retrievalOnly: boolean;
ragOnly: boolean;
skipPreflight: boolean;
forceEmbedding: boolean;
};

export type RagQualityResult = {
Expand Down Expand Up @@ -150,6 +151,7 @@ function parseArgs(argv: string[]): EvalQualityArgs {
retrievalOnly: false,
ragOnly: false,
skipPreflight: false,
forceEmbedding: false,
};

for (let index = 0; index < argv.length; index += 1) {
Expand All @@ -176,6 +178,10 @@ function parseArgs(argv: string[]): EvalQualityArgs {
args.skipPreflight = true;
continue;
}
if (token === "--force-embedding") {
args.forceEmbedding = true;
continue;
}

const value = argv[index + 1];
if (!value || value.startsWith("--")) throw new Error(`Missing value for ${token}`);
Expand Down Expand Up @@ -476,6 +482,11 @@ export function buildEvalQualityReport(args: {
`retrieval content_recall_at_5 ${retrievalSummary.content_recall_at_5} below ${qualityThresholds.retrievalContentRecallAt5}`,
);
}
if (retrievalSummary.force_embedding_failure_count > 0) {
thresholdFailures.push(
`retrieval force_embedding_failure_count ${retrievalSummary.force_embedding_failure_count} above 0`,
);
}
if (governance.stale_rate > qualityThresholds.staleTopResultRate) {
thresholdFailures.push(
`top-result stale_rate ${governance.stale_rate} above ${qualityThresholds.staleTopResultRate}`,
Expand Down Expand Up @@ -664,6 +675,8 @@ ${markdownTable([
## Retrieval Decision Metrics

${markdownTable([
["Force-embedding cases", retrieval.force_embedding_case_count],
["Force-embedding failures", retrieval.force_embedding_failure_count],
["Embedding skipped rate", retrieval.embedding_skipped_rate],
["Median text candidate budget", retrieval.median_text_candidate_budget],
["Second-stage rerank rate", retrieval.second_stage_rerank_rate],
Expand Down Expand Up @@ -728,6 +741,7 @@ async function runRetrievalQualityCases(args: {
ownerId?: string;
limit?: number;
query?: string;
forceEmbedding?: boolean;
supabase: Awaited<ReturnType<typeof loadAdminClient>>;
}) {
const [{ searchChunksWithTelemetry }, capturedCases] = await Promise.all([
Expand Down Expand Up @@ -756,7 +770,7 @@ async function runRetrievalQualityCases(args: {
topK: retrievalLimitForGoldenCase(testCase),
minSimilarity: 0.12,
skipCache: true,
forceEmbedding: testCase.forceEmbedding,
forceEmbedding: testCase.forceEmbedding || args.forceEmbedding,
}),
);
const latencyMs =
Expand Down
24 changes: 24 additions & 0 deletions scripts/eval-retrieval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type EvalArgs = {
export type GoldenRetrievalResult = {
id: string;
query: string;
forceEmbedding: boolean;
expectedQueryClass: string;
actualQueryClass: string | null;
expectedDocumentSubstrings: string[];
Expand Down Expand Up @@ -516,6 +517,11 @@ export function evaluateGoldenRetrievalCase(args: {
const tableEvidenceFoundAtK = hasTableEvidence(args.results, topK);
const actualQueryClass = args.telemetry.query_class ?? null;
const failures: string[] = [];
const vectorLayerCount = Object.entries(args.telemetry.retrieval_layer_counts ?? {}).reduce(
(sum, [layer, count]) =>
["embedding_fields", "index_units", "hybrid_vector", "vector_fallback"].includes(layer) ? sum + count : sum,
0,
);
const hitAtK =
documentHitsAtK.missing.length === 0 &&
contentHitsAtK.missing.length === 0 &&
Expand All @@ -533,10 +539,23 @@ export function evaluateGoldenRetrievalCase(args: {
if (args.testCase.expectTableEvidence && !tableEvidenceFound) {
failures.push("expected table evidence in top 5");
}
if (args.testCase.forceEmbedding) {
if (args.telemetry.embedding_skipped) failures.push("forceEmbedding expected embedding to run");
if (args.telemetry.retrieval_strategy === "search_cache") failures.push("forceEmbedding served search cache");
if (
args.telemetry.retrieval_strategy === "text_fast_path" ||
args.telemetry.retrieval_strategy === "document_lookup_fast_path"
) {
failures.push(`forceEmbedding returned lexical strategy ${args.telemetry.retrieval_strategy}`);
}
if (args.telemetry.coverage_gate_decision === "accepted") failures.push("forceEmbedding returned coverage gate");
if (vectorLayerCount <= 0) failures.push("forceEmbedding found no vector-layer candidates");
}

return {
id: args.testCase.id,
query: args.testCase.query,
forceEmbedding: args.testCase.forceEmbedding ?? false,
expectedQueryClass: args.testCase.expectedQueryClass,
actualQueryClass,
expectedDocumentSubstrings: args.testCase.expectedDocumentSubstrings,
Expand Down Expand Up @@ -612,6 +631,7 @@ export function summarizeGoldenRetrievalResults(results: GoldenRetrievalResult[]
}
return counts;
}, {});
const forceEmbeddingResults = results.filter((result) => result.forceEmbedding);
return {
case_count: results.length,
document_recall_at_5: Number(
Expand Down Expand Up @@ -647,6 +667,8 @@ export function summarizeGoldenRetrievalResults(results: GoldenRetrievalResult[]
embedding_skip_reason_counts: embeddingSkipReasonCounts,
text_fast_path_reason_counts: textFastPathReasonCounts,
retrieval_layer_counts: layerCounts,
force_embedding_case_count: forceEmbeddingResults.length,
force_embedding_failure_count: forceEmbeddingResults.filter((result) => result.failures.length > 0).length,
median_text_candidate_budget: percentile(textCandidateBudgets, 50),
second_stage_rerank_rate: Number(
(results.filter((result) => result.secondStageRerankUsed).length / Math.max(results.length, 1)).toFixed(4),
Expand Down Expand Up @@ -723,6 +745,8 @@ function printHumanSummary(summary: ReturnType<typeof summarizeGoldenRetrievalRe
console.log(` retrieval_strategy_counts=${JSON.stringify(summary.retrieval_strategy_counts)}`);
console.log(` retrieval_plan_counts=${JSON.stringify(summary.retrieval_plan_counts)}`);
console.log(` retrieval_layer_counts=${JSON.stringify(summary.retrieval_layer_counts)}`);
console.log(` force_embedding_case_count=${summary.force_embedding_case_count}`);
console.log(` force_embedding_failure_count=${summary.force_embedding_failure_count}`);
console.log(` embedding_skipped_rate=${summary.embedding_skipped_rate}`);
console.log(` embedding_skip_reason_counts=${JSON.stringify(summary.embedding_skip_reason_counts)}`);
console.log(` text_fast_path_reason_counts=${JSON.stringify(summary.text_fast_path_reason_counts)}`);
Expand Down
80 changes: 80 additions & 0 deletions scripts/promote-public-documents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { loadEnvConfig } from "@next/env";

loadEnvConfig(process.cwd());

type PromoteArgs = {
ownerId?: string;
};

async function loadAdminClient() {
const { createAdminClient } = await import("@/lib/supabase/admin");
return createAdminClient();
}

function parseArgs(argv: string[]): PromoteArgs {
const args: PromoteArgs = {
ownerId: process.env.PUBLIC_WORKSPACE_OWNER_ID ?? process.env.LOCAL_NO_AUTH_OWNER_ID,
};

for (let index = 0; index < argv.length; index += 1) {
const token = argv[index];
if (token === "--owner-id") {
args.ownerId = argv[index + 1];
index += 1;
continue;
}
throw new Error(`Unknown argument: ${token}`);
}

return args;
}

async function countCandidates(supabase: Awaited<ReturnType<typeof loadAdminClient>>, ownerId?: string) {
let query = supabase
.from("documents")
.select("id", { count: "exact", head: true })
.eq("status", "indexed")
.not("owner_id", "is", null)
.in("metadata->>clinical_validation_status", ["locally_reviewed", "approved"]);

if (ownerId) query = query.eq("owner_id", ownerId);

const { count, error } = await query;
if (error) throw new Error(error.message);
return count ?? 0;
}

async function countPublic(supabase: Awaited<ReturnType<typeof loadAdminClient>>) {
const { count, error } = await supabase
.from("documents")
.select("id", { count: "exact", head: true })
.eq("status", "indexed")
.is("owner_id", null);

if (error) throw new Error(error.message);
return count ?? 0;
}

async function main() {
const args = parseArgs(process.argv.slice(2));
const supabase = await loadAdminClient();

const [candidateCount, publicCount] = await Promise.all([
countCandidates(supabase, args.ownerId),
countPublic(supabase),
]);

console.log("[public-documents:promote] indexed public documents:", publicCount);
console.log(
`[public-documents:promote] pending promotion${args.ownerId ? ` for owner ${args.ownerId}` : ""}:`,
candidateCount,
);
console.log(
"Apply migration 20260705220000_promote_locally_reviewed_documents_public.sql with `npx supabase db push --linked`.",
);
}

main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
4 changes: 2 additions & 2 deletions src/app/api/answer/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { demoAnswer } from "@/lib/demo-data";
import { isDemoMode, isLocalNoAuthMode } from "@/lib/env";
import { answerQuestionWithScope } from "@/lib/rag";
import { jsonError, PublicApiError } from "@/lib/http";
import { consumeSubjectApiRateLimit, rateLimitJsonResponse } from "@/lib/api-rate-limit";
import { allowRateLimitInMemoryFallbackOnUnavailable, consumeSubjectApiRateLimit, rateLimitJsonResponse } from "@/lib/api-rate-limit";
import { publicAccessContext } from "@/lib/public-api-access";
import { classifyRagQuery } from "@/lib/clinical-search";
import { buildSmartRagApiPlan } from "@/lib/smart-rag-api";
Expand Down Expand Up @@ -70,7 +70,7 @@ export async function POST(request: Request) {
supabase,
subject: access.rateLimitSubject,
bucket: "answer",
allowInMemoryFallbackOnUnavailable: isLocalNoAuthMode(),
allowInMemoryFallbackOnUnavailable: allowRateLimitInMemoryFallbackOnUnavailable(),
});
if (rateLimit.limited) {
return rateLimitJsonResponse("Too many answer requests. Retry shortly.", rateLimit);
Expand Down
4 changes: 2 additions & 2 deletions src/app/api/answer/stream/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { z } from "zod";
import { demoAnswer } from "@/lib/demo-data";
import { isDemoMode, isLocalNoAuthMode } from "@/lib/env";
import { PublicApiError, jsonError } from "@/lib/http";
import { consumeSubjectApiRateLimit, type ApiRateLimitResult } from "@/lib/api-rate-limit";
import { allowRateLimitInMemoryFallbackOnUnavailable, consumeSubjectApiRateLimit, type ApiRateLimitResult } from "@/lib/api-rate-limit";
import { publicAccessContext } from "@/lib/public-api-access";
import { answerQuestionWithScope, type AnswerProgressEvent } from "@/lib/rag";
import { classifyRagQuery } from "@/lib/clinical-search";
Expand Down Expand Up @@ -232,7 +232,7 @@ export async function POST(request: Request) {
supabase,
subject: access.rateLimitSubject,
bucket: "answer",
allowInMemoryFallbackOnUnavailable: isLocalNoAuthMode(),
allowInMemoryFallbackOnUnavailable: allowRateLimitInMemoryFallbackOnUnavailable(),
});
if (rateLimit.limited) return rateLimitStream(rateLimit);

Expand Down
8 changes: 4 additions & 4 deletions src/app/api/differentials/[slug]/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { z } from "zod";

import { consumeSubjectApiRateLimit, rateLimitJsonResponse } from "@/lib/api-rate-limit";
import { allowRateLimitInMemoryFallbackOnUnavailable, consumeSubjectApiRateLimit, rateLimitJsonResponse } from "@/lib/api-rate-limit";
import {
deriveGovernanceFromSnapshot,
normalizeDifferentialSlug,
Expand All @@ -14,7 +14,7 @@ import { ensureDifferentialsSeeded, loadDifferentialSnapshot } from "@/lib/diffe
import { getDifferentialRecord, getPresentationWorkflow } from "@/lib/differentials";
import { isDemoMode, isLocalNoAuthMode } from "@/lib/env";
import { jsonError } from "@/lib/http";
import { hasPublicApiAuthSignal, publicAccessContext } from "@/lib/public-api-access";
import { publicAccessContext, shouldResolvePublicCatalogAccess } from "@/lib/public-api-access";
import { createAdminClient } from "@/lib/supabase/admin";
import { AuthenticationError, unauthorizedResponse } from "@/lib/supabase/auth";
import { parseRequestQuery } from "@/lib/validation/query";
Expand Down Expand Up @@ -63,7 +63,7 @@ export async function GET(request: Request, context: { params: Promise<{ slug: s
});
}

if (!hasPublicApiAuthSignal(request)) {
if (!shouldResolvePublicCatalogAccess(request)) {
const snapshot = loadDifferentialSnapshot();
const governance = deriveGovernanceFromSnapshot(snapshot);
if (kind === "presentation") {
Expand Down Expand Up @@ -91,7 +91,7 @@ export async function GET(request: Request, context: { params: Promise<{ slug: s
supabase,
subject: access.rateLimitSubject,
bucket: "registry",
allowInMemoryFallbackOnUnavailable: isLocalNoAuthMode(),
allowInMemoryFallbackOnUnavailable: allowRateLimitInMemoryFallbackOnUnavailable(),
});
if (rateLimit.limited) {
return rateLimitJsonResponse("Differential requests are rate limited. Try again shortly.", rateLimit);
Expand Down
Loading