diff --git a/docs/architecture.md b/docs/architecture.md index 4f19412..00e777f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,10 +73,10 @@ Read from `src/lib/aadi/client.ts`, `gateway.ts`, `aadi/service/app.py`, `engine 1. **Browser** validates the case and runs the identity check, then POSTs `{case}`. 2. **Route** checks the user is signed in, verified, and has consented (`getBetaAccess().resolve()`). 3. **Gateway** (`src/lib/aadi/gateway.ts`), in order: checks the request's origin and host; caps the body at 32 KB; re-runs the identity check; enforces a one-at-a-time limit by default; checks the engine is healthy. -4. **TheOracle search**: the case is turned into numbers (an embedding) on the local CPU and compared with all passages. Up to 6 passages come back, at most 2 per document; one of the six is swapped for a passage likely to contain a dose. +4. **TheOracle search**: the case is turned into numbers (an embedding) on the local CPU and compared with all passages. Up to 6 passages come back, at most 2 per document; one of the six is swapped for a passage likely to contain a dose. A passage below the **relevance floor** (`THEORACLE_MIN_SIMILARITY`, cosine similarity, 0.35 since 2026-11-26, chosen by Gaffer from the real-index benchmark: weakest on-topic query 0.3725, strongest of 8 off-topic queries 0.2597; re-check after every index rebuild) is never sent, including the dose passage. When no passage clears it, the search answers `THEORACLE_NO_MATCH`: the gateway returns 422, makes no model call, and the composer shows "Tidak ada bukti di Oracle" with the local SOAP draft as the only offer (no "Coba lagi", since the same text gives the same answer). 5. **Engine call**: the gateway sends case + passages to AADI with a secret token. AADI checks the token, rate limit, size, and runs its own identity scan before any model call. 6. **Model call**: AADI makes up to three raced Gemini calls (diagnosis, work-up, therapy), under a 20-second deadline and a cost cap. It validates the answer against a fixed schema. -7. **Targeted therapy** (on by default): the gateway takes the top diagnosis, searches TheOracle again for treatment passages, and calls AADI a second time. +7. **Targeted therapy** (on by default): the gateway takes the top diagnosis, searches TheOracle again for treatment passages, and calls AADI a second time. The same floor applies; when no treatment passage clears it, the diagnosis is returned without therapy and the "Cek dosis obat" fold says no relevant therapy reference was found. 8. **Evidence gate** (`src/lib/theoracle-evidence-gate.ts`): removes any drug not named in the passages; flags a dose unless every strength appears in a passage about that diagnosis; drops the whole therapy if the disease codes do not match. It is an exact-text and pattern match, **not** a meaning check. 9. **Response** goes back to the browser, which re-validates it and applies the gate a **second time** before anything becomes a draft. diff --git a/docs/testing.md b/docs/testing.md index 9f1d3bd..9474a8e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -32,7 +32,7 @@ Static declaration counts (a text search for `it(`/`test(` and `def test_`, not | --- | --- | --- | | Gateway and AADI client | `aadi-client`, `aadi-pipeline`, `aadi-paid`, `aadi-beta-access`, `aadi-composer`, `theoracle-aadi` | `src/lib/aadi/`: the gateway as the trust boundary (origin and host checks, body size, single-flight and `maxConcurrent`, timeout, cancellation, grounding required before retrieval and inference, no inference after a no-match), the targeted therapy second step, client-side validation and identity checks, case assembly from the composer, contract and schema validation with the schema hashes, and the draft built from a result. Gateways get a fake `fetchFn` and fake retrievers, so nothing leaves the process. `aadi-paid` is named for the paid profile but is mocked | | Evidence gate and presentation | `theoracle-evidence-gate` (the largest file), `diagnosis-presentation`, `analysis-view` | `applyTherapyGate`: dose forms (tablet and capsule counts, percent, per-kg, ranges, Unicode minus, unit stripping), cross-referenced SSOT doses, OAT abbreviations; the six-section document, doctor summary, copy and referral text, pipeline trace, and how stored results are re-gated for display | -| Retrieval | `theoracle-grounding`, `theoracle-eval`, `public-data`, `icd-name-match`, `guards`, `pii-parity` | Retrieval over a small index the test generates in a temporary folder with a fake embedder (two-per-document cap, dose-passage swap, privacy filter, tampered or incomplete index refused, warm-up). One test uses the real index and the local model. `theoracle-eval` scores retrieval and the evidence gate on a public synthetic corpus with the pinned model (see below). The public build without the database, the eval ICD name matcher, shared shape guards, and the client side of the identity parity rows | +| Retrieval | `theoracle-grounding`, `theoracle-eval`, `public-data`, `icd-name-match`, `guards`, `pii-parity` | Retrieval over a small index the test generates in a temporary folder with a fake embedder (two-per-document cap, dose-passage swap, relevance floor and its no-match answer, privacy filter, tampered or incomplete index refused, warm-up). One test uses the real index and the local model. `theoracle-eval` scores retrieval and the evidence gate on a public synthetic corpus with the pinned model (see below). The public build without the database, the eval ICD name matcher, shared shape guards, and the client side of the identity parity rows | | Closed beta and auth | `beta-auth`, `beta-auth-routes`, `beta-auth-proxy`, `beta-auth-pages.test.tsx`, `auth-headers`, `clerk-webhook`, `user-access-flow.test.tsx` | Configuration resolution, server-owned access and consent decisions, `/api/aadi` authorization, proxy behaviour and browser hardening, the CSP, the `user.deleted` webhook, and the self-service access flow, including the `/apply` waitlist page. Clerk and Next modules are replaced with `vi.mock` | | Workspace data | `workspace`, `workspace-session`, `workspace-storage`, `workspace-fixtures`, `workflow` | The reducer, validation, restore and the unreadable-backup path, principal-owned storage keys, frozen saved workspaces, personal templates, revisions and review guards, keyboard shortcuts | | Sync | `sync-guard`, `sync-merge`, `sync-messages`, `sync-principal`, `sync-schema` | De-identified projection before upload, add-only merge on pull, Indonesian messages, the sync principal, and the SQL migrations read as text (forced row-level security, a non-owner runtime role, the exact table set). No database is contacted | @@ -95,7 +95,7 @@ Acceptance criteria (thresholds live in `cases.json`; raise them as scores rise, | Evidence gate | every case gets its expected status, in layer 1 with declared evidence and in layer 2 with retrieved evidence | | Known gaps | a case marked `knownGap` runs as an expected failure (`it.fails`): green while the gap is open, red once it is fixed, so the marker is removed with the fix | -The run writes `node_modules/.cache/theoracle-eval/report.json` (per-case ranks, latency, the top similarity of on-topic and off-topic queries) and, in GitHub Actions, the summary to the job page. The off-topic similarities are recorded, not asserted: retrieval has no similarity floor yet, and these numbers are the data for choosing one. +The run writes `node_modules/.cache/theoracle-eval/report.json` (per-case ranks, latency, the top similarity of on-topic and off-topic queries) and, in GitHub Actions, the summary to the job page. The eval retrieves with the relevance floor off (`minSimilarity: -1`), because the synthetic corpus scores lower than the real index and the production floor (0.35) is calibrated on the real index only. It asserts that the weakest on-topic case still scores above the strongest off-topic query, and records both numbers. First run with the model (GitHub Actions run 45874985015, 2026-11-26, about 24 s for the file): clinical recall@6 1 and MRR 1, lay recall@6 1 and MRR 0.938, therapy dose recall 1, every gate case as expected; the lowest top similarity of an on-topic case was 0.2496 and the highest of an off-topic query 0.1457. The thresholds above were set from that run. @@ -107,7 +107,7 @@ First run with the model (GitHub Actions run 45874985015, 2026-11-26, about 24 s - **Docker.** CI builds the image but never runs it; no test starts it. - **Live Clerk, Neon, Resend, Cloudflare, GitHub Actions.** Replaced by mocks, text checks or a JavaScript evaluation of the workflow conditions. - **Non-Windows launcher guardian**, and macOS entirely. -- **Retrieval quality on the real knowledge base**: `npm run benchmark:oracle` scores recall on the private index locally and is not part of `test:all`. CI scores only the synthetic corpus below, which shows regressions in the retriever, the model pin and the gate, not how well the real corpus is covered. +- **Retrieval quality on the real knowledge base**: `npm run benchmark:oracle` scores recall on the private index locally and is not part of `test:all`. CI scores only the synthetic corpus below, which shows regressions in the retriever, the model pin and the gate, not how well the real corpus is covered. Its `relevanceFloor` section calibrates `THEORACLE_MIN_SIMILARITY`: the best passage's similarity for every eval query and for a fixed set of non-clinical queries, and for each candidate floor from 0.20 to 0.60 how many eval queries it would reject and how many non-clinical queries it would let through. Eval queries that answer no-match at the current floor are listed and count as misses. ## Running one file diff --git a/scripts/benchmark-theoracle-grounding.mjs b/scripts/benchmark-theoracle-grounding.mjs index bc94289..d0743e0 100644 --- a/scripts/benchmark-theoracle-grounding.mjs +++ b/scripts/benchmark-theoracle-grounding.mjs @@ -20,7 +20,7 @@ try { const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText; writeFileSync(path.join(scratch, `${name}.mjs`), compiled.replace(/from "\.\/([\w-]+)"/g, 'from "./$1.mjs"')); } - const { retrieveTheOracleGrounding, retrieveTheOracleTherapyGrounding } = await import(pathToFileURL(path.join(scratch, "theoracle-grounding.mjs")).href); + const { retrieveTheOracleGrounding, retrieveTheOracleTherapyGrounding, THEORACLE_MIN_SIMILARITY } = await import(pathToFileURL(path.join(scratch, "theoracle-grounding.mjs")).href); const caseFor = complaint => ({ demographics: { ageYears: null, sex: "unknown" }, chiefComplaint: complaint, anamnesis: {}, physicalExam: [], results: [], currentMedications: [], knownConditions: [] }); const before = hash(); const rssBefore = process.memoryUsage().rss; @@ -28,25 +28,27 @@ try { const first = await retrieveTheOracleGrounding(caseFor("malaria demam"), { indexDir }); const coldStartMs = Math.round(performance.now() - coldStart); const { queries } = JSON.parse(readFileSync(evalSet, "utf8")); - const rows = [], latency = [], doseRows = [], targetedRows = [], targetedLatency = []; + const rows = [], latency = [], doseRows = [], targetedRows = [], targetedLatency = [], noMatch = []; + // Under the relevance floor a query can find nothing; that counts as a miss, not a crash. + const orNoMatch = (promise, id) => promise.catch(error => { if (error?.code !== "THEORACLE_NO_MATCH") throw error; noMatch.push(id); return { evidence: [] }; }); const DOSE = /\d+(?:[.,]\d+)?\s?(?:mg|mcg|g|iu)\b(?!\s*\/\s*(?:dl|l)\b)/i; // a drug amount, not a lab value such as 126 mg/dL const STEM_FILLER = new Set(["dewasa", "remaja", "infeksi", "penyakit", "tahap", "akhir", "kronik", "tanpa", "dengan", "stadium", "tindakan", "perdoski", "dermatovenereologi"]); for (const item of queries) { const tick = performance.now(); - const bundle = await retrieveTheOracleGrounding(caseFor(item.query), { indexDir, limit: 5 }); + const bundle = await orNoMatch(retrieveTheOracleGrounding(caseFor(item.query), { indexDir, limit: 5 }), item.id); latency.push(performance.now() - tick); const hit = item.term ? bundle.evidence.some(e => e.text.toLowerCase().includes(item.term.toLowerCase())) : bundle.evidence.some(e => item.gold.includes(e.source.title)); rows.push({ category: item.category, subtype: item.subtype, hit }); // Dose recall: with the production evidence limit, does a chunk that states a dose for the gold disease reach the // model? The disease markdowns carry no doses, so a dose chunk from any guideline counts when it names the disease. if (item.gold?.length && !item.term) { - const full = await retrieveTheOracleGrounding(caseFor(item.query), { indexDir }); + const full = await orNoMatch(retrieveTheOracleGrounding(caseFor(item.query), { indexDir }), item.id); const stems = item.gold.flatMap(title => title.replace(/\.\w+$/, "").split("-")).filter(word => word.length >= 5 && !STEM_FILLER.has(word)); const dose = full.evidence.filter(e => DOSE.test(e.text)); doseRows.push({ id: item.id, hit: dose.some(e => item.gold.includes(e.source.title) || stems.some(stem => e.text.toLowerCase().includes(stem))), doseTitles: dose.map(e => e.source.title) }); const label = item.gold[0].replace(/\.\w+$/, "").replace(/-\d{4}$/, "").replaceAll("-", " "); const tick2 = performance.now(); - const targeted = await retrieveTheOracleTherapyGrounding(caseFor(item.query), { icd10: "", label }, { indexDir }); + const targeted = await orNoMatch(retrieveTheOracleTherapyGrounding(caseFor(item.query), { icd10: "", label }, { indexDir }), `${item.id}:therapy`); targetedLatency.push(performance.now() - tick2); const tdose = targeted.evidence.filter(e => DOSE.test(e.text)); targetedRows.push({ id: item.id, label, hit: tdose.some(e => item.gold.includes(e.source.title) || stems.some(stem => e.text.toLowerCase().includes(stem))), doseTitles: tdose.map(e => e.source.title) }); @@ -57,6 +59,21 @@ try { const group = rows.filter(r => key === "overall" || r.category === key || `exact_terms.${r.subtype}` === key); recall[key] = { hits: group.filter(r => r.hit).length, total: group.length, recallAt5: Math.round(group.filter(r => r.hit).length / group.length * 1000) / 1000 }; } + // Relevance floor calibration: the best passage's similarity with the floor off, for every eval query (all clinical, + // so each should clear the floor) and for queries with no clinical content (each should fall below it). + const OFF_TOPIC = ["resep kue bolu pandan", "jadwal kereta Jakarta Bandung", "harga saham hari ini", "cara mengganti ban mobil", "lirik lagu kebangsaan", "skor pertandingan sepak bola semalam", "asdf qwer zxcv", "tips menanam cabai di pot"]; + const best = async query => (await retrieveTheOracleGrounding(caseFor(query), { indexDir, minSimilarity: -1 })).evidence[0]?.similarity ?? -1; + const onTopicBest = [], offTopicBest = []; + for (const item of queries) onTopicBest.push({ id: item.id, best: await best(item.query) }); + for (const query of OFF_TOPIC) offTopicBest.push({ query, best: await best(query) }); + const candidates = Array.from({ length: 9 }, (_, i) => Math.round((0.2 + i * 0.05) * 100) / 100); + const relevanceFloor = { + current: THEORACLE_MIN_SIMILARITY, + noMatchAtCurrentFloor: noMatch, + onTopicBest: { min: pct(onTopicBest.map(r => r.best * 1000), 0) / 1000, p05: pct(onTopicBest.map(r => r.best * 1000), 0.05) / 1000, median: pct(onTopicBest.map(r => r.best * 1000), 0.5) / 1000, lowest: [...onTopicBest].sort((a, b) => a.best - b.best).slice(0, 5) }, + offTopicBest, + candidates: candidates.map(floor => ({ floor, onTopicRejected: onTopicBest.filter(r => r.best < floor).length, onTopicTotal: onTopicBest.length, offTopicAccepted: offTopicBest.filter(r => r.best >= floor).length, offTopicTotal: offTopicBest.length })), + }; const after = hash(); if (after !== before) throw new Error("Index changed during benchmark"); console.log(JSON.stringify({ @@ -67,6 +84,7 @@ try { warmLatencyMs: { median: pct(latency, 0.5), p95: pct(latency, 0.95), max: pct(latency, 1) }, recallAt5: recall, doseRecall: { hits: doseRows.filter(r => r.hit).length, total: doseRows.length, rate: Math.round(doseRows.filter(r => r.hit).length / doseRows.length * 1000) / 1000, rows: doseRows }, + relevanceFloor, targetedDoseRecall: { hits: targetedRows.filter(r => r.hit).length, total: targetedRows.length, rate: Math.round(targetedRows.filter(r => r.hit).length / targetedRows.length * 1000) / 1000, latencyMs: { median: pct(targetedLatency, 0.5), p95: pct(targetedLatency, 0.95) }, rows: targetedRows }, }, null, 2)); } finally { diff --git a/src/app/globals.css b/src/app/globals.css index 1505c90..44363b6 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -360,6 +360,8 @@ label.button:has(input:focus-visible) { outline: 2px solid var(--workspace-focus .notice { background: var(--workspace-accent-soft); color: var(--workspace-accent-ink); display: flex; align-items: flex-start; gap: 9px; border-radius: var(--radius); padding: 12px; font-size: var(--text-xs); line-height: 1.65; margin-bottom: 22px; } .notice svg { margin-top: 2px; flex-shrink: 0; } .form-warning { padding: 12px; border-radius: var(--radius); background: var(--workspace-error-bg); color: var(--workspace-error-text); font-size: var(--text-sm); line-height: var(--leading-relaxed); margin: 12px 0; } +.no-evidence strong { display: block; } +.no-evidence p { margin: 4px 0 0; } .danger-ghost, .text-danger { color: var(--workspace-error-text); } .text-danger { padding: 0; text-decoration: underline; } .danger { color: var(--workspace-white); background: var(--workspace-error-text); border-color: var(--workspace-error-text); } diff --git a/src/components/composer.tsx b/src/components/composer.tsx index 5e6f3e1..46b64ba 100644 --- a/src/components/composer.tsx +++ b/src/components/composer.tsx @@ -13,7 +13,7 @@ import type { PersonalTemplate } from "../lib/workflow"; import type { Encounter, Settings } from "../lib/workspace"; import { useDictation } from "./use-dictation"; -interface Props { prompt: string; onPrompt: (value: string) => void; mode: ModeId; onMode: (mode: ModeId) => void; settings: Settings; onModel: (model: Settings["model"]) => void; context: string; onContext: () => void; onScribe: () => void; encounter?: Pick; patientName?: string; templates: PersonalTemplate[]; favorites: string[]; templateKey: string | null; onTemplate: (key: string) => void; onSubmit: () => void; busy: boolean; aadiEnabled?: boolean; analysisError?: string; onCancelAnalysis?: () => void; onFallback?: () => void; mismatch?: { onNew: () => void; onKeep: () => void } | null } +interface Props { prompt: string; onPrompt: (value: string) => void; mode: ModeId; onMode: (mode: ModeId) => void; settings: Settings; onModel: (model: Settings["model"]) => void; context: string; onContext: () => void; onScribe: () => void; encounter?: Pick; patientName?: string; templates: PersonalTemplate[]; favorites: string[]; templateKey: string | null; onTemplate: (key: string) => void; onSubmit: () => void; busy: boolean; aadiEnabled?: boolean; analysisError?: string; analysisNoMatch?: boolean; onCancelAnalysis?: () => void; onFallback?: () => void; mismatch?: { onNew: () => void; onKeep: () => void } | null } const modeLabel = (id: ModeId) => modes.find((item) => item.id === id)!.label; @@ -75,7 +75,9 @@ export function Composer(props: Props) { {dictation.error &&

{dictation.error}

} {props.aadiEnabled &&

Sebelum mengirim ke layanan AI, hapus identitas pasien dari pertanyaan, catatan, dan konteks.

} {props.mismatch &&

Data usia/jenis kelamin berbeda dari encounter ini.

} - {props.aadiEnabled && props.analysisError &&

{props.analysisError}

{props.prompt.trim() && !props.busy &&
{props.onFallback && }
}
} + {/* No relevant guideline passage: retrying the same text gives the same answer, so the doctor is asked to add findings instead. */} + {props.aadiEnabled && props.analysisError && props.analysisNoMatch &&
Tidak ada bukti di Oracle

{props.analysisError}

Tanpa kutipan pedoman yang relevan, Sentrapedia tidak menyusun diagnosis atau terapi. Perjelas keluhan utama atau tambahkan temuan klinis, lalu analisis lagi.

{props.prompt.trim() && !props.busy && props.onFallback &&
}
} + {props.aadiEnabled && props.analysisError && !props.analysisNoMatch &&

{props.analysisError}

{props.prompt.trim() && !props.busy &&
{props.onFallback && }
}
} {/* Options are the rows themselves: focus stays in the textarea, which points at the active row. */} {slashOpen &&
{groups.map((group, g) =>
{group.options.map((item, i) => { const at = groups.slice(0, g).reduce((n, earlier) => n + earlier.options.length, 0) + i; return
event.preventDefault()} onClick={() => choose(item.key)}>{item.label}{item.key === current ? : item.hint && {item.hint}}
; })}
)}{!options.length &&

Tidak ada templat yang cocok.

}
} ; diff --git a/src/components/workspace.tsx b/src/components/workspace.tsx index 7051d32..9fae351 100644 --- a/src/components/workspace.tsx +++ b/src/components/workspace.tsx @@ -25,7 +25,7 @@ import { diagnosisContent, aadiMessage, pcareCopies } from "../lib/aadi/presenta import { paneDocuments } from "../lib/document-pane"; import type { AadiAnalysis } from "../lib/aadi/contract"; import { caseMismatch, composerCase, composerUsesAadi, composerAadiMessages, emptyCaseFields, knownCaseFields, readCaseFields, type CaseFields } from "../lib/aadi/composer"; -import { requestAadiAnalysis } from "../lib/aadi/client"; +import { AadiRequestError, requestAadiAnalysis } from "../lib/aadi/client"; import type { StageEvent } from "../lib/aadi/stage-stream"; import { smooth } from "./smooth"; import { useMediaQuery, useToast, useWorkspacePersistence } from "./workspace-hooks"; @@ -70,6 +70,8 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s const [caseFields, setCaseFields] = useState(emptyCaseFields); const resetCaseFields = useCallback(() => setCaseFields(emptyCaseFields()), []); const [analysisError, setAnalysisError] = useState(""); + // TheOracle found no passage relevant enough to the case: shown as "no evidence", not as a service failure. + const [analysisNoMatch, setAnalysisNoMatch] = useState(false); // A case whose age or sex differs from the open encounter waits here until the doctor picks where it goes (P0 #3). // It belongs to the encounter it was held in; opening another encounter voids it (the text stays in the composer). const [held, setHeld] = useState<{ encounterId: string; text: string; mode: ModeId; useTemplate: boolean; local: boolean; fallback?: string } | null>(null); @@ -145,7 +147,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s // never automatic; the draft's source records why AADI did not answer. function fallbackDraft() { if (!prompt.trim() || busy) return; - const reason = analysisError; setAnalysisError(""); + const reason = analysisError; setAnalysisError(""); setAnalysisNoMatch(false); generate(prompt, "clinic", false, true, reason, { confirmed: true, fresh: failedIntoNew.current }); // Like an answered analysis, the next case starts with an empty strip. resetCaseFields(); @@ -154,7 +156,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s async function analyzeMain(text: string, selectedMode: ModeId, current: Encounter, isNew: boolean, casePatient?: Patient) { if (analysisController.current) return; const controller = new AbortController(); analysisController.current = controller; - setBusy(true); setAnalysisError(""); pendingText.current = text.trim(); setPendingQuestion(text.trim()); setStages([]); setPrompt(""); + setBusy(true); setAnalysisError(""); setAnalysisNoMatch(false); pendingText.current = text.trim(); setPendingQuestion(text.trim()); setStages([]); setPrompt(""); // The home composer gives way to the chat composer; keep typing where the reader is. requestAnimationFrame(() => document.querySelector(".chat-composer textarea")?.focus()); const finish = () => { if (analysisController.current === controller) { analysisController.current = null; setBusy(false); setPendingQuestion(null); setQueuePosition(null); setStages([]); pendingText.current = null; } }; @@ -174,7 +176,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s finish(); }, "arrive"); } catch (error) { - if (!controller.signal.aborted) { failedIntoNew.current = isNew; setAnalysisError(error instanceof Error ? error.message : "Analisis belum tersedia. Keluhan tetap tersedia."); setPrompt(text); } + if (!controller.signal.aborted) { failedIntoNew.current = isNew; setAnalysisError(error instanceof Error ? error.message : "Analisis belum tersedia. Keluhan tetap tersedia."); setAnalysisNoMatch(error instanceof AadiRequestError && error.code === "THEORACLE_NO_MATCH"); setPrompt(text); } } finally { if (!arriving) finish(); } @@ -223,7 +225,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s onMakeTasks: (text: string) => { const typed = prompt; generate(text, "tasks", false); setPrompt(typed); }, }; const paneFor = (onClose: () => void) => encounter && setPane({ activeId })} overview={} tools={paneTools} onClose={onClose} dispatch={dispatch} onToast={notify} drafts={drafts} onDraft={setDraft}/>; - const composerProps: ComponentProps = { prompt, onPrompt: updatePrompt, mode, onMode: changeMode, settings: state.settings, onModel: (model) => dispatch({ type: "settings.save", settings: { ...state.settings, model } }), context, onContext: () => openDialog("context"), onScribe: () => openDialog("scribe"), encounter, patientName: patient?.name, templates: state.templates ?? [], favorites: state.favorites ?? [], templateKey, onTemplate: chooseTemplate, onSubmit: () => generate(), busy, aadiEnabled: composerUsesAadi(mode, !!selectedTemplate), analysisError, onCancelAnalysis: cancelAnalysis, onFallback: fallbackDraft, + const composerProps: ComponentProps = { prompt, onPrompt: updatePrompt, mode, onMode: changeMode, settings: state.settings, onModel: (model) => dispatch({ type: "settings.save", settings: { ...state.settings, model } }), context, onContext: () => openDialog("context"), onScribe: () => openDialog("scribe"), encounter, patientName: patient?.name, templates: state.templates ?? [], favorites: state.favorites ?? [], templateKey, onTemplate: chooseTemplate, onSubmit: () => generate(), busy, aadiEnabled: composerUsesAadi(mode, !!selectedTemplate), analysisError, analysisNoMatch, onCancelAnalysis: cancelAnalysis, onFallback: fallbackDraft, mismatch: heldHere && { onNew: () => generate(heldHere.text, heldHere.mode, heldHere.useTemplate, heldHere.local, heldHere.fallback, { confirmed: true, fresh: true }), onKeep: () => generate(heldHere.text, heldHere.mode, heldHere.useTemplate, heldHere.local, heldHere.fallback, { confirmed: true }) } }; if (restoring) return

Membuka workspace…

; diff --git a/src/lib/aadi/gateway.ts b/src/lib/aadi/gateway.ts index 805dd1d..2707d62 100644 --- a/src/lib/aadi/gateway.ts +++ b/src/lib/aadi/gateway.ts @@ -232,7 +232,10 @@ export function createAadiGateway(options: Options = {}) { if (controller.signal.aborted) throw error; if (error instanceof ServiceFailure && error.code === "RATE_LIMITED") return rateLimited(error.retryAfter); therapyGrounding = undefined; - evidenceGate = absent("Referensi atau langkah terapi Oracle tidak tersedia; terapi dan dosis tidak ditampilkan."); + // No passage cleared the relevance floor: say so, rather than suggesting the service failed. + evidenceGate = absent(error instanceof TheOracleGroundingError && error.code === "THEORACLE_NO_MATCH" + ? "Oracle tidak menemukan referensi terapi yang cukup relevan untuk diagnosis ini; terapi dan dosis tidak ditampilkan." + : "Referensi atau langkah terapi Oracle tidak tersedia; terapi dan dosis tidak ditampilkan."); } finally { stage.abort(); } } if (final.therapy) { diff --git a/src/lib/theoracle-grounding.ts b/src/lib/theoracle-grounding.ts index a725cd8..4a8aaf4 100644 --- a/src/lib/theoracle-grounding.ts +++ b/src/lib/theoracle-grounding.ts @@ -21,6 +21,12 @@ const THERAPY_EVIDENCE = 1; const THERAPY_QUERY = "\npenatalaksanaan terapi dosis obat"; // A drug amount such as 500 mg or 1 g, not a laboratory value such as 126 mg/dL. const DOSE = /\d+(?:[.,]\d+)?\s?(?:mg|mcg|g|iu)\b(?!\s*\/\s*(?:dl|l)\b)/i; +// Relevance floor: a passage whose cosine similarity to the query is below this is not evidence for the case, so it is +// never sent to the model. When no passage of the case search clears it, retrieval answers THEORACLE_NO_MATCH and no +// analysis runs. Set to 0.35 by Gaffer on 2026-11-26 from `npm run benchmark:oracle` on the real index: weakest on-topic +// best passage 0.3725 (88 eval queries), strongest off-topic 0.2597 (8 queries); 0.40 rejected two on-topic queries. +// The on-topic margin is small (about 0.02): re-run the benchmark's relevanceFloor section after every index rebuild. +export const THEORACLE_MIN_SIMILARITY = 0.35; const REVIEW_PROVENANCE = "Derived from official guidelines (KMK 1186/2022, Permenkes 5/2014, PNPK); clinically reviewed by Gaffer on 2026-10-23. Review status per entry is recorded in the knowledge SSOT (status.review_klinis)."; export interface TheOracleManifest { @@ -34,7 +40,7 @@ export interface TheOracleManifest { interface Chunk { id: string; title: string; docSource: string; origin: string; text: string; textSha256: string } type Embed = (text: string) => Promise; interface LoadedIndex { manifest: TheOracleManifest; chunks: Chunk[]; vectors: Float32Array; embed: Embed } -interface RetrieveOptions { indexDir?: string; modelDir?: string; limit?: number; now?: () => Date; embedder?: (manifest: TheOracleManifest, modelDir: string) => Promise } +interface RetrieveOptions { indexDir?: string; modelDir?: string; limit?: number; minSimilarity?: number; now?: () => Date; embedder?: (manifest: TheOracleManifest, modelDir: string) => Promise } const loaded = new Map>(); const sha256 = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex"); @@ -157,6 +163,9 @@ async function rankChunks({ manifest, chunks, vectors, embed }: LoadedIndex, tex return { ranked: [...scores.keys()].sort((a, b) => scores[b] - scores[a]), scores }; } +// The floor in force for one call; an invalid option falls back to the default rather than switching the floor off. +const floorFor = (options: RetrieveOptions) => typeof options.minSimilarity === "number" && Number.isFinite(options.minSimilarity) ? options.minSimilarity : THEORACLE_MIN_SIMILARITY; + const evidenceItem = (chunk: Chunk, score: number): Omit => ({ evidenceId: chunk.id, text: evidenceText(chunk.text), similarity: Math.round(score * 10_000) / 10_000, source: { title: chunk.title, docSource: chunk.docSource, origin: chunk.origin, textSha256: chunk.textSha256 } }); export async function retrieveTheOracleGrounding(caseData: CaseState, options: RetrieveOptions = {}): Promise { @@ -166,11 +175,13 @@ export async function retrieveTheOracleGrounding(caseData: CaseState, options: R const index = await indexFor(options); const { manifest, chunks } = index; const dims = manifest.model.dims; + const floor = floorFor(options); const { ranked, scores } = await rankChunks(index, query); const selected: Omit[] = []; const perDocument = new Map(); + // Ranked best first, so the first passage under the floor ends the search. for (const i of ranked) { - if (selected.length >= limit) break; + if (selected.length >= limit || scores[i] < floor) break; const chunk = chunks[i]; if ((perDocument.get(chunk.title) ?? 0) >= MAX_PER_DOCUMENT) continue; const item = evidenceItem(chunk, scores[i]); @@ -178,14 +189,14 @@ export async function retrieveTheOracleGrounding(caseData: CaseState, options: R perDocument.set(chunk.title, (perDocument.get(chunk.title) ?? 0) + 1); selected.push(item); } - if (!selected.length) throw new TheOracleGroundingError("THEORACLE_NO_MATCH", "Oracle tidak menemukan referensi untuk keluhan ini. Analisis tidak dijalankan."); + if (!selected.length) throw new TheOracleGroundingError("THEORACLE_NO_MATCH", "Oracle tidak menemukan referensi yang cukup relevan untuk keluhan ini. Analisis tidak dijalankan."); // A complaint matches symptom passages; doses sit in treatment passages, often of another guideline (PPK, Fornas). // Search the whole corpus again for treatment and add the best passage that states a dose, in place of the lowest match. const therapy: typeof selected = []; if (limit > 1) { const { ranked: therapyRanked, scores: therapyScores } = await rankChunks(index, query + THERAPY_QUERY); for (const i of therapyRanked) { - if (therapy.length >= THERAPY_EVIDENCE) break; + if (therapy.length >= THERAPY_EVIDENCE || therapyScores[i] < floor) break; const chunk = chunks[i]; if (!DOSE.test(chunk.text) || selected.some(item => item.evidenceId === chunk.id)) continue; const item = evidenceItem(chunk, therapyScores[i]); @@ -238,12 +249,13 @@ export async function retrieveTheOracleTherapyGrounding(caseData: CaseState, dia const query = therapyQuery(caseData, diagnosis); const index = await indexFor(options); const { manifest, chunks } = index; + const floor = floorFor(options); const { ranked, scores } = await rankChunks(index, query); const selected: Omit[] = []; const perDocument = new Map(); for (const wantDose of [true, false]) { for (const i of ranked) { - if (selected.length >= (wantDose ? THERAPY_DOSE_EVIDENCE : MAX_EVIDENCE)) break; + if (selected.length >= (wantDose ? THERAPY_DOSE_EVIDENCE : MAX_EVIDENCE) || scores[i] < floor) break; const chunk = chunks[i]; if (DOSE.test(chunk.text) !== wantDose || (perDocument.get(chunk.title) ?? 0) >= MAX_PER_DOCUMENT) continue; const item = evidenceItem(chunk, scores[i]); @@ -252,7 +264,7 @@ export async function retrieveTheOracleTherapyGrounding(caseData: CaseState, dia selected.push(item); } } - if (!selected.length) throw new TheOracleGroundingError("THEORACLE_NO_MATCH", "Oracle tidak menemukan referensi terapi untuk diagnosis ini."); + if (!selected.length) throw new TheOracleGroundingError("THEORACLE_NO_MATCH", "Oracle tidak menemukan referensi terapi yang cukup relevan untuk diagnosis ini."); return freezeBundle({ version: THEORACLE_GROUNDING_CAPABILITY, corpus: { name: "TheOracle", indexSha256: manifest.indexSha256, embeddingModel: { id: manifest.model.id, revision: manifest.model.revision, dtype: manifest.model.dtype, dims: manifest.model.dims }, retrievedAt: (options.now ?? (() => new Date()))().toISOString(), reviewProvenance: REVIEW_PROVENANCE }, diff --git a/tests/aadi-pipeline.test.ts b/tests/aadi-pipeline.test.ts index f2c4c4a..9ca9116 100644 --- a/tests/aadi-pipeline.test.ts +++ b/tests/aadi-pipeline.test.ts @@ -12,6 +12,7 @@ const bundle = (text: string): TheOracleGroundingBundle => ({ version: THEORACLE const diagnosisResult = (likely: { icd10: string; label: string; confidenceTier: string }[]) => ({ contractVersion: "1", status: "ok", differential: { likely, alternatives: [], cannotMiss: [] }, evidence: [], missingInformation: [], nextBestActions: [], disposition: null, unfilled: [], meta }); const pneumonia = { icd10: "J18.9", label: "Pneumonia", confidenceTier: "low" }; const UNAVAILABLE = "Referensi atau langkah terapi Oracle tidak tersedia; terapi dan dosis tidak ditampilkan."; +const NO_THERAPY_MATCH = "Oracle tidak menemukan referensi terapi yang cukup relevan untuk diagnosis ini; terapi dan dosis tidak ditampilkan."; const absent = (reason = UNAVAILABLE, forDiagnosis = { icd10: "J18.9", label: "Pneumonia" }) => ({ forDiagnosis, therapyRemoved: true, reason, drugs: [] }); const therapy = { forDiagnosis: { icd10: "J18.9", label: "Pneumonia" }, regimen: [{ drug: "Amoxicillin", dose: "3x500mg", route: "PO", duration: "5 hari", note: "" }, { drug: "Levofloxacin", dose: "1x750mg", route: "PO", duration: "5 hari", note: "" }], interactions: [], contraindications: [] }; @@ -69,7 +70,8 @@ describe("targeted therapy pipeline", () => { expect(posts.map(p => p.path)).toEqual(["/v1/diagnosis/step"]); expect(body.result.therapy).toBeUndefined(); expect(body.result.differential.likely[0].icd10).toBe("J18.9"); - expect(body.evidenceGate).toEqual(absent()); + // No relevant therapy passage is reported as such, not as an outage. + expect(body.evidenceGate).toEqual(absent(NO_THERAPY_MATCH)); expect(logs.find(l => l.stage === "retrieve_tx")).toMatchObject({ ok: false, code: "THEORACLE_NO_MATCH" }); }); it("skips therapy when the diagnosis step has no likely diagnosis", async () => { diff --git a/tests/theoracle-eval.test.ts b/tests/theoracle-eval.test.ts index 2dfbd1a..f6786ec 100644 --- a/tests/theoracle-eval.test.ts +++ b/tests/theoracle-eval.test.ts @@ -81,6 +81,9 @@ it.runIf(required && !modelReady)("has the pinned embedding model that SENTRAPED describe.runIf(modelReady)("TheOracle retrieval on the synthetic index with the pinned model", () => { let indexDir = ""; + // The production floor is calibrated on the real index, which scores higher than this short-passage corpus; with it on, + // genuine eval cases would answer no-match. The eval measures retrieval with the floor off. + const FLOOR_OFF = -1; const report: Record = { measuredAt: new Date().toISOString(), node: process.version, model: { id: profile.id, revision: profile.revision } }; const rate = (hits: number, total: number) => Math.round(hits / total * 1000) / 1000; @@ -106,7 +109,7 @@ describe.runIf(modelReady)("TheOracle retrieval on the synthetic index with the const manifest = JSON.parse(readFileSync(path.join(indexDir, "manifest.json"), "utf8")) as TheOracleManifest; expect(manifest.model).toMatchObject({ id: profile.id, revision: profile.revision, dtype: profile.dtype, dims: profile.dims }); expect(manifest.chunks.count).toBe(passages.length); - const bundle = await retrieveTheOracleGrounding(caseFor(cases.retrieval[0]), { indexDir }); + const bundle = await retrieveTheOracleGrounding(caseFor(cases.retrieval[0]), { indexDir, minSimilarity: FLOOR_OFF }); expect(validTheOracleGrounding(bundle)).toBe(true); expect(bundle.corpus.indexSha256).toBe(manifest.indexSha256); }, 300_000); @@ -115,7 +118,7 @@ describe.runIf(modelReady)("TheOracle retrieval on the synthetic index with the const rows: { id: string; category: string; rank: number; top: string; topSimilarity: number; ms: number }[] = []; for (const item of cases.retrieval) { const started = performance.now(); - const bundle = await retrieveTheOracleGrounding(caseFor(item), { indexDir }); + const bundle = await retrieveTheOracleGrounding(caseFor(item), { indexDir, minSimilarity: FLOOR_OFF }); const rank = bundle.evidence.findIndex(e => e.source.title === item.gold) + 1; rows.push({ id: item.id, category: item.category, rank, top: bundle.evidence[0].source.title, topSimilarity: bundle.evidence[0].similarity, ms: Math.round(performance.now() - started) }); } @@ -134,7 +137,7 @@ describe.runIf(modelReady)("TheOracle retrieval on the synthetic index with the it("brings the diagnosis's dose passage into the therapy step's evidence", async () => { const rows: { id: string; hit: boolean; rank: number }[] = []; for (const item of cases.therapy) { - const bundle = await retrieveTheOracleTherapyGrounding(emptyCase(), item.diagnosis, { indexDir }); + const bundle = await retrieveTheOracleTherapyGrounding(emptyCase(), item.diagnosis, { indexDir, minSimilarity: FLOOR_OFF }); rows.push({ id: item.id, hit: bundle.evidence.some(e => e.evidenceId === item.dosePassage), rank: bundle.evidence.findIndex(e => e.evidenceId === item.dosePassage) + 1 }); } const doseRecall = rate(rows.filter(r => r.hit).length, rows.length); @@ -145,7 +148,7 @@ describe.runIf(modelReady)("TheOracle retrieval on the synthetic index with the it("never returns a passage that trips the AADI privacy guard, however close it is to the query", async () => { for (const query of cases.privacy.queries) { - const ids = [...(await retrieveTheOracleGrounding(caseFor({ query }), { indexDir })).evidence, ...(await retrieveTheOracleTherapyGrounding(caseFor({ query }), { icd10: "J18.9", label: "Pneumonia komunitas" }, { indexDir })).evidence].map(e => e.evidenceId); + const ids = [...(await retrieveTheOracleGrounding(caseFor({ query }), { indexDir, minSimilarity: FLOOR_OFF })).evidence, ...(await retrieveTheOracleTherapyGrounding(caseFor({ query }), { icd10: "J18.9", label: "Pneumonia komunitas" }, { indexDir, minSimilarity: FLOOR_OFF })).evidence].map(e => e.evidenceId); expect(ids).not.toContain(cases.privacy.trap); } }, 300_000); @@ -153,18 +156,19 @@ describe.runIf(modelReady)("TheOracle retrieval on the synthetic index with the // The cases whose outcome does not depend on which other passages come back; known gaps are left to layer 1. const endToEnd = gateCases.filter(item => !item.retrievalDependent && !item.knownGap); for (const item of endToEnd) it(`gates ${item.id} against the evidence retrieval actually returned: ${item.about}`, async () => { - const dx = await retrieveTheOracleGrounding(caseFor(item), { indexDir }); - const tx = await retrieveTheOracleTherapyGrounding(caseFor(item), item.diagnosis, { indexDir }); + const dx = await retrieveTheOracleGrounding(caseFor(item), { indexDir, minSimilarity: FLOOR_OFF }); + const tx = await retrieveTheOracleTherapyGrounding(caseFor(item), item.diagnosis, { indexDir, minSimilarity: FLOOR_OFF }); checkGate(item, gateEvidence(tx, dx)!, false); }, 300_000); - // No similarity floor exists yet (known gap): an off-topic query still gets six passages. Recorded so a floor can be - // chosen from data; not asserted. - it("records how similar off-topic queries score, for choosing a similarity floor", async () => { + // The floor itself is not asserted here (see FLOOR_OFF); that on-topic and off-topic queries separate on this corpus is. + it("scores every on-topic case above every off-topic query, and records both for the floor", async () => { const offTopic: { query: string; topSimilarity: number }[] = []; - for (const query of cases.outOfDomain) offTopic.push({ query, topSimilarity: (await retrieveTheOracleGrounding(caseFor({ query }), { indexDir })).evidence[0].similarity }); + for (const query of cases.outOfDomain) offTopic.push({ query, topSimilarity: (await retrieveTheOracleGrounding(caseFor({ query }), { indexDir, minSimilarity: FLOOR_OFF })).evidence[0].similarity }); const rows = (report.retrieval as { rows: { rank: number; topSimilarity: number }[] } | undefined)?.rows ?? []; report.summary = { ...(report.summary as object), offTopicMaxSimilarity: Math.max(...offTopic.map(r => r.topSimilarity)), onTopicMinTopSimilarity: rows.length ? Math.min(...rows.map(r => r.topSimilarity)) : null }; report.outOfDomain = offTopic; + // The retrieval rows come from the recall test above; run alone, this test only records. + if (rows.length) expect(Math.min(...rows.map(r => r.topSimilarity))).toBeGreaterThan(Math.max(...offTopic.map(r => r.topSimilarity))); }, 300_000); }); diff --git a/tests/theoracle-grounding.test.ts b/tests/theoracle-grounding.test.ts index 7420678..6c50c11 100644 --- a/tests/theoracle-grounding.test.ts +++ b/tests/theoracle-grounding.test.ts @@ -9,6 +9,7 @@ import { THEORACLE_GROUNDING_CAPABILITY, TheOracleGroundingError, retrieveTheOracleGrounding, + THEORACLE_MIN_SIMILARITY, retrieveTheOracleTherapyGrounding, warmTheOracleGrounding, type TheOracleManifest, @@ -25,7 +26,7 @@ const fixtureChunks = [ chunk("A2", "PNPK Pneumonia.md", "Amoksisilin 3 x 500 mg selama 5 hari.", [0.9, 0.1, 0]), chunk("A3", "PNPK Pneumonia.md", "Bagian ketiga yang tidak boleh lolos.", [0.85, 0.15, 0]), chunk("C1", "Kontak.md", "Hubungi 081234567890 untuk konsultasi.", [0.95, 0.05, 0]), - chunk("B1", "PNPK Tuberkulosis.md", "Batuk lebih dari dua minggu.", [0.2, 0.98, 0]), + chunk("B1", "PNPK Tuberkulosis.md", "Batuk lebih dari dua minggu.", [0.15, 0.99, 0]), chunk("D1", "PPK Fasyankes Primer.pdf", "Penatalaksanaan pneumonia: amoksisilin 3 x 500 mg.", [0, 0.3, 1]), chunk("D2", "PPK Fasyankes Primer.pdf", "Terapi 500 mg, hubungi 081234567890.", [0, 0, 1]), ]; @@ -75,7 +76,8 @@ describe("TheOracle vector grounding", () => { }); it("keeps at most two passages per document and skips sources that trip the AADI privacy guard", async () => { - const bundle = await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir: fixtureIndex(), embedder: fakeEmbedder([]) }); + // The floor is off here so the low-similarity passages B1 and D1 show the cap and the privacy filter. + const bundle = await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir: fixtureIndex(), embedder: fakeEmbedder([]), minSimilarity: -1 }); expect(bundle.evidence.map(item => item.evidenceId)).toEqual(["A1", "A2", "B1", "D1"]); expect(bundle.evidence.map(item => item.retrievalRank)).toEqual([1, 2, 3, 4]); }); @@ -90,11 +92,11 @@ describe("TheOracle vector grounding", () => { it("adds the best treatment passage that states a dose, from any guideline, in place of the lowest-ranked match", async () => { const therapyEmbedder = async () => async (text: string) => Float32Array.from(text.endsWith("dosis obat") ? [0, 0, 1] : [1, 0, 0]); const indexDir = fixtureIndex(); - const bundle = await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir, embedder: therapyEmbedder }); + const bundle = await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir, embedder: therapyEmbedder, minSimilarity: -1 }); expect(validTheOracleGrounding(bundle)).toBe(true); expect(bundle.evidence.map(item => item.evidenceId)).toEqual(["A1", "A2", "B1", "D1"]); expect(bundle.evidence.map(item => item.retrievalRank)).toEqual([1, 2, 3, 4]); - expect((await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir, embedder: therapyEmbedder, limit: 3 })).evidence.map(item => item.evidenceId)).toEqual(["A1", "A2", "D1"]); + expect((await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir, embedder: therapyEmbedder, limit: 3, minSimilarity: -1 })).evidence.map(item => item.evidenceId)).toEqual(["A1", "A2", "D1"]); }); it("keeps the two-per-document cap: the dose passage takes its document's lower match and the next match moves up", async () => { @@ -114,7 +116,7 @@ describe("TheOracle vector grounding", () => { it("retrieves therapy for a diagnosis: dose passages first, then others, with patient context in the query", async () => { const calls: string[] = []; const embedder = async () => async (text: string) => { calls.push(text); return Float32Array.from([0, 0, 1]); }; - const bundle = await retrieveTheOracleTherapyGrounding({ ...caseFor("batuk"), demographics: { ageYears: 30, sex: "F", pregnant: true }, currentMedications: ["warfarin"] }, { icd10: "J18.9", label: "Pneumonia" }, { indexDir: fixtureIndex(), embedder }); + const bundle = await retrieveTheOracleTherapyGrounding({ ...caseFor("batuk"), demographics: { ageYears: 30, sex: "F", pregnant: true }, currentMedications: ["warfarin"] }, { icd10: "J18.9", label: "Pneumonia" }, { indexDir: fixtureIndex(), embedder, minSimilarity: -1 }); expect(validTheOracleGrounding(bundle)).toBe(true); expect(calls).toEqual(["task: search result | query: Pneumonia (J18.9)\npenatalaksanaan terapi dosis obat\n30 tahun, perempuan, hamil\nObat rutin: warfarin"]); expect(bundle.evidence.map(item => item.evidenceId)).toEqual(["D1", "A2", "A1", "B1"]); @@ -135,6 +137,47 @@ describe("TheOracle vector grounding", () => { expect(error).toMatchObject({ code: "THEORACLE_NO_MATCH" }); }); + describe("relevance floor", () => { + // Query [1, 0, 0] against the fixture: A1 1.0, A2 0.994, B1 0.15, D1 0.0 (C1 and D2 fail the privacy filter). + it("sends only passages at or above the floor, and swaps in no dose passage that is below it", async () => { + const bundle = await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir: fixtureIndex(), embedder: fakeEmbedder([]) }); + expect(validTheOracleGrounding(bundle)).toBe(true); + expect(bundle.evidence.map(item => item.evidenceId)).toEqual(["A1", "A2"]); + expect(bundle.evidence.every(item => item.similarity >= THEORACLE_MIN_SIMILARITY)).toBe(true); + }); + + it("answers THEORACLE_NO_MATCH when no passage clears the floor, and runs no therapy search", async () => { + const calls: string[] = []; + const embedder = async () => async (text: string) => { calls.push(text); return Float32Array.from([0, 0, 1]); }; + const offTopic = fixtureChunks.filter(item => item.vector[2] === 0); + const error: unknown = await retrieveTheOracleGrounding(caseFor("resep kue bolu"), { indexDir: fixtureIndex(false, offTopic), embedder }).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(TheOracleGroundingError); + expect(error).toMatchObject({ code: "THEORACLE_NO_MATCH", message: "Oracle tidak menemukan referensi yang cukup relevan untuk keluhan ini. Analisis tidak dijalankan." }); + expect(calls).toHaveLength(1); + }); + + it("takes a stricter floor from the options", async () => { + const bundle = await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir: fixtureIndex(), embedder: fakeEmbedder([]), minSimilarity: 0.995 }); + expect(bundle.evidence.map(item => item.evidenceId)).toEqual(["A1"]); + }); + + it("keeps the default floor when the option is not a finite number", async () => { + for (const minSimilarity of [Number.NaN, Number.NEGATIVE_INFINITY]) { + const bundle = await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir: fixtureIndex(), embedder: fakeEmbedder([]), minSimilarity }); + expect(bundle.evidence.map(item => item.evidenceId)).toEqual(["A1", "A2"]); + } + }); + + it("applies the floor to therapy retrieval and answers THEORACLE_NO_MATCH when nothing clears it", async () => { + const toward = (vector: number[]) => async () => async () => Float32Array.from(vector); + // Query [0, 0, 1]: D1 0.958 clears the floor; the A and B passages score 0 or near it. + const bundle = await retrieveTheOracleTherapyGrounding(caseFor("batuk"), { icd10: "J18.9", label: "Pneumonia" }, { indexDir: fixtureIndex(), embedder: toward([0, 0, 1]) }); + expect(bundle.evidence.map(item => item.evidenceId)).toEqual(["D1"]); + const error: unknown = await retrieveTheOracleTherapyGrounding(caseFor("batuk"), { icd10: "J18.9", label: "Pneumonia" }, { indexDir: fixtureIndex(), embedder: toward([0, -1, 0]) }).catch((caught: unknown) => caught); + expect(error).toMatchObject({ code: "THEORACLE_NO_MATCH", message: "Oracle tidak menemukan referensi terapi yang cukup relevan untuk diagnosis ini." }); + }); + }); + it("clamps the evidence limit", async () => { const indexDir = fixtureIndex(); expect((await retrieveTheOracleGrounding(caseFor("batuk"), { indexDir, embedder: fakeEmbedder([]), limit: 1 })).evidence).toHaveLength(1); diff --git a/tests/ui/draft-actions.test.tsx b/tests/ui/draft-actions.test.tsx index d36d80e..fdc20f2 100644 --- a/tests/ui/draft-actions.test.tsx +++ b/tests/ui/draft-actions.test.tsx @@ -26,11 +26,14 @@ const analysis = (data: CaseState): AadiAnalysis => ({ let sent: CaseState[] = []; let failAnalysis = false; +let noMatch = false; const failure = "Layanan analisis sedang tidak tersedia."; +const noMatchMessage = "Oracle tidak menemukan referensi yang cukup relevan untuk keluhan ini. Analisis tidak dijalankan."; beforeEach(() => { sent = []; failAnalysis = false; + noMatch = false; localStorage.clear(); // Reduced motion: the answer appears whole, so the test needs no timers. Object.defineProperty(window, "matchMedia", { writable: true, value: vi.fn().mockImplementation((query: string) => ({ matches: query.includes("reduce"), media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn() })) }); @@ -41,6 +44,7 @@ beforeEach(() => { if (init?.method !== "POST") return new Response(JSON.stringify({ configured: true, modelReady: true, groundingReady: true, ready: true }), { status: 200, headers: { "Content-Type": "application/json" } }); const body = JSON.parse(String(init.body)) as { case: CaseState }; sent.push(body.case); + if (noMatch) return new Response(JSON.stringify({ error: { code: "THEORACLE_NO_MATCH", message: noMatchMessage } }), { status: 422, headers: { "Content-Type": "application/json" } }); if (failAnalysis) return new Response(JSON.stringify({ error: { code: "UPSTREAM_UNAVAILABLE", message: failure } }), { status: 502, headers: { "Content-Type": "application/json" } }); return new Response(JSON.stringify(analysis(body.case)), { status: 200, headers: { "Content-Type": "application/json" } }); }); @@ -94,3 +98,45 @@ describe("local draft when the analysis fails", () => { expect(screen.queryByRole("button", { name: "Susun draf SOAP lokal" })).toBeNull(); }); }); + +describe("no evidence in TheOracle", () => { + async function noEvidence() { + noMatch = true; + render(); + await act(async () => { await Promise.resolve(); }); + fireEvent.change(textarea(), { target: { value: complaint } }); + await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Analisis kasus" })); }); + await act(async () => { await Promise.resolve(); }); + return screen.findByRole("alert"); + } + + it("says plainly that there is no evidence, asks for more findings, and offers no pointless retry", async () => { + const alert = await noEvidence(); + expect(alert.textContent).toContain("Tidak ada bukti di Oracle"); + expect(alert.textContent).toContain(noMatchMessage); + expect(alert.textContent).toContain("tidak menyusun diagnosis atau terapi"); + expect(screen.queryByRole("button", { name: "Coba lagi" })).toBeNull(); + expect(screen.getByRole("button", { name: "Susun draf SOAP lokal" })).toBeTruthy(); + expect(textarea().value).toBe(complaint); + expect(sent).toHaveLength(1); + }); + + it("builds the local SOAP draft without a diagnosis and records why", async () => { + await noEvidence(); + await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Susun draf SOAP lokal" })); }); + const draft = savedDraft(); + expect(draft.sourceText).toContain(noMatchMessage); + expect(draft.content).not.toMatch(/\b[A-Z]\d{2}(\.\d)?\b/); + expect(hasAadiSource(draft)).toBe(false); + }); + + it("returns to the ordinary failure notice when a later analysis fails for another reason", async () => { + await noEvidence(); + noMatch = false; failAnalysis = true; + await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Analisis kasus" })); }); + await act(async () => { await Promise.resolve(); }); + expect((await screen.findByRole("alert")).textContent).toContain(failure); + expect(screen.queryByText("Tidak ada bukti di Oracle")).toBeNull(); + expect(screen.getByRole("button", { name: "Coba lagi" })).toBeTruthy(); + }); +});