diff --git a/evaluation/README.md b/evaluation/README.md index e57007d..dd15741 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -25,7 +25,12 @@ evaluation/ run.ts ← CLI entry (manifest-driven) example/example-adapter.ts ← worked example adapter (in-memory, contract-shaped) example/broken-adapter.ts ← deliberate negative control (must fail the corpus) + src/corrections/ ← conversational corrections corpus (independent; see below) + adapter.ts · fixture-types.ts · fixtures.ts · runner.ts · run.ts + example/example-adapter.ts ← reference rule adapter (15/15) + example/broken-adapter.ts ← five-fault negative control fixtures/ ← fixture areas (data only); registration in fixtures/manifest.json + corrections/ ← the corrections corpus: household env + 6 case files (data only) ``` ## The adapter contract @@ -249,3 +254,100 @@ Observed per-fixture results are printed by the runner; nothing was skipped. this judges all candidates identically on capture-pipeline semantics. - No publish/review transitions, multi-child scoping, or authz — corpus scope is one child's draft timeline. + +--- + +# Conversational Corrections Challenge Corpus (`src/corrections/`) + +A second, independent corpus for the conversational correction problem: +caregivers issue spoken follow-ups ("Actually, two thirty.", "That was actually +Mia, not Nora.", "Undo that.") and the candidate decides, per turn, whether the +utterance is **applied** (correction appended), **rejected** (write +authorization fails — state must not change), or a **clarification** (ambiguous +or unresolvable — nothing written). Same design rules as the capture corpus: +fixtures are data only, the runner is fixed and deterministic, and any adapter +that exports the factory can be driven through it. + +```bash +bun src/corrections/run.ts # reference adapter: 15/15, exit 0 +bun src/corrections/run.ts --adapter=./src/corrections/example/broken-adapter.ts --expect-failure # control: must fail, exit 0 +``` + +## The correction adapter contract + +Implement `CorrectionCandidateAdapter` (see `src/corrections/adapter.ts`) and +export an **environment-dependent factory** from one module: + +```ts +import type { CorrectionCandidateAdapter, HouseholdEnv } from '../../evaluation/src/corrections/adapter.ts' + +export function createCorrectionAdapter(env: HouseholdEnv): CorrectionCandidateAdapter { + return { + name: 'my-candidate', + async processTurn(turn) { /* ... */ }, + async publishEntry(captureId) { /* ... */ }, + async readJournal() { /* ... */ }, + } +} +``` + +- **`processTurn`** consumes one full utterance turn (speaker, verbatim text, + capture instant, correctionId when known) and resolves to `applied`, + `rejected`, or `clarification` with a reason. +- **`readJournal`** returns the wire journal: entries (raw transcript, + original author, status, events) plus the append-only revision lineage. +- **`publishEntry`** is the ONLY status transition and is runner-driven — + corrections never publish, retract, or change visibility, exactly like the + capture corpus's publish separation. + +## The corpus (household env + 6 case files, 15 cases, data only) + +| Family | Cases | Pins | +|---|---|---| +| Time corrections | CC-01, CC-02 | spoken absolute times retarget the event in the capture timezone (DST-safe), even on a published entry (status unchanged), with the original author preserved | +| Wrong child | CC-03, CC-04 | retarget "was actually X, not Y" moves the entry (supersede, never duplicate) — or is rejected, read-only, when the actor lacks write grants | +| Wrong prior event | CC-05, CC-06 | ambiguous or missing referents clarify with **zero writes**; an unambiguous content referent corrects only the intended entry | +| Multiple authors / stale | CC-07, CC-08, CC-12 | compound time+content turns append one revision; a replayed `correctionId` is an applied no-op (stale suppression); repeated corrections stay idempotent | +| Negation | CC-09, CC-10, CC-11 | negations reverse notes (verbatim wording preserved), zero-care reports ("didn't nap") are **captured** as reviewable records — never a 0-duration quantity — and pending entries can be cancelled | +| Undo | CC-13, CC-14, CC-15 | undo restores the state before the last mutation ("undo everything": the capture state) as an appended undo revision; undo is read-only-rejected without write grants | + +Semantics enforced mechanically on every turn and at final state: raw +transcripts and original `authorId`s are immutable; corrections append +revisions and never delete or duplicate entries; entry count deltas are exact; +revision lineage (kind + author per entry) is pinned end-to-end. + +Each case also declares the **forbidden-op vocabulary** it guards +(`entry.duplicate_without_supersession`, `lineage.truncate`, `stale.clobber`, +`write.without_grant`, `write.suppressed_when_due`, +`quantity.zero_duration_sleep_representation`, …) so cross-review can name the +failure class, not just the case. + +- **Reference adapter** (`src/corrections/example/example-adapter.ts`): a + mechanical rule interpreter — regex dispatch, lexical child/entry resolution, + snapshot-stack undo, timezone-safe wall-clock retargeting via `Intl` — no + I/O, no LLM, no clock. Passes **15/15**. +- **Negative control** (`src/corrections/example/broken-adapter.ts`): the + reference with five named faults (duplicate-on-retarget, lineage truncation, + stale clobber on replay, skipped grant check, suppressed zero-care write). + The corpus fails it on **7/15 cases**, one per fault, and + `--expect-failure` inverts the exit code. + +## Validation evidence (observed, this branch) + +| Command | Result | +|---|---| +| `bun src/corrections/run.ts` | **15/15 cases PASS**, exit 0 — all five families, every replay probe clean | +| `bun src/corrections/run.ts --adapter=./src/corrections/example/broken-adapter.ts` | **7/15** — CC-03/04 (duplicate + missing grant check), CC-08/12 (stale clobber), CC-13/14 (lineage truncation), CC-10 (suppressed zero-care write); exit 1 | +| same + `--expect-failure` | faults caught, exit 0 | +| `bun x tsc --noEmit` | exit 0 — strict, `noUncheckedIndexedAccess`, `verbatimModuleSyntax` | + +## Scope note + +Proposal-level evaluation tooling: it does not change `packages/domain` (no +correction/revision schema exists there yet — lineage shapes remain owned by +the contract lane) and does not ship product correction behavior. It pins the +semantics a product implementation must satisfy when that work starts. The +corrections corpus is **not** a manifest-registered fixture area: it has its +own runner and turn-protocol adapter contract, so the fixture-area manifest +(see above) does not govern it. If cross-review later wants one CLI, a +dedicated `correction-protocol` fixture class would be the seam. diff --git a/evaluation/corrections/cases/multi-author.json b/evaluation/corrections/cases/multi-author.json new file mode 100644 index 0000000..f2a9b97 --- /dev/null +++ b/evaluation/corrections/cases/multi-author.json @@ -0,0 +1,157 @@ +{ + "cases": [ + { + "id": "CC-07-multi-author-correction", + "category": "multi-author", + "description": "Dad corrects Mom's entry. Attribution splits: the entry keeps its original author (Mom) and the revision is attributed to the corrector (Dad).", + "exercises": ["cross-author correction allowed within grants", "original authorship never rewritten", "revision attributed to the corrector"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc07_dinner", + "speakerId": "fx_u_mom", + "capturedAt": 1789508100000, + "text": "Nora ate mac and cheese at 5:30.", + "seedEvents": [ + { "category": "meal", "occurredAt": 1789507800000, "note": "mac and cheese" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789508400000, + "text": "Actually that was at Grandma's — make it 5:00.", + "correctionId": "cc07-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { + "ofCaptureId": "fx_cc07_dinner", + "authorIdMustRemain": "fx_u_mom", + "transcriptUnchanged": true, + "events": [{ "category": "meal", "occurredAt": 1789506000000, "noteContains": ["grandma"] }] + } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc07_dinner", "kind": "correction", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc07_dinner", + "childId": "fx_child_nora", + "authorId": "fx_u_mom", + "status": "draft", + "transcriptByteEquals": "Nora ate mac and cheese at 5:30.", + "events": [{ "category": "meal", "occurredAt": 1789506000000, "noteContains": ["grandma"] }], + "revisionKinds": ["capture", "correction"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "revision.attribution_rewrite", + "entry.delete", + "entry.duplicate_without_supersession", + "raw.mutate" + ] + }, + { + "id": "CC-08-multi-author-stale-suppression", + "category": "multi-author", + "description": "Two authors correct the same field, then Mom's earlier correction (same correctionId) replays out of order after Dad's later one. Final value must stay Dad's 15:00; the replay must be a no-op.", + "exercises": ["out-of-order arrival", "stale-result suppression at the correction layer", "correctionId idempotent replay", "append-only lineage of both real corrections"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc08_nap", + "speakerId": "fx_u_dad", + "capturedAt": 1789496400000, + "text": "Nora went down for her nap at 2:15.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789496100000, "note": "nap" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_mom", + "capturedAt": 1789496700000, + "text": "Actually, two thirty.", + "correctionId": "cc08-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { "ofCaptureId": "fx_cc08_nap", "events": [{ "category": "sleep", "occurredAt": 1789497000000 }] } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc08_nap", "kind": "correction", "authorId": "fx_u_mom", "count": 1 } + ] + } + } + }, + { + "turnId": "t2", + "speakerId": "fx_u_dad", + "capturedAt": 1789497300000, + "text": "Make it 3:00.", + "correctionId": "cc08-t2", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { "ofCaptureId": "fx_cc08_nap", "events": [{ "category": "sleep", "occurredAt": 1789498800000 }] } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc08_nap", "kind": "correction", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "replay": { + "turnIndex": 0, + "note": "Mom's cc08-t1 arrives again, out of order, after t2 — same correctionId, same capturedAt.", + "expectResponseClass": "applied" + }, + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc08_nap", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora went down for her nap at 2:15.", + "events": [{ "category": "sleep", "occurredAt": 1789498800000 }], + "revisionKinds": ["capture", "correction", "correction"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "stale.clobber", + "idempotent.duplicate_revision", + "revision.attribution_rewrite", + "lineage.truncate", + "entry.delete" + ] + } + ] +} diff --git a/evaluation/corrections/cases/negation.json b/evaluation/corrections/cases/negation.json new file mode 100644 index 0000000..834bdaf --- /dev/null +++ b/evaluation/corrections/cases/negation.json @@ -0,0 +1,239 @@ +{ + "cases": [ + { + "id": "CC-09-negation-reverses-claim", + "category": "negation", + "description": "Dad negates Mom's logged claim (\"she didn't eat the spinach — she threw it on the floor\"). The prior assertion is superseded by a corrective revision — not deleted, not left current.", + "exercises": ["negation of a prior assertion = content revision", "current event no longer asserts the retracted claim", "raw transcript still carries the original words", "cross-author attribution"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc09_meal", + "speakerId": "fx_u_mom", + "capturedAt": 1789510200000, + "text": "Nora ate her spinach at dinner.", + "seedEvents": [ + { "category": "meal", "occurredAt": 1789509600000, "note": "ate her spinach" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789510500000, + "text": "She didn't eat the spinach — she threw it on the floor.", + "correctionId": "cc09-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { + "ofCaptureId": "fx_cc09_meal", + "authorIdMustRemain": "fx_u_mom", + "transcriptUnchanged": true, + "events": [ + { + "category": "meal", + "occurredAt": 1789509600000, + "noteContains": ["threw it on the floor"], + "noteNotContains": ["ate her spinach"] + } + ] + } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc09_meal", "kind": "correction", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc09_meal", + "childId": "fx_child_nora", + "authorId": "fx_u_mom", + "status": "draft", + "transcriptByteEquals": "Nora ate her spinach at dinner.", + "events": [ + { + "category": "meal", + "occurredAt": 1789509600000, + "noteContains": ["threw it on the floor"], + "noteNotContains": ["ate her spinach"] + } + ], + "revisionKinds": ["capture", "correction"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "entry.delete", + "raw.mutate", + "entry.duplicate_without_supersession", + "revision.attribution_rewrite", + "lineage.truncate" + ] + }, + { + "id": "CC-10-negation-zero-care", + "category": "negation", + "description": "\"Nora didn't nap at all today\" with NO nap entry in the log. This is an explicit zero-care observation that must be CAPTURED as a reviewable record — not read as missing data, not written as a 0-minute nap quantity, and not suppressed. Proposal-pinned representation: sleep-category event, no quantity, note carries the negation; occurredAt = the assertion instant.", + "exercises": ["missing ≠ zero care (the distinction in both directions)", "zero-care must be captured when stated", "zero-duration quantity representation forbidden", "new entry from a negation turn"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc10_breakfast", + "speakerId": "fx_u_dad", + "capturedAt": 1789478400000, + "text": "Nora had pancakes at 9.", + "seedEvents": [ + { "category": "meal", "occurredAt": 1789477200000, "note": "pancakes" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_mom", + "capturedAt": 1789502400000, + "text": "Nora didn't nap at all today.", + "correctionId": "cc10-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryCountDelta": 1, + "newEntries": [ + { + "childId": "fx_child_nora", + "authorId": "fx_u_mom", + "status": "draft", + "events": [ + { + "category": "sleep", + "occurredAt": 1789502400000, + "noteContains": ["no nap"] + } + ], + "revisionKinds": ["capture"] + } + ] + } + } + } + ], + "final": { + "entryCount": 2, + "entries": [ + { + "ofCaptureId": "fx_cc10_breakfast", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora had pancakes at 9.", + "events": [{ "category": "meal", "occurredAt": 1789477200000 }], + "revisionKinds": ["capture"] + } + ], + "newEntries": [ + { + "childId": "fx_child_nora", + "authorId": "fx_u_mom", + "status": "draft", + "events": [ + { + "category": "sleep", + "occurredAt": 1789502400000, + "noteContains": ["no nap"] + } + ], + "revisionKinds": ["capture"] + } + ] + }, + "forbidden": [ + "write.suppressed_when_due", + "quantity.zero_duration_sleep_representation", + "zero_care.assert_without_capture", + "entry.delete" + ] + }, + { + "id": "CC-11-negation-cancel-pending", + "category": "negation", + "description": "\"Actually wait — don't log that\" immediately after a capture, while the entry is still draft and unpublished. The cancel withdraws the structured events and keeps the entry as a draft with its raw transcript byte-intact. Cancelling is never a hard delete, and never publishes.", + "exercises": ["cancel-before-publication semantics", "raw preserved even when withdrawn", "cancel ≠ delete", "cancel ≠ publish"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc11_meltdown", + "speakerId": "fx_u_mom", + "capturedAt": 1789502700000, + "text": "Leo had a meltdown at the store at 4.", + "seedEvents": [ + { "category": "mood", "occurredAt": 1789502400000, "note": "meltdown at the store" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_mom", + "capturedAt": 1789502820000, + "text": "Actually wait — don't log that.", + "correctionId": "cc11-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { + "ofCaptureId": "fx_cc11_meltdown", + "status": "draft", + "transcriptUnchanged": true, + "events": [] + } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc11_meltdown", "kind": "cancel", "authorId": "fx_u_mom", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc11_meltdown", + "childId": "fx_child_leo", + "authorId": "fx_u_mom", + "status": "draft", + "transcriptByteEquals": "Leo had a meltdown at the store at 4.", + "events": [], + "revisionKinds": ["capture", "cancel"], + "lastRevisionAuthorId": "fx_u_mom" + } + ] + }, + "forbidden": [ + "entry.delete", + "raw.delete", + "raw.mutate", + "publication.change_via_correction" + ] + } + ] +} diff --git a/evaluation/corrections/cases/repeated-undo.json b/evaluation/corrections/cases/repeated-undo.json new file mode 100644 index 0000000..9406dd7 --- /dev/null +++ b/evaluation/corrections/cases/repeated-undo.json @@ -0,0 +1,328 @@ +{ + "cases": [ + { + "id": "CC-12-repeated-corrections-idempotent", + "category": "repeated-corrections-and-undo", + "description": "Two sequential corrections of the same field (2:15 → 2:30 → 2:45), then the second correction replays verbatim. Final value 14:45, exactly two correction revisions, replay is a no-op.", + "exercises": ["sequential corrections keep the full intermediate lineage", "idempotent replay produces no duplicate revision", "no collapsed single revision"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc12_nap", + "speakerId": "fx_u_dad", + "capturedAt": 1789496400000, + "text": "Nora went down for her nap at 2:15.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789496100000, "note": "nap" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789496700000, + "text": "Actually, two thirty.", + "correctionId": "cc12-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { "ofCaptureId": "fx_cc12_nap", "events": [{ "category": "sleep", "occurredAt": 1789497000000 }] } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc12_nap", "kind": "correction", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + }, + { + "turnId": "t2", + "speakerId": "fx_u_dad", + "capturedAt": 1789496880000, + "text": "No wait — 2:45.", + "correctionId": "cc12-t2", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { "ofCaptureId": "fx_cc12_nap", "events": [{ "category": "sleep", "occurredAt": 1789497900000 }] } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc12_nap", "kind": "correction", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "replay": { + "turnIndex": 1, + "note": "cc12-t2 re-sent verbatim (same correctionId) — idempotency probe.", + "expectResponseClass": "applied" + }, + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc12_nap", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora went down for her nap at 2:15.", + "events": [{ "category": "sleep", "occurredAt": 1789497900000 }], + "revisionKinds": ["capture", "correction", "correction"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "idempotent.duplicate_revision", + "lineage.truncate", + "entry.delete", + "raw.mutate" + ] + }, + { + "id": "CC-13-undo-restore-value", + "category": "repeated-corrections-and-undo", + "description": "After two corrections (2:15 → 2:30 → 2:45), \"undo that\" restores 2:30. The undo is a new append-only revision that references the undone one — history keeps every step.", + "exercises": ["undo as append-only restore, not history rewrite", "value history fully preserved", "undo attribution to the undoing author"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc13_nap", + "speakerId": "fx_u_dad", + "capturedAt": 1789496400000, + "text": "Nora went down for her nap at 2:15.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789496100000, "note": "nap" } + ] + }, + { + "turnId": "s2", + "speakerId": "fx_u_dad", + "capturedAt": 1789496700000, + "text": "Actually, two thirty.", + "correctionId": "cc13-t1" + }, + { + "turnId": "s3", + "speakerId": "fx_u_dad", + "capturedAt": 1789496880000, + "text": "No wait — 2:45.", + "correctionId": "cc13-t2" + } + ], + "baseline": { + "entryCount": 1, + "entries": [ + { "ofCaptureId": "fx_cc13_nap", "events": [{ "category": "sleep", "occurredAt": 1789497900000 }] } + ], + "revisionKinds": { "fx_cc13_nap": ["capture", "correction", "correction"] } + } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789497300000, + "text": "Undo that — 2:30 was right.", + "correctionId": "cc13-t3", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { "ofCaptureId": "fx_cc13_nap", "transcriptUnchanged": true, "events": [{ "category": "sleep", "occurredAt": 1789497000000 }] } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc13_nap", "kind": "undo", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc13_nap", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora went down for her nap at 2:15.", + "events": [{ "category": "sleep", "occurredAt": 1789497000000 }], + "revisionKinds": ["capture", "correction", "correction", "undo"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "lineage.truncate", + "entry.delete", + "raw.mutate", + "revision.attribution_rewrite" + ] + }, + { + "id": "CC-14-undo-to-original", + "category": "repeated-corrections-and-undo", + "description": "\"Undo everything\" after corrections and a prior undo walks the value back to the ORIGINAL captured 2:15 — again via append-only undo revisions, with raw transcript and full history intact.", + "exercises": ["undo-to-capture-state semantics", "append-only lineage across two undos", "raw transcript still byte-identical to first dictation"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc14_nap", + "speakerId": "fx_u_dad", + "capturedAt": 1789496400000, + "text": "Nora went down for her nap at 2:15.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789496100000, "note": "nap" } + ] + }, + { + "turnId": "s2", + "speakerId": "fx_u_dad", + "capturedAt": 1789496700000, + "text": "Actually, two thirty.", + "correctionId": "cc14-t1" + }, + { + "turnId": "s3", + "speakerId": "fx_u_dad", + "capturedAt": 1789496880000, + "text": "No wait — 2:45.", + "correctionId": "cc14-t2" + }, + { + "turnId": "s4", + "speakerId": "fx_u_dad", + "capturedAt": 1789497300000, + "text": "Undo that — 2:30 was right.", + "correctionId": "cc14-t3" + } + ], + "baseline": { + "entryCount": 1, + "entries": [ + { "ofCaptureId": "fx_cc14_nap", "events": [{ "category": "sleep", "occurredAt": 1789497000000 }] } + ], + "revisionKinds": { "fx_cc14_nap": ["capture", "correction", "correction", "undo"] } + } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789498200000, + "text": "Actually, undo everything — 2:15 was right after all.", + "correctionId": "cc14-t4", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { "ofCaptureId": "fx_cc14_nap", "transcriptUnchanged": true, "events": [{ "category": "sleep", "occurredAt": 1789496100000 }] } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc14_nap", "kind": "undo", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc14_nap", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora went down for her nap at 2:15.", + "events": [{ "category": "sleep", "occurredAt": 1789496100000 }], + "revisionKinds": ["capture", "correction", "correction", "undo", "undo"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "lineage.truncate", + "entry.delete", + "raw.mutate", + "publication.change_via_correction" + ] + }, + { + "id": "CC-15-undo-unauthorized", + "category": "repeated-corrections-and-undo", + "description": "Nana holds a read-only grant on Nora. Her attempt to undo Mom's correction must fail closed: rejection, zero writes, and no revision record for the attempt.", + "exercises": ["authorization fail-closed on undo", "read-only grant cannot write", "no revision record for rejected turns"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc15_nap", + "speakerId": "fx_u_mom", + "capturedAt": 1789496400000, + "text": "Nora went down for her nap at 2:15.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789496100000, "note": "nap" } + ] + }, + { + "turnId": "s2", + "speakerId": "fx_u_mom", + "capturedAt": 1789496700000, + "text": "Actually, two thirty.", + "correctionId": "cc15-t1" + } + ], + "baseline": { + "entryCount": 1, + "entries": [ + { "ofCaptureId": "fx_cc15_nap", "events": [{ "category": "sleep", "occurredAt": 1789497000000 }] } + ], + "revisionKinds": { "fx_cc15_nap": ["capture", "correction"] } + } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_nana", + "capturedAt": 1789497000000, + "text": "Undo Mom's change.", + "correctionId": "cc15-t2", + "expect": { + "responseClass": "rejected", + "stateDelta": "none" + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc15_nap", + "childId": "fx_child_nora", + "authorId": "fx_u_mom", + "status": "draft", + "transcriptByteEquals": "Nora went down for her nap at 2:15.", + "events": [{ "category": "sleep", "occurredAt": 1789497000000 }], + "revisionKinds": ["capture", "correction"], + "lastRevisionAuthorId": "fx_u_mom" + } + ] + }, + "forbidden": [ + "write.without_grant", + "lineage.truncate", + "revision.attribution_rewrite", + "entry.delete" + ] + } + ] +} diff --git a/evaluation/corrections/cases/time-corrections.json b/evaluation/corrections/cases/time-corrections.json new file mode 100644 index 0000000..a219c45 --- /dev/null +++ b/evaluation/corrections/cases/time-corrections.json @@ -0,0 +1,143 @@ +{ + "cases": [ + { + "id": "CC-01-time-correction-basic", + "category": "time-correction", + "description": "The brief's headline phrase: a bare conversational time correction (\"actually two thirty\") against the most recent capture.", + "exercises": ["bare time phrase binds to latest entry in scope", "revision replaces value, not duplicate", "raw transcript byte preservation", "correction attribution to the speaker"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc01_nap", + "speakerId": "fx_u_dad", + "capturedAt": 1789496400000, + "text": "Nora went down for her nap at 2:15.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789496100000, "note": "nap" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789496700000, + "text": "Actually, two thirty.", + "correctionId": "cc01-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { + "ofCaptureId": "fx_cc01_nap", + "events": [{ "category": "sleep", "occurredAt": 1789497000000 }] + } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc01_nap", "kind": "correction", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc01_nap", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora went down for her nap at 2:15.", + "events": [{ "category": "sleep", "occurredAt": 1789497000000 }], + "revisionKinds": ["capture", "correction"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "entry.delete", + "event.duplicate_without_supersession", + "revision.attribution_rewrite", + "raw.mutate", + "publication.change_via_correction", + "lineage.truncate" + ] + }, + { + "id": "CC-02-time-correction-published", + "category": "time-correction", + "description": "Same correction against an already-published entry: the value updates in place via revision and publication state must not flip.", + "exercises": ["audience/publication separation under correction", "no silent unpublish-republish cycle"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc02_nap", + "speakerId": "fx_u_dad", + "capturedAt": 1789496400000, + "text": "Nora went down for her nap at 2:15.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789496100000, "note": "nap" } + ] + } + ], + "publish": ["fx_cc02_nap"], + "baseline": { + "entryCount": 1, + "entries": [{ "ofCaptureId": "fx_cc02_nap", "status": "published" }] + } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789497600000, + "text": "Actually, two thirty.", + "correctionId": "cc02-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { + "ofCaptureId": "fx_cc02_nap", + "status": "published", + "transcriptUnchanged": true, + "events": [{ "category": "sleep", "occurredAt": 1789497000000 }] + } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc02_nap", "kind": "correction", "authorId": "fx_u_dad", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc02_nap", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "published", + "transcriptByteEquals": "Nora went down for her nap at 2:15.", + "events": [{ "category": "sleep", "occurredAt": 1789497000000 }], + "revisionKinds": ["capture", "correction"], + "lastRevisionAuthorId": "fx_u_dad" + } + ] + }, + "forbidden": [ + "publication.change_via_correction", + "entry.delete", + "event.duplicate_without_supersession", + "raw.mutate", + "revision.attribution_rewrite" + ] + } + ] +} diff --git a/evaluation/corrections/cases/wrong-child.json b/evaluation/corrections/cases/wrong-child.json new file mode 100644 index 0000000..d55b497 --- /dev/null +++ b/evaluation/corrections/cases/wrong-child.json @@ -0,0 +1,128 @@ +{ + "cases": [ + { + "id": "CC-03-wrong-child-sibling", + "category": "wrong-child", + "description": "A capture logged under the wrong sibling is retargeted conversationally. The raw transcript still says \"Leo\" — raw is preserved even though the structured record moves.", + "exercises": ["child retarget with lineage", "raw transcript keeps the original name", "no duplicate entry per child", "retarget authorization within grants"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc03_meal", + "speakerId": "fx_u_mom", + "capturedAt": 1789489200000, + "text": "Leo ate all his pasta at noon.", + "seedEvents": [ + { "category": "meal", "occurredAt": 1789488000000, "note": "pasta at noon" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_mom", + "capturedAt": 1789489500000, + "text": "That was actually Mia, not Leo.", + "correctionId": "cc03-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { + "ofCaptureId": "fx_cc03_meal", + "childId": "fx_child_mia", + "authorIdMustRemain": "fx_u_mom", + "transcriptUnchanged": true, + "events": [{ "category": "meal", "occurredAt": 1789488000000 }] + } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc03_meal", "kind": "correction", "authorId": "fx_u_mom", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc03_meal", + "childId": "fx_child_mia", + "authorId": "fx_u_mom", + "status": "draft", + "transcriptByteEquals": "Leo ate all his pasta at noon.", + "events": [{ "category": "meal", "occurredAt": 1789488000000 }], + "revisionKinds": ["capture", "correction"], + "lastRevisionAuthorId": "fx_u_mom" + } + ] + }, + "forbidden": [ + "entry.duplicate_without_supersession", + "event.retarget_without_lineage", + "raw.mutate", + "entry.delete", + "revision.attribution_rewrite" + ] + }, + { + "id": "CC-04-wrong-child-unauthorized", + "category": "wrong-child", + "description": "Rosa holds a read-write grant on Leo only. Her retarget to Mia (no grant at all) must fail closed: rejection, zero writes, no partial application.", + "exercises": ["authorization fail-closed on retarget", "zero state delta on rejection", "no partial retarget"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc04_nap", + "speakerId": "fx_u_rosa", + "capturedAt": 1789492800000, + "text": "Leo refused his nap at 1.", + "seedEvents": [ + { "category": "sleep", "occurredAt": 1789491600000, "note": "refused his nap" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_rosa", + "capturedAt": 1789493100000, + "text": "That was actually Mia, not Leo.", + "correctionId": "cc04-t1", + "expect": { + "responseClass": "rejected", + "stateDelta": "none" + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc04_nap", + "childId": "fx_child_leo", + "authorId": "fx_u_rosa", + "status": "draft", + "transcriptByteEquals": "Leo refused his nap at 1.", + "events": [{ "category": "sleep", "occurredAt": 1789491600000 }], + "revisionKinds": ["capture"] + } + ] + }, + "forbidden": [ + "write.without_grant", + "entry.duplicate_without_supersession", + "event.retarget_without_lineage", + "entry.delete", + "raw.mutate" + ] + } + ] +} diff --git a/evaluation/corrections/cases/wrong-referent.json b/evaluation/corrections/cases/wrong-referent.json new file mode 100644 index 0000000..f4b2746 --- /dev/null +++ b/evaluation/corrections/cases/wrong-referent.json @@ -0,0 +1,150 @@ +{ + "cases": [ + { + "id": "CC-05-wrong-prior-event-missing", + "category": "wrong-prior-event", + "description": "\"Scratch the swim lesson\" — no swim lesson was ever logged. The candidate must clarify, write nothing, and must not misread the missing log as a zero-care observation.", + "exercises": ["missing referent → clarification", "missing log ≠ zero care", "no fabricated cancellation", "missing ≠ no-data marker"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc05_breakfast", + "speakerId": "fx_u_dad", + "capturedAt": 1789478400000, + "text": "Nora had pancakes at 9.", + "seedEvents": [ + { "category": "meal", "occurredAt": 1789477200000, "note": "pancakes" } + ] + } + ], + "baseline": { "entryCount": 1 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_dad", + "capturedAt": 1789480800000, + "text": "Scratch the swim lesson from today.", + "correctionId": "cc05-t1", + "expect": { + "responseClass": "clarification", + "stateDelta": "none" + } + } + ], + "final": { + "entryCount": 1, + "entries": [ + { + "ofCaptureId": "fx_cc05_breakfast", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora had pancakes at 9.", + "events": [{ "category": "meal", "occurredAt": 1789477200000, "noteContains": ["pancakes"] }], + "revisionKinds": ["capture"] + } + ] + }, + "forbidden": [ + "event.create_fabricated", + "entry.delete", + "zero_care.assert_without_capture", + "entry.duplicate_without_supersession", + "raw.mutate" + ] + }, + { + "id": "CC-06-wrong-prior-event-ambiguous-referent", + "category": "wrong-prior-event", + "description": "Two same-day meal entries from different authors. The correction names distinguishing content (\"not pasta\"), which binds it to Mom's lunch — not the most recent entry overall (Dad's dinner). Binding proposal: content-mention filter first, then speaker's most recent; ambiguous beyond that → clarify.", + "exercises": ["content-referent binding over recency", "wrong-entry application forbidden", "untouched sibling entry unchanged"], + "setup": { + "turns": [ + { + "turnId": "s1", + "captureId": "fx_cc06_lunch", + "speakerId": "fx_u_mom", + "capturedAt": 1789489200000, + "text": "Nora had pasta at noon.", + "seedEvents": [ + { "category": "meal", "occurredAt": 1789488000000, "note": "pasta at noon" } + ] + }, + { + "turnId": "s2", + "captureId": "fx_cc06_dinner", + "speakerId": "fx_u_dad", + "capturedAt": 1789510800000, + "text": "Nora had chicken at 6.", + "seedEvents": [ + { "category": "meal", "occurredAt": 1789509600000, "note": "chicken at 6" } + ] + } + ], + "baseline": { "entryCount": 2 } + }, + "turns": [ + { + "turnId": "t1", + "speakerId": "fx_u_mom", + "capturedAt": 1789511100000, + "text": "Actually, it was rigatoni, not pasta.", + "correctionId": "cc06-t1", + "expect": { + "responseClass": "applied", + "stateDelta": { + "entryChanges": [ + { + "ofCaptureId": "fx_cc06_lunch", + "transcriptUnchanged": true, + "events": [{ "category": "meal", "occurredAt": 1789488000000, "noteContains": ["rigatoni"] }] + }, + { + "ofCaptureId": "fx_cc06_dinner", + "transcriptUnchanged": true, + "events": [{ "category": "meal", "occurredAt": 1789509600000, "noteContains": ["chicken"] }] + } + ], + "appendedRevisions": [ + { "ofCaptureId": "fx_cc06_lunch", "kind": "correction", "authorId": "fx_u_mom", "count": 1 } + ] + } + } + } + ], + "final": { + "entryCount": 2, + "entries": [ + { + "ofCaptureId": "fx_cc06_lunch", + "childId": "fx_child_nora", + "authorId": "fx_u_mom", + "status": "draft", + "transcriptByteEquals": "Nora had pasta at noon.", + "events": [{ "category": "meal", "occurredAt": 1789488000000, "noteContains": ["rigatoni"] }], + "revisionKinds": ["capture", "correction"], + "lastRevisionAuthorId": "fx_u_mom" + }, + { + "ofCaptureId": "fx_cc06_dinner", + "childId": "fx_child_nora", + "authorId": "fx_u_dad", + "status": "draft", + "transcriptByteEquals": "Nora had chicken at 6.", + "events": [{ "category": "meal", "occurredAt": 1789509600000, "noteContains": ["chicken"] }], + "revisionKinds": ["capture"] + } + ] + }, + "forbidden": [ + "revision.wrong_target", + "entry.duplicate_without_supersession", + "raw.mutate", + "entry.delete", + "revision.attribution_rewrite" + ] + } + ] +} diff --git a/evaluation/corrections/household-env.json b/evaluation/corrections/household-env.json new file mode 100644 index 0000000..05ec720 --- /dev/null +++ b/evaluation/corrections/household-env.json @@ -0,0 +1,52 @@ +{ + "envVersion": "0.1.0", + "description": "Shared synthetic household for the conversational correction challenge corpus. All fixture instants fall on 2026-09-15 (America/New_York, EDT) and were machine-computed against the IANA tzdb. Grants are explicit role grants — audience permissions live here, never on entries.", + "household": { + "householdId": "fx_house_main", + "timezone": "America/New_York", + "fixtureDate": "2026-09-15", + "children": [ + { "childId": "fx_child_nora", "displayName": "Nora" }, + { "childId": "fx_child_leo", "displayName": "Leo" }, + { "childId": "fx_child_mia", "displayName": "Mia" } + ], + "members": [ + { + "memberId": "fx_u_mom", + "displayName": "Mom", + "role": "parent", + "childGrants": { + "fx_child_nora": "read-write", + "fx_child_leo": "read-write", + "fx_child_mia": "read-write" + } + }, + { + "memberId": "fx_u_dad", + "displayName": "Dad", + "role": "parent", + "childGrants": { + "fx_child_nora": "read-write", + "fx_child_leo": "read-write", + "fx_child_mia": "read-write" + } + }, + { + "memberId": "fx_u_rosa", + "displayName": "Rosa", + "role": "caregiver", + "childGrants": { + "fx_child_leo": "read-write" + } + }, + { + "memberId": "fx_u_nana", + "displayName": "Nana", + "role": "caregiver", + "childGrants": { + "fx_child_nora": "read" + } + } + ] + } +} diff --git a/evaluation/package.json b/evaluation/package.json index 6e0419c..accecf7 100644 --- a/evaluation/package.json +++ b/evaluation/package.json @@ -9,7 +9,9 @@ "test": "bun src/run.ts", "typecheck": "tsc --noEmit", "eval:broken": "bun src/run.ts --adapter=./src/example/broken-adapter.ts --expect-failure", - "selfcheck:manifest": "bun src/manifest-selfcheck.ts" + "selfcheck:manifest": "bun src/manifest-selfcheck.ts", + "eval:corrections": "bun src/corrections/run.ts", + "eval:corrections:broken": "bun src/corrections/run.ts --adapter=./src/corrections/example/broken-adapter.ts --expect-failure" }, "devDependencies": { "@types/node": "^20.14.0", diff --git a/evaluation/src/corrections/adapter.ts b/evaluation/src/corrections/adapter.ts new file mode 100644 index 0000000..58e69e3 --- /dev/null +++ b/evaluation/src/corrections/adapter.ts @@ -0,0 +1,105 @@ +/** + * Candidate-agnostic correction-adapter contract for the conversational + * correction challenge corpus (evaluation/corrections). + * + * PROPOSAL-LEVEL: this observation view is intentionally narrower than the + * canonical domain contracts (packages/domain). No correction/revision schema + * exists there yet (contract v0.3 owns the lineage fold separately), so this + * corpus evaluates candidates against a proposal-marked journal view instead + * of touching canonical schemas. See corrections/README.md. + * + * A candidate adapter is a replaceable in-memory correction engine: it + * receives conversational turns, returns an outcome class per turn, and + * exposes the resulting journal view. Deterministic; no I/O, no LLM, no clock. + */ + +export type EventCategory = 'potty' | 'meal' | 'sleep' | 'mood' | 'milestone' | 'school' +export type EntryStatus = 'draft' | 'published' +export type RevisionKind = 'capture' | 'correction' | 'undo' | 'cancel' +export type ChildGrant = 'read' | 'read-write' + +export interface HouseholdChild { + readonly childId: string + readonly displayName: string +} + +export interface HouseholdMember { + readonly memberId: string + readonly displayName: string + readonly role: 'parent' | 'caregiver' + readonly childGrants: Readonly> +} + +/** Shared synthetic household (evaluation/corrections/household-env.json). */ +export interface HouseholdEnv { + readonly householdId: string + readonly timezone: string + readonly children: readonly HouseholdChild[] + readonly members: readonly HouseholdMember[] +} + +/** Current-value event as observed in the journal view (lineage lives on revisions). */ +export interface JournalEvent { + readonly category: EventCategory + readonly occurredAt: number + readonly quantity?: { readonly value: number; readonly unit: string } + readonly note?: string +} + +export interface JournalEntry { + readonly captureId: string + readonly childId: string + /** Original capture author — never rewritten by corrections. */ + readonly authorId: string + /** Byte-faithful raw transcript — never mutated or deleted by corrections. */ + readonly rawTranscript: string + readonly status: EntryStatus + readonly events: readonly JournalEvent[] +} + +export interface JournalRevision { + readonly kind: RevisionKind + readonly entryCaptureId: string + /** Who made this revision (corrector / canceller / undoer). */ + readonly authorId: string + readonly capturedAt: number + /** Idempotency key when the turn carried one. */ + readonly correctionId?: string + readonly summary: string +} + +export interface JournalView { + /** Entries in creation order; revisions in append order. */ + readonly entries: readonly JournalEntry[] + readonly revisions: readonly JournalRevision[] +} + +export interface UtteranceTurn { + readonly turnId: string + readonly speakerId: string + readonly text: string + readonly capturedAt: number + readonly correctionId?: string + /** For capture turns: the capture identity the recorded entry must use. */ + readonly captureId?: string + /** Seed events mark a setup capture turn: the candidate records them as the entry's current events. */ + readonly seedEvents?: readonly JournalEvent[] +} + +export type ResponseClass = 'applied' | 'clarification' | 'rejected' + +export interface TurnOutcome { + readonly responseClass: ResponseClass + readonly reason?: string +} + +export interface CorrectionCandidateAdapter { + readonly name: string + processTurn(turn: UtteranceTurn): Promise + /** Publication is runner-driven only; corrections must never change status. */ + publishEntry(captureId: string): Promise + readJournal(): Promise +} + +/** Factory signature for correction adapters (env-dependent, unlike the capture corpus). */ +export type CorrectionAdapterFactory = (env: HouseholdEnv) => CorrectionCandidateAdapter diff --git a/evaluation/src/corrections/example/broken-adapter.ts b/evaluation/src/corrections/example/broken-adapter.ts new file mode 100644 index 0000000..2e1756b --- /dev/null +++ b/evaluation/src/corrections/example/broken-adapter.ts @@ -0,0 +1,411 @@ +/** + * DELIBERATELY BROKEN negative control — a copy of the reference adapter with + * five introduced faults, mirroring the capture corpus's broken-adapter + * pattern. --expect-failure requires the corpus to fail against this module. + * + * Faults (each maps to forbidden-op vocabulary in the case fixtures): + * FAULT 1 entry.duplicate_without_supersession — retarget copies the entry + * for the new child and leaves the original intact. + * FAULT 2 lineage.truncate — undo drops the last revision record instead of + * appending an undo revision. + * FAULT 3 stale.clobber / idempotent.duplicate_revision — replayed + * correctionIds are re-applied as fresh corrections. + * FAULT 4 write.without_grant — retarget authorization is skipped. + * FAULT 5 write.suppressed_when_due — zero-care negation clarifies instead + * of capturing the required no-nap entry. + */ +import type { + CorrectionCandidateAdapter, + EntryStatus, + EventCategory, + HouseholdEnv, + HouseholdMember, + JournalEntry, + JournalEvent, + JournalRevision, + JournalView, + ResponseClass, + TurnOutcome, + UtteranceTurn, +} from '../adapter.ts' + +const WORD_HOURS: Record = { + one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, + seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, +} +const WORD_MINUTES: Record = { + five: 5, ten: 10, fifteen: 15, twenty: 20, thirty: 30, 'forty-five': 45, 'forty five': 45, +} + +interface InternalEvent { + category: EventCategory + occurredAt: number + quantity?: { value: number; unit: string } + note?: string +} + +interface InternalEntry { + captureId: string + childId: string + authorId: string + rawTranscript: string + status: EntryStatus + events: InternalEvent[] + history: InternalEvent[][] +} + +function copyEvents(events: readonly InternalEvent[]): InternalEvent[] { + return events.map((e) => { + const c: InternalEvent = { category: e.category, occurredAt: e.occurredAt } + if (e.quantity !== undefined) c.quantity = { ...e.quantity } + if (e.note !== undefined) c.note = e.note + return c + }) +} + +function toJournalEvent(e: InternalEvent): JournalEvent { + return { + category: e.category, + occurredAt: e.occurredAt, + ...(e.quantity !== undefined ? { quantity: { ...e.quantity } } : {}), + ...(e.note !== undefined ? { note: e.note } : {}), + } +} + +function zonedMinutesOfDay(epochMs: number, timeZone: string): number { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone, hour12: false, hour: '2-digit', minute: '2-digit', + }).formatToParts(new Date(epochMs)) + const hour = Number(parts.find((p) => p.type === 'hour')?.value) % 24 + const minute = Number(parts.find((p) => p.type === 'minute')?.value) + return hour * 60 + minute +} + +function utcMinutesOfDay(epochMs: number): number { + return Math.floor((epochMs / 60000) % 1440) +} + +function shiftToWallClock(baseEpochMs: number, hour: number, minute: number, timeZone: string): number { + const baseZoned = zonedMinutesOfDay(baseEpochMs, timeZone) + const baseHour = Math.floor(baseZoned / 60) + const adjustedHour = baseHour >= 12 && hour < 12 ? hour + 12 : hour + const offset = baseZoned - utcMinutesOfDay(baseEpochMs) + return baseEpochMs - utcMinutesOfDay(baseEpochMs) * 60000 + (adjustedHour * 60 + minute - offset) * 60000 +} + +interface TimeExpr { hour: number; minute: number } + +function parseTimeExpr(text: string): TimeExpr | undefined { + const digits = /\b(\d{1,2})(?::(\d{2}))?\b/.exec(text) + if (digits && digits[1] !== undefined) { + return { hour: Number(digits[1]), minute: digits[2] !== undefined ? Number(digits[2]) : 0 } + } + const words = /\b(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)(?:\s+(fifteen|twenty|thirty|forty-five|forty five|ten|five))?\b/.exec(text) + if (words && words[1] !== undefined) { + const hour = WORD_HOURS[words[1]] + if (hour === undefined) return undefined + const minuteWord = words[2] + return { hour, minute: minuteWord !== undefined ? (WORD_MINUTES[minuteWord] ?? 0) : 0 } + } + return undefined +} + +const NEGATION_STOPWORDS = new Set([ + 'she', 'didnt', "didn't", 'the', 'that', 'this', 'was', 'not', 'her', 'his', 'they', 'them', + 'actually', 'wait', 'today', 'from', 'with', 'all', 'at', 'on', 'it', 'its', "it's", 'a', 'an', 'and', +]) + +function contentTokens(text: string): string[] { + return text.toLowerCase().match(/[a-z']+/g)?.filter((t) => t.length > 3 && !NEGATION_STOPWORDS.has(t)) ?? [] +} + +export function createCorrectionAdapter(env: HouseholdEnv): CorrectionCandidateAdapter { + const entries = new Map() + const revisions: JournalRevision[] = [] + // FAULT 3: seenCorrections is never populated — replayed correctionIds re-apply. + + const findChildByName = (name: string) => + env.children.find((c) => c.displayName.toLowerCase() === name.replace(/'s$/, '')) + const findChildInText = (text: string) => { + const lower = text.toLowerCase() + return env.children.find((c) => new RegExp(`\\b${c.displayName.toLowerCase()}\\b`).test(lower)) + } + const findMember = (memberId: string) => env.members.find((m) => m.memberId === memberId) + const canWrite = (member: HouseholdMember, childId: string) => member.childGrants[childId] === 'read-write' + const mostRecent = (pred: (e: InternalEntry) => boolean): InternalEntry | undefined => { + const all = [...entries.values()] + for (let i = all.length - 1; i >= 0; i--) { + const e = all[i] + if (e && pred(e)) return e + } + return undefined + } + + const appendRevision = ( + kind: JournalRevision['kind'], + entry: InternalEntry, + turn: UtteranceTurn, + summary: string, + ): void => { + const rev: JournalRevision = { + kind, + entryCaptureId: entry.captureId, + authorId: findMember(turn.speakerId)?.memberId ?? turn.speakerId, + capturedAt: turn.capturedAt, + ...(turn.correctionId !== undefined ? { correctionId: turn.correctionId } : {}), + summary, + } + revisions.push(rev) + } + + const mutate = (entry: InternalEntry, next: (events: InternalEvent[]) => void): void => { + entry.history.push(copyEvents(entry.events)) + next(entry.events) + } + + const captureTurn = (turn: UtteranceTurn): TurnOutcome => { + if (turn.captureId === undefined) return { responseClass: 'clarification', reason: 'capture turn without captureId' } + const child = findChildInText(turn.text) + if (child === undefined) { + return { responseClass: 'clarification', reason: 'capture turn without a resolvable child' } + } + const events: InternalEvent[] = (turn.seedEvents ?? []).map((e) => { + const out: InternalEvent = { category: e.category, occurredAt: e.occurredAt } + if (e.quantity !== undefined) out.quantity = { ...e.quantity } + if (e.note !== undefined) out.note = e.note + return out + }) + const entry: InternalEntry = { + captureId: turn.captureId, + childId: child.childId, + authorId: turn.speakerId, + rawTranscript: turn.text, + status: 'draft', + events, + history: [copyEvents(events)], + } + entries.set(entry.captureId, entry) + appendRevision('capture', entry, turn, 'captured') + return { responseClass: 'applied' } + } + + const cancelTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + const target = mostRecent(() => true) + if (target === undefined) return { responseClass: 'clarification', reason: 'nothing to cancel' } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + events.length = 0 + }) + appendRevision('cancel', target, turn, `cancelled: "${turn.text}"`) + return { responseClass: 'applied' } + } + + const scratchTurn = (turn: UtteranceTurn, member: HouseholdMember, subject: string): TurnOutcome => { + const subjectWords = subject.trim().split(/\s+/) + const target = mostRecent((e) => { + const transcript = e.rawTranscript.toLowerCase() + return subjectWords.some((w) => w.length > 2 && transcript.includes(w)) + }) + if (target === undefined) { + return { responseClass: 'clarification', reason: `no logged entry matching "${subject.trim()}" — nothing written` } + } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + events.length = 0 + }) + appendRevision('cancel', target, turn, `scratched "${subject.trim()}"`) + return { responseClass: 'applied' } + } + + const undoTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + const everything = /\bundo\s+everything\b/.test(turn.text.toLowerCase()) + const target = mostRecent((e) => e.history.length > 1) + if (target === undefined) return { responseClass: 'clarification', reason: 'nothing to undo' } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + if (everything) { + const restored = target.history[0] + target.history = [copyEvents(restored as InternalEvent[])] + target.events = copyEvents(restored as InternalEvent[]) + } else { + const restored = target.history.pop() + target.events = copyEvents(restored as InternalEvent[]) + } + // FAULT 2: truncate lineage — drop the entry's last revision instead of appending an undo. + const entryRevisions = revisions.filter((r) => r.entryCaptureId === target.captureId) + const lastIndex = revisions.lastIndexOf(entryRevisions.at(-1) as JournalRevision) + if (lastIndex >= 0) revisions.splice(lastIndex, 1) + return { responseClass: 'applied' } + } + + const retargetTurn = (turn: UtteranceTurn, member: HouseholdMember, newName: string, oldName: string): TurnOutcome => { + const newChild = findChildByName(newName) + const oldChild = findChildByName(oldName) + if (newChild === undefined || oldChild === undefined) { + return { responseClass: 'clarification', reason: 'could not resolve both children by name' } + } + const target = mostRecent((e) => { + const transcript = e.rawTranscript.toLowerCase() + return e.childId === oldChild.childId || transcript.includes(oldChild.displayName.toLowerCase()) + }) + if (target === undefined) { + return { responseClass: 'clarification', reason: `no entry attributed to ${oldChild.displayName}` } + } + // FAULT 4: authorization check skipped entirely. + // FAULT 1: duplicate instead of supersede — copy the entry to the new child, + // keep the original entry as-is, and record the revision on the copy. + const copyCaptureId = `${target.captureId}-copy` + const copy: InternalEntry = { + captureId: copyCaptureId, + childId: newChild.childId, + authorId: target.authorId, + rawTranscript: target.rawTranscript, + status: target.status, + events: copyEvents(target.events), + history: [copyEvents(target.events)], + } + entries.set(copyCaptureId, copy) + appendRevision('correction', copy, turn, `retarget child ${oldChild.displayName} -> ${newChild.displayName}`) + return { responseClass: 'applied' } + } + + const zeroCareTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + void member + // FAULT 5: suppress the required write — clarify instead of capturing. + return { responseClass: 'clarification', reason: 'no-care reports need confirmation before capture' } + } + + const negateClaimTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + const tokens = contentTokens(turn.text) + const target = mostRecent((e) => { + const transcriptTokens = new Set(contentTokens(e.rawTranscript)) + return tokens.some((t) => transcriptTokens.has(t)) + }) + if (target === undefined) { + return { responseClass: 'clarification', reason: 'no logged entry matches the negated claim' } + } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + const first = events[0] + if (first !== undefined) first.note = turn.text + }) + appendRevision('correction', target, turn, 'negation reverses earlier claim') + return { responseClass: 'applied' } + } + + const contentCorrectionTurn = (turn: UtteranceTurn, member: HouseholdMember, newContent: string, oldContent: string): TurnOutcome => { + const target = mostRecent((e) => e.rawTranscript.toLowerCase().includes(oldContent)) + if (target === undefined) { + return { responseClass: 'clarification', reason: `no logged entry mentioning "${oldContent}"` } + } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + const first = events[0] + if (first !== undefined) first.note = turn.text + }) + appendRevision('correction', target, turn, `content: ${oldContent} -> ${newContent}`) + return { responseClass: 'applied' } + } + + const timeCorrectionTurn = (turn: UtteranceTurn, member: HouseholdMember, time: TimeExpr, withNote: boolean): TurnOutcome => { + const target = mostRecent(() => true) + if (target === undefined) return { responseClass: 'clarification', reason: 'no entry to correct' } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + const first = target.events[0] + if (first === undefined) return { responseClass: 'clarification', reason: 'entry has no event to retime' } + const previous = first.occurredAt + const next = shiftToWallClock(first.occurredAt, time.hour, time.minute, env.timezone) + mutate(target, (events) => { + const ev = events[0] + if (ev !== undefined) { + ev.occurredAt = next + if (withNote) ev.note = turn.text + } + }) + appendRevision('correction', target, turn, `time ${previous} -> ${next}${withNote ? ' + note' : ''}`) + return { responseClass: 'applied' } + } + + const dispatch = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + if (turn.seedEvents !== undefined) return captureTurn(turn) + const text = turn.text.toLowerCase() + + if (/\bdon'?t\s+log\s+(?:that|it)\b/.test(text)) return cancelTurn(turn, member) + + const scratch = /\bscratch\s+(?:the\s+)?([a-z\s]+?)(?:\s+from|[,.;]|$)/.exec(text) + if (scratch !== null && scratch[1] !== undefined) return scratchTurn(turn, member, scratch[1]) + + if (/\bundo\b/.test(text)) return undoTurn(turn, member) + + const retarget = /\bwas\s+actually\s+([a-z]+),\s*not\s+([a-z]+)/.exec(text) + if (retarget !== null && retarget[1] !== undefined && retarget[2] !== undefined) { + return retargetTurn(turn, member, retarget[1], retarget[2]) + } + + if (/\b(?:didn'?t\s+(?:take\s+)?(?:a\s+)?nap|no\s+nap|didn'?t\s+sleep)\b/.test(text)) { + return zeroCareTurn(turn, member) + } + + if (/\bdidn'?t\b/.test(text)) return negateClaimTurn(turn, member) + + const content = /\bit\s+was\s+([a-z]+),\s*not\s+([a-z]+)/.exec(text) + if (content !== null && content[1] !== undefined && content[2] !== undefined) { + return contentCorrectionTurn(turn, member, content[1], content[2]) + } + + if (/\b(?:actually|make it|no wait)\b/.test(text)) { + const time = parseTimeExpr(text) + if (time === undefined) { + return { responseClass: 'clarification', reason: 'time correction without a parsable time' } + } + return timeCorrectionTurn(turn, member, time, /\bthat\s+was\s+at\b/.test(text)) + } + + return { responseClass: 'clarification', reason: 'no correction rule matched this phrasing' } + } + + return { + name: 'broken-negative-control', + async processTurn(turn: UtteranceTurn): Promise { + const member = findMember(turn.speakerId) + const outcome = member === undefined + ? { responseClass: 'clarification' as ResponseClass, reason: 'unknown speaker' } + : dispatch(turn, member) + return outcome + }, + async publishEntry(captureId: string): Promise { + const e = entries.get(captureId) + if (e !== undefined) e.status = 'published' + }, + async readJournal(): Promise { + const journalEntries: JournalEntry[] = [...entries.values()].map((e) => ({ + captureId: e.captureId, + childId: e.childId, + authorId: e.authorId, + rawTranscript: e.rawTranscript, + status: e.status, + events: copyEvents(e.events).map(toJournalEvent), + })) + const journalRevisions: JournalRevision[] = revisions.map((r) => ({ + kind: r.kind, + entryCaptureId: r.entryCaptureId, + authorId: r.authorId, + capturedAt: r.capturedAt, + ...(r.correctionId !== undefined ? { correctionId: r.correctionId } : {}), + summary: r.summary, + })) + return { entries: journalEntries, revisions: journalRevisions } + }, + } +} diff --git a/evaluation/src/corrections/example/example-adapter.ts b/evaluation/src/corrections/example/example-adapter.ts new file mode 100644 index 0000000..bbac1f7 --- /dev/null +++ b/evaluation/src/corrections/example/example-adapter.ts @@ -0,0 +1,433 @@ +/** + * Reference implementation of the correction-adapter contract — the worked + * example the corpus must pass (and the negative-control contrast class). + * + * Deliberately mechanical: a rule interpreter that resolves references to + * household children and logged entries, checks authorization BEFORE any + * mutation, performs append-only corrections, and supports undo via a + * snapshot stack. Deterministic: no I/O, no LLM, no clock. + * + * Semantics pinned by the corpus: + * - raw transcripts and original authorIds are immutable + * - corrections append revisions; entries are never deleted or duplicated + * - undo restores the state before the last mutation ("undo everything": + * the capture state); undo is itself an appended revision + * - a replayed correctionId is an applied no-op (stale-suppression) + * - publication is runner-driven; corrections never touch status + * - write authorization is the household child grant map, fail-closed + */ +import type { + CorrectionCandidateAdapter, + EntryStatus, + EventCategory, + HouseholdEnv, + HouseholdMember, + JournalEntry, + JournalEvent, + JournalRevision, + JournalView, + ResponseClass, + TurnOutcome, + UtteranceTurn, +} from '../adapter.ts' + +const WORD_HOURS: Record = { + one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, + seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, +} +const WORD_MINUTES: Record = { + five: 5, ten: 10, fifteen: 15, twenty: 20, thirty: 30, 'forty-five': 45, 'forty five': 45, +} + +interface InternalEvent { + category: EventCategory + occurredAt: number + quantity?: { value: number; unit: string } + note?: string +} + +interface InternalEntry { + captureId: string + childId: string + authorId: string + rawTranscript: string + status: EntryStatus + events: InternalEvent[] + /** Snapshot stack: index 0 = capture state; each mutation pushes the prior state first. */ + history: InternalEvent[][] +} + +function copyEvents(events: readonly InternalEvent[]): InternalEvent[] { + return events.map((e) => { + const c: InternalEvent = { category: e.category, occurredAt: e.occurredAt } + if (e.quantity !== undefined) c.quantity = { ...e.quantity } + if (e.note !== undefined) c.note = e.note + return c + }) +} + +function toJournalEvent(e: InternalEvent): JournalEvent { + return { + category: e.category, + occurredAt: e.occurredAt, + ...(e.quantity !== undefined ? { quantity: { ...e.quantity } } : {}), + ...(e.note !== undefined ? { note: e.note } : {}), + } +} + +// --- timezone-safe wall-clock retarget (same half-day as the base event) --- + +function zonedMinutesOfDay(epochMs: number, timeZone: string): number { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone, hour12: false, hour: '2-digit', minute: '2-digit', + }).formatToParts(new Date(epochMs)) + const hour = Number(parts.find((p) => p.type === 'hour')?.value) % 24 + const minute = Number(parts.find((p) => p.type === 'minute')?.value) + return hour * 60 + minute +} + +function utcMinutesOfDay(epochMs: number): number { + return Math.floor((epochMs / 60000) % 1440) +} + +function shiftToWallClock(baseEpochMs: number, hour: number, minute: number, timeZone: string): number { + const baseZoned = zonedMinutesOfDay(baseEpochMs, timeZone) + const baseHour = Math.floor(baseZoned / 60) + const adjustedHour = baseHour >= 12 && hour < 12 ? hour + 12 : hour + const offset = baseZoned - utcMinutesOfDay(baseEpochMs) + return baseEpochMs - utcMinutesOfDay(baseEpochMs) * 60000 + (adjustedHour * 60 + minute - offset) * 60000 +} + +interface TimeExpr { hour: number; minute: number } + +function parseTimeExpr(text: string): TimeExpr | undefined { + const digits = /\b(\d{1,2})(?::(\d{2}))?\b/.exec(text) + if (digits && digits[1] !== undefined) { + return { hour: Number(digits[1]), minute: digits[2] !== undefined ? Number(digits[2]) : 0 } + } + const words = /\b(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)(?:\s+(fifteen|twenty|thirty|forty-five|forty five|ten|five))?\b/.exec(text) + if (words && words[1] !== undefined) { + const hour = WORD_HOURS[words[1]] + if (hour === undefined) return undefined + const minuteWord = words[2] + return { hour, minute: minuteWord !== undefined ? (WORD_MINUTES[minuteWord] ?? 0) : 0 } + } + return undefined +} + +const NEGATION_STOPWORDS = new Set([ + 'she', 'didnt', "didn't", 'the', 'that', 'this', 'was', 'not', 'her', 'his', 'they', 'them', + 'actually', 'wait', 'today', 'from', 'with', 'all', 'at', 'on', 'it', 'its', "it's", 'a', 'an', 'and', +]) + +function contentTokens(text: string): string[] { + return text.toLowerCase().match(/[a-z']+/g)?.filter((t) => t.length > 3 && !NEGATION_STOPWORDS.has(t)) ?? [] +} + +export function createCorrectionAdapter(env: HouseholdEnv): CorrectionCandidateAdapter { + const entries = new Map() + const revisions: JournalRevision[] = [] + const seenCorrections = new Set() + + const findChildByName = (name: string) => + env.children.find((c) => c.displayName.toLowerCase() === name.replace(/'s$/, '')) + const findChildInText = (text: string) => { + const lower = text.toLowerCase() + return env.children.find((c) => new RegExp(`\\b${c.displayName.toLowerCase()}\\b`).test(lower)) + } + const findMember = (memberId: string) => env.members.find((m) => m.memberId === memberId) + const canWrite = (member: HouseholdMember, childId: string) => member.childGrants[childId] === 'read-write' + const mostRecent = (pred: (e: InternalEntry) => boolean): InternalEntry | undefined => { + const all = [...entries.values()] + for (let i = all.length - 1; i >= 0; i--) { + const e = all[i] + if (e && pred(e)) return e + } + return undefined + } + const revisionsFor = (captureId: string) => revisions.filter((r) => r.entryCaptureId === captureId) + + const appendRevision = ( + kind: JournalRevision['kind'], + entry: InternalEntry, + turn: UtteranceTurn, + summary: string, + ): void => { + const rev: JournalRevision = { + kind, + entryCaptureId: entry.captureId, + authorId: findMember(turn.speakerId)?.memberId ?? turn.speakerId, + capturedAt: turn.capturedAt, + ...(turn.correctionId !== undefined ? { correctionId: turn.correctionId } : {}), + summary, + } + revisions.push(rev) + } + + const mutate = (entry: InternalEntry, next: (events: InternalEvent[]) => void): void => { + entry.history.push(copyEvents(entry.events)) + next(entry.events) + } + + // --- rule implementations --- + + const captureTurn = (turn: UtteranceTurn): TurnOutcome => { + if (turn.captureId === undefined) return { responseClass: 'clarification', reason: 'capture turn without captureId' } + const child = findChildInText(turn.text) + if (child === undefined) { + return { responseClass: 'clarification', reason: 'capture turn without a resolvable child in the transcript' } + } + const events: InternalEvent[] = (turn.seedEvents ?? []).map((e) => { + const out: InternalEvent = { category: e.category, occurredAt: e.occurredAt } + if (e.quantity !== undefined) out.quantity = { ...e.quantity } + if (e.note !== undefined) out.note = e.note + return out + }) + const entry: InternalEntry = { + captureId: turn.captureId, + childId: child.childId, + authorId: turn.speakerId, + rawTranscript: turn.text, + status: 'draft', + events, + history: [copyEvents(events)], + } + entries.set(entry.captureId, entry) + appendRevision('capture', entry, turn, 'captured') + return { responseClass: 'applied' } + } + + const cancelTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + const target = mostRecent(() => true) + if (target === undefined) return { responseClass: 'clarification', reason: 'nothing to cancel' } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + events.length = 0 + }) + appendRevision('cancel', target, turn, `cancelled: "${turn.text}"`) + return { responseClass: 'applied' } + } + + const scratchTurn = (turn: UtteranceTurn, member: HouseholdMember, subject: string): TurnOutcome => { + const subjectWords = subject.trim().split(/\s+/) + const target = mostRecent((e) => { + const transcript = e.rawTranscript.toLowerCase() + return subjectWords.some((w) => w.length > 2 && transcript.includes(w)) + }) + if (target === undefined) { + return { responseClass: 'clarification', reason: `no logged entry matching "${subject.trim()}" — nothing written` } + } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + events.length = 0 + }) + appendRevision('cancel', target, turn, `scratched "${subject.trim()}"`) + return { responseClass: 'applied' } + } + + const undoTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + const everything = /\bundo\s+everything\b/.test(turn.text.toLowerCase()) + const target = mostRecent((e) => e.history.length > 1) + if (target === undefined) return { responseClass: 'clarification', reason: 'nothing to undo' } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + if (everything) { + const restored = target.history[0] + target.history = [copyEvents(restored as InternalEvent[])] + target.events = copyEvents(restored as InternalEvent[]) + } else { + const restored = target.history.pop() + target.events = copyEvents(restored as InternalEvent[]) + } + appendRevision('undo', target, turn, everything ? 'undid all corrections' : `undid: "${turn.text}"`) + return { responseClass: 'applied' } + } + + const retargetTurn = (turn: UtteranceTurn, member: HouseholdMember, newName: string, oldName: string): TurnOutcome => { + const newChild = findChildByName(newName) + const oldChild = findChildByName(oldName) + if (newChild === undefined || oldChild === undefined) { + return { responseClass: 'clarification', reason: 'could not resolve both children by name' } + } + const target = mostRecent((e) => { + const transcript = e.rawTranscript.toLowerCase() + return e.childId === oldChild.childId || transcript.includes(oldChild.displayName.toLowerCase()) + }) + if (target === undefined) { + return { responseClass: 'clarification', reason: `no entry attributed to ${oldChild.displayName}` } + } + if (!canWrite(member, newChild.childId) || !canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for retarget to ${newChild.displayName}` } + } + mutate(target, () => {}) + target.childId = newChild.childId + appendRevision('correction', target, turn, `retarget child ${oldChild.displayName} -> ${newChild.displayName}`) + return { responseClass: 'applied' } + } + + const zeroCareTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + const nameMatch = /\b(nora|leo|mia)\b/.exec(turn.text.toLowerCase()) + const child = nameMatch !== null && nameMatch[1] !== undefined ? findChildByName(nameMatch[1]) : undefined + if (child === undefined) { + return { responseClass: 'clarification', reason: 'could not resolve the child for the no-care report' } + } + if (!canWrite(member, child.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${child.childId}` } + } + const captureId = `cap_${turn.turnId}` + const events: InternalEvent[] = [ + { category: 'sleep', occurredAt: turn.capturedAt, note: `no nap — caregiver stated: "${turn.text}"` }, + ] + entries.set(captureId, { + captureId, + childId: child.childId, + authorId: member.memberId, + rawTranscript: turn.text, + status: 'draft', + events, + history: [copyEvents(events)], + }) + appendRevision('capture', entries.get(captureId) as InternalEntry, turn, 'captured explicit no-care report') + return { responseClass: 'applied' } + } + + const negateClaimTurn = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + const tokens = contentTokens(turn.text) + const target = mostRecent((e) => { + const transcriptTokens = new Set(contentTokens(e.rawTranscript)) + return tokens.some((t) => transcriptTokens.has(t)) + }) + if (target === undefined) { + return { responseClass: 'clarification', reason: 'no logged entry matches the negated claim' } + } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + const first = events[0] + if (first !== undefined) first.note = turn.text + }) + appendRevision('correction', target, turn, 'negation reverses earlier claim') + return { responseClass: 'applied' } + } + + const contentCorrectionTurn = (turn: UtteranceTurn, member: HouseholdMember, newContent: string, oldContent: string): TurnOutcome => { + const target = mostRecent((e) => e.rawTranscript.toLowerCase().includes(oldContent)) + if (target === undefined) { + return { responseClass: 'clarification', reason: `no logged entry mentioning "${oldContent}"` } + } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + mutate(target, (events) => { + const first = events[0] + if (first !== undefined) first.note = turn.text + }) + appendRevision('correction', target, turn, `content: ${oldContent} -> ${newContent}`) + return { responseClass: 'applied' } + } + + const timeCorrectionTurn = (turn: UtteranceTurn, member: HouseholdMember, time: TimeExpr, withNote: boolean): TurnOutcome => { + const target = mostRecent(() => true) + if (target === undefined) return { responseClass: 'clarification', reason: 'no entry to correct' } + if (!canWrite(member, target.childId)) { + return { responseClass: 'rejected', reason: `no write grant for ${target.childId}` } + } + const first = target.events[0] + if (first === undefined) return { responseClass: 'clarification', reason: 'entry has no event to retime' } + const previous = first.occurredAt + const next = shiftToWallClock(first.occurredAt, time.hour, time.minute, env.timezone) + mutate(target, (events) => { + const ev = events[0] + if (ev !== undefined) { + ev.occurredAt = next + if (withNote) ev.note = turn.text + } + }) + appendRevision('correction', target, turn, `time ${previous} -> ${next}${withNote ? ' + note' : ''}`) + return { responseClass: 'applied' } + } + + const dispatch = (turn: UtteranceTurn, member: HouseholdMember): TurnOutcome => { + if (turn.seedEvents !== undefined) return captureTurn(turn) + const text = turn.text.toLowerCase() + + if (/\bdon'?t\s+log\s+(?:that|it)\b/.test(text)) return cancelTurn(turn, member) + + const scratch = /\bscratch\s+(?:the\s+)?([a-z\s]+?)(?:\s+from|[,.;]|$)/.exec(text) + if (scratch !== null && scratch[1] !== undefined) return scratchTurn(turn, member, scratch[1]) + + if (/\bundo\b/.test(text)) return undoTurn(turn, member) + + const retarget = /\bwas\s+actually\s+([a-z]+),\s*not\s+([a-z]+)/.exec(text) + if (retarget !== null && retarget[1] !== undefined && retarget[2] !== undefined) { + return retargetTurn(turn, member, retarget[1], retarget[2]) + } + + if (/\b(?:didn'?t\s+(?:take\s+)?(?:a\s+)?nap|no\s+nap|didn'?t\s+sleep)\b/.test(text)) { + return zeroCareTurn(turn, member) + } + + if (/\bdidn'?t\b/.test(text)) return negateClaimTurn(turn, member) + + const content = /\bit\s+was\s+([a-z]+),\s*not\s+([a-z]+)/.exec(text) + if (content !== null && content[1] !== undefined && content[2] !== undefined) { + return contentCorrectionTurn(turn, member, content[1], content[2]) + } + + if (/\b(?:actually|make it|no wait)\b/.test(text)) { + const time = parseTimeExpr(text) + if (time === undefined) { + return { responseClass: 'clarification', reason: 'time correction without a parsable time' } + } + return timeCorrectionTurn(turn, member, time, /\bthat\s+was\s+at\b/.test(text)) + } + + return { responseClass: 'clarification', reason: 'no correction rule matched this phrasing' } + } + + return { + name: 'reference-rule-adapter', + async processTurn(turn: UtteranceTurn): Promise { + if (turn.correctionId !== undefined && seenCorrections.has(turn.correctionId)) { + return { responseClass: 'applied', reason: 'duplicate correctionId — already applied, no-op' } + } + const member = findMember(turn.speakerId) + const outcome = member === undefined + ? { responseClass: 'clarification' as ResponseClass, reason: 'unknown speaker' } + : dispatch(turn, member) + if (outcome.responseClass === 'applied' && turn.correctionId !== undefined) { + seenCorrections.add(turn.correctionId) + } + return outcome + }, + async publishEntry(captureId: string): Promise { + const e = entries.get(captureId) + if (e !== undefined) e.status = 'published' + }, + async readJournal(): Promise { + const journalEntries: JournalEntry[] = [...entries.values()].map((e) => ({ + captureId: e.captureId, + childId: e.childId, + authorId: e.authorId, + rawTranscript: e.rawTranscript, + status: e.status, + events: copyEvents(e.events).map(toJournalEvent), + })) + const journalRevisions: JournalRevision[] = revisions.map((r) => ({ + kind: r.kind, + entryCaptureId: r.entryCaptureId, + authorId: r.authorId, + capturedAt: r.capturedAt, + ...(r.correctionId !== undefined ? { correctionId: r.correctionId } : {}), + summary: r.summary, + })) + return { entries: journalEntries, revisions: journalRevisions } + }, + } +} diff --git a/evaluation/src/corrections/fixture-types.ts b/evaluation/src/corrections/fixture-types.ts new file mode 100644 index 0000000..e40a1fb --- /dev/null +++ b/evaluation/src/corrections/fixture-types.ts @@ -0,0 +1,163 @@ +/** + * Fixture shapes + controlled vocabularies for the conversational correction + * challenge corpus (evaluation/corrections). Data-only module: no I/O. + */ +import type { HouseholdEnv, ResponseClass } from './adapter.ts' + +export interface SeedEventFixture { + category: string + occurredAt: number + note?: string + quantity?: { value: number; unit: string } +} + +export interface SetupTurnFixture { + turnId: string + captureId?: string + speakerId: string + capturedAt: number + text: string + seedEvents?: SeedEventFixture[] +} + +export interface EventExpectationFixture { + category: string + occurredAt: number + toleranceMs?: number + /** Absent: the event must NOT carry a quantity (zero-care representation check). */ + quantity?: { value: number; unit: string } | null + noteContains?: string[] + noteNotContains?: string[] +} + +export interface EntryChangeFixture { + ofCaptureId: string + childId?: string + status?: string + authorIdMustRemain?: string + transcriptUnchanged?: boolean + events?: EventExpectationFixture[] +} + +export interface AppendedRevisionFixture { + ofCaptureId: string + kind: string + authorId: string + count?: number +} + +export interface NewEntryExpectationFixture { + childId: string + authorId: string + status: string + events: EventExpectationFixture[] + revisionKinds?: string[] +} + +export interface StateDeltaFixture { + entryCountDelta?: number + entryChanges?: EntryChangeFixture[] + newEntries?: NewEntryExpectationFixture[] + appendedRevisions?: AppendedRevisionFixture[] +} + +export interface TurnExpectationFixture { + responseClass: string + stateDelta?: 'none' | StateDeltaFixture +} + +export interface ChallengeTurnFixture { + turnId: string + speakerId: string + capturedAt: number + text: string + correctionId?: string + expect: TurnExpectationFixture +} + +export interface ReplayFixture { + turnIndex: number + note?: string + expectResponseClass?: string +} + +export interface BaselineEntryCheckFixture { + ofCaptureId: string + status?: string + events?: EventExpectationFixture[] +} + +export interface FinalEntryCheckFixture { + ofCaptureId: string + childId: string + authorId: string + status: string + transcriptByteEquals: string + events: EventExpectationFixture[] + revisionKinds: string[] + lastRevisionAuthorId?: string +} + +export interface FinalExpectationFixture { + entryCount: number + entries?: FinalEntryCheckFixture[] + newEntries?: NewEntryExpectationFixture[] +} + +export interface CorrectionCaseFixture { + id: string + category: string + description: string + exercises: string[] + setup: { + turns: SetupTurnFixture[] + publish?: string[] + baseline: { + entryCount: number + entries?: BaselineEntryCheckFixture[] + revisionKinds?: Record + } + } + turns: ChallengeTurnFixture[] + replay?: ReplayFixture + final: FinalExpectationFixture + forbidden: string[] +} + +export interface CorrectionCorpus { + env: HouseholdEnv + cases: CorrectionCaseFixture[] +} + +export const CASE_CATEGORIES = [ + 'time-correction', + 'wrong-child', + 'wrong-prior-event', + 'multi-author', + 'negation', + 'repeated-corrections-and-undo', +] as const + +export const RESPONSE_CLASSES: readonly ResponseClass[] = ['applied', 'clarification', 'rejected'] + +/** Controlled vocabulary of prohibited behaviors (documentation + validation). */ +export const FORBIDDEN_OPS = [ + 'entry.delete', + 'entry.duplicate_without_supersession', + 'raw.mutate', + 'raw.delete', + 'event.duplicate_without_supersession', + 'event.create_fabricated', + 'event.retarget_without_lineage', + 'revision.attribution_rewrite', + 'revision.wrong_target', + 'lineage.truncate', + 'write.without_grant', + 'write.suppressed_when_due', + 'stale.clobber', + 'idempotent.duplicate_revision', + 'publication.change_via_correction', + 'audience.change_via_correction', + 'zero_care.assert_without_capture', + 'quantity.zero_duration_sleep_representation', +] as const diff --git a/evaluation/src/corrections/fixtures.ts b/evaluation/src/corrections/fixtures.ts new file mode 100644 index 0000000..96981c3 --- /dev/null +++ b/evaluation/src/corrections/fixtures.ts @@ -0,0 +1,434 @@ +/** + * Fail-fast loader/validator for the conversational correction challenge + * corpus. Data lives in evaluation/corrections (household env + cases/*.json). + * Every field is narrowed and cross-referenced here BEFORE the runner sees it: + * a corpus that fails validation cannot run at all. + */ +import { readFileSync, readdirSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import type { HouseholdEnv } from './adapter.ts' +import { + CASE_CATEGORIES, + FORBIDDEN_OPS, + RESPONSE_CLASSES, +} from './fixture-types.ts' +import type { + BaselineEntryCheckFixture, + CorrectionCaseFixture, + CorrectionCorpus, + EntryChangeFixture, + EventExpectationFixture, + FinalExpectationFixture, + NewEntryExpectationFixture, + ReplayFixture, + SeedEventFixture, + SetupTurnFixture, + StateDeltaFixture, + TurnExpectationFixture, +} from './fixture-types.ts' + +const CASE_ID_PATTERN = /^CC-\d{2}-[a-z0-9-]+$/ + +class CorpusError extends Error {} + +function fail(context: string, message: string): never { + throw new CorpusError(`${context}: ${message}`) +} + +function isObj(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v) +} + +function str(v: unknown, context: string, field: string): string { + if (typeof v !== 'string' || v.length === 0) fail(context, `${field} must be a non-empty string`) + return v +} + +function int(v: unknown, context: string, field: string): number { + if (typeof v !== 'number' || !Number.isInteger(v)) fail(context, `${field} must be an integer`) + return v +} + +function arr(v: unknown, context: string, field: string): unknown[] { + if (!Array.isArray(v)) fail(context, `${field} must be an array`) + return v +} + +function optStr(v: unknown, context: string, field: string): string | undefined { + if (v === undefined) return undefined + return str(v, context, field) +} + +function optStrArr(v: unknown, context: string, field: string): string[] | undefined { + if (v === undefined) return undefined + return arr(v, context, field).map((s) => str(s, context, `${field}[]`)) +} + +function validateQuantityObj(v: unknown, context: string, field: string): { value: number; unit: string } { + if (!isObj(v)) fail(context, `${field} must be an object`) + return { value: int(v.value, context, `${field}.value`), unit: str(v.unit, context, `${field}.unit`) } +} + +function validateEventExpectation(v: unknown, context: string, field: string): EventExpectationFixture { + if (!isObj(v)) fail(context, `${field} must be an object`) + const out: Record = { + category: str(v.category, context, `${field}.category`), + occurredAt: int(v.occurredAt, context, `${field}.occurredAt`), + } + if (v.toleranceMs !== undefined) out.toleranceMs = int(v.toleranceMs, context, `${field}.toleranceMs`) + if (v.quantity !== undefined) { + // Explicit null pins "no quantity"; an object pins an exact quantity. + out.quantity = v.quantity === null ? null : validateQuantityObj(v.quantity, context, `${field}.quantity`) + } + const nc = optStrArr(v.noteContains, context, `${field}.noteContains`) + if (nc !== undefined) out.noteContains = nc + const nnc = optStrArr(v.noteNotContains, context, `${field}.noteNotContains`) + if (nnc !== undefined) out.noteNotContains = nnc + return out as unknown as EventExpectationFixture +} + +function validateSeedEvent(v: unknown, context: string, field: string): SeedEventFixture { + if (!isObj(v)) fail(context, `${field} must be an object`) + const out: Record = { + category: str(v.category, context, `${field}.category`), + occurredAt: int(v.occurredAt, context, `${field}.occurredAt`), + } + const note = optStr(v.note, context, `${field}.note`) + if (note !== undefined) out.note = note + if (v.quantity !== undefined) out.quantity = validateQuantityObj(v.quantity, context, `${field}.quantity`) + return out as unknown as SeedEventFixture +} + +function validateBaselineRevisionKinds( + v: unknown, + context: string, + captureIds: Set, +): Record { + if (!isObj(v)) fail(context, 'must be an object') + const out: Record = {} + for (const [cap, kinds] of Object.entries(v)) { + if (!captureIds.has(cap)) fail(context, `references unknown captureId ${cap}`) + out[cap] = arr(kinds, context, `revisionKinds[${cap}]`).map((k, i) => + str(k, context, `revisionKinds[${cap}][${i}]`), + ) + } + return out +} + +function readJson(url: URL, label: string): unknown { + let raw: string + try { + raw = readFileSync(fileURLToPath(url), 'utf8') + } catch (err) { + throw new CorpusError(`${label}: cannot read ${fileURLToPath(url)} — ${String(err)}`) + } + try { + return JSON.parse(raw) as unknown + } catch (err) { + throw new CorpusError(`${label}: invalid JSON — ${String(err)}`) + } +} + +function validateEnv(url: URL): HouseholdEnv { + const raw = readJson(url, 'household-env') + if (!isObj(raw) || !isObj(raw.household)) throw new CorpusError('household-env: missing household object') + const h = raw.household + const children = arr(h.children, 'household-env', 'household.children').map((c, i) => { + const ctx = `household.children[${i}]` + if (!isObj(c)) fail(ctx, 'must be an object') + return { childId: str(c.childId, ctx, 'childId'), displayName: str(c.displayName, ctx, 'displayName') } + }) + const childIds = new Set(children.map((c) => c.childId)) + if (childIds.size !== children.length) throw new CorpusError('household-env: duplicate childId') + + const memberIds = new Set() + const members = arr(h.members, 'household-env', 'household.members').map((m, i) => { + const ctx = `household.members[${i}]` + if (!isObj(m)) fail(ctx, 'must be an object') + const memberId = str(m.memberId, ctx, 'memberId') + if (memberIds.has(memberId)) fail(ctx, `duplicate memberId ${memberId}`) + memberIds.add(memberId) + const roleRaw = str(m.role, ctx, 'role') + if (roleRaw !== 'parent' && roleRaw !== 'caregiver') fail(ctx, `invalid role ${roleRaw}`) + const role: 'parent' | 'caregiver' = roleRaw + if (!isObj(m.childGrants)) fail(ctx, 'childGrants must be an object') + const grants: Record = {} + for (const [childId, grant] of Object.entries(m.childGrants)) { + if (grant !== 'read' && grant !== 'read-write') fail(ctx, `invalid grant ${String(grant)} for ${childId}`) + if (!childIds.has(childId)) fail(ctx, `grant references unknown child ${childId}`) + grants[childId] = grant + } + return { memberId, displayName: str(m.displayName, ctx, 'displayName'), role, childGrants: grants } + }) + if (members.length === 0) throw new CorpusError('household-env: no members') + + return { + householdId: str(h.householdId, 'household-env', 'household.householdId'), + timezone: str(h.timezone, 'household-env', 'household.timezone'), + children, + members, + } +} + +function validateCase(raw: unknown, file: string, seenIds: Set, env: HouseholdEnv): CorrectionCaseFixture { + if (!isObj(raw)) fail(file, 'case must be an object') + const id = str(raw.id, file, 'id') + if (!CASE_ID_PATTERN.test(id)) fail(id, `id must match ${CASE_ID_PATTERN}`) + if (seenIds.has(id)) fail(id, 'duplicate case id') + seenIds.add(id) + const category = str(raw.category, id, 'category') + if (!(CASE_CATEGORIES as readonly string[]).includes(category)) fail(id, `unknown category ${category}`) + str(raw.description, id, 'description') + arr(raw.exercises, id, 'exercises').forEach((e, i) => str(e, id, `exercises[${i}]`)) + + const childIds = new Set(env.children.map((c) => c.childId)) + const memberIds = new Set(env.members.map((m) => m.memberId)) + + if (!isObj(raw.setup)) fail(id, 'setup must be an object') + const setupRaw = raw.setup + const captureIds = new Set() + const setupTurns = arr(setupRaw.turns, id, 'setup.turns').map((t, i) => { + const ctx = `${id}.setup.turns[${i}]` + if (!isObj(t)) fail(ctx, 'must be an object') + const turnId = str(t.turnId, ctx, 'turnId') + const captureId = optStr(t.captureId, ctx, 'captureId') + if (captureId !== undefined) { + if (captureIds.has(captureId)) fail(id, `duplicate setup captureId ${captureId}`) + captureIds.add(captureId) + } + const speakerId = str(t.speakerId, ctx, 'speakerId') + if (!memberIds.has(speakerId)) fail(id, `unknown setup speaker ${speakerId}`) + const seedEvents = t.seedEvents === undefined + ? undefined + : arr(t.seedEvents, ctx, 'seedEvents').map((e, j) => validateSeedEvent(e, ctx, `seedEvents[${j}]`)) + if (captureId === undefined && seedEvents !== undefined) fail(id, `${turnId}: capture turns must declare captureId`) + return { + turnId, + captureId, + speakerId, + capturedAt: int(t.capturedAt, ctx, 'capturedAt'), + text: str(t.text, ctx, 'text'), + seedEvents, + } satisfies SetupTurnFixture + }) + + const publish = setupRaw.publish === undefined + ? undefined + : arr(setupRaw.publish, id, 'setup.publish').map((p, i) => { + const captureId = str(p, id, `setup.publish[${i}]`) + if (!captureIds.has(captureId)) fail(id, `publish references unknown captureId ${captureId}`) + return captureId + }) + + if (!isObj(setupRaw.baseline)) fail(id, 'setup.baseline must be an object') + const baselineRaw = setupRaw.baseline + const baseline = { + entryCount: int(baselineRaw.entryCount, id, 'setup.baseline.entryCount'), + entries: baselineRaw.entries === undefined + ? undefined + : arr(baselineRaw.entries, id, 'baseline.entries').map((e, i) => { + const ctx = `${id}.baseline.entries[${i}]` + if (!isObj(e)) fail(ctx, 'must be an object') + const ofCaptureId = str(e.ofCaptureId, ctx, 'ofCaptureId') + if (!captureIds.has(ofCaptureId)) fail(id, `baseline references unknown captureId ${ofCaptureId}`) + return { + ofCaptureId, + status: optStr(e.status, ctx, 'status'), + events: e.events === undefined + ? undefined + : arr(e.events, ctx, 'events').map((ev, j) => validateEventExpectation(ev, ctx, `events[${j}]`)), + } satisfies BaselineEntryCheckFixture + }), + revisionKinds: baselineRaw.revisionKinds === undefined + ? undefined + : validateBaselineRevisionKinds(baselineRaw.revisionKinds, `${id}.baseline.revisionKinds`, captureIds), + } + + const turns = arr(raw.turns, id, 'turns').map((t, i) => { + const ctx = `${id}.turns[${i}]` + if (!isObj(t)) fail(ctx, 'must be an object') + const speakerId = str(t.speakerId, ctx, 'speakerId') + if (!memberIds.has(speakerId)) fail(id, `unknown speaker ${speakerId}`) + if (!isObj(t.expect)) fail(ctx, 'expect must be an object') + const responseClass = str(t.expect.responseClass, ctx, 'expect.responseClass') + if (!RESPONSE_CLASSES.includes(responseClass as (typeof RESPONSE_CLASSES)[number])) { + fail(id, `unknown responseClass ${responseClass}`) + } + + let stateDelta: TurnExpectationFixture['stateDelta'] + const rawDelta = t.expect.stateDelta + if (rawDelta !== undefined) { + if (rawDelta === 'none') { + stateDelta = 'none' + } else if (isObj(rawDelta)) { + const sd = rawDelta + const parsed: StateDeltaFixture = {} + if (sd.entryCountDelta !== undefined) { + parsed.entryCountDelta = int(sd.entryCountDelta, ctx, 'stateDelta.entryCountDelta') + } + if (sd.entryChanges !== undefined) { + parsed.entryChanges = arr(sd.entryChanges, ctx, 'stateDelta.entryChanges').map((c, j) => { + const cctx = `${ctx}.entryChanges[${j}]` + if (!isObj(c)) fail(cctx, 'must be an object') + const ofCaptureId = str(c.ofCaptureId, cctx, 'ofCaptureId') + if (!captureIds.has(ofCaptureId)) fail(id, `entryChanges reference unknown captureId ${ofCaptureId}`) + return { + ofCaptureId, + childId: optStr(c.childId, cctx, 'childId'), + status: optStr(c.status, cctx, 'status'), + authorIdMustRemain: optStr(c.authorIdMustRemain, cctx, 'authorIdMustRemain'), + transcriptUnchanged: c.transcriptUnchanged === undefined ? undefined : Boolean(c.transcriptUnchanged), + events: c.events === undefined + ? undefined + : arr(c.events, cctx, 'events').map((ev, k) => validateEventExpectation(ev, cctx, `events[${k}]`)), + } satisfies EntryChangeFixture + }) + } + if (sd.newEntries !== undefined) { + parsed.newEntries = arr(sd.newEntries, ctx, 'stateDelta.newEntries').map((n, j) => { + const nctx = `${ctx}.newEntries[${j}]` + if (!isObj(n)) fail(nctx, 'must be an object') + const childId = str(n.childId, nctx, 'childId') + if (!childIds.has(childId)) fail(id, `newEntries reference unknown child ${childId}`) + return { + childId, + authorId: str(n.authorId, nctx, 'authorId'), + status: str(n.status, nctx, 'status'), + events: arr(n.events, nctx, 'events').map((ev, k) => validateEventExpectation(ev, nctx, `events[${k}]`)), + revisionKinds: n.revisionKinds === undefined + ? undefined + : arr(n.revisionKinds, nctx, 'revisionKinds').map((k, ki) => str(k, nctx, `revisionKinds[${ki}]`)), + } satisfies NewEntryExpectationFixture + }) + } + if (sd.appendedRevisions !== undefined) { + parsed.appendedRevisions = arr(sd.appendedRevisions, ctx, 'stateDelta.appendedRevisions').map((r, j) => { + const rctx = `${ctx}.appendedRevisions[${j}]` + if (!isObj(r)) fail(rctx, 'must be an object') + const ofCaptureId = str(r.ofCaptureId, rctx, 'ofCaptureId') + if (!captureIds.has(ofCaptureId)) fail(id, `appendedRevisions reference unknown captureId ${ofCaptureId}`) + return { + ofCaptureId, + kind: str(r.kind, rctx, 'kind'), + authorId: str(r.authorId, rctx, 'authorId'), + count: r.count === undefined ? undefined : int(r.count, rctx, 'count'), + } satisfies import('./fixture-types.ts').AppendedRevisionFixture + }) + } + stateDelta = parsed + } else { + fail(id, 'stateDelta must be "none" or an object') + } + } + return { + turnId: str(t.turnId, ctx, 'turnId'), + speakerId, + capturedAt: int(t.capturedAt, ctx, 'capturedAt'), + text: str(t.text, ctx, 'text'), + correctionId: optStr(t.correctionId, ctx, 'correctionId'), + expect: { responseClass, stateDelta } satisfies TurnExpectationFixture, + } satisfies import('./fixture-types.ts').ChallengeTurnFixture + }) + + const replay = raw.replay === undefined + ? undefined + : (() => { + if (!isObj(raw.replay)) fail(id, 'replay must be an object') + const turnIndex = int(raw.replay.turnIndex, id, 'replay.turnIndex') + if (turnIndex < 0 || turnIndex >= turns.length) fail(id, `replay.turnIndex ${turnIndex} out of range`) + return { + turnIndex, + note: optStr(raw.replay.note, id, 'replay.note'), + expectResponseClass: optStr(raw.replay.expectResponseClass, id, 'replay.expectResponseClass'), + } satisfies ReplayFixture + })() + + if (!isObj(raw.final)) fail(id, 'final must be an object') + const finalRaw = raw.final + const final: FinalExpectationFixture = { + entryCount: int(finalRaw.entryCount, id, 'final.entryCount'), + entries: finalRaw.entries === undefined + ? undefined + : arr(finalRaw.entries, id, 'final.entries').map((e, i) => { + const ctx = `${id}.final.entries[${i}]` + if (!isObj(e)) fail(ctx, 'must be an object') + const ofCaptureId = str(e.ofCaptureId, ctx, 'ofCaptureId') + if (!captureIds.has(ofCaptureId)) fail(id, `final entry references unknown captureId ${ofCaptureId}`) + const childId = str(e.childId, ctx, 'childId') + if (!childIds.has(childId)) fail(id, `final entry references unknown child ${childId}`) + const authorId = str(e.authorId, ctx, 'authorId') + if (!memberIds.has(authorId)) fail(id, `final entry references unknown author ${authorId}`) + return { + ofCaptureId, + childId, + authorId, + status: str(e.status, ctx, 'status'), + transcriptByteEquals: str(e.transcriptByteEquals, ctx, 'transcriptByteEquals'), + events: arr(e.events, ctx, 'events').map((ev, j) => validateEventExpectation(ev, ctx, `events[${j}]`)), + revisionKinds: arr(e.revisionKinds, ctx, 'revisionKinds').map((k, j) => str(k, ctx, `revisionKinds[${j}]`)), + lastRevisionAuthorId: optStr(e.lastRevisionAuthorId, ctx, 'lastRevisionAuthorId'), + } satisfies import('./fixture-types.ts').FinalEntryCheckFixture + }), + newEntries: finalRaw.newEntries === undefined + ? undefined + : arr(finalRaw.newEntries, id, 'final.newEntries').map((n, j) => { + const nctx = `${id}.final.newEntries[${j}]` + if (!isObj(n)) fail(nctx, 'must be an object') + const childId = str(n.childId, nctx, 'childId') + if (!childIds.has(childId)) fail(id, `final newEntry references unknown child ${childId}`) + return { + childId, + authorId: str(n.authorId, nctx, 'authorId'), + status: str(n.status, nctx, 'status'), + events: arr(n.events, nctx, 'events').map((ev, k) => validateEventExpectation(ev, nctx, `events[${k}]`)), + revisionKinds: n.revisionKinds === undefined + ? undefined + : arr(n.revisionKinds, nctx, 'revisionKinds').map((k, ki) => str(k, nctx, `revisionKinds[${ki}]`)), + } satisfies NewEntryExpectationFixture + }), + } + + const forbidden = arr(raw.forbidden, id, 'forbidden').map((op, i) => { + const opStr = str(op, id, `forbidden[${i}]`) + if (!(FORBIDDEN_OPS as readonly string[]).includes(opStr)) fail(id, `unknown forbidden op ${opStr}`) + return opStr + }) + + return { + id, + category, + description: raw.description as string, + exercises: raw.exercises as string[], + setup: { turns: setupTurns, publish, baseline }, + turns, + replay, + final, + forbidden, + } +} + +/** Load + validate the household env and every case file. Throws on any defect. */ +export function loadCorrectionFixtures(correctionsDir: URL): CorrectionCorpus { + const env = validateEnv(new URL('household-env.json', correctionsDir)) + const casesDir = new URL('cases/', correctionsDir) + let names: string[] + try { + names = readdirSync(fileURLToPath(casesDir)) + } catch (err) { + throw new CorpusError(`cannot list cases directory — ${String(err)}`) + } + const jsonFiles = names.filter((n) => n.endsWith('.json')).sort() + if (jsonFiles.length === 0) throw new CorpusError('cases directory contains no case files') + + const seenIds = new Set() + const cases: CorrectionCaseFixture[] = [] + for (const name of jsonFiles) { + const raw = readJson(new URL(name, casesDir), name) + if (!isObj(raw) || !Array.isArray(raw.cases)) fail(name, 'must be an object with a cases array') + for (const c of raw.cases) { + cases.push(validateCase(c, name, seenIds, env)) + } + } + if (cases.length === 0) throw new CorpusError('no cases loaded') + return { env, cases } +} diff --git a/evaluation/src/corrections/run.ts b/evaluation/src/corrections/run.ts new file mode 100644 index 0000000..f81fdcc --- /dev/null +++ b/evaluation/src/corrections/run.ts @@ -0,0 +1,45 @@ +#!/usr/bin/env bun +/** + * CLI for the conversational correction challenge corpus. + * + * bun src/corrections/run.ts + * bun src/corrections/run.ts --adapter=./src/corrections/example/broken-adapter.ts --expect-failure + * + * The adapter module must export `createCorrectionAdapter(env)` (env-dependent, + * unlike the capture corpus's no-arg `createAdapter`). Exit codes match the + * existing capture-corpus CLI: 0 on success (or on expected failure), 1 otherwise. + */ +import process from 'node:process' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import type { CorrectionAdapterFactory } from './adapter.ts' +import { createCorrectionAdapter as referenceFactory } from './example/example-adapter.ts' +import { loadCorrectionFixtures } from './fixtures.ts' +import { runCorrectionCorpus } from './runner.ts' + +async function loadFactory(modulePath: string): Promise { + const resolved = pathToFileURL(path.resolve(process.cwd(), modulePath)).href + const mod = (await import(resolved)) as Record + const factory = mod['createCorrectionAdapter'] + if (typeof factory !== 'function') { + throw new Error(`adapter module ${modulePath} must export createCorrectionAdapter(env)`) + } + return factory as CorrectionAdapterFactory +} + +const args = process.argv.slice(2) +const adapterArg = args.find((a) => a.startsWith('--adapter='))?.slice('--adapter='.length) +const expectFailure = args.includes('--expect-failure') + +const correctionsDir = new URL('../../corrections/', import.meta.url) +const { env, cases } = loadCorrectionFixtures(correctionsDir) +const factory = adapterArg !== undefined ? await loadFactory(adapterArg) : referenceFactory +const summary = await runCorrectionCorpus(factory, env, cases) + +for (const r of summary.results) { + const mark = r.ok ? 'PASS' : 'FAIL' + console.log(`${mark} ${r.caseId}`) + for (const f of r.failures) console.log(` · ${f}`) +} +console.log(`\n${summary.passed}/${summary.results.length} cases passed for adapter "${summary.adapterName}"`) +process.exitCode = summary.ok === !expectFailure ? 0 : 1 diff --git a/evaluation/src/corrections/runner.ts b/evaluation/src/corrections/runner.ts new file mode 100644 index 0000000..e07771f --- /dev/null +++ b/evaluation/src/corrections/runner.ts @@ -0,0 +1,405 @@ +/** + * Deterministic runner for the conversational correction challenge corpus. + * Candidate-agnostic: drives any CorrectionCandidateAdapter through setup, + * challenge turns, replay probes, and final-state assertions. Every check + * produces a failure string; a case passes only with zero failures. + */ +import type { CorrectionCandidateAdapter, HouseholdEnv, JournalEntry, JournalEvent, UtteranceTurn } from './adapter.ts' +import type { + CorrectionCaseFixture, + EventExpectationFixture, + NewEntryExpectationFixture, +} from './fixture-types.ts' + +export interface CorrectionResult { + caseId: string + ok: boolean + failures: string[] +} + +export interface CorrectionSummary { + adapterName: string + results: CorrectionResult[] + passed: number + ok: boolean +} + +/** Stable JSON for state-equality snapshots (sorted keys, deterministic). */ +function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]` + if (typeof value === 'object' && value !== null) { + const obj = value as Record + const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort() + return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(',')}}` + } + return JSON.stringify(value) ?? 'null' +} + +interface KnownEntryState { + transcript: string + authorId: string + status: string + childId: string +} + +function failInto(failures: string[], message: string): void { + failures.push(message) +} + +function matchEvents( + events: readonly JournalEvent[], + expectations: readonly EventExpectationFixture[], + ctx: string, + failures: string[], +): void { + const byCategory = new Map() + for (const e of events) { + const list = byCategory.get(e.category) ?? [] + list.push(e) + byCategory.set(e.category, list) + } + const wantByCategory = new Map() + for (const x of expectations) { + const list = wantByCategory.get(x.category) ?? [] + list.push(x) + wantByCategory.set(x.category, list) + } + for (const [cat, wants] of wantByCategory) { + const have = byCategory.get(cat) ?? [] + if (have.length !== wants.length) { + failInto(failures, `${ctx}: ${have.length} ${cat} event(s) present, expected ${wants.length}`) + continue + } + wants.forEach((w, i) => { + const ev = have[i] + if (ev === undefined) return + const tolerance = w.toleranceMs ?? 0 + if (Math.abs(ev.occurredAt - w.occurredAt) > tolerance) { + failInto(failures, `${ctx}: ${cat} event occurredAt ${ev.occurredAt}, expected ${w.occurredAt} (+/-${tolerance}ms)`) + } + if (w.quantity === null) { + if (ev.quantity !== undefined) { + failInto(failures, `${ctx}: ${cat} event must not carry a quantity (zero-care representation)`) + } + } else if (w.quantity !== undefined) { + if (ev.quantity?.value !== w.quantity.value || ev.quantity?.unit !== w.quantity.unit) { + failInto(failures, `${ctx}: ${cat} event quantity mismatch`) + } + } + const note = (ev.note ?? '').toLowerCase() + for (const needle of w.noteContains ?? []) { + if (!note.includes(needle.toLowerCase())) { + failInto(failures, `${ctx}: ${cat} event note missing "${needle}"`) + } + } + for (const needle of w.noteNotContains ?? []) { + if (note.includes(needle.toLowerCase())) { + failInto(failures, `${ctx}: ${cat} event note must not contain "${needle}"`) + } + } + }) + } + for (const [cat, have] of byCategory) { + if (!wantByCategory.has(cat) && have.length > 0) { + failInto(failures, `${ctx}: unexpected ${cat} event(s) present`) + } + } +} + +function checkNewEntry( + n: NewEntryExpectationFixture, + entry: JournalEntry, + ctx: string, + failures: string[], + kinds: string[], +): void { + if (entry.childId !== n.childId) failInto(failures, `${ctx}: childId ${entry.childId}, expected ${n.childId}`) + if (entry.authorId !== n.authorId) failInto(failures, `${ctx}: authorId ${entry.authorId}, expected ${n.authorId}`) + if (entry.status !== n.status) failInto(failures, `${ctx}: status ${entry.status}, expected ${n.status}`) + matchEvents(entry.events, n.events, ctx, failures) + if (n.revisionKinds !== undefined && kinds.join(',') !== n.revisionKinds.join(',')) { + failInto(failures, `${ctx}: revision kinds [${kinds.join(',')}] expected [${n.revisionKinds.join(',')}]`) + } +} + +async function runCase( + factory: (env: HouseholdEnv) => CorrectionCandidateAdapter, + env: HouseholdEnv, + testCase: CorrectionCaseFixture, +): Promise { + const failures: string[] = [] + const adapter = factory(env) + const known = new Map() + let journal = await adapter.readJournal() + const read = async (): Promise => { + journal = await adapter.readJournal() + } + const toUtterance = (t: { + turnId: string + speakerId: string + capturedAt: number + text: string + correctionId?: string + captureId?: string + seedEvents?: unknown + }): UtteranceTurn => { + const u: UtteranceTurn = { + turnId: t.turnId, + speakerId: t.speakerId, + text: t.text, + capturedAt: t.capturedAt, + ...(t.correctionId !== undefined ? { correctionId: t.correctionId } : {}), + ...(t.captureId !== undefined ? { captureId: t.captureId } : {}), + ...(t.seedEvents !== undefined ? { seedEvents: t.seedEvents as UtteranceTurn['seedEvents'] } : {}), + } + return u + } + + // --- setup --- + for (const t of testCase.setup.turns) { + const outcome = await adapter.processTurn(toUtterance(t)) + if (outcome.responseClass !== 'applied') { + failInto(failures, `setup turn ${t.turnId}: expected applied, got ${outcome.responseClass}${outcome.reason !== undefined ? ` (${outcome.reason})` : ''}`) + } + if (t.captureId !== undefined) { + await read() + const e = journal.entries.find((x) => x.captureId === t.captureId) + if (e === undefined) { + failInto(failures, `setup turn ${t.turnId}: expected entry ${t.captureId} to exist after capture`) + } else { + known.set(t.captureId, { + transcript: e.rawTranscript, + authorId: e.authorId, + status: e.status, + childId: e.childId, + }) + } + } + } + for (const captureId of testCase.setup.publish ?? []) { + await adapter.publishEntry(captureId) + await read() + const e = journal.entries.find((x) => x.captureId === captureId) + if (e === undefined) { + failInto(failures, `publish: entry ${captureId} missing`) + } else { + const k = known.get(captureId) + if (k !== undefined) k.status = e.status + if (e.status !== 'published') failInto(failures, `publish: entry ${captureId} status ${e.status}, expected published`) + } + } + + await read() + if (journal.entries.length !== testCase.setup.baseline.entryCount) { + failInto(failures, `baseline: ${journal.entries.length} entries, expected ${testCase.setup.baseline.entryCount}`) + } + for (const chk of testCase.setup.baseline.entries ?? []) { + const e = journal.entries.find((x) => x.captureId === chk.ofCaptureId) + if (e === undefined) { + failInto(failures, `baseline: entry ${chk.ofCaptureId} missing`) + continue + } + if (chk.status !== undefined && e.status !== chk.status) { + failInto(failures, `baseline ${chk.ofCaptureId}: status ${e.status}, expected ${chk.status}`) + } + if (chk.events !== undefined) matchEvents(e.events, chk.events, `baseline ${chk.ofCaptureId}`, failures) + } + for (const [cap, kinds] of Object.entries(testCase.setup.baseline.revisionKinds ?? {})) { + const actual = journal.revisions.filter((r) => r.entryCaptureId === cap).map((r) => r.kind) + if (actual.join(',') !== kinds.join(',')) { + failInto(failures, `baseline ${cap}: revision kinds [${actual.join(',')}] expected [${kinds.join(',')}]`) + } + } + + let before = canonicalJson(journal) + let prevCount = journal.entries.length + const turnCreated: string[] = [] + const revCounts = new Map() + for (const r of journal.revisions) { + revCounts.set(r.entryCaptureId, (revCounts.get(r.entryCaptureId) ?? 0) + 1) + } + + // --- challenge turns --- + for (const t of testCase.turns) { + const outcome = await adapter.processTurn(toUtterance(t)) + if (outcome.responseClass !== t.expect.responseClass) { + failInto(failures, `turn ${t.turnId}: expected ${t.expect.responseClass}, got ${outcome.responseClass}${outcome.reason !== undefined ? ` (${outcome.reason})` : ''}`) + } + await read() + const after = canonicalJson(journal) + const delta = t.expect.stateDelta + if (delta === 'none') { + if (after !== before) failInto(failures, `turn ${t.turnId}: state changed on a no-write turn`) + } else { + const newOnes = journal.entries.filter((e) => !known.has(e.captureId)) + const expectedCount = delta?.entryCountDelta !== undefined + ? prevCount + delta.entryCountDelta + : delta?.newEntries !== undefined + ? prevCount + delta.newEntries.length + : prevCount + if (journal.entries.length !== expectedCount) { + failInto(failures, `turn ${t.turnId}: ${journal.entries.length} entries after turn, expected ${expectedCount}`) + } + for (const [cap, k] of known) { + const e = journal.entries.find((x) => x.captureId === cap) + if (e === undefined) { + failInto(failures, `turn ${t.turnId}: entry ${cap} disappeared`) + continue + } + if (e.rawTranscript !== k.transcript) failInto(failures, `turn ${t.turnId}: raw transcript of ${cap} mutated`) + if (e.authorId !== k.authorId) failInto(failures, `turn ${t.turnId}: original authorId of ${cap} rewritten`) + if (e.status !== k.status) failInto(failures, `turn ${t.turnId}: status of ${cap} changed without publish (${k.status} -> ${e.status})`) + } + for (const ch of delta?.entryChanges ?? []) { + const e = journal.entries.find((x) => x.captureId === ch.ofCaptureId) + if (e === undefined) { + failInto(failures, `turn ${t.turnId}: expected entry ${ch.ofCaptureId} present`) + continue + } + if (ch.childId !== undefined && e.childId !== ch.childId) { + failInto(failures, `turn ${t.turnId}: ${ch.ofCaptureId} childId ${e.childId}, expected ${ch.childId}`) + } + if (ch.status !== undefined && e.status !== ch.status) { + failInto(failures, `turn ${t.turnId}: ${ch.ofCaptureId} status ${e.status}, expected ${ch.status}`) + } + if (ch.authorIdMustRemain !== undefined && e.authorId !== ch.authorIdMustRemain) { + failInto(failures, `turn ${t.turnId}: ${ch.ofCaptureId} authorId ${e.authorId}, expected ${ch.authorIdMustRemain}`) + } + if (ch.transcriptUnchanged === true) { + const k = known.get(ch.ofCaptureId) + if (k !== undefined && e.rawTranscript !== k.transcript) { + failInto(failures, `turn ${t.turnId}: ${ch.ofCaptureId} transcript changed`) + } + } + if (ch.events !== undefined) matchEvents(e.events, ch.events, `turn ${t.turnId} ${ch.ofCaptureId}`, failures) + } + const expectedNew = delta?.newEntries ?? [] + if (newOnes.length !== expectedNew.length) { + failInto(failures, `turn ${t.turnId}: ${newOnes.length} new entries, expected ${expectedNew.length}`) + } + for (let i = 0; i < Math.min(newOnes.length, expectedNew.length); i++) { + const n = newOnes[i] as JournalEntry + const x = expectedNew[i] as NewEntryExpectationFixture + const kinds = journal.revisions.filter((r) => r.entryCaptureId === n.captureId).map((r) => r.kind) + checkNewEntry(x, n, `turn ${t.turnId} new entry ${n.captureId}`, failures, kinds) + known.set(n.captureId, { + transcript: n.rawTranscript, + authorId: n.authorId, + status: n.status, + childId: n.childId, + }) + turnCreated.push(n.captureId) + revCounts.set(n.captureId, kinds.length) + } + for (const ar of delta?.appendedRevisions ?? []) { + const all = journal.revisions.filter((r) => r.entryCaptureId === ar.ofCaptureId) + const prev = revCounts.get(ar.ofCaptureId) ?? 0 + const appended = all.slice(prev) + const want = ar.count ?? 1 + if (appended.length !== want) { + failInto(failures, `turn ${t.turnId}: expected ${want} new revision(s) on ${ar.ofCaptureId}, got ${appended.length}`) + } + for (const r of appended) { + if (r.kind !== ar.kind) { + failInto(failures, `turn ${t.turnId}: new revision on ${ar.ofCaptureId} kind ${r.kind}, expected ${ar.kind}`) + } + if (r.authorId !== ar.authorId) { + failInto(failures, `turn ${t.turnId}: new revision on ${ar.ofCaptureId} author ${r.authorId}, expected ${ar.authorId}`) + } + } + revCounts.set(ar.ofCaptureId, all.length) + } + } + for (const e of journal.entries) { + const k = known.get(e.captureId) + if (k !== undefined) { + k.transcript = e.rawTranscript + k.authorId = e.authorId + k.status = e.status + k.childId = e.childId + } + } + prevCount = journal.entries.length + before = canonicalJson(journal) + } + + // --- replay probe --- + if (testCase.replay !== undefined) { + const t = testCase.turns[testCase.replay.turnIndex] + if (t === undefined) { + failInto(failures, `replay: turnIndex ${testCase.replay.turnIndex} out of range`) + } else { + const outcome = await adapter.processTurn(toUtterance(t)) + const wantCls = testCase.replay.expectResponseClass ?? t.expect.responseClass + if (outcome.responseClass !== wantCls) { + failInto(failures, `replay: expected ${wantCls}, got ${outcome.responseClass}${outcome.reason !== undefined ? ` (${outcome.reason})` : ''}`) + } + await read() + if (canonicalJson(journal) !== before) { + failInto(failures, 'replay: journal mutated on a replayed turn (idempotency violation)') + } + } + } + + // --- final state --- + await read() + if (journal.entries.length !== testCase.final.entryCount) { + failInto(failures, `final: ${journal.entries.length} entries, expected ${testCase.final.entryCount}`) + } + for (const fe of testCase.final.entries ?? []) { + const e = journal.entries.find((x) => x.captureId === fe.ofCaptureId) + if (e === undefined) { + failInto(failures, `final: entry ${fe.ofCaptureId} missing`) + continue + } + if (e.childId !== fe.childId) failInto(failures, `final ${fe.ofCaptureId}: childId ${e.childId}, expected ${fe.childId}`) + if (e.authorId !== fe.authorId) failInto(failures, `final ${fe.ofCaptureId}: authorId ${e.authorId}, expected ${fe.authorId}`) + if (e.status !== fe.status) failInto(failures, `final ${fe.ofCaptureId}: status ${e.status}, expected ${fe.status}`) + if (e.rawTranscript !== fe.transcriptByteEquals) { + failInto(failures, `final ${fe.ofCaptureId}: raw transcript not byte-equal to the original capture`) + } + matchEvents(e.events, fe.events, `final ${fe.ofCaptureId}`, failures) + const kinds = journal.revisions.filter((r) => r.entryCaptureId === fe.ofCaptureId).map((r) => r.kind) + if (kinds.join(',') !== fe.revisionKinds.join(',')) { + failInto(failures, `final ${fe.ofCaptureId}: revision kinds [${kinds.join(',')}] expected [${fe.revisionKinds.join(',')}]`) + } + if (fe.lastRevisionAuthorId !== undefined) { + const last = journal.revisions.filter((r) => r.entryCaptureId === fe.ofCaptureId).at(-1) + if (last === undefined || last.authorId !== fe.lastRevisionAuthorId) { + failInto(failures, `final ${fe.ofCaptureId}: last revision author ${last?.authorId ?? 'none'}, expected ${fe.lastRevisionAuthorId}`) + } + } + } + const finalNew = testCase.final.newEntries ?? [] + if (turnCreated.length !== finalNew.length) { + failInto(failures, `final: ${turnCreated.length} entries created during turns, expected ${finalNew.length}`) + } + for (let i = 0; i < Math.min(turnCreated.length, finalNew.length); i++) { + const captureId = turnCreated[i] as string + const x = finalNew[i] as NewEntryExpectationFixture + const n = journal.entries.find((e) => e.captureId === captureId) + if (n === undefined) { + failInto(failures, `final: turn-created entry ${captureId} missing at final state`) + continue + } + const kinds = journal.revisions.filter((r) => r.entryCaptureId === captureId).map((r) => r.kind) + checkNewEntry(x, n, `final new entry ${captureId}`, failures, kinds) + } + + return { caseId: testCase.id, ok: failures.length === 0, failures } +} + +export async function runCorrectionCorpus( + factory: (env: HouseholdEnv) => CorrectionCandidateAdapter, + env: HouseholdEnv, + cases: readonly CorrectionCaseFixture[], +): Promise { + const probe = factory(env) + const adapterName = probe.name + const results: CorrectionResult[] = [] + for (const testCase of cases) { + results.push(await runCase(factory, env, testCase)) + } + const passed = results.filter((r) => r.ok).length + return { adapterName, results, passed, ok: passed === results.length } +}