Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
6 changes: 3 additions & 3 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.

Expand All @@ -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

Expand Down
28 changes: 23 additions & 5 deletions scripts/benchmark-theoracle-grounding.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,33 +20,35 @@ 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;
const coldStart = performance.now();
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) });
Expand All @@ -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({
Expand All @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand Down
Loading
Loading