From ac9604a23c04b1ad455fdcdd2814ea12093a6be3 Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 18:51:35 +0000 Subject: [PATCH 1/2] =?UTF-8?q?feat(spike):=20agent-experience=20reference?= =?UTF-8?q?s=20prototype=20=E2=80=94=20clarify=20reducer=20+=20answer=20in?= =?UTF-8?q?validation=20(F-AX-001..006)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Slice 1 of the Remember & Retrieve synthesis (art_gfwpdmWF), implementing the ambiguous-reference clarify + correction-driven answer-invalidation contract from art_gCDrtx4S: bounded read-only clarify reducer, lineage watermark, citation-intersection invalidation, never-serve-superseded answer gate, six deterministic fixtures, and a bun suite (23 tests / 134 assertions). Co-authored-by: Gilbert Polanco --- spikes/agent-experience/references/README.md | 128 ++++ .../references/fixtures/F-AX-CLARIFY-001.json | 61 ++ .../fixtures/F-AX-CORRECT-ANSWER-001.json | 120 ++++ .../references/fixtures/F-AX-LEAK-001.json | 56 ++ .../fixtures/F-AX-RESUME-REFS-001.json | 126 ++++ .../fixtures/F-AX-STALE-ANSWER-001.json | 43 ++ .../F-AX-UNRESOLVED-CORRECTION-001.json | 38 ++ .../agent-experience/references/package.json | 11 + spikes/agent-experience/references/reducer.ts | 297 +++++++++ .../references/references.test.ts | 581 ++++++++++++++++++ spikes/agent-experience/references/schema.ts | 279 +++++++++ .../agent-experience/references/tsconfig.json | 7 + .../references/tsconfig.test.json | 8 + 13 files changed, 1755 insertions(+) create mode 100644 spikes/agent-experience/references/README.md create mode 100644 spikes/agent-experience/references/fixtures/F-AX-CLARIFY-001.json create mode 100644 spikes/agent-experience/references/fixtures/F-AX-CORRECT-ANSWER-001.json create mode 100644 spikes/agent-experience/references/fixtures/F-AX-LEAK-001.json create mode 100644 spikes/agent-experience/references/fixtures/F-AX-RESUME-REFS-001.json create mode 100644 spikes/agent-experience/references/fixtures/F-AX-STALE-ANSWER-001.json create mode 100644 spikes/agent-experience/references/fixtures/F-AX-UNRESOLVED-CORRECTION-001.json create mode 100644 spikes/agent-experience/references/package.json create mode 100644 spikes/agent-experience/references/reducer.ts create mode 100644 spikes/agent-experience/references/references.test.ts create mode 100644 spikes/agent-experience/references/schema.ts create mode 100644 spikes/agent-experience/references/tsconfig.json create mode 100644 spikes/agent-experience/references/tsconfig.test.json diff --git a/spikes/agent-experience/references/README.md b/spikes/agent-experience/references/README.md new file mode 100644 index 0000000..5efe7a1 --- /dev/null +++ b/spikes/agent-experience/references/README.md @@ -0,0 +1,128 @@ +# References & Answer Invalidation — Spike Prototype + +Bounded, dependency-free prototype of slice 1 of the Remember & Retrieve synthesis: +**ambiguous-reference clarify** and **correction-driven answer invalidation** — the +read-only clarify gate and the never-serve-superseded answer rule, as pure +deterministic reducers over typed contracts. + +## Contract source + +- **Contract:** `art_gCDrtx4S` — "Remember & Retrieve — Ambiguous References & + Correction Invalidation (proposal v0.1)" — §3 (schema deltas: LineageWatermark, + ClarifyQuestion/ClarifyOutcome, RevisionLink, additive `Answered` fields, + AnswerError), §5–6 (fixture cases + option-derivation rule). +- **Synthesis:** `art_gfwpdmWF` — cross-area synthesis §3 (fold-reconciliation + constraints) and §6 (executable slice queue; this is slice 1). + +## Layout + +``` +schema.ts Effect v4 contract schemas (the proposal's deltas, standalone) +reducer.ts Pure reducers: computeClarify, bumpWatermark, commitRevision, + invalidateAnswers, serveAnswer +fixtures/ 6 deterministic JSON cases (F-AX-*) +references.test.ts bun suite: round-trips, per-case outcomes, invariants +``` + +## Schemas (schema.ts) + +Implements the proposal's contract deltas as Effect v4 schemas pinned to +`4.0.0-rc.115`: + +- `LineageWatermark` — `(captureId, attempt)` lineage plus monotonic `version` + (unix-ms era integer), applied to the corpus. +- `ClarifyOption` / `ClarifyQuestion` / `ClarifyOutcome` — bounded (≤ 4 options), + read-only; carries no write payload. +- `ResolvedBinding` — the resolved arm of the outcome (provenance-qualified). +- `RevisionLink` — correction revision with an explicit `changedRecordIds` set. +- `Answered` additive fields — `answerId`, `readWatermark` (keyed by + `(envelopeId, readWatermark.version)`), `status`, `supersededByRevisionId`, + `citations` (citation-intersection inputs). +- `AnswerError` — `unresolved-reference` and `watermark-moved`, both `retryable`- + flagged, both carrying no user content. + +Conventions followed (matching `packages/domain/src/event.ts` and the folded +v0.3 domain): root `import { Schema } from "effect"` (the `effect/Schema` path +does not resolve on this pin); `Schema.Struct` with `Schema.optionalKey` for +absent-key optionals; `_tag` literal-union discriminants with unix-ms numbers +(`Schema.Number`); `convexId(table)` string annotations on id fields; branded id +types; `.js` import extensions; strict / `noUncheckedIndexedAccess` clean. + +## Reducers (reducer.ts) + +Pure, deterministic TypeScript — no Convex, no LLM, no clock, no randomness: + +- `computeClarify(envelope)` → `ClarifyOutcome`: `resolved` (single in-scope + candidate, or exactly one user-asserted candidate among several) | + `clarification` (2–4 options, provenance-labeled, visibility-filtered, + current-child first) | `unresolved-reference` (no candidate, cross-child + blocked, invisible target, or bound exceeded — typed `reason`, no + existence leak). +- `bumpWatermark` + `commitRevision` — strictly monotonic +1 watermark bump; + idempotent, append-only revision commit. +- `invalidateAnswers` — an `Answered` is superseded **iff** its cited record ids + intersect the revision's `changedRecordIds` (entry-level citations cover + contained events); exhausts every match. +- `serveAnswer` — returns the answer only when not superseded and the stored + watermark matches the current one; otherwise a typed + `watermark-moved`/superseded error that **never** includes the old content. + Never-serve-superseded is the hard rule. + +## Fixtures (fixtures/) + +The proposal's six cases as pure-data JSON with fixed ISO-8601 UTC times +(`2026-09-17T18:30:00Z` family), synthetic `fx_*` ids only, no real names, no +medical content. Every `expected` block is derivable from scenario semantics +alone: + +| Case | Scenario | Exercised rule | +| --- | --- | --- | +| `F-AX-CLARIFY-001` | "we took both" with two in-scope children | bounded clarification, exact options | +| `F-AX-CORRECT-ANSWER-001` | correction supersedes an answered claim | citation-intersection invalidation + lineage bump | +| `F-AX-RESUME-REFS-001` | re-opened capture re-resolves from restated refs | provenance-driven re-binding, historical supersession | +| `F-AX-STALE-ANSWER-001` | answer predates a committed revision | typed retryable stale error, never the old value | +| `F-AX-UNRESOLVED-CORRECTION-001` | correction names nothing resolvable | typed unresolved error, zero writes | +| `F-AX-LEAK-001` | private sibling reference in viewContext | fails typed without leaking id or content | + +## Evidence labels (honest) + +- **LOCAL-REAL (deterministic reducer):** `reducer.ts` + `schema.ts` are real, + running code verified by `bun test` on the exact commit SHA reported in the PR + (23 tests, 134 assertions) plus strict `tsc --noEmit`. No provider, no network, + no clock, no randomness anywhere in the module. +- **DETERMINISTIC DOUBLE (fixtures):** the six fixture cases are pure JSON + doubles — they demonstrate reducer semantics, not provider or device behavior. + Nothing here exercises a real extraction provider or an LLM call. +- **Nothing device-verified:** no iOS/audio/capture-path verification of any + kind is claimed by this spike. +- **Placement pending the v0.4 fold:** this lives under `spikes/` on purpose. + The fold home for the schemas is `packages/domain/src/clarifyAnswer.ts` + (per the synthesis); the reducers graduate only with that fold. This module is + deliberately **not** a pnpm workspace member, so CI's turbo pipeline covers it + via its own `test`/`typecheck` scripts (bun + tsc, hoisted resolution), and the + standalone suites (`security/`, `evaluation/`) are unaffected. +- **Fixture namespace pending manifest reconciliation:** the `F-AX-*` namespace + is claimed for the agent-experience area, but registering these cases into + `evaluation/`'s manifest-driven registry is the harness owner's decision + (todo_UXReKD0P) and is intentionally **not** done here. + +## Reconciliation notes + +- **Envelope equivalents are restated, not imported.** The task premise said the + context-envelope module was not on `origin/master` yet; master has since + absorbed the v0.3 fold (`packages/domain/src/contextEnvelope.ts`, + `operations.ts`, `lineage.ts`, `ids.ts`). The isolation instruction stands: + this spike still restates minimal locals (envelope id fields, provenance, + candidate-reference record) rather than importing `packages/domain`, so it + cannot couple to lanes still in flight. The `RECONCILIATION` comments in + `schema.ts` name the canonical exports that drop-in replace each restated + symbol at the fold. +- **Spike-local additions the proposal implies but the folded domain does not yet + carry** (each flagged inline): `relatedChildId` on references (needed to derive + child options per the proposal's option rule), the `resolved` reducer outcome + arm (proposal describes clarify as question-or-error; the reducer must also + express the no-question path), `retryable` on `unresolved-reference`, and the + five-kind citation union's pending growth at the fold. None change the + proposal's semantics; each is a naming/shaping decision for the fold. +- **Import-path deviations only:** no deviation from `art_gCDrtx4S` beyond + root-effect imports and the reconciliation comments above. diff --git a/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-001.json b/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-001.json new file mode 100644 index 0000000..fa98461 --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-001.json @@ -0,0 +1,61 @@ +{ + "fixtureId": "F-AX-CLARIFY-001", + "kind": "acceptance", + "title": "\"she slept an hour\" with two children in scope -> focused clarification, never a guess", + "contractSource": "art_gCDrtx4S section 5, F-AX-CLARIFY-001", + "scenario": { + "narrative": "Mom dictates 'she slept an hour at nap today' with the child picker empty (currentChild absent), the timeline open with no selected record, and two nap events in references - one per child. Two candidates, no envelope tiebreaker: the system names no child and asks one bounded question whose options are exactly the two in-scope children.", + "anchors": { "askUtc": "2026-09-17T18:30:00Z" } + }, + "input": { + "envelope": { + "envelopeId": "fx_env_clarify_001", + "captureId": "fx_capture_001", + "capturedAt": 1789669800000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "she slept an hour at nap today", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "viewContext": { + "value": { "screen": "timeline" }, + "source": "app-known", + "basis": "timeline screen open" + }, + "references": [ + { + "referenceId": "fx_ref_001", + "kind": "event", + "targetId": "fx_evt_sleep_001", + "relatedChildId": "fx_child_m", + "snippet": "Mia - nap, 1 hour", + "source": "app-known", + "visibleToActor": true + }, + { + "referenceId": "fx_ref_002", + "kind": "event", + "targetId": "fx_evt_leo_nap_001", + "relatedChildId": "fx_child_l", + "snippet": "Leo - nap, 45 minutes", + "source": "app-known", + "visibleToActor": true + } + ] + } + }, + "expected": { + "outcomeTag": "clarify-question", + "question": "Which of these did you mean?", + "optionCount": 2, + "optionTargetIds": ["fx_child_m", "fx_child_l"], + "optionKinds": ["child", "child"], + "optionLabels": ["Mia - nap, 1 hour", "Leo - nap, 45 minutes"], + "optionProvenance": ["app-known", "app-known"], + "ambiguousReferenceIds": ["fx_evt_sleep_001", "fx_evt_leo_nap_001"], + "zeroWrites": true + } +} diff --git a/spikes/agent-experience/references/fixtures/F-AX-CORRECT-ANSWER-001.json b/spikes/agent-experience/references/fixtures/F-AX-CORRECT-ANSWER-001.json new file mode 100644 index 0000000..455b69f --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-CORRECT-ANSWER-001.json @@ -0,0 +1,120 @@ +{ + "fixtureId": "F-AX-CORRECT-ANSWER-001", + "kind": "acceptance", + "title": "\"actually 45 minutes,\" then re-ask: the answer cites the revision chain and the prior answer is superseded", + "contractSource": "art_gCDrtx4S section 5, F-AX-CORRECT-ANSWER-001", + "scenario": { + "narrative": "(a) Mom asks how long Mia napped; answer A1 at watermark version 0 states 1 hour citing fx_evt_sleep_001. (b) At 4:30 PM mom says 'actually 45 minutes' with fx_evt_sleep_001 selected in viewContext; revision fx_rev_001 commits and the household watermark bumps to version 1. (c) At 7:00 PM the re-ask produces answer A2 at the new watermark. The only write in the chain is the authorized revision.", + "anchors": { + "askUtc": "2026-09-17T18:30:00Z", + "correctionCommittedUtc": "2026-09-17T20:30:00Z", + "reAskUtc": "2026-09-17T23:00:00Z" + } + }, + "input": { + "envelopeAsk": { + "envelopeId": "fx_env_ask_001", + "captureId": "fx_capture_ask_001", + "capturedAt": 1789669800000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "how long did Mia nap?", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "references": [ + { + "referenceId": "fx_ref_ask_001", + "kind": "event", + "targetId": "fx_evt_sleep_001", + "relatedChildId": "fx_child_m", + "snippet": "Mia - nap, 1 hour", + "source": "app-known", + "visibleToActor": true + } + ] + }, + "answerA1": { + "_tag": "answered", + "envelopeId": "fx_env_ask_001", + "response": "Mia napped for 1 hour.", + "citations": [{ "recordId": "fx_evt_sleep_001", "recordKind": "event" }], + "answerId": "fx_ans_001", + "readWatermark": { "householdId": "fx_household_1", "version": 0 }, + "status": "current" + }, + "revision": { + "revisionId": "fx_rev_001", + "targetRecordId": "fx_evt_sleep_001", + "containingEntryId": "fx_entry_sleep_001", + "revisedAt": 1789677000000, + "summary": "quantity: 1 hour -> 45 minutes" + }, + "envelopeCorrect": { + "envelopeId": "fx_env_correct_001", + "captureId": "fx_capture_correct_001", + "capturedAt": 1789677000000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "actually 45 minutes", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "viewContext": { + "value": { + "screen": "entry-detail", + "selectedRecord": { "recordId": "fx_evt_sleep_001", "recordKind": "event" } + }, + "source": "app-known", + "basis": "mom confirmed on the event's detail screen" + } + }, + "answerA2": { + "_tag": "answered", + "envelopeId": "fx_env_reask_001", + "response": "Mia napped for 45 minutes - corrected from 1 hour.", + "citations": [ + { "recordId": "fx_evt_sleep_001", "recordKind": "event" }, + { "recordId": "fx_rev_001", "recordKind": "revision" } + ], + "answerId": "fx_ans_002", + "readWatermark": { "householdId": "fx_household_1", "version": 1 }, + "status": "current", + "revisionChain": [ + { + "revisionId": "fx_rev_001", + "targetRecordId": "fx_evt_sleep_001", + "containingEntryId": "fx_entry_sleep_001", + "revisedAt": 1789677000000, + "summary": "quantity: 1 hour -> 45 minutes" + } + ] + } + }, + "expected": { + "clarifyOnCorrectionEnvelope": { + "outcomeTag": "resolved", + "targetId": "fx_evt_sleep_001", + "kind": "event", + "provenance": "app-known" + }, + "a2Status": "current", + "a1ReadWatermarkVersion": 0, + "a2ReadWatermarkVersion": 1, + "a2VersionStrictlyGreaterThanA1": true, + "a2ResponseStates": "45 minutes", + "a2CitationRecordIds": ["fx_evt_sleep_001", "fx_rev_001"], + "a2CitationRecordKinds": ["event", "revision"], + "a2RevisionChainLength": 1, + "a2RevisionChainSummary": "quantity: 1 hour -> 45 minutes", + "a1FinalStatus": "superseded", + "a1SupersededByRevisionId": "fx_rev_001", + "a1RetrievableAfterRevision": true, + "a1ServableAsCurrent": false, + "zeroWritesFromAnswerOps": true + } +} diff --git a/spikes/agent-experience/references/fixtures/F-AX-LEAK-001.json b/spikes/agent-experience/references/fixtures/F-AX-LEAK-001.json new file mode 100644 index 0000000..581249e --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-LEAK-001.json @@ -0,0 +1,56 @@ +{ + "fixtureId": "F-AX-LEAK-001", + "kind": "adversarial", + "title": "nothing private leaks into any answer - publication state and audience stay separate, role never widens scope", + "contractSource": "art_gCDrtx4S section 5, F-AX-LEAK-001 (serves slot 15)", + "scenario": { + "narrative": "Caregiver fx_caregiver_1 asks what mom noted about tomorrow's pickup. The envelope carries a smuggled reference to fx_entry_private_001 - draft publication state, parents-only audience, visibleToActor false for this caregiver. Two independent exclusion reasons (publication state draft; audience not including the caregiver), never fused into one, and the failure leaks neither the draft's content, nor its title, nor which id exists - only the typed reason. Role never widens scope: a caregiver asking does not turn a private record visible.", + "anchors": { "askUtc": "2026-09-17T18:30:00Z" } + }, + "input": { + "envelope": { + "envelopeId": "fx_env_leak_001", + "captureId": "fx_capture_leak_001", + "capturedAt": 1789669800000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "what did mom note about tomorrow's pickup?", + "actor": { "authorId": "fx_caregiver_1", "role": "caregiver" }, + "householdId": "fx_household_1", + "references": [ + { + "referenceId": "fx_ref_private_001", + "kind": "entry", + "targetId": "fx_entry_private_001", + "snippet": "pickup plan draft - mom's private note", + "source": "app-known", + "visibleToActor": false + } + ] + }, + "privateRecord": { + "recordId": "fx_entry_private_001", + "title": "pickup plan draft - mom's private note", + "publicationState": "draft", + "audience": ["fx_parent_a", "fx_parent_b"] + } + }, + "expected": { + "outcomeTag": "unresolved-reference", + "reason": "target-not-visible", + "retryable": false, + "detailAbsent": true, + "serializedOutcomeMustNotContain": [ + "fx_entry_private_001", + "fx_ref_private_001", + "pickup", + "private note", + "draft" + ], + "roleNeverWidensScope": true, + "zeroWrites": true + } +} diff --git a/spikes/agent-experience/references/fixtures/F-AX-RESUME-REFS-001.json b/spikes/agent-experience/references/fixtures/F-AX-RESUME-REFS-001.json new file mode 100644 index 0000000..f702a97 --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-RESUME-REFS-001.json @@ -0,0 +1,126 @@ +{ + "fixtureId": "F-AX-RESUME-REFS-001", + "kind": "acceptance", + "title": "resume produces the same envelope refs as fresh capture; the historical answer renders at its current status", + "contractSource": "art_gCDrtx4S section 5, F-AX-RESUME-REFS-001 (serves slot 17)", + "scenario": { + "narrative": "Mom asks 'she slept an hour' (the F-AX-CLARIFY-001 envelope); the clarification is shown; the app is killed. While the app is closed, revision fx_rev_001 commits (watermark v1). Mom reopens and answers 'Mia'. The resumed session's follow-up envelope carries the same references[] (same referenceIds, targetIds, visibleToActor) with currentChild now user-asserted, and the previously served answer A1 from history renders superseded - never the pre-correction value as current.", + "anchors": { + "askUtc": "2026-09-17T18:30:00Z", + "revisionCommittedUtc": "2026-09-17T20:30:00Z", + "resumeUtc": "2026-09-17T23:00:00Z" + } + }, + "input": { + "originalEnvelope": { + "envelopeId": "fx_env_clarify_001", + "captureId": "fx_capture_001", + "capturedAt": 1789669800000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "she slept an hour at nap today", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "viewContext": { + "value": { "screen": "timeline" }, + "source": "app-known", + "basis": "timeline screen open" + }, + "references": [ + { + "referenceId": "fx_ref_001", + "kind": "event", + "targetId": "fx_evt_sleep_001", + "relatedChildId": "fx_child_m", + "snippet": "Mia - nap, 1 hour", + "source": "app-known", + "visibleToActor": true + }, + { + "referenceId": "fx_ref_002", + "kind": "event", + "targetId": "fx_evt_leo_nap_001", + "relatedChildId": "fx_child_l", + "snippet": "Leo - nap, 45 minutes", + "source": "app-known", + "visibleToActor": true + } + ] + }, + "historicalAnswerA1": { + "_tag": "answered", + "envelopeId": "fx_env_ask_001", + "response": "Mia napped for 1 hour.", + "citations": [{ "recordId": "fx_evt_sleep_001", "recordKind": "event" }], + "answerId": "fx_ans_001", + "readWatermark": { "householdId": "fx_household_1", "version": 0 }, + "status": "current" + }, + "revisionWhileClosed": { + "revisionId": "fx_rev_001", + "targetRecordId": "fx_evt_sleep_001", + "containingEntryId": "fx_entry_sleep_001", + "revisedAt": 1789677000000, + "summary": "quantity: 1 hour -> 45 minutes" + }, + "resumedEnvelope": { + "envelopeId": "fx_env_resume_001", + "captureId": "fx_capture_resume_001", + "capturedAt": 1789686000000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "Mia", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "currentChild": { + "value": { "childId": "fx_child_m", "displayName": "Mia" }, + "source": "user-asserted", + "basis": "mom's spoken answer to the pending clarification" + }, + "viewContext": { + "value": { "screen": "timeline" }, + "source": "app-known", + "basis": "timeline screen open" + }, + "references": [ + { + "referenceId": "fx_ref_001", + "kind": "event", + "targetId": "fx_evt_sleep_001", + "relatedChildId": "fx_child_m", + "snippet": "Mia - nap, 1 hour", + "source": "app-known", + "visibleToActor": true + }, + { + "referenceId": "fx_ref_002", + "kind": "event", + "targetId": "fx_evt_leo_nap_001", + "relatedChildId": "fx_child_l", + "snippet": "Leo - nap, 45 minutes", + "source": "app-known", + "visibleToActor": true + } + ] + } + }, + "expected": { + "sameReferenceIds": ["fx_ref_001", "fx_ref_002"], + "sameTargetIds": ["fx_evt_sleep_001", "fx_evt_leo_nap_001"], + "sameVisibleToActor": [true, true], + "resumedCurrentChildSource": "user-asserted", + "resumedCurrentChildChildId": "fx_child_m", + "reClarifyOutcomeTag": "resolved", + "reClarifyTargetId": "fx_child_m", + "reClarifyProvenance": "user-asserted", + "historicalAnswerStatusAfterRestore": "superseded", + "historicalAnswerSupersededByRevisionId": "fx_rev_001", + "historicalAnswerServableAsCurrent": false + } +} diff --git a/spikes/agent-experience/references/fixtures/F-AX-STALE-ANSWER-001.json b/spikes/agent-experience/references/fixtures/F-AX-STALE-ANSWER-001.json new file mode 100644 index 0000000..d84ae60 --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-STALE-ANSWER-001.json @@ -0,0 +1,43 @@ +{ + "fixtureId": "F-AX-STALE-ANSWER-001", + "kind": "adversarial", + "title": "a served answer never retains the pre-correction value", + "contractSource": "art_gCDrtx4S section 5, F-AX-STALE-ANSWER-001 (serving-layer behavior over the F-AX-CORRECT-ANSWER-001 lineage)", + "scenario": { + "narrative": "Any request that would return A1 after fx_rev_001 has committed - a replay of A1's (envelopeId, watermark) key, a history render, or a cached serve. No serving path may present the pre-correction value as current truth: every path either recomputes at the current watermark or renders A1 only as superseded with the revision pointer visible.", + "anchors": { + "correctionCommittedUtc": "2026-09-17T20:30:00Z", + "attemptedServeUtc": "2026-09-17T23:00:00Z" + } + }, + "input": { + "storedAnswerA1": { + "_tag": "answered", + "envelopeId": "fx_env_ask_001", + "response": "Mia napped for 1 hour.", + "citations": [{ "recordId": "fx_evt_sleep_001", "recordKind": "event" }], + "answerId": "fx_ans_001", + "readWatermark": { "householdId": "fx_household_1", "version": 0 }, + "status": "superseded", + "supersededByRevisionId": "fx_rev_001" + }, + "revision": { + "revisionId": "fx_rev_001", + "targetRecordId": "fx_evt_sleep_001", + "containingEntryId": "fx_entry_sleep_001", + "revisedAt": 1789677000000, + "summary": "quantity: 1 hour -> 45 minutes" + }, + "currentWatermarkVersion": 1, + "servingPaths": ["replayed-key", "history-render", "cached-serve"] + }, + "expected": { + "everyPathOutcomeTag": "watermark-moved", + "observedVersion": 0, + "currentVersion": 1, + "errorRetryable": true, + "serializedErrorMustNotContain": ["Mia napped for 1 hour", "1 hour", "fx_ans_001"], + "preCorrectionValueNeverCurrent": true, + "recomputedAnswerCitesRevisionId": "fx_rev_001" + } +} diff --git a/spikes/agent-experience/references/fixtures/F-AX-UNRESOLVED-CORRECTION-001.json b/spikes/agent-experience/references/fixtures/F-AX-UNRESOLVED-CORRECTION-001.json new file mode 100644 index 0000000..f94fad9 --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-UNRESOLVED-CORRECTION-001.json @@ -0,0 +1,38 @@ +{ + "fixtureId": "F-AX-UNRESOLVED-CORRECTION-001", + "kind": "adversarial", + "title": "a correction with no resolvable target invents nothing", + "contractSource": "art_gCDrtx4S section 5, F-AX-UNRESOLVED-CORRECTION-001", + "scenario": { + "narrative": "Mom says 'actually 45 minutes' with no reference in the envelope and no selected record - only the child context. currentChild does not license a target: a child is not a correction target. The system invents nothing - no 'most recent event' default, no duration-only fabricated event, no guessed binding - and returns the typed unresolved-reference error, never an error string naming a real record.", + "anchors": { "correctionAttemptUtc": "2026-09-17T20:30:00Z" } + }, + "input": { + "envelope": { + "envelopeId": "fx_env_corr_001", + "captureId": "fx_capture_corr_001", + "capturedAt": 1789677000000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "actually 45 minutes", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "currentChild": { + "value": { "childId": "fx_child_m", "displayName": "Mia" }, + "source": "app-known", + "basis": "child detail screen" + } + } + }, + "expected": { + "outcomeTag": "unresolved-reference", + "reason": "no-reference", + "retryable": false, + "detailAbsent": true, + "serializedOutcomeMustNotContain": ["45", "fx_evt_sleep_001", "fx_rev_001", "fx_child_m"], + "zeroWrites": true + } +} diff --git a/spikes/agent-experience/references/package.json b/spikes/agent-experience/references/package.json new file mode 100644 index 0000000..b0c135f --- /dev/null +++ b/spikes/agent-experience/references/package.json @@ -0,0 +1,11 @@ +{ + "name": "@spike/agent-experience-references", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Spike: ambiguous-reference clarify reducer + correction-driven answer invalidation (slice 1 of Remember & Retrieve, art_gCDrtx4S)", + "scripts": { + "test": "bun test", + "typecheck": "tsc -p tsconfig.test.json --noEmit" + } +} diff --git a/spikes/agent-experience/references/reducer.ts b/spikes/agent-experience/references/reducer.ts new file mode 100644 index 0000000..ef5def5 --- /dev/null +++ b/spikes/agent-experience/references/reducer.ts @@ -0,0 +1,297 @@ +/** + * Pure deterministic reducers for ambiguous-reference clarify and + * correction-driven answer invalidation (spike slice 1). + * + * Contract source: art_gCDrtx4S §2.1 (envelope-only resolution table), + * §2.2 (lineage watermark + citation-intersection invalidation), §4 + * (operation semantics). No Convex, no LLM, no clock, no randomness: every + * function here is a pure function of its inputs, so the same inputs always + * produce the same outputs and the fixtures are executable proofs. + * + * Runtime note (verified on effect@4.0.0-rc.115): there is no + * Effect.catchAll and no bare Effect.catch on this pin — but no effect + * composition is needed here at all; these are plain functions. + */ + +import type { + Answered, + ClarifyOutcome, + ClarifyQuestion, + LineageWatermark, + ReferenceEnvelope, + RevisionLink, + WatermarkMoved, +} from "./schema.js" + +/** Hard rule (art_gCDrtx4S §2.2): a superseded answer is never served. */ +const CLARIFY_QUESTION = "Which of these did you mean?" + +/** Maximum clarification options (art_gCDrtx4S §4, open question 2 default). */ +const MAX_OPTIONS = 4 + +/** + * The records a revision marks as changed: the revised record plus its + * containing entry, when present (art_gCDrtx4S §2.2 — "a revision of an + * event marks both the event and its containing entry as revised, so + * entry-level citations catch it too"). + */ +export const changedRecordSet = (revision: RevisionLink): readonly string[] => + revision.containingEntryId === undefined + ? [revision.targetRecordId] + : [revision.targetRecordId, revision.containingEntryId] + +/** + * Monotonic watermark bump — exactly +1 per committed revision. No clock, + * no randomness: the version is derived purely from the previous version. + */ +export const bumpWatermark = (watermark: LineageWatermark): LineageWatermark => ({ + householdId: watermark.householdId, + version: watermark.version + 1, +}) + +/** + * Citation-intersection invalidation (art_gCDrtx4S §2.2): an answer is + * superseded iff its cited record ids intersect the revision's changed-record + * set. Exhaustive because envelope citations name every record read. + * + * Only `current` answers flip: a superseded answer keeps the revision that + * retired it (first pointer wins — never overwritten by later revisions). + * Marked, never deleted: every answer in the input appears in the output. + */ +export const invalidateAnswers = ( + answers: readonly Answered[], + revision: RevisionLink, +): { answers: Answered[]; supersededAnswerIds: string[] } => { + const changed = changedRecordSet(revision) + const supersededAnswerIds: string[] = [] + const next = answers.map((answer) => { + if (answer.status !== "current") return answer + const intersects = answer.citations.some((citation) => changed.includes(citation.recordId)) + if (!intersects) return answer + supersededAnswerIds.push(answer.answerId) + return { ...answer, status: "superseded" as const, supersededByRevisionId: revision.revisionId } + }) + return { answers: next, supersededAnswerIds } +} + +/** + * Append-only answer/revision corpus for one household. Pure data — the + * Convex persistence mapping is out of spike scope (no adapter here). + */ +export interface ReferenceStore { + readonly householdId: string + /** Current lineage version; bumped only by commitRevision. */ + readonly watermarkVersion: number + /** Every answer ever persisted, current and superseded — never deleted. */ + readonly answers: readonly Answered[] + /** Revision ids already applied — append-only, guards re-commit. */ + readonly committedRevisionIds: readonly string[] +} + +/** + * Commit a correction revision: bump the household lineage watermark and + * supersede every answer whose citations intersect the changed-record set. + * Idempotent on `revision.revisionId` — re-committing an already-applied + * revision is a recorded no-op (no second bump, no re-invalidation). + * + * The only write in a correction chain happens here, by construction: the + * clarify and answer operations below cannot produce a mutation. + */ +export const commitRevision = ( + store: ReferenceStore, + revision: RevisionLink, +): { store: ReferenceStore; supersededAnswerIds: readonly string[] } => { + if (store.committedRevisionIds.includes(revision.revisionId)) { + return { store, supersededAnswerIds: [] } + } + const { answers, supersededAnswerIds } = invalidateAnswers(store.answers, revision) + return { + store: { + householdId: store.householdId, + watermarkVersion: bumpWatermark({ + householdId: store.householdId, + version: store.watermarkVersion, + }).version, + answers, + committedRevisionIds: [...store.committedRevisionIds, revision.revisionId], + }, + supersededAnswerIds, + } +} + +/** + * Serving gate (art_gCDrtx4S §4 "Serving rule"): a stored answer is served + * only while `status = "current"`. A superseded answer is never served as + * content — the caller gets a typed, retryable `watermark-moved` error and + * recomputes at the current watermark. An absent answer is `undefined` + * (truthful not-stored; the caller recomputes). + * + * A `current` answer stays servable even when the watermark has moved: + * invalidation is citation-intersection, not version comparison — a revision + * to unrelated records must not retire a truthful answer. + */ +export const serveAnswer = ( + answer: Answered | undefined, + currentVersion: number, +): Answered | WatermarkMoved | undefined => { + if (answer === undefined) return undefined + if (answer.status === "superseded") { + return { + _tag: "watermark-moved", + observedVersion: answer.readWatermark.version, + currentVersion, + retryable: true, + } + } + return answer +} + +// ---- clarify: envelope-only reference resolution (art_gCDrtx4S §2.1) ---- + +interface Candidate { + readonly targetId: string + readonly kind: "child" | "entry" | "event" | "message" + readonly label: string + readonly provenance: ClarifyQuestion["options"][number]["provenance"] + /** The record a reference-derived candidate was derived from, if any. */ + readonly viaRecordId?: string +} + +/** + * Resolve the envelope's ambiguous reference, or bound it into a focused + * clarification. Uses EXACTLY the proposal's three inputs — currentChild, + * viewContext.selectedRecord, references[] — and nothing else: no corpus + * statistics, no recency defaults, no cross-child inference. + * + * Outcome table (art_gCDrtx4S §2.1): + * - 0 visible record candidates → unresolved-reference / no-reference + * (or / target-not-visible when candidates existed but none were visible + * to the actor — the typed reason is the only existence disclosure) + * - exactly 1 → resolved binding, provenance recorded + * - 2–4, all visible → focused clarification: one question, + * options = the candidates, read-scoped + * - more than the bound → unresolved-reference / ambiguous + * - candidate not visible / other child → target-not-visible / + * cross-child-blocked — never a softened read + * + * currentChild is a TIEBREAKER, never a candidate: "a child is not a + * correction target" (§5 F-AX-UNRESOLVED-CORRECTION-001) — a child-only + * envelope resolves nothing. When currentChild is asserted and child-kind + * candidates exist, the candidates bound to that child win; if none match, + * the reference points at another child → cross-child-blocked. + */ +export const computeClarify = (envelope: ReferenceEnvelope): ClarifyOutcome => { + const references = envelope.references ?? [] + const visible = references.filter((reference) => reference.visibleToActor) + const hadInvisible = visible.length < references.length + + const candidates: Candidate[] = [] + for (const reference of visible) { + if (reference.relatedChildId !== undefined) { + candidates.push({ + targetId: reference.relatedChildId, + kind: "child", + label: reference.snippet ?? reference.relatedChildId, + provenance: reference.source, + viaRecordId: reference.targetId, + }) + } else { + candidates.push({ + targetId: reference.targetId, + kind: reference.kind, + label: reference.snippet ?? reference.targetId, + provenance: reference.source, + viaRecordId: reference.targetId, + }) + } + } + const viewContext = envelope.viewContext + const selectedRecord = viewContext?.value.selectedRecord + if (viewContext !== undefined && selectedRecord !== undefined) { + candidates.push({ + targetId: selectedRecord.recordId, + kind: selectedRecord.recordKind, + label: selectedRecord.recordId, + provenance: viewContext.source, + viaRecordId: selectedRecord.recordId, + }) + } + + const currentChildId = envelope.currentChild?.value.childId + let working = candidates + let tied = false + if (currentChildId !== undefined) { + const childCandidates = working.filter((candidate) => candidate.kind === "child") + if (childCandidates.length > 0) { + const matching = childCandidates.filter((candidate) => candidate.targetId === currentChildId) + if (matching.length === 0) { + return { + _tag: "unresolved-reference", + envelopeId: envelope.envelopeId, + reason: "cross-child-blocked", + retryable: false, + } + } + working = matching + tied = true + } + } + + if (working.length === 0) { + return { + _tag: "unresolved-reference", + envelopeId: envelope.envelopeId, + reason: hadInvisible ? "target-not-visible" : "no-reference", + retryable: false, + } + } + + const only = working.length === 1 ? working[0] : undefined + if (only !== undefined) { + return { + _tag: "resolved", + envelopeId: envelope.envelopeId, + targetId: only.targetId, + kind: only.kind, + provenance: tied ? (envelope.currentChild?.source ?? only.provenance) : only.provenance, + basis: tied + ? `bound by ${envelope.currentChild?.source ?? "currentChild"} currentChild via reference ${only.viaRecordId ?? only.targetId}` + : "sole visible candidate in envelope context", + } + } + + if (working.length > MAX_OPTIONS) { + return { + _tag: "unresolved-reference", + envelopeId: envelope.envelopeId, + reason: "ambiguous", + detail: `reference bound exceeded: ${working.length} candidates, maximum ${MAX_OPTIONS}`, + retryable: false, + } + } + + const seen = new Set() + const options = working + .map((candidate) => ({ + targetId: candidate.targetId, + kind: candidate.kind, + label: candidate.label, + provenance: candidate.provenance, + })) + .filter((option) => { + const key = `${option.kind}:${option.targetId}` + if (seen.has(key)) return false + seen.add(key) + return true + }) + + const ambiguousReferenceIds = [...new Set(working.flatMap((c) => (c.viaRecordId ? [c.viaRecordId] : [])))] + const question: ClarifyQuestion = { + _tag: "clarify-question", + envelopeId: envelope.envelopeId, + question: CLARIFY_QUESTION, + options, + ambiguousReferenceIds, + } + return question +} diff --git a/spikes/agent-experience/references/references.test.ts b/spikes/agent-experience/references/references.test.ts new file mode 100644 index 0000000..e52534b --- /dev/null +++ b/spikes/agent-experience/references/references.test.ts @@ -0,0 +1,581 @@ +/** + * Executable proofs for the ambiguous-reference clarify + correction-driven + * answer invalidation spike (art_gCDrtx4S, synthesis art_gfwpdmWF §3/§6). + * + * Every fixture case runs against the pure reducers in reducer.ts with fixed + * times and synthetic fx_* ids only — no provider, no clock, no randomness. + * The `expected` blocks in the fixture JSON drive the exact-string asserts. + */ + +import { describe, expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import { join } from "node:path" +import { Schema } from "effect" +import { + bumpWatermark, + changedRecordSet, + commitRevision, + computeClarify, + invalidateAnswers, + serveAnswer, + type ReferenceStore, +} from "./reducer.js" +import { + Answered, + Citation, + ClarifyOption, + ClarifyOutcome, + LineageWatermark, + ProvenanceSource, + ReferenceEnvelope, + RevisionLink, + UnresolvedReference, +} from "./schema.js" + +// ---- fixture loading + schema bridges ---- + +interface Fixture { + fixtureId: string + input: Record + expected: Record +} + +const loadFixture = (name: string): Fixture => + JSON.parse(readFileSync(join(import.meta.dir, "fixtures", `${name}.json`), "utf8")) + +const decodeEnvelope = (value: unknown): ReferenceEnvelope => + Schema.decodeUnknownSync(ReferenceEnvelope)(value) + +/** Decode + encodeSync round-trip: the wire shape survives the full cycle. */ +const envelopeRoundTrip = (value: unknown): ReferenceEnvelope => { + const decoded = decodeEnvelope(value) + // the wire value provably decodes (line above) — comparing shapes against the same value + expect(Schema.encodeSync(ReferenceEnvelope)(decoded)).toEqual(value as ReferenceEnvelope) + return decoded +} + +const decodeAnswered = (value: unknown): Answered => Schema.decodeUnknownSync(Answered)(value) + +const decodeRevision = (value: unknown): RevisionLink => Schema.decodeUnknownSync(RevisionLink)(value) + +const expectTag = ( + outcome: ClarifyOutcome, + tag: Tag, +): Extract => { + if (outcome._tag !== tag) throw new Error(`expected ${tag}, got ${outcome._tag}`) + return outcome as Extract +} + +const emptyStore = (...answers: readonly Answered[]): ReferenceStore => ({ + householdId: "fx_household_1", + watermarkVersion: 0, + answers: [...answers], + committedRevisionIds: [], +}) + +// ---- schema decode round-trips ---- + +describe("schema decode round-trips", () => { + test("every fixture envelope decodes and encodes to identical JSON", () => { + envelopeRoundTrip(loadFixture("F-AX-CLARIFY-001").input.envelope) + const correct = loadFixture("F-AX-CORRECT-ANSWER-001") + envelopeRoundTrip(correct.input.envelopeAsk) + envelopeRoundTrip(correct.input.envelopeCorrect) + const resume = loadFixture("F-AX-RESUME-REFS-001") + envelopeRoundTrip(resume.input.originalEnvelope) + envelopeRoundTrip(resume.input.resumedEnvelope) + envelopeRoundTrip(loadFixture("F-AX-UNRESOLVED-CORRECTION-001").input.envelope) + envelopeRoundTrip(loadFixture("F-AX-LEAK-001").input.envelope) + }) + + test("fixture answers, revision, and watermark decode and round-trip", () => { + const correct = loadFixture("F-AX-CORRECT-ANSWER-001") + const a1 = decodeAnswered(correct.input.answerA1) + const a2 = decodeAnswered(correct.input.answerA2) + const revision = decodeRevision(correct.input.revision) + const stale = loadFixture("F-AX-STALE-ANSWER-001") + const superseded = decodeAnswered(stale.input.storedAnswerA1) + expect(Schema.encodeSync(Answered)(a1)).toEqual(a1) + expect(Schema.encodeSync(Answered)(a2)).toEqual(a2) + expect(Schema.encodeSync(Answered)(superseded)).toEqual(superseded) + expect(Schema.encodeSync(RevisionLink)(revision)).toEqual(revision) + expect(Schema.encodeSync(LineageWatermark)(a1.readWatermark)).toEqual(a1.readWatermark) + expect(Schema.encodeSync(LineageWatermark)(a2.readWatermark)).toEqual(a2.readWatermark) + expect(a1.status).toBe("current") + expect(superseded.status).toBe("superseded") + }) + + test("malformed values fail closed at decode", () => { + expect(() => Schema.decodeUnknownSync(ProvenanceSource)("guessed")).toThrow() + expect(() => + Schema.decodeUnknownSync(UnresolvedReference)({ + _tag: "unresolved-reference", + envelopeId: "fx_env_x", + reason: "most-recent-guess", + retryable: false, + }), + ).toThrow() + }) + + test("every fixture clarify outcome decodes against the read-only union", () => { + const outcomes = [ + computeClarify(envelopeRoundTrip(loadFixture("F-AX-CLARIFY-001").input.envelope)), + computeClarify(decodeEnvelope(loadFixture("F-AX-CORRECT-ANSWER-001").input.envelopeCorrect)), + computeClarify(decodeEnvelope(loadFixture("F-AX-RESUME-REFS-001").input.resumedEnvelope)), + computeClarify(decodeEnvelope(loadFixture("F-AX-UNRESOLVED-CORRECTION-001").input.envelope)), + computeClarify(decodeEnvelope(loadFixture("F-AX-LEAK-001").input.envelope)), + ] + for (const outcome of outcomes) { + expect(Schema.decodeUnknownSync(ClarifyOutcome)(outcome)).toEqual(outcome) + expect(Schema.encodeSync(ClarifyOutcome)(outcome)).toEqual(outcome) + } + }) +}) + +// ---- F-AX-CLARIFY-001 ---- + +describe("F-AX-CLARIFY-001", () => { + test("two in-scope children produce one bounded clarification with exact options", () => { + const fixture = loadFixture("F-AX-CLARIFY-001") + const expected = fixture.expected as { + question: string + optionCount: number + optionTargetIds: string[] + optionKinds: ClarifyOption["kind"][] + optionLabels: string[] + optionProvenance: ProvenanceSource[] + ambiguousReferenceIds: string[] + } + const outcome = computeClarify(envelopeRoundTrip(fixture.input.envelope)) + const question = expectTag(outcome, "clarify-question") + + expect(question.question).toBe(expected.question) + expect(question.options).toHaveLength(expected.optionCount) + expect(question.options.map((option) => option.targetId)).toEqual(expected.optionTargetIds) + expect(question.options.map((option) => option.kind)).toEqual(expected.optionKinds) + expect(question.options.map((option) => option.label)).toEqual(expected.optionLabels) + expect(question.options.map((option) => option.provenance)).toEqual(expected.optionProvenance) + expect(question.ambiguousReferenceIds).toEqual(expected.ambiguousReferenceIds) + }) + + test("clarification is read-scoped: input untouched, no write payload anywhere", () => { + const fixture = loadFixture("F-AX-CLARIFY-001") + const envelope = decodeEnvelope(fixture.input.envelope) + const snapshot = structuredClone(envelope) + const outcome = computeClarify(envelope) + + expect(envelope).toEqual(snapshot) + expect(Object.keys(outcome).sort()).toEqual( + ["_tag", "ambiguousReferenceIds", "envelopeId", "options", "question"].sort(), + ) + for (const option of expectTag(outcome, "clarify-question").options) { + expect(Object.keys(option).sort()).toEqual(["kind", "label", "provenance", "targetId"].sort()) + } + }) +}) + +// ---- F-AX-CORRECT-ANSWER-001 ---- + +describe("F-AX-CORRECT-ANSWER-001", () => { + const fixture = loadFixture("F-AX-CORRECT-ANSWER-001") + const expected = fixture.expected as { + clarifyOnCorrectionEnvelope: { outcomeTag: string; targetId: string; kind: ClarifyOption["kind"]; provenance: ProvenanceSource } + a2Status: Answered["status"] + a1ReadWatermarkVersion: number + a2ReadWatermarkVersion: number + a2VersionStrictlyGreaterThanA1: boolean + a2ResponseStates: string + a2CitationRecordIds: string[] + a2CitationRecordKinds: Citation["recordKind"][] + a2RevisionChainLength: number + a2RevisionChainSummary: string + a1FinalStatus: Answered["status"] + a1SupersededByRevisionId: string + a1RetrievableAfterRevision: boolean + a1ServableAsCurrent: boolean + zeroWritesFromAnswerOps: boolean + } + const a1 = decodeAnswered(fixture.input.answerA1) + const a2 = decodeAnswered(fixture.input.answerA2) + const revision = decodeRevision(fixture.input.revision) + const correctionEnvelope = decodeEnvelope(fixture.input.envelopeCorrect) + + test("the correction envelope resolves its target from viewContext alone", () => { + const outcome = computeClarify(correctionEnvelope) + const binding = expectTag(outcome, "resolved") + const expectedTarget = expected.clarifyOnCorrectionEnvelope + expect(binding.targetId).toBe(expectedTarget.targetId) + expect(binding.kind).toBe(expectedTarget.kind) + expect(binding.provenance).toBe(expectedTarget.provenance) + }) + + test("committing the revision supersedes A1 exhaustively and bumps the watermark exactly once", () => { + const { store, supersededAnswerIds } = commitRevision(emptyStore(a1), revision) + + expect(store.watermarkVersion).toBe(expected.a2ReadWatermarkVersion) + expect(supersededAnswerIds).toEqual(["fx_ans_001"]) + // marked, never deleted + expect(store.answers).toHaveLength(1) + const a1After = store.answers[0] + expect(a1After?.status).toBe(expected.a1FinalStatus) + // RevisionId is a branded string — normalize for the comparison + expect(String(a1After?.supersededByRevisionId)).toBe(expected.a1SupersededByRevisionId) + expect(store.committedRevisionIds).toEqual(["fx_rev_001"]) + }) + + test("A2 cites the revision chain and is servable; A1 is never servable as current", () => { + expect(a2.status).toBe(expected.a2Status) + expect(a2.readWatermark.version > a1.readWatermark.version).toBe(expected.a2VersionStrictlyGreaterThanA1) + expect(a2.citations.map((citation) => citation.recordId)).toEqual(expected.a2CitationRecordIds) + expect(a2.citations.map((citation) => citation.recordKind)).toEqual(expected.a2CitationRecordKinds) + const chain = a2.revisionChain ?? [] + expect(chain).toHaveLength(expected.a2RevisionChainLength) + expect(chain[0]?.summary).toBe(expected.a2RevisionChainSummary) + + const servedA2 = serveAnswer(a2, 1) + expect(servedA2).toBe(a2) // current answer served as-is + + const { store } = commitRevision(emptyStore(a1), revision) + const servedA1 = serveAnswer(store.answers[0], 1) + if (servedA1 === undefined || servedA1._tag !== "watermark-moved") { + throw new Error(`expected watermark-moved, got ${JSON.stringify(servedA1)}`) + } + expect(servedA1.observedVersion).toBe(expected.a1ReadWatermarkVersion) + expect(servedA1.currentVersion).toBe(expected.a2ReadWatermarkVersion) + expect(JSON.stringify(servedA1)).not.toContain("1 hour") + }) +}) + +// ---- F-AX-RESUME-REFS-001 ---- + +describe("F-AX-RESUME-REFS-001", () => { + const fixture = loadFixture("F-AX-RESUME-REFS-001") + const expected = fixture.expected as { + sameReferenceIds: string[] + sameTargetIds: string[] + sameVisibleToActor: boolean[] + resumedCurrentChildSource: ProvenanceSource + resumedCurrentChildChildId: string + reClarifyOutcomeTag: string + reClarifyTargetId: string + reClarifyProvenance: ProvenanceSource + historicalAnswerStatusAfterRestore: Answered["status"] + historicalAnswerSupersededByRevisionId: string + historicalAnswerServableAsCurrent: boolean + } + const original = decodeEnvelope(fixture.input.originalEnvelope) + const resumed = decodeEnvelope(fixture.input.resumedEnvelope) + const historical = decodeAnswered(fixture.input.historicalAnswerA1) + const revision = decodeRevision(fixture.input.revisionWhileClosed) + + test("the resumed envelope carries the same references with currentChild user-asserted", () => { + const projected = (envelope: ReferenceEnvelope) => + envelope.references?.map((reference) => ({ + referenceId: reference.referenceId, + targetId: reference.targetId, + visibleToActor: reference.visibleToActor, + })) + expect(projected(resumed)).toEqual(projected(original)) + expect(projected(resumed)?.map((reference) => reference.referenceId)).toEqual(expected.sameReferenceIds) + expect(projected(resumed)?.map((reference) => reference.targetId)).toEqual(expected.sameTargetIds) + expect(projected(resumed)?.map((reference) => reference.visibleToActor)).toEqual(expected.sameVisibleToActor) + expect(resumed.currentChild?.source).toBe(expected.resumedCurrentChildSource) + expect(resumed.currentChild?.value.childId).toBe(expected.resumedCurrentChildChildId) + }) + + test("the spoken answer resolves by user-asserted provenance, not by re-guessing", () => { + const outcome = computeClarify(resumed) + const binding = expectTag(outcome, "resolved") + expect(binding.targetId).toBe(expected.reClarifyTargetId) + expect(binding.provenance).toBe(expected.reClarifyProvenance) + }) + + test("a historical answer renders superseded after restore — never as current truth", () => { + const { store } = commitRevision(emptyStore(historical), revision) + const restored = store.answers[0] + expect(restored?.status).toBe(expected.historicalAnswerStatusAfterRestore) + // RevisionId is a branded string — normalize for the comparison + expect(String(restored?.supersededByRevisionId)).toBe(expected.historicalAnswerSupersededByRevisionId) + const served = serveAnswer(restored, store.watermarkVersion) + if (served === undefined || served._tag !== "watermark-moved") { + throw new Error(`expected watermark-moved, got ${JSON.stringify(served)}`) + } + expect(served.observedVersion).toBe(historical.readWatermark.version) + }) +}) + +// ---- F-AX-STALE-ANSWER-001 ---- + +describe("F-AX-STALE-ANSWER-001", () => { + const fixture = loadFixture("F-AX-STALE-ANSWER-001") + const expected = fixture.expected as { + everyPathOutcomeTag: string + observedVersion: number + currentVersion: number + errorRetryable: boolean + serializedErrorMustNotContain: string[] + preCorrectionValueNeverCurrent: boolean + recomputedAnswerCitesRevisionId: string + } + const stale = decodeAnswered(fixture.input.storedAnswerA1) + const currentVersion = fixture.input.currentWatermarkVersion as number + + test("every serving path gets the typed retryable error — never the pre-correction value", () => { + for (const path of fixture.input.servingPaths as string[]) { + const served = serveAnswer(stale, currentVersion) + if (served === undefined || served._tag !== "watermark-moved") { + throw new Error(`path ${path}: expected watermark-moved, got ${JSON.stringify(served)}`) + } + expect(served.observedVersion).toBe(expected.observedVersion) + expect(served.currentVersion).toBe(expected.currentVersion) + expect(served.retryable).toBe(expected.errorRetryable) + const serialized = JSON.stringify(served) + for (const forbidden of expected.serializedErrorMustNotContain) { + expect(serialized).not.toContain(forbidden) + } + // never the stored response, never the stored object + expect(served).not.toBe(stale) + expect(served).not.toHaveProperty("response") + } + }) + + test("the recomputed answer cites the revision and is servable at the current watermark", () => { + const a2 = decodeAnswered(loadFixture("F-AX-CORRECT-ANSWER-001").input.answerA2) + expect(a2.citations.some((citation) => citation.recordId === expected.recomputedAnswerCitesRevisionId)).toBe( + true, + ) + expect(serveAnswer(a2, currentVersion)).toBe(a2) + }) +}) + +// ---- F-AX-UNRESOLVED-CORRECTION-001 ---- + +describe("F-AX-UNRESOLVED-CORRECTION-001", () => { + const fixture = loadFixture("F-AX-UNRESOLVED-CORRECTION-001") + const expected = fixture.expected as { + outcomeTag: string + reason: UnresolvedReference["reason"] + retryable: boolean + detailAbsent: boolean + serializedOutcomeMustNotContain: string[] + zeroWrites: boolean + } + + test("a correction with no resolvable target returns the typed error and invents nothing", () => { + const envelope = decodeEnvelope(fixture.input.envelope) + const snapshot = structuredClone(envelope) + const outcome = computeClarify(envelope) + const unresolved = expectTag(outcome, "unresolved-reference") + + expect(unresolved.reason).toBe(expected.reason) + expect(unresolved.retryable).toBe(expected.retryable) + expect("detail" in unresolved).toBe(false) + + const serialized = JSON.stringify(outcome) + for (const forbidden of expected.serializedOutcomeMustNotContain) { + expect(serialized).not.toContain(forbidden) + } + expect(envelope).toEqual(snapshot) + }) +}) + +// ---- F-AX-LEAK-001 ---- + +describe("F-AX-LEAK-001", () => { + const fixture = loadFixture("F-AX-LEAK-001") + const expected = fixture.expected as { + outcomeTag: string + reason: UnresolvedReference["reason"] + retryable: boolean + detailAbsent: boolean + serializedOutcomeMustNotContain: string[] + roleNeverWidensScope: boolean + zeroWrites: boolean + } + + test("an invisible private reference fails typed and leaks neither id nor content", () => { + const envelope = decodeEnvelope(fixture.input.envelope) + const snapshot = structuredClone(envelope) + const outcome = computeClarify(envelope) + const unresolved = expectTag(outcome, "unresolved-reference") + + expect(unresolved.reason).toBe(expected.reason) + expect(unresolved.retryable).toBe(expected.retryable) + expect("detail" in unresolved).toBe(false) + + const serialized = JSON.stringify(outcome) + for (const forbidden of expected.serializedOutcomeMustNotContain) { + expect(serialized).not.toContain(forbidden) + } + expect(envelope).toEqual(snapshot) + }) + + test("publication state and audience hold separately, and role never widens scope", () => { + const envelope = decodeEnvelope(fixture.input.envelope) + const privateRecord = fixture.input.privateRecord as { + publicationState: string + audience: string[] + } + // two independent exclusion reasons, never fused into one field + expect(privateRecord.publicationState).toBe("draft") + expect(privateRecord.audience).not.toContain("fx_caregiver_1") + + const baseline = computeClarify(envelope) + // flipping the role to parent without touching per-record visibility must not widen scope + const flipped = { ...envelope, actor: { authorId: "fx_caregiver_1", role: "parent" as const } } + const flippedOutcome = computeClarify(flipped) + expect(flippedOutcome).toEqual(baseline) + expect(expectTag(flippedOutcome, "unresolved-reference").reason).toBe("target-not-visible") + }) +}) + +// ---- invariants beyond the six fixtures ---- + +describe("invariants beyond the fixtures", () => { + test("changedRecordSet covers the event and its containing entry", () => { + const withEntry = decodeRevision({ + revisionId: "fx_rev_t001", + targetRecordId: "fx_evt_sleep_001", + containingEntryId: "fx_entry_sleep_001", + revisedAt: 1789677000000, + summary: "test revision", + }) + const withoutEntry = decodeRevision({ + revisionId: "fx_rev_t002", + targetRecordId: "fx_evt_sleep_001", + revisedAt: 1789677000000, + summary: "test revision", + }) + expect([...changedRecordSet(withEntry)]).toEqual(["fx_evt_sleep_001", "fx_entry_sleep_001"]) + expect([...changedRecordSet(withoutEntry)]).toEqual(["fx_evt_sleep_001"]) + }) + + test("invalidation is exhaustive over cited records and catches entry-level citations", () => { + const citesEvent = decodeAnswered({ + _tag: "answered", + envelopeId: "fx_env_t001", + response: "test answer citing the event", + citations: [{ recordId: "fx_evt_sleep_001", recordKind: "event" }], + answerId: "fx_ans_t001", + readWatermark: { householdId: "fx_household_1", version: 0 }, + status: "current", + }) + const citesEntryOnly = decodeAnswered({ + _tag: "answered", + envelopeId: "fx_env_t002", + response: "test answer citing only the containing entry", + citations: [{ recordId: "fx_entry_sleep_001", recordKind: "entry" }], + answerId: "fx_ans_t002", + readWatermark: { householdId: "fx_household_1", version: 0 }, + status: "current", + }) + const citesElsewhere = decodeAnswered({ + _tag: "answered", + envelopeId: "fx_env_t003", + response: "test answer citing unrelated records", + citations: [{ recordId: "fx_evt_leo_nap_001", recordKind: "event" }], + answerId: "fx_ans_t003", + readWatermark: { householdId: "fx_household_1", version: 0 }, + status: "current", + }) + const revision = decodeRevision({ + revisionId: "fx_rev_t003", + targetRecordId: "fx_evt_sleep_001", + containingEntryId: "fx_entry_sleep_001", + revisedAt: 1789677000000, + summary: "test revision", + }) + + const { answers, supersededAnswerIds } = invalidateAnswers( + [citesEvent, citesEntryOnly, citesElsewhere], + revision, + ) + expect(supersededAnswerIds).toEqual(["fx_ans_t001", "fx_ans_t002"]) + expect(answers).toHaveLength(3) + expect(answers[2]?.status).toBe("current") + // RevisionId is a branded string — normalize for the comparison + expect(String(answers[0]?.supersededByRevisionId)).toBe("fx_rev_t003") + }) + + test("re-committing the same revision is a recorded no-op — one bump, one invalidation", () => { + const revision = decodeRevision({ + revisionId: "fx_rev_t004", + targetRecordId: "fx_evt_sleep_001", + revisedAt: 1789677000000, + summary: "test revision", + }) + const answer = decodeAnswered({ + _tag: "answered", + envelopeId: "fx_env_t004", + response: "test answer", + citations: [{ recordId: "fx_evt_sleep_001", recordKind: "event" }], + answerId: "fx_ans_t004", + readWatermark: { householdId: "fx_household_1", version: 0 }, + status: "current", + }) + const first = commitRevision(emptyStore(answer), revision) + expect(first.store.watermarkVersion).toBe(1) + expect(first.supersededAnswerIds).toEqual(["fx_ans_t004"]) + const second = commitRevision(first.store, revision) + expect(second.store.watermarkVersion).toBe(1) + expect(second.supersededAnswerIds).toEqual([]) + }) + + test("an unrelated revision bumps the watermark but leaves truthful answers servable", () => { + const answer = decodeAnswered({ + _tag: "answered", + envelopeId: "fx_env_t005", + response: "test answer about unrelated records", + citations: [{ recordId: "fx_evt_sleep_001", recordKind: "event" }], + answerId: "fx_ans_t005", + readWatermark: { householdId: "fx_household_1", version: 0 }, + status: "current", + }) + const unrelated = decodeRevision({ + revisionId: "fx_rev_t005", + targetRecordId: "fx_evt_other_999", + revisedAt: 1789677000000, + summary: "test revision elsewhere", + }) + const { store, supersededAnswerIds } = commitRevision(emptyStore(answer), unrelated) + expect(store.watermarkVersion).toBe(1) + expect(supersededAnswerIds).toEqual([]) + expect(serveAnswer(store.answers[0], store.watermarkVersion)).toBe(store.answers[0]) + }) + + test("more candidates than the option bound fail typed as ambiguous", () => { + const envelope = decodeEnvelope({ + envelopeId: "fx_env_t006", + captureId: "fx_capture_t006", + capturedAt: 1789669800000, + capturedAtTimezone: { + value: "America/New_York", + source: "app-known", + basis: "device settings at capture time", + }, + utterance: "test utterance", + actor: { authorId: "fx_parent_a", role: "parent" }, + householdId: "fx_household_1", + references: [1, 2, 3, 4, 5].map((n) => ({ + referenceId: `fx_ref_t00${n}`, + kind: "event", + targetId: `fx_evt_t00${n}`, + snippet: `test event ${n}`, + source: "app-known", + visibleToActor: true, + })), + }) + const outcome = computeClarify(envelope) + const unresolved = expectTag(outcome, "unresolved-reference") + expect(unresolved.reason).toBe("ambiguous") + expect(unresolved.retryable).toBe(false) + }) + + test("bumpWatermark is strictly monotonic by one", () => { + let watermark: LineageWatermark = { householdId: "fx_household_1", version: 0 } + watermark = bumpWatermark(watermark) + expect(watermark.version).toBe(1) + watermark = bumpWatermark(watermark) + expect(watermark.version).toBe(2) + }) +}) diff --git a/spikes/agent-experience/references/schema.ts b/spikes/agent-experience/references/schema.ts new file mode 100644 index 0000000..3cd9276 --- /dev/null +++ b/spikes/agent-experience/references/schema.ts @@ -0,0 +1,279 @@ +import { Schema } from "effect" + +/** + * Ambiguous references + correction-driven answer invalidation (spike slice 1). + * + * Contract source: art_gCDrtx4S — "Remember & Retrieve — Ambiguous References + * & Correction Invalidation (proposal v0.1)" §3 (schema deltas) and §5–6 + * (fixture cases). Cross-area constraints: art_gfwpdmWF §3 (v0.4 fold + * reconciliation) and §6 (executable slice queue, slice 1). + * + * RECONCILIATION (v0.4 fold, per art_gfwpdmWF §3.3): this module restates + * minimal envelope equivalents instead of importing packages/domain — the + * spike must not couple to the canonical domain package while lanes are in + * flight. Every restated export below is drop-in replaced by the folded + * domain module (packages/domain/src/contextEnvelope.ts, operations.ts) at + * the fold; the fold home for the NEW schemas is + * packages/domain/src/clarifyAnswer.ts. + */ + +/** + * RECONCILIATION: restated from packages/domain/src/ids.ts (same bytes) so + * the spike stays import-free; the fold imports the canonical helper. + */ +export const CONVEX_TABLE_ANNOTATION = "convexTable" + +export const convexId = (table: string) => Schema.String.annotate({ [CONVEX_TABLE_ANNOTATION]: table }) + +// ---- restated envelope id fields (art_gCDrtx4S §3 "imported, not redefined") ---- + +export const EnvelopeId = Schema.NonEmptyString +export type EnvelopeId = typeof EnvelopeId["Type"] + +export const RecordId = Schema.NonEmptyString +export type RecordId = typeof RecordId["Type"] + +/** Restated verbatim from packages/domain/src/contextEnvelope.ts. */ +export const ProvenanceSource = Schema.Literals(["user-asserted", "app-known", "inferred"]) +export type ProvenanceSource = typeof ProvenanceSource["Type"] + +export const Actor = Schema.Struct({ + authorId: Schema.String, + role: Schema.Literals(["parent", "caregiver"]), +}) +export type Actor = typeof Actor["Type"] + +export const ProvenancedChild = Schema.Struct({ + value: Schema.Struct({ + childId: convexId("children"), + displayName: Schema.NonEmptyString, + }), + source: ProvenanceSource, + basis: Schema.optionalKey(Schema.NonEmptyString), +}) +export type ProvenancedChild = typeof ProvenancedChild["Type"] + +export const ProvenancedView = Schema.Struct({ + value: Schema.Struct({ + screen: Schema.Literals(["capture", "timeline", "child-detail", "entry-detail"]), + selectedRecord: Schema.optionalKey( + Schema.Struct({ + recordId: Schema.NonEmptyString, + recordKind: Schema.Literals(["entry", "event"]), + }) + ), + }), + source: ProvenanceSource, + basis: Schema.optionalKey(Schema.NonEmptyString), +}) +export type ProvenancedView = typeof ProvenancedView["Type"] + +/** + * Restated PriorReference with one spike-local addition: `relatedChildId`. + * + * RECONCILIATION (flagged for slot 09 / the v0.4 fold): the landed envelope's + * PriorReference carries no child association, but F-AX-CLARIFY-001's + * expected outcome — options are the two in-scope CHILDREN derived from two + * event references — is not derivable envelope-only without it. The clarify + * reducer uses it to (a) offer child options for record references and + * (b) apply the user-asserted currentChild tiebreaker. Whether references + * carry child association is the fold's decision, not this spike's. + */ +export const PriorReference = Schema.Struct({ + referenceId: Schema.NonEmptyString, + kind: Schema.Literals(["entry", "event", "message"]), + targetId: RecordId, + /** Spike-local enrichment — see comment above. */ + relatedChildId: Schema.optionalKey(RecordId), + snippet: Schema.optionalKey(Schema.NonEmptyString), + source: ProvenanceSource, + visibleToActor: Schema.Boolean, +}) +export type PriorReference = typeof PriorReference["Type"] + +/** + * Restated lite ContextEnvelope (packages/domain/src/contextEnvelope.ts) — + * only the fields the clarify/answer reducers read. Replaced wholesale by + * the domain module at the fold. + */ +export const ReferenceEnvelope = Schema.Struct({ + envelopeId: EnvelopeId, + captureId: Schema.NonEmptyString, + /** Unix ms on the wire. */ + capturedAt: Schema.Number, + capturedAtTimezone: Schema.Struct({ + value: Schema.NonEmptyString, + source: ProvenanceSource, + basis: Schema.optionalKey(Schema.NonEmptyString), + }), + utterance: Schema.NonEmptyString, + actor: Actor, + /** Access-control root for every read. */ + householdId: convexId("households"), + currentChild: Schema.optionalKey(ProvenancedChild), + viewContext: Schema.optionalKey(ProvenancedView), + references: Schema.optionalKey(Schema.Array(PriorReference)), +}) +export type ReferenceEnvelope = typeof ReferenceEnvelope["Type"] + +// ---- new branded ids (answer layer, art_gCDrtx4S §3) ---- + +export const AnswerId = Schema.NonEmptyString.pipe(Schema.brand("AnswerId")) +export type AnswerId = typeof AnswerId["Type"] + +export const RevisionId = Schema.NonEmptyString.pipe(Schema.brand("RevisionId")) +export type RevisionId = typeof RevisionId["Type"] + +/** + * Household lineage watermark — the captureId+attempt pattern applied to the + * corpus (art_gCDrtx4S §2.2). Bumped by every committed EventRevision; + * version 0 is the uncorrected baseline. + */ +export const LineageWatermark = Schema.Struct({ + householdId: convexId("households"), + version: Schema.Natural, // monotonic; 0 = corpus baseline, no revisions +}) +export type LineageWatermark = typeof LineageWatermark["Type"] + +// ---- focused clarification (bounded, read-scoped) ---- + +export const ClarifyOption = Schema.Struct({ + targetId: Schema.NonEmptyString, // a child or record already present in the envelope + kind: Schema.Literals(["child", "entry", "event", "message"]), + label: Schema.NonEmptyString, // display text drawn from the record's own fields + provenance: ProvenanceSource, // which envelope field supplied this candidate +}) +export type ClarifyOption = typeof ClarifyOption["Type"] + +/** + * Manual `_tag` literal instead of Schema.TaggedStruct — the tagged-struct + * helper does not exist on effect@4.0.0-rc.115 (verified this session); the + * wire shape is identical to the proposal's sketch. + * RECONCILIATION: the folded domain uses an explicit `outcome` literal field + * instead (Convex rejects underscore-prefixed stored fields, adaptation A1); + * this spike is Convex-free, so the proposal's `_tag` wire shape stands. + */ +export const ClarifyQuestion = Schema.Struct({ + _tag: Schema.Literals(["clarify-question"]), + envelopeId: EnvelopeId, + question: Schema.NonEmptyString, // exactly one question; never open-ended + options: Schema.Array(ClarifyOption), // operation invariant: 2–4 options, all envelope-derived + ambiguousReferenceIds: Schema.Array(RecordId), // which envelope references the question disambiguates +}) +export type ClarifyQuestion = typeof ClarifyQuestion["Type"] + +/** + * Resolved binding — the third ClarifyOutcome member. The proposal's + * ClarifyOutcome union has two members (clarify-question | + * unresolved-reference) because "one candidate is not a clarification — that + * is the resolver's normal binding path"; this spike's reducer covers both + * paths, so the binding is a union member with its provenance recorded + * (art_gCDrtx4S §2.1 table, row 1). The fold decides whether `resolved` + * joins the folded union or stays the resolver's separate return path. + */ +export const ResolvedBinding = Schema.Struct({ + _tag: Schema.Literals(["resolved"]), + envelopeId: EnvelopeId, + targetId: RecordId, + kind: Schema.Literals(["child", "entry", "event", "message"]), + provenance: ProvenanceSource, + basis: Schema.optionalKey(Schema.NonEmptyString), +}) +export type ResolvedBinding = typeof ResolvedBinding["Type"] + +/** + * Answer-layer unresolved-reference: the envelope shape (reason + detail) + * plus the proposal's `retryable` flag (always false — only the user can + * clear it, by supplying context with provenance `user-asserted`). + * RECONCILIATION: the landed operations.ts member has no `retryable`; the + * fold must settle one shape (art_gCDrtx4S §3 vs operations.ts adaptation). + */ +export const UnresolvedReference = Schema.Struct({ + _tag: Schema.Literals(["unresolved-reference"]), + envelopeId: EnvelopeId, + reason: Schema.Literals(["no-reference", "cross-child-blocked", "target-not-visible", "ambiguous"]), + detail: Schema.optionalKey(Schema.NonEmptyString), + retryable: Schema.Boolean, +}) +export type UnresolvedReference = typeof UnresolvedReference["Type"] + +export const ClarifyOutcome = Schema.Union([ResolvedBinding, ClarifyQuestion, UnresolvedReference]) +export type ClarifyOutcome = typeof ClarifyOutcome["Type"] + +// ---- revision citation link ---- + +export const RevisionLink = Schema.Struct({ + revisionId: RevisionId, + targetRecordId: Schema.NonEmptyString, // the record the correction revises + containingEntryId: Schema.optionalKey(Schema.NonEmptyString), + /** Unix ms on the wire. */ + revisedAt: Schema.Number, + summary: Schema.NonEmptyString, // slot 10's change summary, e.g. "quantity: 1 hour → 45 minutes" +}) +export type RevisionLink = typeof RevisionLink["Type"] + +// ---- Answered, additive delta (rule 2) ---- + +export const Citation = Schema.Struct({ + recordId: Schema.NonEmptyString, + // 'revision' added per the proposal; the v0.4 fold unifies the vocabulary + // to five kinds by adding 'knowledge' (art_gfwpdmWF §3.1). + recordKind: Schema.Literals(["entry", "event", "message", "revision"]), +}) +export type Citation = typeof Citation["Type"] + +/** + * Answered v0.2 — the proposal's five additive fields on the landed v0.3 + * shape (envelopeId, response, citations), keyed by + * (envelopeId, readWatermark.version) for idempotent re-serve. + */ +export const Answered = Schema.Struct({ + _tag: Schema.Literals(["answered"]), + envelopeId: EnvelopeId, + response: Schema.NonEmptyString, + citations: Schema.Array(Citation), + // ---- additive (art_gCDrtx4S §3) ---- + answerId: AnswerId, + readWatermark: LineageWatermark, // lineage observed at answer time + status: Schema.Literals(["current", "superseded"]), + supersededByRevisionId: Schema.optionalKey(RevisionId), // present iff status is 'superseded' + revisionChain: Schema.optionalKey(Schema.Array(RevisionLink)), // present when read records carry corrections +}) +export type Answered = typeof Answered["Type"] + +// ---- tagged error union (answer layer) ---- + +export const WatermarkMoved = Schema.Struct({ + _tag: Schema.Literals(["watermark-moved"]), + observedVersion: Schema.Natural, + currentVersion: Schema.Natural, + retryable: Schema.Boolean, // true — the system recomputes at the current watermark +}) +export type WatermarkMoved = typeof WatermarkMoved["Type"] + +export const ProviderFailure = Schema.Struct({ + _tag: Schema.Literals(["provider-failure"]), + detail: Schema.optionalKey(Schema.NonEmptyString), + retryable: Schema.Boolean, // true +}) +export type ProviderFailure = typeof ProviderFailure["Type"] + +export const MalformedModelOutput = Schema.Struct({ + _tag: Schema.Literals(["malformed-model-output"]), + detail: Schema.optionalKey(Schema.NonEmptyString), + retryable: Schema.Boolean, // false — deterministic on identical input +}) +export type MalformedModelOutput = typeof MalformedModelOutput["Type"] + +/** + * AnswerError union (art_gCDrtx4S §3). Retryability per member is pinned by + * the §4 table and asserted by the tests; the schemas stay permissive + * (`Schema.Boolean`) exactly as the proposal wrote them. + */ +export const AnswerError = Schema.Union([ + UnresolvedReference, + WatermarkMoved, + ProviderFailure, + MalformedModelOutput, +]) +export type AnswerError = typeof AnswerError["Type"] diff --git a/spikes/agent-experience/references/tsconfig.json b/spikes/agent-experience/references/tsconfig.json new file mode 100644 index 0000000..ee14fb2 --- /dev/null +++ b/spikes/agent-experience/references/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true + }, + "include": ["."] +} diff --git a/spikes/agent-experience/references/tsconfig.test.json b/spikes/agent-experience/references/tsconfig.test.json new file mode 100644 index 0000000..44095c6 --- /dev/null +++ b/spikes/agent-experience/references/tsconfig.test.json @@ -0,0 +1,8 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["bun"] + }, + "include": ["."] +} From 70f3693d161be85b525c10b0735f06e4f1b445d7 Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 19:16:58 +0000 Subject: [PATCH 2/2] =?UTF-8?q?fix(spike):=20review=20findings=20F1-F5=20?= =?UTF-8?q?=E2=80=94=20dedup=20before=20count=20checks=20+=20evidence-labe?= =?UTF-8?q?l=20corrections?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F1 (semantic): computeClarify now dedups candidates by kind:targetId BEFORE the sole-candidate and bound checks — two visible references to the same child collapse to one candidate and resolve (with or without currentChild), never emitting a 1-option clarification (schema pins options to 2-4). New fixtures F-AX-CLARIFY-002/003 cover both paths; new invariant asserts the 2-4 option bound over every fixture envelope. F2: README no longer claims CI's turbo pipeline covers the spike — the pnpm-workspace.yaml globs exclude spikes/ and verification.yml does not run it; the only execution evidence is local runs (same treatment as security/ and evaluation/). F3: base tsconfig.json gains types:["bun"] so it typechecks the test file standalone (was 7 errors; now clean, matching tsconfig.test.json). F4: README + PR body say RevisionLink carries targetRecordId/containingEntryId per art_gCDrtx4S section 3 with the changed-record set derived by the tested pure changedRecordSet(revision) — not an explicit changedRecordIds field. F5: README serveAnswer bullet now matches the code: a current answer stays servable at a moved watermark (invalidation is citation-intersection, not version comparison); superseded answers are never served. Local gates at this head: bun test 26/26 (149 assertions), strict tsc clean on both tsconfig.test.json and tsconfig.json. Co-authored-by: Gilbert Polanco --- spikes/agent-experience/references/README.md | 42 ++++++---- .../references/fixtures/F-AX-CLARIFY-002.json | 59 ++++++++++++++ .../references/fixtures/F-AX-CLARIFY-003.json | 64 +++++++++++++++ spikes/agent-experience/references/reducer.ts | 39 +++++---- .../references/references.test.ts | 80 +++++++++++++++++++ .../agent-experience/references/tsconfig.json | 3 +- 6 files changed, 254 insertions(+), 33 deletions(-) create mode 100644 spikes/agent-experience/references/fixtures/F-AX-CLARIFY-002.json create mode 100644 spikes/agent-experience/references/fixtures/F-AX-CLARIFY-003.json diff --git a/spikes/agent-experience/references/README.md b/spikes/agent-experience/references/README.md index 5efe7a1..afc58f4 100644 --- a/spikes/agent-experience/references/README.md +++ b/spikes/agent-experience/references/README.md @@ -20,7 +20,7 @@ deterministic reducers over typed contracts. schema.ts Effect v4 contract schemas (the proposal's deltas, standalone) reducer.ts Pure reducers: computeClarify, bumpWatermark, commitRevision, invalidateAnswers, serveAnswer -fixtures/ 6 deterministic JSON cases (F-AX-*) +fixtures/ 8 deterministic JSON cases (F-AX-*) references.test.ts bun suite: round-trips, per-case outcomes, invariants ``` @@ -34,7 +34,9 @@ Implements the proposal's contract deltas as Effect v4 schemas pinned to - `ClarifyOption` / `ClarifyQuestion` / `ClarifyOutcome` — bounded (≤ 4 options), read-only; carries no write payload. - `ResolvedBinding` — the resolved arm of the outcome (provenance-qualified). -- `RevisionLink` — correction revision with an explicit `changedRecordIds` set. +- `RevisionLink` — correction revision carrying `targetRecordId` (+ optional + `containingEntryId`) exactly as art_gCDrtx4S §3 specifies; the changed-record + set is derived by the tested pure `changedRecordSet(revision)`. - `Answered` additive fields — `answerId`, `readWatermark` (keyed by `(envelopeId, readWatermark.version)`), `status`, `supersededByRevisionId`, `citations` (citation-intersection inputs). @@ -61,16 +63,20 @@ Pure, deterministic TypeScript — no Convex, no LLM, no clock, no randomness: - `bumpWatermark` + `commitRevision` — strictly monotonic +1 watermark bump; idempotent, append-only revision commit. - `invalidateAnswers` — an `Answered` is superseded **iff** its cited record ids - intersect the revision's `changedRecordIds` (entry-level citations cover - contained events); exhausts every match. -- `serveAnswer` — returns the answer only when not superseded and the stored - watermark matches the current one; otherwise a typed - `watermark-moved`/superseded error that **never** includes the old content. - Never-serve-superseded is the hard rule. + intersect the revision's derived `changedRecordSet(revision)` (entry-level + citations cover contained events); exhausts every match. +- `serveAnswer` — serves a stored answer while its `status` is `current`, + **even when the watermark has moved**: invalidation is citation-intersection, + not version comparison, so a revision to unrelated records must not retire a + truthful answer. A superseded answer is never served — the caller gets a + typed, retryable `watermark-moved` error that **never** includes the old + content, and recomputes at the current watermark. Never-serve-superseded is + the hard rule. ## Fixtures (fixtures/) -The proposal's six cases as pure-data JSON with fixed ISO-8601 UTC times +The proposal's six canonical cases plus two dedup-refinement cases from the +PR #28 review (finding F1), all pure-data JSON with fixed ISO-8601 UTC times (`2026-09-17T18:30:00Z` family), synthetic `fx_*` ids only, no real names, no medical content. Every `expected` block is derivable from scenario semantics alone: @@ -83,24 +89,30 @@ alone: | `F-AX-STALE-ANSWER-001` | answer predates a committed revision | typed retryable stale error, never the old value | | `F-AX-UNRESOLVED-CORRECTION-001` | correction names nothing resolvable | typed unresolved error, zero writes | | `F-AX-LEAK-001` | private sibling reference in viewContext | fails typed without leaking id or content | +| `F-AX-CLARIFY-002` | two visible references to the same child, currentChild absent | dedup before count checks → resolved, never a 1-option question | +| `F-AX-CLARIFY-003` | same, with currentChild asserted | tiebreak then dedup → resolved via currentChild, never a 1-option question | ## Evidence labels (honest) - **LOCAL-REAL (deterministic reducer):** `reducer.ts` + `schema.ts` are real, running code verified by `bun test` on the exact commit SHA reported in the PR - (23 tests, 134 assertions) plus strict `tsc --noEmit`. No provider, no network, + (26 tests, 149 assertions) plus strict `tsc --noEmit`. No provider, no network, no clock, no randomness anywhere in the module. -- **DETERMINISTIC DOUBLE (fixtures):** the six fixture cases are pure JSON - doubles — they demonstrate reducer semantics, not provider or device behavior. +- **DETERMINISTIC DOUBLE (fixtures):** the eight fixture cases (six canonical, + two dedup-refinement) are pure JSON doubles — they demonstrate reducer + semantics, not provider or device behavior. Nothing here exercises a real extraction provider or an LLM call. - **Nothing device-verified:** no iOS/audio/capture-path verification of any kind is claimed by this spike. - **Placement pending the v0.4 fold:** this lives under `spikes/` on purpose. The fold home for the schemas is `packages/domain/src/clarifyAnswer.ts` (per the synthesis); the reducers graduate only with that fold. This module is - deliberately **not** a pnpm workspace member, so CI's turbo pipeline covers it - via its own `test`/`typecheck` scripts (bun + tsc, hoisted resolution), and the - standalone suites (`security/`, `evaluation/`) are unaffected. + deliberately **not** a pnpm workspace member: the `pnpm-workspace.yaml` globs + (apps/, packages/) exclude `spikes/`, so CI's turbo pipeline does NOT run it, + and `.github/workflows/verification.yml` does not run it either. The only + execution evidence for this spike is local runs (`bun test` + strict + `tsc --noEmit`) — the same treatment `.obvious/obvious.md` gives the + standalone `security/` and `evaluation/` suites. - **Fixture namespace pending manifest reconciliation:** the `F-AX-*` namespace is claimed for the agent-experience area, but registering these cases into `evaluation/`'s manifest-driven registry is the harness owner's decision diff --git a/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-002.json b/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-002.json new file mode 100644 index 0000000..4489f01 --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-002.json @@ -0,0 +1,59 @@ +{ + "fixtureId": "F-AX-CLARIFY-002", + "kind": "acceptance", + "title": "\"she went down for her nap\" with two visible nap events for the SAME child -> dedup collapses to one candidate, resolved binding, never a 1-option question", + "contractSource": "art_gCDrtx4S section 5, F-AX-CLARIFY-001 — dedup-before-count refinement (PR #28 review finding F1)", + "scenario": { + "narrative": "Mom dictates 'she went down for her nap' with the child picker empty (currentChild absent) and two visible nap events in references - both bound to the SAME child. The candidates dedup by kind:targetId BEFORE the count checks, so the two references collapse to a single child candidate. One candidate is the resolver's normal binding path: the outcome is a resolved binding with provenance recorded - never a clarification question with a single option (the schema pins clarification options to 2-4).", + "anchors": { "askUtc": "2026-09-17T18:30:00Z" } + }, + "input": { + "envelope": { + "envelopeId": "fx_env_clarify_002", + "captureId": "fx_capture_002", + "capturedAt": 1789669800000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "she went down for her nap", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "viewContext": { + "value": { "screen": "timeline" }, + "source": "app-known", + "basis": "timeline screen open" + }, + "references": [ + { + "referenceId": "fx_ref_003", + "kind": "event", + "targetId": "fx_evt_sleep_002", + "relatedChildId": "fx_child_m", + "snippet": "Mia - nap, 1 hour", + "source": "app-known", + "visibleToActor": true + }, + { + "referenceId": "fx_ref_004", + "kind": "event", + "targetId": "fx_evt_sleep_003", + "relatedChildId": "fx_child_m", + "snippet": "Mia - second nap, 40 minutes", + "source": "app-known", + "visibleToActor": true + } + ] + } + }, + "expected": { + "outcomeTag": "resolved", + "targetId": "fx_child_m", + "kind": "child", + "provenance": "app-known", + "basis": "sole visible candidate in envelope context", + "clarifyQuestionEmitted": false, + "zeroWrites": true + } +} diff --git a/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-003.json b/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-003.json new file mode 100644 index 0000000..2df57df --- /dev/null +++ b/spikes/agent-experience/references/fixtures/F-AX-CLARIFY-003.json @@ -0,0 +1,64 @@ +{ + "fixtureId": "F-AX-CLARIFY-003", + "kind": "acceptance", + "title": "\"she's down for her nap now\" with two visible nap events for the SAME child and currentChild asserted -> tiebreak then dedup collapse to one candidate, resolved binding via currentChild, never a 1-option question", + "contractSource": "art_gCDrtx4S section 5, F-AX-CLARIFY-001 — dedup-before-count refinement (PR #28 review finding F1)", + "scenario": { + "narrative": "Mom dictates 'she's down for her nap now' with the child picker set to Mia (currentChild asserted) and two visible nap events in references - both bound to Mia. The currentChild tiebreak keeps both child-kind candidates (both match), then the kind:targetId dedup collapses them to a single candidate BEFORE the count checks. One candidate resolves through the currentChild binding path: provenance is the currentChild's source and the basis names the tiebreak and the first via reference - never a clarification question with a single option (the schema pins clarification options to 2-4).", + "anchors": { "askUtc": "2026-09-17T18:30:00Z" } + }, + "input": { + "envelope": { + "envelopeId": "fx_env_clarify_003", + "captureId": "fx_capture_003", + "capturedAt": 1789669800000, + "capturedAtTimezone": { + "value": "America/New_York", + "source": "app-known", + "basis": "device settings at capture time" + }, + "utterance": "she's down for her nap now", + "actor": { "authorId": "fx_parent_a", "role": "parent" }, + "householdId": "fx_household_1", + "currentChild": { + "value": { "childId": "fx_child_m", "displayName": "Mia" }, + "source": "user-asserted", + "basis": "child picker selection" + }, + "viewContext": { + "value": { "screen": "timeline" }, + "source": "app-known", + "basis": "timeline screen open" + }, + "references": [ + { + "referenceId": "fx_ref_005", + "kind": "event", + "targetId": "fx_evt_sleep_004", + "relatedChildId": "fx_child_m", + "snippet": "Mia - nap, 1 hour", + "source": "app-known", + "visibleToActor": true + }, + { + "referenceId": "fx_ref_006", + "kind": "event", + "targetId": "fx_evt_sleep_005", + "relatedChildId": "fx_child_m", + "snippet": "Mia - second nap, 40 minutes", + "source": "app-known", + "visibleToActor": true + } + ] + } + }, + "expected": { + "outcomeTag": "resolved", + "targetId": "fx_child_m", + "kind": "child", + "provenance": "user-asserted", + "basis": "bound by user-asserted currentChild via reference fx_evt_sleep_004", + "clarifyQuestionEmitted": false, + "zeroWrites": true + } +} diff --git a/spikes/agent-experience/references/reducer.ts b/spikes/agent-experience/references/reducer.ts index ef5def5..2307611 100644 --- a/spikes/agent-experience/references/reducer.ts +++ b/spikes/agent-experience/references/reducer.ts @@ -246,7 +246,20 @@ export const computeClarify = (envelope: ReferenceEnvelope): ClarifyOutcome => { } } - const only = working.length === 1 ? working[0] : undefined + // Dedup by kind:targetId BEFORE the sole-candidate and bound checks: two + // visible references to the same candidate collapse to one, and one + // candidate is a resolved binding — never a 1-option question (the + // clarification schema pins options to 2–4; art_gCDrtx4S: one candidate = + // resolved binding). + const seen = new Set() + const distinct = working.filter((candidate) => { + const key = `${candidate.kind}:${candidate.targetId}` + if (seen.has(key)) return false + seen.add(key) + return true + }) + + const only = distinct.length === 1 ? distinct[0] : undefined if (only !== undefined) { return { _tag: "resolved", @@ -260,30 +273,22 @@ export const computeClarify = (envelope: ReferenceEnvelope): ClarifyOutcome => { } } - if (working.length > MAX_OPTIONS) { + if (distinct.length > MAX_OPTIONS) { return { _tag: "unresolved-reference", envelopeId: envelope.envelopeId, reason: "ambiguous", - detail: `reference bound exceeded: ${working.length} candidates, maximum ${MAX_OPTIONS}`, + detail: `reference bound exceeded: ${distinct.length} candidates, maximum ${MAX_OPTIONS}`, retryable: false, } } - const seen = new Set() - const options = working - .map((candidate) => ({ - targetId: candidate.targetId, - kind: candidate.kind, - label: candidate.label, - provenance: candidate.provenance, - })) - .filter((option) => { - const key = `${option.kind}:${option.targetId}` - if (seen.has(key)) return false - seen.add(key) - return true - }) + const options = distinct.map((candidate) => ({ + targetId: candidate.targetId, + kind: candidate.kind, + label: candidate.label, + provenance: candidate.provenance, + })) const ambiguousReferenceIds = [...new Set(working.flatMap((c) => (c.viaRecordId ? [c.viaRecordId] : [])))] const question: ClarifyQuestion = { diff --git a/spikes/agent-experience/references/references.test.ts b/spikes/agent-experience/references/references.test.ts index e52534b..c3ec0bf 100644 --- a/spikes/agent-experience/references/references.test.ts +++ b/spikes/agent-experience/references/references.test.ts @@ -174,6 +174,69 @@ describe("F-AX-CLARIFY-001", () => { }) }) +// ---- F-AX-CLARIFY-002 (review finding F1: dedup BEFORE the count checks) ---- + +describe("F-AX-CLARIFY-002", () => { + const fixture = loadFixture("F-AX-CLARIFY-002") + const expected = fixture.expected as { + outcomeTag: string + targetId: string + kind: "child" | "entry" | "event" | "message" + provenance: ProvenanceSource + basis: string + clarifyQuestionEmitted: boolean + zeroWrites: boolean + } + + test("two visible references to the same child collapse to ONE candidate — a resolved binding, never a 1-option question", () => { + const envelope = decodeEnvelope(fixture.input.envelope) + const snapshot = structuredClone(envelope) + const outcome = computeClarify(envelope) + + expect((outcome._tag === "clarify-question")).toBe(expected.clarifyQuestionEmitted) + const resolved = expectTag(outcome, "resolved") + expect(resolved.targetId).toBe(expected.targetId) + expect(resolved.kind).toBe(expected.kind) + expect(resolved.provenance).toBe(expected.provenance) + expect(resolved.basis).toBe(expected.basis) + + // the outcome decodes against the read-only union and writes nothing + expect(Schema.decodeUnknownSync(ClarifyOutcome)(outcome)).toEqual(outcome) + expect(envelope).toEqual(snapshot) + }) +}) + +// ---- F-AX-CLARIFY-003 (review finding F1: dedup AFTER the currentChild tiebreak) ---- + +describe("F-AX-CLARIFY-003", () => { + const fixture = loadFixture("F-AX-CLARIFY-003") + const expected = fixture.expected as { + outcomeTag: string + targetId: string + kind: "child" | "entry" | "event" | "message" + provenance: ProvenanceSource + basis: string + clarifyQuestionEmitted: boolean + zeroWrites: boolean + } + + test("with currentChild asserted, tiebreak keeps both same-child candidates and dedup still resolves — never a 1-option question", () => { + const envelope = decodeEnvelope(fixture.input.envelope) + const snapshot = structuredClone(envelope) + const outcome = computeClarify(envelope) + + expect((outcome._tag === "clarify-question")).toBe(expected.clarifyQuestionEmitted) + const resolved = expectTag(outcome, "resolved") + expect(resolved.targetId).toBe(expected.targetId) + expect(resolved.kind).toBe(expected.kind) + expect(resolved.provenance).toBe(expected.provenance) + expect(resolved.basis).toBe(expected.basis) + + expect(Schema.decodeUnknownSync(ClarifyOutcome)(outcome)).toEqual(outcome) + expect(envelope).toEqual(snapshot) + }) +}) + // ---- F-AX-CORRECT-ANSWER-001 ---- describe("F-AX-CORRECT-ANSWER-001", () => { @@ -432,6 +495,23 @@ describe("F-AX-LEAK-001", () => { // ---- invariants beyond the six fixtures ---- describe("invariants beyond the fixtures", () => { + test("no emitted clarify question ever has fewer than two or more than four options (F1 invariant, all fixtures)", () => { + const envelopeInputs = [ + loadFixture("F-AX-CLARIFY-001").input.envelope, + loadFixture("F-AX-CLARIFY-002").input.envelope, + loadFixture("F-AX-CLARIFY-003").input.envelope, + loadFixture("F-AX-CORRECT-ANSWER-001").input.envelopeCorrect, + loadFixture("F-AX-RESUME-REFS-001").input.resumedEnvelope, + loadFixture("F-AX-UNRESOLVED-CORRECTION-001").input.envelope, + loadFixture("F-AX-LEAK-001").input.envelope, + ] + for (const value of envelopeInputs) { + const outcome = computeClarify(decodeEnvelope(value)) + if (outcome._tag === "clarify-question") { + expect(outcome.options.length >= 2 && outcome.options.length <= 4).toBe(true) + } + } + }) test("changedRecordSet covers the event and its containing entry", () => { const withEntry = decodeRevision({ revisionId: "fx_rev_t001", diff --git a/spikes/agent-experience/references/tsconfig.json b/spikes/agent-experience/references/tsconfig.json index ee14fb2..44095c6 100644 --- a/spikes/agent-experience/references/tsconfig.json +++ b/spikes/agent-experience/references/tsconfig.json @@ -1,7 +1,8 @@ { "extends": "../../../tsconfig.base.json", "compilerOptions": { - "noEmit": true + "noEmit": true, + "types": ["bun"] }, "include": ["."] }