From 42e1b9180b65a4d5ade3b8bc137bd2fcc45e541c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:15:26 +0000 Subject: [PATCH 1/3] feat(theoracle): add relevance floor and explicit no-evidence path Retrieval sent the top passages to the model whatever their similarity, so an off-topic case was still "grounded" on unrelated guideline text. - THEORACLE_MIN_SIMILARITY (provisional 0.30, uncalibrated) drops every passage below the floor in case, dose-swap and therapy retrieval; nothing above it -> THEORACLE_NO_MATCH (422, no model call). - Therapy no-match now says "no relevant therapy reference" instead of reporting an outage. - Composer shows "Tidak ada bukti di Oracle" for no-match, without the pointless "Coba lagi"; the local SOAP draft stays available. - benchmark:oracle gains a relevanceFloor calibration section and no longer crashes when a query answers no-match. - Tests: 7 new (red before, green after); docs updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ta9C7XhCnabM5SwJLKnmU --- docs/architecture.md | 4 +- docs/testing.md | 4 +- scripts/benchmark-theoracle-grounding.mjs | 28 ++++++++++--- src/app/globals.css | 3 ++ src/components/composer.tsx | 6 ++- src/components/workspace.tsx | 12 +++--- src/lib/aadi/gateway.ts | 5 ++- src/lib/theoracle-grounding.ts | 23 +++++++--- tests/aadi-pipeline.test.ts | 4 +- tests/theoracle-grounding.test.ts | 51 +++++++++++++++++++++-- tests/ui/draft-actions.test.tsx | 46 ++++++++++++++++++++ 11 files changed, 158 insertions(+), 28 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 4f19412..36c3df4 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, provisionally 0.30 since 2026-11-26 and not yet calibrated on the real index) 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 c1e4b05..e9e1be9 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`, `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. 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`, `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. 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 | @@ -85,7 +85,7 @@ Never paste database passages into tests, fixtures or documents. - **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** beyond fixtures: `npm run benchmark:oracle` scores recall locally but is not part of `test:all`. +- **Retrieval quality** beyond fixtures: `npm run benchmark:oracle` scores recall locally but is not part of `test:all`. 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 358c404..2ba3c6e 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -358,6 +358,9 @@ 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; } +.no-evidence .text-button { margin-top: 6px; } .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 f83fcee..b37d6b1 100644 --- a/src/components/composer.tsx +++ b/src/components/composer.tsx @@ -12,7 +12,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 } +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 } const modeLabel = (id: ModeId) => modes.find((item) => item.id === id)!.label; @@ -72,7 +72,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.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 ba37008..f70d28a 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 { composerCase, composerUsesAadi, composerAadiMessages, emptyCaseFields, readCaseFields, type CaseFields } from "../lib/aadi/composer"; -import { requestAadiAnalysis } from "../lib/aadi/client"; +import { AadiRequestError, requestAadiAnalysis } from "../lib/aadi/client"; import { smooth } from "./smooth"; import { useMediaQuery, useToast, useWorkspacePersistence } from "./workspace-hooks"; import { WorkspaceUnlock } from "./workspace-unlock"; @@ -69,6 +69,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); // The question being analysed: shown at once as the user's message, saved only with its answer. const [pendingQuestion, setPendingQuestion] = useState(null); const [queuePosition, setQueuePosition] = useState(null); @@ -134,7 +136,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); // Like an answered analysis, the next case starts with an empty strip. resetCaseFields(); @@ -143,7 +145,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s async function analyzeMain(text: string, selectedMode: ModeId, current: Encounter) { if (analysisController.current) return; const controller = new AbortController(); analysisController.current = controller; - setBusy(true); setAnalysisError(""); pendingText.current = text.trim(); setPendingQuestion(text.trim()); setPrompt(""); + setBusy(true); setAnalysisError(""); setAnalysisNoMatch(false); pendingText.current = text.trim(); setPendingQuestion(text.trim()); setPrompt(""); // The home composer gives way to the chat composer; keep typing where the reader is. requestAnimationFrame(() => document.querySelector(".chat-composer textarea")?.focus()); try { @@ -154,7 +156,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s resetCaseFields(); dispatch({ type: "encounter.select", id: current.id }); } catch (error) { - if (!controller.signal.aborted) { setAnalysisError(error instanceof Error ? error.message : "Analisis belum tersedia. Keluhan tetap tersedia."); setPrompt(text); } + if (!controller.signal.aborted) { 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 (analysisController.current === controller) { analysisController.current = null; setBusy(false); setPendingQuestion(null); setQueuePosition(null); pendingText.current = null; } } @@ -198,7 +200,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 }; if (restoring) return

Membuka workspace…

; if (locked) return ; diff --git a/src/lib/aadi/gateway.ts b/src/lib/aadi/gateway.ts index f9a30e9..7e717dc 100644 --- a/src/lib/aadi/gateway.ts +++ b/src/lib/aadi/gateway.ts @@ -228,7 +228,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..412cfc2 100644 --- a/src/lib/theoracle-grounding.ts +++ b/src/lib/theoracle-grounding.ts @@ -21,6 +21,11 @@ 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. PROVISIONAL (2026-11-26): chosen without the private index; calibrate with `npm run benchmark:oracle` +// (its relevanceFloor section) on the real index before release. +export const THEORACLE_MIN_SIMILARITY = 0.3; 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 +39,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 +162,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 +174,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 +188,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 +248,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 +263,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-grounding.test.ts b/tests/theoracle-grounding.test.ts index 7420678..3ac433f 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, @@ -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.2, 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 9365f4f..fc127f2 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(); + }); +}); From 7bd2fe2a967bd65d9cdb2c093c50cb41bc81bd7e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:26:24 +0000 Subject: [PATCH 2/3] fix(theoracle): set provisional relevance floor to 0.20 from CI eval data The pinned model on the synthetic CI eval index scored the weakest on-topic case at 0.250 and the strongest off-topic query at 0.146; 0.30 would have rejected a genuine case. Still to be confirmed on the real index. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ta9C7XhCnabM5SwJLKnmU --- docs/architecture.md | 2 +- src/lib/theoracle-grounding.ts | 7 ++++--- tests/theoracle-grounding.test.ts | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 36c3df4..14d59ff 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,7 +73,7 @@ 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. A passage below the **relevance floor** (`THEORACLE_MIN_SIMILARITY`, cosine similarity, provisionally 0.30 since 2026-11-26 and not yet calibrated on the real index) 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). +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, provisionally 0.20 since 2026-11-26, set from the synthetic CI eval index and not yet confirmed on the real index) 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. 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. diff --git a/src/lib/theoracle-grounding.ts b/src/lib/theoracle-grounding.ts index 412cfc2..a333003 100644 --- a/src/lib/theoracle-grounding.ts +++ b/src/lib/theoracle-grounding.ts @@ -23,9 +23,10 @@ const THERAPY_QUERY = "\npenatalaksanaan terapi dosis obat"; 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. PROVISIONAL (2026-11-26): chosen without the private index; calibrate with `npm run benchmark:oracle` -// (its relevanceFloor section) on the real index before release. -export const THEORACLE_MIN_SIMILARITY = 0.3; +// analysis runs. PROVISIONAL (2026-11-26): set between the off-topic maximum (0.146) and the weakest on-topic case (0.250) +// measured with the pinned model on the synthetic CI eval index; confirm with `npm run benchmark:oracle` (its relevanceFloor +// section) on the real index before release. +export const THEORACLE_MIN_SIMILARITY = 0.2; 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 { diff --git a/tests/theoracle-grounding.test.ts b/tests/theoracle-grounding.test.ts index 3ac433f..6c50c11 100644 --- a/tests/theoracle-grounding.test.ts +++ b/tests/theoracle-grounding.test.ts @@ -26,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]), ]; @@ -138,7 +138,7 @@ describe("TheOracle vector grounding", () => { }); describe("relevance floor", () => { - // Query [1, 0, 0] against the fixture: A1 1.0, A2 0.994, B1 0.2, D1 0.0 (C1 and D2 fail the privacy filter). + // 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); From 349605913fdbca00db5fe4b8df87a26464685827 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:37:33 +0000 Subject: [PATCH 3/3] feat(theoracle): set relevance floor to 0.35 from the real-index benchmark Real index (88 on-topic, 8 off-topic queries): weakest on-topic 0.3725, strongest off-topic 0.2597; 0.40 rejects two on-topic queries. Floor chosen by Gaffer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ta9C7XhCnabM5SwJLKnmU --- docs/architecture.md | 2 +- src/lib/theoracle-grounding.ts | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 14d59ff..00e777f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,7 +73,7 @@ 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. A passage below the **relevance floor** (`THEORACLE_MIN_SIMILARITY`, cosine similarity, provisionally 0.20 since 2026-11-26, set from the synthetic CI eval index and not yet confirmed on the real index) 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). +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. 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. diff --git a/src/lib/theoracle-grounding.ts b/src/lib/theoracle-grounding.ts index a333003..4a8aaf4 100644 --- a/src/lib/theoracle-grounding.ts +++ b/src/lib/theoracle-grounding.ts @@ -23,10 +23,10 @@ const THERAPY_QUERY = "\npenatalaksanaan terapi dosis obat"; 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. PROVISIONAL (2026-11-26): set between the off-topic maximum (0.146) and the weakest on-topic case (0.250) -// measured with the pinned model on the synthetic CI eval index; confirm with `npm run benchmark:oracle` (its relevanceFloor -// section) on the real index before release. -export const THEORACLE_MIN_SIMILARITY = 0.2; +// 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 {