From 2811cfd6554c4a3bf28b3a193f738988da4a962b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:17:20 +0000 Subject: [PATCH 1/2] test(theoracle): public synthetic retrieval and evidence-gate eval for CI CI skipped every retrieval-quality test because the knowledge base is private. Add a synthetic corpus (31 passages, 16 documents) and case set (23 retrieval, 12 therapy-retrieval, 11 gate cases) under tests/fixtures/theoracle-eval/. Layer 1 runs the gate on each case's declared evidence, with no model. Layer 2 builds a temporary index with the production builder and the pinned EmbeddingGemma model, then scores recall@6/MRR, therapy dose recall, the privacy filter and the gate on what was actually retrieved. CI sets SENTRAPEDIA_ORACLE_EVAL=required so a missing model fails instead of skipping. build-theoracle-index.mjs gains --index-dir so the eval reuses the real builder. Known gap found by layer 1 (g08, it.fails): the tablet rule does not read a weight band written as a range ("BB 41-59 kg"), so that clause verifies a tablet count for any patient weight. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ta9C6s513KoCTM6zpyNXH --- .github/workflows/ci.yml | 3 + docs/testing.md | 30 ++- scripts/build-theoracle-index.mjs | 10 +- tests/fixtures/theoracle-eval/cases.json | 127 +++++++++++++ tests/fixtures/theoracle-eval/corpus.json | 212 ++++++++++++++++++++++ tests/scripts.node-test.mjs | 12 ++ tests/theoracle-eval.test.ts | 170 +++++++++++++++++ 7 files changed, 557 insertions(+), 7 deletions(-) create mode 100644 tests/fixtures/theoracle-eval/cases.json create mode 100644 tests/fixtures/theoracle-eval/corpus.json create mode 100644 tests/theoracle-eval.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7dacbe8..8b676f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,9 @@ jobs: timeout-minutes: 45 env: NEXT_TELEMETRY_DISABLED: "1" + # The public synthetic TheOracle eval (tests/theoracle-eval.test.ts) embeds its corpus with the pinned model that + # postinstall downloads; "required" makes a missing model fail the run instead of skipping the eval. + SENTRAPEDIA_ORACLE_EVAL: required steps: # LFS holds the site PNGs and the video and WebP media. The repository holds no private data (2026-11-18): # the tests that need the TheOracle index, the catalogue or the ICD-10 list skip, and the build runs on samples. diff --git a/docs/testing.md b/docs/testing.md index c1e4b05..546d7a7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -18,7 +18,7 @@ Tests import application code from `../src/`. `tests/theoracle-aadi.test.ts` rea | Layer | Runner and command | Files | Environment | | --- | --- | --- | --- | -| App tests | Vitest 5 (`vitest run`, the first half of `npm test`) | 42 `*.test.ts[x]` files in `tests/` and 17 in `tests/ui/` | Node by default; jsdom where a file starts with the `@vitest-environment` docblock (all of `tests/ui/`, plus a few others) | +| App tests | Vitest 5 (`vitest run`, the first half of `npm test`) | 43 `*.test.ts[x]` files in `tests/` and 17 in `tests/ui/` | Node by default; jsdom where a file starts with the `@vitest-environment` docblock (all of `tests/ui/`, plus a few others) | | System tests | `node --test`, `npm run test:system` | Nine `tests/*.node-test.mjs` files, named one by one in `package.json` | Plain Node; some build temporary capsules, local HTTP stubs or temporary git repositories | | Site tests | `npm --prefix apps/site test` (second half of `npm test`): builds the site, then `node --test` in `apps/site` | 8 files in `apps/site/tests/`, 13 `*.test.mjs` files in `apps/site/scripts/` | Built-in Node modules only | | Engine tests | `npm run test:aadi` runs `scripts/test-aadi.mjs`, which starts the venv Python on `aadi/test.py`, which runs pytest on `aadi/service/tests` | 9 files | Python 3.11 venv in `.runtime/aadi/venv`, model client always a fake | @@ -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`, `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 | | 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 | @@ -71,12 +71,34 @@ Static declaration counts (a text search for `it(`/`test(` and `def test_`, not Public code ships without the database (`docs/data.md`). Three skip mechanisms keep the suites green there: -1. Vitest: `tests/private-data.ts` exports `withCatalog` (true when the real catalog is installed) and `withIndex` (the manifest and `vectors.f32` both exist). Affected tests use `skipIf`: catalog tests in `theoracle-aadi`, `diagnosis-presentation` and `theoracle-evidence-gate`, and the real-index test in `theoracle-grounding`. +1. Vitest: `tests/private-data.ts` exports `withCatalog` (true when the real catalog is installed) and `withIndex` (the manifest and `vectors.f32` both exist). Affected tests use `skipIf`: catalog tests in `theoracle-aadi`, `diagnosis-presentation` and `theoracle-evidence-gate`, and the real-index test in `theoracle-grounding`. `theoracle-eval` needs no private data, only the public model, and runs in CI. 2. Node tests: `skip` options for the installed-index check, and the chunk-build tests when the SSOT or manifest is missing. 3. pytest: the Med Assist contract-copy test needs an environment variable pointing at that contract folder. Never paste database passages into tests, fixtures or documents. +## Public synthetic TheOracle eval + +`tests/theoracle-eval.test.ts` gives the public repository and CI a retrieval and evidence-gate eval without the private knowledge base. Its inputs are two fixtures written for it, never copied from the database: `tests/fixtures/theoracle-eval/corpus.json` (31 passages in 16 documents, all titled `SINTETIS ...`, including one off-topic document and one passage with a phone number that the privacy filter must drop) and `cases.json` (23 retrieval cases, 12 therapy-retrieval cases, 11 evidence-gate cases, the thresholds). The passages are not clinically reviewed; the eval measures retrieval and matching, not clinical correctness. + +- **Layer 1, no model** (runs everywhere): every gate case through `gateTherapy` with the evidence the case declares. Statuses, evidence ids and the shown tablet strength must match. +- **Layer 2, pinned model** (runs when `theoracle/model` holds the pinned EmbeddingGemma files): `scripts/build-theoracle-index.mjs --index-dir ` embeds the corpus with the production builder; the production retriever answers every case from that folder; the gate reads what was actually retrieved. In CI `SENTRAPEDIA_ORACLE_EVAL=required` turns a missing model into a failure instead of a skip. + +Acceptance criteria (thresholds live in `cases.json`; raise them as scores rise, never lower one without Gaffer's word): + +| Check | Criterion | +| --- | --- | +| Clinical-wording retrieval (15 cases) | gold document in the six passages for every case (recall@6 = 1), MRR >= 0.8 | +| Lay-wording retrieval (8 cases) | recall@6 >= 0.75 | +| Therapy retrieval | the diagnosis's dose passage reaches the therapy evidence for all 12 diagnoses | +| Privacy | the phone-number passage is never returned, even for a query written to match it | +| 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 thresholds are provisional until the first CI run with the model; this document's author could not run layer 2 (no access to the model host from the authoring environment). + ## What is not tested - **Live model calls and real engine answers.** Every model client is a fake. `aadi/service/smoke_live.py` is the manual path, costs money and needs Gaffer's approval. `eval-theoracle-pipeline.mjs` is also paid when pointed at a real server; its test uses a stub. @@ -85,7 +107,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 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. ## Running one file diff --git a/scripts/build-theoracle-index.mjs b/scripts/build-theoracle-index.mjs index 422d61b..5f5327b 100644 --- a/scripts/build-theoracle-index.mjs +++ b/scripts/build-theoracle-index.mjs @@ -1,12 +1,16 @@ // Embeds theoracle/index/chunks.jsonl with the pinned local model and writes vectors.f32 + manifest.json. -// Usage: node scripts/build-theoracle-index.mjs [--device cpu|dml] [--append]. Resumable after interruption. +// Usage: node scripts/build-theoracle-index.mjs [--device cpu|dml] [--append] [--index-dir ]. Resumable after interruption. // --append keeps the vectors of the existing rows and embeds only rows added to chunks.jsonl since the last build. +// --index-dir builds another folder's chunks.jsonl with the same model and code (the public synthetic eval, tests/theoracle-eval.test.ts). import { createHash } from "node:crypto"; import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { resolve, sep } from "node:path"; import { AutoModel, AutoTokenizer, env } from "@huggingface/transformers"; -import { fileSha256, indexDir, modelDir, profile } from "./theoracle-model.mjs"; +import { fileSha256, indexDir as defaultIndexDir, modelDir, profile } from "./theoracle-model.mjs"; -const device = process.argv.includes("--device") ? process.argv[process.argv.indexOf("--device") + 1] : "cpu"; +const option = name => process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : undefined; +const device = option("--device") ?? "cpu"; +const indexDir = option("--index-dir") ? resolve(option("--index-dir")) + sep : defaultIndexDir; env.allowRemoteModels = false; env.localModelPath = modelDir; for (const [name, expected] of Object.entries(profile.files)) { if (await fileSha256(`${modelDir}${profile.id}/${name}`) !== expected.sha256) throw new Error(`Model file ${name} does not match its pinned hash. Run node scripts/install-theoracle-model.mjs.`); diff --git a/tests/fixtures/theoracle-eval/cases.json b/tests/fixtures/theoracle-eval/cases.json new file mode 100644 index 0000000..3625059 --- /dev/null +++ b/tests/fixtures/theoracle-eval/cases.json @@ -0,0 +1,127 @@ +{ + "notice": "SYNTHETIC TEST FIXTURE. Invented consultations without patient identity, scored against corpus.json by tests/theoracle-eval.test.ts. Expected outcomes describe retrieval and evidence-gate behaviour, not clinical correctness.", + "thresholds": { + "note": "Provisional floors, calibrated on the first CI run with the pinned model. Raise them when the score rises; never lower one without Gaffer's word.", + "clinicalRecallAt6": 1, + "layRecallAt6": 0.75, + "clinicalMrr": 0.8, + "therapyDoseRecall": 1 + }, + "retrieval": [ + { "id": "r01", "category": "clinical", "query": "Demam menggigil dan berkeringat berkala setelah pulang dari Papua", "gold": "SINTETIS Malaria Falsiparum.md" }, + { "id": "r02", "category": "clinical", "query": "Demam tinggi mendadak hari ketiga, petekie dan uji torniket positif", "gold": "SINTETIS Demam Berdarah Dengue.md" }, + { "id": "r03", "category": "clinical", "query": "Demam naik bertahap terutama sore hari sejak 8 hari, lidah kotor", "gold": "SINTETIS Demam Tifoid.md" }, + { "id": "r04", "category": "clinical", "query": "Batuk berdahak, demam dan sesak napas, ronki basah di paru kanan", "gold": "SINTETIS Pneumonia Komunitas.md" }, + { "id": "r05", "category": "clinical", "query": "Batuk lebih dari dua minggu, keringat malam dan berat badan turun", "gold": "SINTETIS Tuberkulosis Paru.md" }, + { "id": "r06", "category": "clinical", "query": "Buang air besar cair 5 kali sehari sejak kemarin, mata cekung dan haus", "gold": "SINTETIS Diare Akut.md" }, + { "id": "r07", "category": "clinical", "query": "Tekanan darah 160/100 mmHg pada dua kunjungan, tengkuk terasa berat", "gold": "SINTETIS Hipertensi Esensial.md" }, + { "id": "r08", "category": "clinical", "query": "Sering haus dan sering buang air kecil, gula darah puasa 180 mg/dL", "gold": "SINTETIS Diabetes Melitus Tipe 2.md" }, + { "id": "r09", "category": "clinical", "query": "Sesak napas berulang dengan mengi, memburuk malam hari", "gold": "SINTETIS Asma.md" }, + { "id": "r10", "category": "clinical", "query": "Nyeri saat berkemih dan sering berkemih sedikit-sedikit, tidak demam", "gold": "SINTETIS Sistitis.md" }, + { "id": "r11", "category": "clinical", "query": "Nyeri ulu hati, kembung dan mual setelah terlambat makan", "gold": "SINTETIS Gastritis.md" }, + { "id": "r12", "category": "clinical", "query": "Gatal hebat malam hari di sela jari tangan, teman sekamar juga gatal", "gold": "SINTETIS Skabies.md" }, + { "id": "r13", "category": "clinical", "query": "Nyeri tenggorokan dan nyeri menelan, demam, faring hiperemis", "gold": "SINTETIS Faringitis Akut.md" }, + { "id": "r14", "category": "clinical", "query": "Nyeri kepala sebelah berdenyut dengan mual dan silau terhadap cahaya", "gold": "SINTETIS Migrain.md" }, + { + "id": "r15", + "category": "clinical", + "query": "Demam hari keempat", + "case": { "anamnesis": { "freeText": "Mimisan dan gusi berdarah sejak tadi pagi." }, "physicalExam": ["Petekie di lengan"], "results": [{ "name": "Trombosit", "value": "85000" }, { "name": "Hematokrit", "value": "48" }] }, + "gold": "SINTETIS Demam Berdarah Dengue.md" + }, + { "id": "l01", "category": "lay", "query": "Panas dingin naik turun, baru pulang kerja dari Timika", "gold": "SINTETIS Malaria Falsiparum.md" }, + { "id": "l02", "category": "lay", "query": "Mencret terus dari kemarin, badan lemas", "gold": "SINTETIS Diare Akut.md" }, + { "id": "l03", "category": "lay", "query": "Anyang-anyangan dan perih waktu pipis", "gold": "SINTETIS Sistitis.md" }, + { "id": "l04", "category": "lay", "query": "Maag kambuh, perut perih kalau telat makan", "gold": "SINTETIS Gastritis.md" }, + { "id": "l05", "category": "lay", "query": "Napas bunyi ngik-ngik kalau kena debu", "gold": "SINTETIS Asma.md" }, + { "id": "l06", "category": "lay", "query": "Kudisan, gatal sekali kalau malam", "gold": "SINTETIS Skabies.md" }, + { "id": "l07", "category": "lay", "query": "Batuk lama tidak sembuh-sembuh, sering keringatan malam", "gold": "SINTETIS Tuberkulosis Paru.md" }, + { "id": "l08", "category": "lay", "query": "Bintik merah di kulit, panas tinggi, gusi berdarah", "gold": "SINTETIS Demam Berdarah Dengue.md" } + ], + "therapy": [ + { "id": "t01", "diagnosis": { "icd10": "B50.9", "label": "Malaria falsiparum" }, "dosePassage": "mal-3" }, + { "id": "t02", "diagnosis": { "icd10": "A91", "label": "Demam berdarah dengue" }, "dosePassage": "dbd-3" }, + { "id": "t03", "diagnosis": { "icd10": "A01.0", "label": "Demam tifoid" }, "dosePassage": "tif-2" }, + { "id": "t04", "diagnosis": { "icd10": "J18.9", "label": "Pneumonia komunitas" }, "dosePassage": "pne-2" }, + { "id": "t05", "diagnosis": { "icd10": "A09", "label": "Diare akut" }, "dosePassage": "dia-2" }, + { "id": "t06", "diagnosis": { "icd10": "I10", "label": "Hipertensi esensial" }, "dosePassage": "htn-2" }, + { "id": "t07", "diagnosis": { "icd10": "E11.9", "label": "Diabetes melitus tipe 2" }, "dosePassage": "dm-2" }, + { "id": "t08", "diagnosis": { "icd10": "J45.9", "label": "Asma" }, "dosePassage": "asm-2" }, + { "id": "t09", "diagnosis": { "icd10": "N30.0", "label": "Sistitis" }, "dosePassage": "isk-2" }, + { "id": "t10", "diagnosis": { "icd10": "K29.7", "label": "Gastritis" }, "dosePassage": "gas-2" }, + { "id": "t11", "diagnosis": { "icd10": "B86", "label": "Skabies" }, "dosePassage": "ska-2" }, + { "id": "t12", "diagnosis": { "icd10": "G43.9", "label": "Migrain" }, "dosePassage": "mig-2" } + ], + "gate": [ + { + "id": "g01", "about": "a dose the passage states is verified", + "query": "Batuk berdahak, demam dan sesak napas", "diagnosis": { "icd10": "J18.9", "label": "Pneumonia komunitas" }, "evidence": ["pne-1", "pne-2"], + "regimen": [{ "drug": "Amoksisilin", "dose": "3 x 500 mg", "route": "PO", "duration": "5 hari", "note": "" }], + "expected": [{ "status": "verified", "evidence": ["pne-2"] }] + }, + { + "id": "g02", "about": "a dose the passage does not state is removed, the drug stays", + "query": "Batuk berdahak, demam dan sesak napas", "diagnosis": { "icd10": "J18.9", "label": "Pneumonia komunitas" }, "evidence": ["pne-1", "pne-2"], + "regimen": [{ "drug": "Amoksisilin", "dose": "3 x 1000 mg", "route": "PO", "duration": "5 hari", "note": "" }], + "expected": [{ "status": "doseRemoved" }] + }, + { + "id": "g03", "about": "a drug no passage names is removed", + "query": "Batuk berdahak, demam dan sesak napas", "diagnosis": { "icd10": "J18.9", "label": "Pneumonia komunitas" }, "evidence": ["pne-1", "pne-2"], + "regimen": [{ "drug": "Levofloksasin", "dose": "1 x 750 mg", "route": "PO", "duration": "5 hari", "note": "" }], + "expected": [{ "status": "removed" }] + }, + { + "id": "g04", "about": "a single strength inside the passage's range is verified", + "query": "Tekanan darah 160/100 mmHg, tengkuk berat", "diagnosis": { "icd10": "I10", "label": "Hipertensi esensial" }, "evidence": ["htn-1", "htn-2"], + "regimen": [{ "drug": "Amlodipin", "dose": "1 x 5 mg", "route": "PO", "duration": "", "note": "" }], + "expected": [{ "status": "verified", "evidence": ["htn-2"] }] + }, + { + "id": "g05", "about": "a strength above the passage's range is removed", + "query": "Tekanan darah 160/100 mmHg, tengkuk berat", "diagnosis": { "icd10": "I10", "label": "Hipertensi esensial" }, "evidence": ["htn-1", "htn-2"], + "regimen": [{ "drug": "Amlodipin", "dose": "1 x 20 mg", "route": "PO", "duration": "", "note": "" }], + "expected": [{ "status": "doseRemoved" }] + }, + { + "id": "g06", "about": "a laboratory value is never a dose, the drug's own strength is", + "query": "Sering haus, sering buang air kecil, gula darah puasa 180 mg/dL", "diagnosis": { "icd10": "E11.9", "label": "Diabetes melitus tipe 2" }, "evidence": ["dm-1", "dm-2"], + "regimen": [{ "drug": "Metformin", "dose": "2 x 500 mg", "route": "PO", "duration": "", "note": "sesudah makan" }, { "drug": "Metformin", "dose": "1 x 126 mg", "route": "PO", "duration": "", "note": "" }], + "expected": [{ "status": "verified", "evidence": ["dm-2"] }, { "status": "doseRemoved" }] + }, + { + "id": "g07", "about": "a tablet count with its weight band is verified and shown with the strength per tablet", + "query": "Demam menggigil berkala setelah pulang dari Papua", "diagnosis": { "icd10": "B50.9", "label": "Malaria falsiparum" }, "evidence": ["mal-1", "mal-3"], + "regimen": [{ "drug": "Dihidroartemisinin + Piperakuin", "dose": "1x4tablet", "route": "PO", "duration": "3 hari", "note": "dosis untuk berat badan >60kg" }], + "expected": [{ "status": "verified", "evidence": ["mal-3"], "shown": { "drug": "Dihidroartemisinin 40 mg + Piperakuin 320 mg", "dose": "4 tablet sekali sehari" } }] + }, + { + "id": "g08", "about": "the other weight band's count is not verified", + "query": "Demam menggigil berkala setelah pulang dari Papua", "diagnosis": { "icd10": "B50.9", "label": "Malaria falsiparum" }, "evidence": ["mal-1", "mal-3"], + "regimen": [{ "drug": "Dihidroartemisinin + Piperakuin", "dose": "1x3tablet", "route": "PO", "duration": "3 hari", "note": "dosis untuk berat badan >60kg" }], + "expected": [{ "status": "doseRemoved" }], + "knownGap": "Found by this eval on 2026-11-26: the tablet rule reads a weight band only as one number before kg (BB 60 kg), not as a range (BB 41-59 kg), so the 3-tablet clause counts as having no weight band and verifies for any weight. Runs as an expected failure until the gate is fixed." + }, + { + "id": "g09", "about": "a dose from another disease's passage does not verify", + "query": "Batuk berdahak, demam dan sesak napas", "diagnosis": { "icd10": "J18.9", "label": "Pneumonia komunitas" }, "evidence": ["pne-1", "pne-2", "gas-2"], + "regimen": [{ "drug": "Omeprazol", "dose": "1 x 20 mg", "route": "PO", "duration": "", "note": "" }], + "expected": [{ "status": "doseRemoved" }], + "retrievalDependent": true + }, + { + "id": "g10", "about": "therapy written for another diagnosis is removed whole", + "query": "Batuk berdahak, demam dan sesak napas", "diagnosis": { "icd10": "J18.9", "label": "Pneumonia komunitas" }, "forDiagnosis": { "icd10": "A15.0", "label": "Tuberkulosis paru" }, "evidence": ["pne-1", "pne-2"], + "regimen": [{ "drug": "Amoksisilin", "dose": "3 x 500 mg", "route": "PO", "duration": "5 hari", "note": "" }], + "expected": [{ "status": "removed" }] + }, + { + "id": "g11", "about": "a percent concentration is a dose", + "query": "Gatal hebat malam hari di sela jari tangan", "diagnosis": { "icd10": "B86", "label": "Skabies" }, "evidence": ["ska-1", "ska-2"], + "regimen": [{ "drug": "Permetrin krim", "dose": "5%", "route": "topikal", "duration": "diulang setelah 1 minggu", "note": "" }, { "drug": "Permetrin krim", "dose": "10%", "route": "topikal", "duration": "", "note": "" }], + "expected": [{ "status": "verified", "evidence": ["ska-2"] }, { "status": "doseRemoved" }] + } + ], + "privacy": { "trap": "kon-1", "queries": ["Konsultasi pneumonia dan batuk lama, minta nomor dokter jaga", "Batuk lama dan tuberkulosis paru"] }, + "outOfDomain": ["Harga tiket pesawat Jakarta Surabaya bulan depan", "Resep rendang daging sapi"] +} diff --git a/tests/fixtures/theoracle-eval/corpus.json b/tests/fixtures/theoracle-eval/corpus.json new file mode 100644 index 0000000..64c5aa2 --- /dev/null +++ b/tests/fixtures/theoracle-eval/corpus.json @@ -0,0 +1,212 @@ +{ + "notice": "SYNTHETIC TEST FIXTURE. Every passage was written for the public TheOracle retrieval and evidence-gate eval (tests/theoracle-eval.test.ts). It is not taken from the private knowledge base, is not clinically reviewed and must never be served as clinical guidance. Doses are only there so the evidence gate has something to match.", + "docSource": "Sentrapedia synthetic eval fixture", + "origin": "synthetic-eval", + "published": "26/11/2026", + "documents": [ + { + "title": "SINTETIS Malaria Falsiparum.md", + "passages": [ + { + "id": "mal-1", + "text": "Malaria falsiparum ditandai demam tinggi yang disertai menggigil dan berkeringat secara berkala, sakit kepala, nyeri otot dan mual. Tanyakan riwayat tinggal atau bepergian ke daerah endemis malaria seperti Papua dan Nusa Tenggara Timur dalam satu bulan terakhir." + }, + { + "id": "mal-2", + "text": "Diagnosis malaria ditegakkan dengan pemeriksaan mikroskopis apusan darah tebal dan tipis atau tes diagnostik cepat (RDT). Waspadai malaria berat bila terdapat penurunan kesadaran, anemia berat, ikterus atau syok." + }, + { + "id": "mal-3", + "text": "Terapi malaria falsiparum tanpa komplikasi adalah dihidroartemisinin + piperakuin (DHP) selama 3 hari; tiap tablet mengandung 40 mg dihidroartemisinin dan 320 mg piperakuin. Dewasa BB 41-59 kg minum 3 tablet DHP sekali sehari; BB 60 kg atau lebih minum 4 tablet DHP sekali sehari. Pada hari pertama ditambahkan primakuin 0,25 mg/kgBB dosis tunggal." + } + ] + }, + { + "title": "SINTETIS Demam Berdarah Dengue.md", + "passages": [ + { + "id": "dbd-1", + "text": "Demam berdarah dengue diawali demam tinggi mendadak selama 2 sampai 7 hari disertai nyeri kepala, nyeri belakang bola mata, nyeri otot dan sendi. Dapat ditemukan bintik perdarahan (petekie), mimisan, gusi berdarah dan uji torniket positif." + }, + { + "id": "dbd-2", + "text": "Pemeriksaan darah pada demam berdarah dengue menunjukkan trombositopenia dan peningkatan hematokrit akibat kebocoran plasma. Tanda bahaya meliputi nyeri perut hebat, muntah terus-menerus, perdarahan mukosa dan gelisah; pasien dengan tanda bahaya dirawat inap." + }, + { + "id": "dbd-3", + "text": "Tatalaksana demam berdarah dengue bersifat suportif dengan cukup cairan oral atau infus kristaloid sesuai derajat kebocoran plasma. Untuk demam diberikan parasetamol 500 mg 3-4 kali sehari pada dewasa. Hindari aspirin dan ibuprofen karena meningkatkan risiko perdarahan." + } + ] + }, + { + "title": "SINTETIS Demam Tifoid.md", + "passages": [ + { + "id": "tif-1", + "text": "Demam tifoid ditandai demam yang naik bertahap terutama sore dan malam hari selama lebih dari satu minggu, disertai nyeri perut, sembelit atau diare, lidah kotor dengan tepi kemerahan dan bradikardia relatif." + }, + { + "id": "tif-2", + "text": "Terapi demam tifoid dewasa adalah kloramfenikol 4 x 500 mg per oral selama 14 hari. Alternatif yang dapat dipakai adalah seftriakson 2 g intravena sekali sehari selama 5 hari." + } + ] + }, + { + "title": "SINTETIS Pneumonia Komunitas.md", + "passages": [ + { + "id": "pne-1", + "text": "Pneumonia komunitas ditandai batuk berdahak, demam, sesak napas dan nyeri dada saat menarik napas. Pada pemeriksaan fisik ditemukan napas cepat dan ronki basah; foto toraks menunjukkan infiltrat." + }, + { + "id": "pne-2", + "text": "Terapi pneumonia komunitas rawat jalan pada dewasa tanpa komorbid adalah amoksisilin 3 x 500 mg per oral selama 5 hari. Evaluasi ulang setelah 48 sampai 72 jam; rujuk bila saturasi oksigen menurun atau napas makin cepat." + } + ] + }, + { + "title": "SINTETIS Tuberkulosis Paru.md", + "passages": [ + { + "id": "tb-1", + "text": "Tuberkulosis paru dicurigai pada batuk berdahak lebih dari dua minggu, kadang berdahak darah, disertai keringat malam tanpa aktivitas, demam ringan, nafsu makan turun dan berat badan menurun." + }, + { + "id": "tb-2", + "text": "Diagnosis tuberkulosis paru memakai tes cepat molekuler (TCM) dahak atau pemeriksaan mikroskopis BTA. Kontak serumah pasien tuberkulosis diperiksa untuk penemuan kasus aktif." + } + ] + }, + { + "title": "SINTETIS Diare Akut.md", + "passages": [ + { + "id": "dia-1", + "text": "Diare akut adalah buang air besar cair lebih dari tiga kali sehari yang berlangsung kurang dari 14 hari. Nilai derajat dehidrasi dari kesadaran, mata cekung, rasa haus dan turgor kulit." + }, + { + "id": "dia-2", + "text": "Tatalaksana diare akut pada anak adalah oralit setiap kali buang air besar cair dan zinc 20 mg sekali sehari selama 10 hari untuk anak usia 6 bulan ke atas. ASI dan makanan tetap diberikan." + } + ] + }, + { + "title": "SINTETIS Hipertensi Esensial.md", + "passages": [ + { + "id": "htn-1", + "text": "Hipertensi ditegakkan bila tekanan darah sistolik 140 mmHg atau lebih atau diastolik 90 mmHg atau lebih pada dua kali kunjungan. Sebagian besar pasien tanpa keluhan; sebagian mengeluh pusing atau tengkuk terasa berat." + }, + { + "id": "htn-2", + "text": "Terapi awal hipertensi esensial pada dewasa dapat memakai amlodipin 5-10 mg sekali sehari per oral, disertai pembatasan garam, aktivitas fisik dan penurunan berat badan." + } + ] + }, + { + "title": "SINTETIS Diabetes Melitus Tipe 2.md", + "passages": [ + { + "id": "dm-1", + "text": "Diabetes melitus tipe 2 dicurigai pada keluhan sering buang air kecil, sering haus, sering lapar dan berat badan turun. Diagnosis ditegakkan bila gula darah puasa 126 mg/dL atau lebih, atau HbA1c 6,5% atau lebih." + }, + { + "id": "dm-2", + "text": "Terapi farmakologis awal diabetes melitus tipe 2 adalah metformin 500 mg 2-3 kali sehari sesudah makan, dinaikkan bertahap sesuai toleransi, bersama pengaturan makan dan aktivitas fisik." + } + ] + }, + { + "title": "SINTETIS Asma.md", + "passages": [ + { + "id": "asm-1", + "text": "Asma ditandai sesak napas berulang dengan bunyi mengi, dada terasa berat dan batuk yang memburuk pada malam hari atau setelah terpapar debu, asap atau udara dingin." + }, + { + "id": "asm-2", + "text": "Serangan asma ringan sampai sedang diatasi dengan salbutamol inhalasi 2-4 puff setiap 20 menit pada jam pertama. Nilai ulang respons; rujuk bila tidak membaik." + } + ] + }, + { + "title": "SINTETIS Sistitis.md", + "passages": [ + { + "id": "isk-1", + "text": "Sistitis atau infeksi saluran kemih bawah ditandai nyeri saat berkemih, sering berkemih sedikit-sedikit (anyang-anyangan), rasa tidak tuntas dan nyeri perut bawah, tanpa demam tinggi." + }, + { + "id": "isk-2", + "text": "Terapi sistitis tanpa komplikasi pada wanita dewasa adalah nitrofurantoin 2 x 100 mg per oral selama 5 hari. Anjurkan minum air yang cukup." + } + ] + }, + { + "title": "SINTETIS Gastritis.md", + "passages": [ + { + "id": "gas-1", + "text": "Gastritis dan dispepsia ditandai nyeri atau perih di ulu hati, perut kembung, mual dan cepat kenyang, sering kambuh saat terlambat makan atau setelah makanan pedas." + }, + { + "id": "gas-2", + "text": "Terapi gastritis adalah omeprazol 20 mg sekali sehari sebelum makan pagi selama 2 sampai 4 minggu, disertai makan teratur dan menghindari makanan pemicu." + } + ] + }, + { + "title": "SINTETIS Skabies.md", + "passages": [ + { + "id": "ska-1", + "text": "Skabies ditandai gatal hebat terutama pada malam hari, papul dan terowongan kecil di sela jari tangan, pergelangan tangan, ketiak dan lipat paha. Keluhan serupa sering dialami anggota keluarga atau teman sekamar di pesantren." + }, + { + "id": "ska-2", + "text": "Terapi skabies adalah permetrin krim 5% dioleskan ke seluruh tubuh dari leher ke bawah, dibiarkan 8 sampai 12 jam lalu dibilas, dan diulang setelah satu minggu. Seluruh anggota keluarga diobati bersamaan." + } + ] + }, + { + "title": "SINTETIS Faringitis Akut.md", + "passages": [ + { + "id": "far-1", + "text": "Faringitis akut ditandai nyeri tenggorokan dan nyeri menelan, demam, faring hiperemis dan pembesaran amandel. Sebagian besar disebabkan virus dan sembuh sendiri." + } + ] + }, + { + "title": "SINTETIS Migrain.md", + "passages": [ + { + "id": "mig-1", + "text": "Migrain ditandai nyeri kepala sebelah yang berdenyut selama 4 sampai 72 jam, memburuk dengan aktivitas, disertai mual, muntah dan silau terhadap cahaya atau suara." + }, + { + "id": "mig-2", + "text": "Serangan migrain ringan diobati dengan ibuprofen 400 mg per oral saat serangan, dapat diulang setelah 6 jam, istirahat di ruangan gelap dan tenang." + } + ] + }, + { + "title": "SINTETIS Administrasi Puskesmas.md", + "passages": [ + { + "id": "adm-1", + "text": "Jadwal pelayanan poli umum Senin sampai Sabtu pukul 08.00 sampai 14.00. Pendaftaran pasien BPJS memakai kartu peserta dan surat rujukan dari fasilitas kesehatan tingkat pertama." + } + ] + }, + { + "title": "SINTETIS Kontak Konsultasi.md", + "passages": [ + { + "id": "kon-1", + "text": "Konsultasi kasus pneumonia, batuk lama dan tuberkulosis paru dapat menghubungi dokter jaga di nomor 081234567890 setiap hari kerja." + } + ] + } + ] +} diff --git a/tests/scripts.node-test.mjs b/tests/scripts.node-test.mjs index 4cae373..0d4d366 100644 --- a/tests/scripts.node-test.mjs +++ b/tests/scripts.node-test.mjs @@ -256,6 +256,18 @@ test("an interrupted index build resumes from its partial vectors and embeds onl assert.ok(!existsSync(join(root, "theoracle/index/vectors.partial.f32")) && !existsSync(join(root, "theoracle/index/vectors.partial.json"))); })); +test("index build --index-dir builds another folder's chunks and leaves theoracle/index alone", withCapsule("index-dir", async root => { + indexFixture(root, ["one"]); + const other = join(root, "eval-index"); + write(root, "eval-index/chunks.jsonl", ["alpha", "beta"].map(text => JSON.stringify({ id: text, text })).join("\n") + "\n"); + const { code, stderr } = await run(join(root, "scripts/build-theoracle-index.mjs"), ["--index-dir", other]); + assert.equal(code, 0, stderr); + const manifest = JSON.parse(readFileSync(join(other, "manifest.json"), "utf8")); + assert.equal(manifest.chunks.count, 2); + assert.equal(manifest.vectors.sha256, sha(readFileSync(join(other, "vectors.f32")))); + assert.ok(!existsSync(join(root, "theoracle/index/vectors.f32")) && !existsSync(join(root, "theoracle/index/manifest.json"))); +})); + test("index build refuses a model file that does not match its pinned hash and writes nothing", withCapsule("index-model", async root => { indexFixture(root, ["one"]); writeFileSync(join(root, "theoracle/model/stub/model/config.json"), "changed"); diff --git a/tests/theoracle-eval.test.ts b/tests/theoracle-eval.test.ts new file mode 100644 index 0000000..2dfbd1a --- /dev/null +++ b/tests/theoracle-eval.test.ts @@ -0,0 +1,170 @@ +// Public, reproducible TheOracle eval: a synthetic corpus and case set (tests/fixtures/theoracle-eval/) that CI can run on +// every pull request, because the real knowledge base is private and its tests skip in the public repository. +// Two layers: +// 1. Evidence gate on the case set with the evidence each case declares. No model; runs everywhere. +// 2. The production index builder embeds the synthetic corpus with the pinned EmbeddingGemma model into a temporary +// folder; the production retriever answers every case from it and the gate reads what was retrieved. Needs the model +// that postinstall downloads. SENTRAPEDIA_ORACLE_EVAL=required (CI) turns a missing model into a failure, not a skip. +// The passages are invented and not clinically reviewed: this measures retrieval and matching, never clinical correctness. +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { emptyCase, type AadiTherapy } from "../src/lib/aadi/contract"; +import type { CaseState } from "../src/lib/aadi/types"; +import { gateEvidence, gateTherapy } from "../src/lib/theoracle-evidence-gate"; +import { retrieveTheOracleGrounding, retrieveTheOracleTherapyGrounding, type TheOracleGroundingBundle, type TheOracleManifest } from "../src/lib/theoracle-grounding"; +import { validTheOracleGrounding } from "../src/lib/theoracle-grounding-types"; +import { modelDir, profile } from "../scripts/theoracle-model.mjs"; +import corpus from "./fixtures/theoracle-eval/corpus.json"; +import cases from "./fixtures/theoracle-eval/cases.json"; + +// `knownGap` marks a case the current gate gets wrong: it runs as an expected failure (it.fails), so CI stays green while the +// gap is open and turns red the day it is fixed, when the marker must go. +type GateCase = (typeof cases.gate)[number] & { forDiagnosis?: { icd10: string; label: string }; retrievalDependent?: boolean; knownGap?: string }; +type Expected = { status: string; evidence?: string[]; shown?: { drug: string; dose: string } }; + +const sha256 = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex"); +// The same header the production chunk build writes (scripts/build-theoracle-chunks.mjs); retrieval strips it from the evidence. +const passages = corpus.documents.flatMap(doc => doc.passages.map(passage => { + const text = `\nsourceDocument: ${doc.title}\npublished: ${corpus.published}\n\n\n${passage.text}`; + return { id: passage.id, title: doc.title, docSource: corpus.docSource, origin: corpus.origin, text, textSha256: sha256(text), body: passage.text }; +})); +const byId = new Map(passages.map(p => [p.id, p])); +const titles = new Set(corpus.documents.map(doc => doc.title)); +const gateCases = cases.gate as GateCase[]; + +const caseFor = (item: { query: string; case?: Partial> }): CaseState => ({ ...emptyCase(), chiefComplaint: item.query, ...(item.case as Partial | undefined) }); +const therapyFor = (item: GateCase): AadiTherapy => ({ forDiagnosis: item.forDiagnosis ?? item.diagnosis, regimen: item.regimen, interactions: [], contraindications: [] }); +const declaredBundle = (ids: string[]): TheOracleGroundingBundle => ({ + version: "theoracle-grounding-v2", + corpus: { name: "TheOracle", indexSha256: "e".repeat(64), embeddingModel: { id: profile.id, revision: profile.revision, dtype: profile.dtype, dims: profile.dims }, retrievedAt: "2026-11-26T00:00:00.000Z", reviewProvenance: "Synthetic eval fixture." }, + queryDigest: "f".repeat(64), + evidence: ids.map((id, index) => { const p = byId.get(id)!; return { evidenceId: p.id, text: p.body, retrievalRank: index + 1, similarity: 0.5, source: { title: p.title, docSource: p.docSource, origin: p.origin, textSha256: p.textSha256 } }; }), +}); +function checkGate(item: GateCase, bundle: TheOracleGroundingBundle, withEvidence: boolean) { + const { therapy, report } = gateTherapy(therapyFor(item), bundle, item.diagnosis); + const expected = item.expected as Expected[]; + expect(report.drugs.map(d => d.status), `${item.id}: ${item.about}`).toEqual(expected.map(e => e.status)); + expected.forEach((e, i) => { + if (withEvidence && e.evidence) expect(report.drugs[i].evidenceIds, `${item.id} evidence`).toEqual(e.evidence); + if (e.shown) expect(therapy?.regimen[i], `${item.id} shown`).toMatchObject(e.shown); + }); +} + +describe("TheOracle synthetic eval set", () => { + it("is self-consistent: unique passage ids, every gold title and passage exists, every passage marked synthetic", () => { + expect(byId.size).toBe(passages.length); + expect(corpus.documents.every(doc => doc.title.startsWith("SINTETIS "))).toBe(true); + for (const item of cases.retrieval) expect(titles.has(item.gold), item.id).toBe(true); + for (const item of cases.therapy) expect(byId.has(item.dosePassage), item.id).toBe(true); + for (const item of gateCases) expect(item.evidence.every(id => byId.has(id)), item.id).toBe(true); + expect(byId.has(cases.privacy.trap)).toBe(true); + expect(new Set([...cases.retrieval, ...cases.therapy, ...gateCases].map(item => item.id)).size).toBe(cases.retrieval.length + cases.therapy.length + gateCases.length); + }); +}); + +describe("evidence gate on the synthetic case set, with each case's declared evidence", () => { + for (const item of gateCases) (item.knownGap ? it.fails : it)(`${item.id}: ${item.about}${item.knownGap ? " (known gap)" : ""}`, () => checkGate(item, declaredBundle(item.evidence), true)); +}); + +// Layer 2: the pinned model. Present when postinstall downloaded it (CI caches it); the hashes are checked by the builder +// and by the retriever's own loader, so a size check is enough to decide whether to run. +const modelReady = Object.entries(profile.files).every(([name, file]) => { const target = path.join(modelDir, profile.id, name); return existsSync(target) && statSync(target).size === file.size; }); +const required = process.env.SENTRAPEDIA_ORACLE_EVAL === "required"; + +it.runIf(required && !modelReady)("has the pinned embedding model that SENTRAPEDIA_ORACLE_EVAL=required asks for", () => { + expect.fail(`The TheOracle model is missing from ${modelDir}; run node scripts/install-theoracle-model.mjs.`); +}); + +describe.runIf(modelReady)("TheOracle retrieval on the synthetic index with the pinned model", () => { + let indexDir = ""; + 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; + + beforeAll(() => { + indexDir = mkdtempSync(path.join(tmpdir(), "sentrapedia-theoracle-eval-")); + writeFileSync(path.join(indexDir, "chunks.jsonl"), passages.map(({ id, title, docSource, origin, text, textSha256 }) => JSON.stringify({ id, title, docSource, origin, text, textSha256 })).join("\n") + "\n"); + const started = performance.now(); + const build = spawnSync(process.execPath, ["scripts/build-theoracle-index.mjs", "--index-dir", indexDir], { encoding: "utf8" }); + if (build.status !== 0) throw new Error(`Index build failed (${build.status}): ${build.stderr}`); + report.indexBuildMs = Math.round(performance.now() - started); + }, 600_000); + + afterAll(() => { + if (indexDir) rmSync(indexDir, { recursive: true, force: true }); + const out = path.resolve("node_modules/.cache/theoracle-eval"); + mkdirSync(out, { recursive: true }); + writeFileSync(path.join(out, "report.json"), JSON.stringify(report, null, 2) + "\n"); + console.log(`TheOracle synthetic eval: ${JSON.stringify(report.summary ?? report)}`); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### TheOracle synthetic eval\n\n\`\`\`json\n${JSON.stringify(report.summary ?? report, null, 2)}\n\`\`\`\n`); + }); + + it("builds the index with the production builder and the pinned model, and retrieves a valid bundle from it", async () => { + 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 }); + expect(validTheOracleGrounding(bundle)).toBe(true); + expect(bundle.corpus.indexSha256).toBe(manifest.indexSha256); + }, 300_000); + + it("finds each case's gold document in the evidence the model receives (recall@6, MRR)", async () => { + 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 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) }); + } + const score = (category: string) => { + const group = rows.filter(r => r.category === category); + return { recallAt6: rate(group.filter(r => r.rank > 0).length, group.length), mrr: Math.round(group.reduce((sum, r) => sum + (r.rank ? 1 / r.rank : 0), 0) / group.length * 1000) / 1000, missed: group.filter(r => !r.rank).map(r => r.id) }; + }; + const clinical = score("clinical"), lay = score("lay"); + report.retrieval = { clinical, lay, rows }; + report.summary = { ...(report.summary as object), clinical: { recallAt6: clinical.recallAt6, mrr: clinical.mrr, missed: clinical.missed }, lay: { recallAt6: lay.recallAt6, mrr: lay.mrr, missed: lay.missed } }; + expect(clinical.recallAt6, `clinical misses: ${clinical.missed.join(", ")}`).toBeGreaterThanOrEqual(cases.thresholds.clinicalRecallAt6); + expect(clinical.mrr).toBeGreaterThanOrEqual(cases.thresholds.clinicalMrr); + expect(lay.recallAt6, `lay misses: ${lay.missed.join(", ")}`).toBeGreaterThanOrEqual(cases.thresholds.layRecallAt6); + }, 300_000); + + 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 }); + 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); + report.therapy = { doseRecall, rows }; + report.summary = { ...(report.summary as object), therapyDoseRecall: doseRecall }; + expect(doseRecall, `missed: ${rows.filter(r => !r.hit).map(r => r.id).join(", ")}`).toBeGreaterThanOrEqual(cases.thresholds.therapyDoseRecall); + }, 300_000); + + 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); + expect(ids).not.toContain(cases.privacy.trap); + } + }, 300_000); + + // 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 }); + 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 () => { + const offTopic: { query: string; topSimilarity: number }[] = []; + for (const query of cases.outOfDomain) offTopic.push({ query, topSimilarity: (await retrieveTheOracleGrounding(caseFor({ query }), { indexDir })).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; + }, 300_000); +}); From 6bc2a31182c46e03e2717b69df3106548937a8b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:24:49 +0000 Subject: [PATCH 2/2] test(theoracle): calibrate synthetic eval thresholds on the first CI run Run 45874985015: clinical recall@6 1 / MRR 1, lay recall@6 1 / MRR 0.938, therapy dose recall 1. Lay recall floor 0.75 -> 1, clinical MRR 0.8 -> 0.9. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ta9C6s513KoCTM6zpyNXH --- docs/testing.md | 6 +++--- tests/fixtures/theoracle-eval/cases.json | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/testing.md b/docs/testing.md index 546d7a7..9f1d3bd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -88,8 +88,8 @@ Acceptance criteria (thresholds live in `cases.json`; raise them as scores rise, | Check | Criterion | | --- | --- | -| Clinical-wording retrieval (15 cases) | gold document in the six passages for every case (recall@6 = 1), MRR >= 0.8 | -| Lay-wording retrieval (8 cases) | recall@6 >= 0.75 | +| Clinical-wording retrieval (15 cases) | gold document in the six passages for every case (recall@6 = 1), MRR >= 0.9 | +| Lay-wording retrieval (8 cases) | recall@6 = 1 | | Therapy retrieval | the diagnosis's dose passage reaches the therapy evidence for all 12 diagnoses | | Privacy | the phone-number passage is never returned, even for a query written to match it | | Evidence gate | every case gets its expected status, in layer 1 with declared evidence and in layer 2 with retrieved evidence | @@ -97,7 +97,7 @@ Acceptance criteria (thresholds live in `cases.json`; raise them as scores rise, 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 thresholds are provisional until the first CI run with the model; this document's author could not run layer 2 (no access to the model host from the authoring environment). +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. ## What is not tested diff --git a/tests/fixtures/theoracle-eval/cases.json b/tests/fixtures/theoracle-eval/cases.json index 3625059..c56a3b0 100644 --- a/tests/fixtures/theoracle-eval/cases.json +++ b/tests/fixtures/theoracle-eval/cases.json @@ -1,10 +1,10 @@ { "notice": "SYNTHETIC TEST FIXTURE. Invented consultations without patient identity, scored against corpus.json by tests/theoracle-eval.test.ts. Expected outcomes describe retrieval and evidence-gate behaviour, not clinical correctness.", "thresholds": { - "note": "Provisional floors, calibrated on the first CI run with the pinned model. Raise them when the score rises; never lower one without Gaffer's word.", + "note": "Calibrated on the first CI run with the pinned model (2026-11-26, Actions run 45874985015: clinical recall@6 1 / MRR 1, lay recall@6 1 / MRR 0.938, therapy dose recall 1). Raise a floor when the score rises; never lower one without Gaffer's word.", "clinicalRecallAt6": 1, - "layRecallAt6": 0.75, - "clinicalMrr": 0.8, + "layRecallAt6": 1, + "clinicalMrr": 0.9, "therapyDoseRecall": 1 }, "retrieval": [