diff --git a/spikes/home-c-handoff/README.md b/spikes/home-c-handoff/README.md new file mode 100644 index 0000000..cb04c2b --- /dev/null +++ b/spikes/home-c-handoff/README.md @@ -0,0 +1,60 @@ +# Parent Home Candidate C — handoff-first (prototype spike) + +Rubric: **art_VyNYOggs v1.0** (frozen), canonical scenario **S1**, candidate **3 — handoff-first**. +Direct worker assignment (thread `th_wkbO7wK7`, root task `todo_IpkisZRm`); the folio-style registry +task `todo_wZdouzJU` is superseded by this assignment, matching what the rubric registry already +records for candidates 1 and 2 (real code on isolated branches, draft PR + evidence document). + +## The lens + +The home **leads with the takeover brief**: what the on-duty caregiver needs to take over care +right now. Capture (voice-first, typed fallback) and the event feed serve the brief. The teaching +point S1 forces: the nap → night-waking **correction changes the plan** for the next caregiver — +a feed-first home buries that; a handoff-first home puts it above the fold with lineage attached. + +## What lives here + +- `src/contract.ts` — contract mirror of **art_I2TCG08V v0.2** (Entry, Event, extraction envelope + with stale-suppression + idempotent apply) on the pinned `effect@4.0.0-rc.115`. +- `src/grants.ts` — audience model: household/relationship grants; per-event restriction as an + explicitly-flagged PROPOSED extension; draft-visibility rule stated in code. +- `src/data.ts` — decodes the committed fixtures through Effect schemas at load; viewer filtering. +- `src/screens/` — Home (takeover brief, feed with per-event audience cues, 30-day strip), + Capture (S1-A scripted replay: interruption → draft saved → typed completion → one + clarification), Inspect (S1-B: correct-with-preview, audience restriction, photo attach), + Month (30-day history with gap disclosure), Review doorway (the one representative screen), + Rosa view (S1-F grants-filtered). Plain react-native; typechecked, not executed. +- `fixtures/` — deterministic synthetic data: `s1-day.json` (all six beats), `month-history.json` + (30 days; final row SET from the S1 day so they cannot diverge), `media/`, `manifest.json` + (self-describing, transcript sha256s). Generated by `scripts/generate-fixtures.ts` (seed 20260915). + +## Run + +```bash +bun test # from spikes/home-c-handoff/ — contract decode + semantics (no install needed; + # hoisted pnpm layout resolves effect/react-native from the workspace root) +bun scripts/generate-fixtures.ts # regenerate — must be a byte-level no-op (tested) +bun run typecheck # tsc strict over src/test/scripts (RN screens included) +``` + +## Deliberate scope lines (rubric ground rule 3) + +Extraction-review card flow (slots 11–14), handoff implementation (slot 23), and digest flow +(slot 24) are OUT of scope — the review flow appears only as a badge/doorway into one +representative screen. The prototype is a home lens, not a backend. + +## Known divergences (for the evaluator) + +1. **Contract doc vs merged domain schema.** `packages/domain` Event uses `timestamp` + + `payload: Record` and has no `_tag`/`occurredAt`/`quantity`/`authorId`/`note`; + the contract document (art_I2TCG08V v0.2) and the evaluation corpus adapter use + `occurredAt`/`quantity`/`authorId`. This fixture set follows the contract document. Already + flagged for the v0.3 contract fold (Event.authorId); the home candidates are not the + reconciliation owner. +2. **Per-event audience restriction** (S1-B "parents only") has no home in contract v0.2 — modeled + here as an additive prototype-layer record; proposals belong to the contract owner. +3. **Personas.** Repo evaluation fixtures use `caregiver-1` / child "Ava"; rubric scenario S1 + (Elena / Marco / Rosa / Sofia, binding) is used verbatim, with slug-style authorIds + (`elena`, `marco`, `rosa`) matching the repo's id style. + +All data is synthetic. Nothing merges from this branch (candidate exclusion — exploration only). diff --git a/spikes/home-c-handoff/fixtures/manifest.json b/spikes/home-c-handoff/fixtures/manifest.json new file mode 100644 index 0000000..178926c --- /dev/null +++ b/spikes/home-c-handoff/fixtures/manifest.json @@ -0,0 +1,64 @@ +{ + "manifestVersion": "0.1.0", + "rubric": { + "artifactId": "art_VyNYOggs", + "version": "1.0 (frozen 2026-09-17)", + "candidate": "3 — handoff-first", + "registryTask": "todo_wZdouzJU (folio version superseded by direct worker assignment)", + "executingThread": "th_wkbO7wK7", + "rootTask": "todo_IpkisZRm" + }, + "contract": { + "artifactId": "art_I2TCG08V", + "version": "0.2", + "effectPin": "4.0.0-rc.115", + "note": "Wire shapes follow the contract document (and the evaluation corpus adapter); the merged packages/domain implementation diverges (timestamp/payload vs occurredAt/quantity) — flagged in the evidence document." + }, + "scenario": { + "scenarioId": "S1", + "personas": [ + "elena", + "marco", + "rosa", + "sofia" + ], + "binding": true + }, + "fixtures": [ + { + "id": "HOME-C-S1-DAY", + "file": "s1-day.json", + "kind": "scenario", + "beats": [ + "S1-A", + "S1-B", + "S1-C", + "S1-D", + "S1-E", + "S1-F" + ] + }, + { + "id": "HOME-C-MONTH-HISTORY", + "file": "month-history.json", + "kind": "history", + "days": 30 + }, + { + "id": "HOME-C-BREAKFAST-PHOTO", + "file": "media/breakfast-photo.png", + "kind": "media", + "bytes": 68, + "sha256": "431ced6916a2a21a156e38701afe55bbd7f88969fbbfc56d7fe099d47f265460", + "note": "synthetic placeholder image (1×1 PNG)" + } + ], + "transcripts": { + "sha256": { + "entry-e1": "c3168035d4f94de160775d04e4ff3ef703e5869576e6ac4d6acecc382fc36040", + "entry-e2": "cf41358be79c0d5d9f9ed8fda3ea7bc95cda8623eb5722b70b5d4505bf5463d2" + }, + "byteFidelityRule": "transcript bytes are exactly what was dictated; interruption markers are session facts, never transcript bytes" + }, + "allSynthetic": true +} diff --git a/spikes/home-c-handoff/fixtures/media/breakfast-photo.png b/spikes/home-c-handoff/fixtures/media/breakfast-photo.png new file mode 100644 index 0000000..26a8c68 Binary files /dev/null and b/spikes/home-c-handoff/fixtures/media/breakfast-photo.png differ diff --git a/spikes/home-c-handoff/fixtures/month-history.json b/spikes/home-c-handoff/fixtures/month-history.json new file mode 100644 index 0000000..ac5c135 --- /dev/null +++ b/spikes/home-c-handoff/fixtures/month-history.json @@ -0,0 +1,670 @@ +{ + "fixtureId": "HOME-C-MONTH-HISTORY", + "window": { + "start": "2026-08-17", + "end": "2026-09-15", + "days": 30 + }, + "deterministic": { + "seed": 20260915, + "generator": "scripts/generate-fixtures.ts", + "prng": "mulberry32" + }, + "note": "The final row is set from the S1 day so month history and scenario can never diverge.", + "days": [ + { + "date": "2026-08-17", + "dayLabel": "Monday", + "captures": 1, + "eventsByCategory": { + "meal": 2, + "sleep": 2, + "potty": 3, + "mood": 1, + "school": 1, + "milestone": 1 + }, + "nightWakings": 0, + "napMinutes": 45, + "pottySuccesses": 3, + "pottyAccidents": 1, + "milestones": [ + "told a full story about her day" + ], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-08-18", + "dayLabel": "Tuesday", + "captures": 1, + "eventsByCategory": { + "meal": 3, + "sleep": 3, + "potty": 2, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 1, + "napMinutes": 75, + "pottySuccesses": 4, + "pottyAccidents": 2, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-19", + "dayLabel": "Wednesday", + "captures": 3, + "eventsByCategory": { + "meal": 2, + "sleep": 2, + "potty": 2, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 75, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-20", + "dayLabel": "Thursday", + "captures": 1, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 2, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 60, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-08-21", + "dayLabel": "Friday", + "captures": 1, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 3, + "mood": 1, + "school": 1, + "milestone": 1 + }, + "nightWakings": 0, + "napMinutes": 60, + "pottySuccesses": 4, + "pottyAccidents": 1, + "milestones": [ + "washed hands without being asked" + ], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-22", + "dayLabel": "Saturday", + "captures": 1, + "eventsByCategory": { + "meal": 3, + "sleep": 1, + "potty": 2, + "mood": 1, + "school": 0, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 0, + "pottySuccesses": 3, + "pottyAccidents": 1, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-23", + "dayLabel": "Sunday", + "captures": 0, + "eventsByCategory": {}, + "nightWakings": 0, + "napMinutes": 0, + "pottySuccesses": 0, + "pottyAccidents": 0, + "milestones": [], + "coverage": "none", + "gapNotes": [ + "no capture — family day out" + ], + "source": "generated" + }, + { + "date": "2026-08-24", + "dayLabel": "Monday", + "captures": 1, + "eventsByCategory": { + "meal": 2, + "sleep": 3, + "potty": 1, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 1, + "napMinutes": 60, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-25", + "dayLabel": "Tuesday", + "captures": 3, + "eventsByCategory": { + "meal": 3, + "sleep": 1, + "potty": 2, + "mood": 0, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 0, + "pottySuccesses": 3, + "pottyAccidents": 0, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-08-26", + "dayLabel": "Wednesday", + "captures": 2, + "eventsByCategory": { + "meal": 2, + "sleep": 1, + "potty": 3, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 0, + "pottySuccesses": 3, + "pottyAccidents": 2, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-27", + "dayLabel": "Thursday", + "captures": 2, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 2, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 75, + "pottySuccesses": 2, + "pottyAccidents": 1, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-08-28", + "dayLabel": "Friday", + "captures": 3, + "eventsByCategory": { + "meal": 2, + "sleep": 2, + "potty": 1, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 60, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-29", + "dayLabel": "Saturday", + "captures": 1, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 2, + "mood": 1, + "school": 0, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 60, + "pottySuccesses": 3, + "pottyAccidents": 2, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-30", + "dayLabel": "Sunday", + "captures": 3, + "eventsByCategory": { + "meal": 2, + "sleep": 3, + "potty": 2, + "mood": 0, + "school": 0, + "milestone": 0 + }, + "nightWakings": 1, + "napMinutes": 90, + "pottySuccesses": 2, + "pottyAccidents": 2, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-08-31", + "dayLabel": "Monday", + "captures": 2, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 1, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 90, + "pottySuccesses": 2, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-01", + "dayLabel": "Tuesday", + "captures": 1, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 1, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 60, + "pottySuccesses": 2, + "pottyAccidents": 0, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-09-02", + "dayLabel": "Wednesday", + "captures": 3, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 1, + "mood": 0, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 45, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-03", + "dayLabel": "Thursday", + "captures": 3, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 3, + "mood": 0, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 60, + "pottySuccesses": 5, + "pottyAccidents": 1, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-09-04", + "dayLabel": "Friday", + "captures": 2, + "eventsByCategory": { + "meal": 2, + "sleep": 3, + "potty": 2, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 1, + "napMinutes": 45, + "pottySuccesses": 3, + "pottyAccidents": 1, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-05", + "dayLabel": "Saturday", + "captures": 3, + "eventsByCategory": { + "meal": 2, + "sleep": 3, + "potty": 1, + "mood": 1, + "school": 0, + "milestone": 0 + }, + "nightWakings": 1, + "napMinutes": 90, + "pottySuccesses": 2, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-06", + "dayLabel": "Sunday", + "captures": 0, + "eventsByCategory": {}, + "nightWakings": 0, + "napMinutes": 0, + "pottySuccesses": 0, + "pottyAccidents": 0, + "milestones": [], + "coverage": "none", + "gapNotes": [ + "no capture — family day out" + ], + "source": "generated" + }, + { + "date": "2026-09-07", + "dayLabel": "Monday", + "captures": 3, + "eventsByCategory": { + "meal": 2, + "sleep": 2, + "potty": 2, + "mood": 0, + "school": 1, + "milestone": 1 + }, + "nightWakings": 1, + "napMinutes": 0, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [ + "first two-wheel scooter attempt" + ], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-08", + "dayLabel": "Tuesday", + "captures": 1, + "eventsByCategory": { + "meal": 2, + "sleep": 2, + "potty": 1, + "mood": 0, + "school": 1, + "milestone": 0 + }, + "nightWakings": 1, + "napMinutes": 0, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-09-09", + "dayLabel": "Wednesday", + "captures": 1, + "eventsByCategory": { + "meal": 3, + "sleep": 3, + "potty": 2, + "mood": 1, + "school": 1, + "milestone": 0 + }, + "nightWakings": 1, + "napMinutes": 75, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-10", + "dayLabel": "Thursday", + "captures": 3, + "eventsByCategory": { + "meal": 2, + "sleep": 2, + "potty": 1, + "mood": 0, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 90, + "pottySuccesses": 5, + "pottyAccidents": 0, + "milestones": [], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-11", + "dayLabel": "Friday", + "captures": 2, + "eventsByCategory": { + "meal": 2, + "sleep": 1, + "potty": 1, + "mood": 0, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 0, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-09-12", + "dayLabel": "Saturday", + "captures": 1, + "eventsByCategory": { + "meal": 2, + "sleep": 1, + "potty": 2, + "mood": 0, + "school": 0, + "milestone": 1 + }, + "nightWakings": 0, + "napMinutes": 0, + "pottySuccesses": 5, + "pottyAccidents": 2, + "milestones": [ + "used the big slide alone" + ], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-09-13", + "dayLabel": "Sunday", + "captures": 3, + "eventsByCategory": { + "meal": 3, + "sleep": 2, + "potty": 2, + "mood": 1, + "school": 0, + "milestone": 1 + }, + "nightWakings": 0, + "napMinutes": 45, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [ + "built a tower of ten blocks" + ], + "coverage": "full", + "gapNotes": [], + "source": "generated" + }, + { + "date": "2026-09-14", + "dayLabel": "Monday", + "captures": 2, + "eventsByCategory": { + "meal": 2, + "sleep": 2, + "potty": 1, + "mood": 0, + "school": 1, + "milestone": 0 + }, + "nightWakings": 0, + "napMinutes": 75, + "pottySuccesses": 4, + "pottyAccidents": 0, + "milestones": [], + "coverage": "partial", + "gapNotes": [ + "no evening capture" + ], + "source": "generated" + }, + { + "date": "2026-09-15", + "dayLabel": "Tuesday", + "captures": 2, + "eventsByCategory": { + "meal": 1, + "sleep": 1, + "school": 1, + "potty": 2, + "milestone": 1, + "mood": 1 + }, + "nightWakings": 1, + "napMinutes": 0, + "pottySuccesses": 2, + "pottyAccidents": 1, + "milestones": [ + "balance bike — pedaled half a block for the first time" + ], + "coverage": "partial", + "gapNotes": [ + "day in progress — captures through 08:09" + ], + "source": "set from HOME-C-S1-DAY (not generated)" + } + ] +} diff --git a/spikes/home-c-handoff/fixtures/s1-day.json b/spikes/home-c-handoff/fixtures/s1-day.json new file mode 100644 index 0000000..cca4258 --- /dev/null +++ b/spikes/home-c-handoff/fixtures/s1-day.json @@ -0,0 +1,515 @@ +{ + "fixtureId": "HOME-C-S1-DAY", + "scenario": "Canonical scenario S1 — rubric art_VyNYOggs v1.0 (binding)", + "candidate": "3 — handoff-first (direct worker assignment, thread th_wkbO7wK7, root todo_IpkisZRm)", + "timezone": "America/New_York", + "dayLabel": "Tuesday", + "day": "2026-09-15", + "renderedMoment": "S1-E 18:10 — Marco opens cold, takeover brief is the home", + "household": { + "householdId": "hh_rivera", + "name": "The Riveras", + "members": [ + { + "userId": "elena", + "displayName": "Elena (mom, primary logger)", + "role": "parent" + }, + { + "userId": "marco", + "displayName": "Marco (dad, takes over bedtime)", + "role": "parent" + }, + { + "userId": "rosa", + "displayName": "Rosa (invited grandmother, weekday afternoons)", + "role": "caregiver" + } + ], + "child": { + "childId": "child_sofia", + "name": "Sofia", + "ageYears": 3 + } + }, + "entries": [ + { + "captureId": "cap-e1-morning", + "entryId": "entry-e1", + "wire": { + "_tag": "Entry", + "transcript": "Breakfast was half the oatmeal, no milk. She woke at eleven last night and was up until twelve thirty. Drop-off at preschool was hard — about five minutes of crying, then she settled. Two potty successes and one accident at home before breakfast. She finally pedaled the balance bike halfway down the block. She was upset again after quiet time.", + "authorId": "elena", + "createdAt": 1789472280000, + "visibility": "published", + "events": [ + { + "_tag": "Event", + "category": "sleep", + "occurredAt": 1789441200000, + "confidence": 1, + "authorId": "elena", + "note": "night waking 23:00–00:30 — corrected from the afternoon-nap misread" + }, + { + "_tag": "Event", + "category": "meal", + "occurredAt": 1789470600000, + "quantity": { + "value": 0.5, + "unit": "serving" + }, + "confidence": 0.88, + "authorId": "elena", + "note": "half the oatmeal, refused milk" + }, + { + "_tag": "Event", + "category": "school", + "occurredAt": 1789471800000, + "confidence": 0.83, + "authorId": "elena", + "note": "hard drop-off — about five minutes of crying, then she settled" + }, + { + "_tag": "Event", + "category": "potty", + "occurredAt": 1789469400000, + "quantity": { + "value": 2, + "unit": "successes" + }, + "confidence": 0.9, + "authorId": "elena", + "note": "two successes before breakfast" + }, + { + "_tag": "Event", + "category": "milestone", + "occurredAt": 1789471500000, + "confidence": 0.88, + "authorId": "elena", + "note": "pedaled the balance bike halfway down the block — first time" + }, + { + "_tag": "Event", + "category": "mood", + "occurredAt": 1789414200000, + "confidence": 1, + "authorId": "elena", + "note": "teary after preschool quiet time yesterday; wanted to keep playing; calmed quickly" + } + ] + }, + "capture": { + "mode": "mixed", + "voiceTopics": [ + 0, + 1, + 2 + ], + "typedTopics": [ + 3, + 4, + 5 + ], + "interruptedAt": 1789472460000, + "resumedAt": 1789473060000, + "interruptionNote": "Incoming call from the preschool after the third topic; Elena returned 10 minutes later and finished by typing while holding Sofia (quiet-input path). Server extraction (attempt 0) was NOT cancelled by the disconnect — envelope rule (a).", + "attempts": [ + { + "attempt": 0, + "startedAt": 1789472340000, + "finishedAt": 1789472520000, + "outcome": "succeeded", + "note": "ran server-side over the partial transcript (topics 1–3) while the client was interrupted" + }, + { + "attempt": 1, + "startedAt": 1789473060000, + "finishedAt": 1789473180000, + "outcome": "succeeded", + "note": "full transcript after typed completion; stale attempt 0 discarded, never merged (rule 2); the extractor again proposed an afternoon nap — suppressed because the caregiver-confirmed correction is pinned (art_rBKvvzIa §3.2)", + "suppressedConflicts": [ + { + "category": "sleep", + "reason": "caregiver-confirmed correction ev-sleep-2 is pinned; rerun never downgrades it" + } + ] + } + ], + "clarification": { + "question": "\"She was upset again after quiet time\" — when was that, and what happened?", + "answer": "Yesterday at preschool, after quiet time — she got teary because she wanted to keep playing; she calmed after a few minutes.", + "askedAt": 1789473180000, + "answeredAt": 1789473240000 + }, + "visibilityTimeline": [ + { + "at": 1789472280000, + "state": "draft" + }, + { + "at": 1789473300000, + "state": "published" + } + ] + } + }, + { + "captureId": "cap-e2-accident", + "entryId": "entry-e2", + "wire": { + "_tag": "Entry", + "transcript": "Follow-up from this morning — she had the one accident at home before breakfast. Wet underwear, I changed her clothes right away.", + "authorId": "elena", + "createdAt": 1789473900000, + "visibility": "published", + "events": [ + { + "_tag": "Event", + "category": "potty", + "occurredAt": 1789469700000, + "quantity": { + "value": 1, + "unit": "accident" + }, + "confidence": 1, + "authorId": "elena", + "note": "one accident at home before breakfast — typed manually after extraction timed out" + } + ] + }, + "capture": { + "mode": "text", + "voiceTopics": [], + "typedTopics": [ + 0 + ], + "attempts": [ + { + "attempt": 0, + "startedAt": 1789473900000, + "finishedAt": 1789473960000, + "outcome": "failed", + "failureReason": "Timeout — provider/network timeout (retryable)", + "note": "visible failed state offered retry; Elena typed the event manually instead. The failed attempt stays in lineage; the raw transcript is preserved — no data loss (S1-D)." + } + ], + "visibilityTimeline": [ + { + "at": 1789473900000, + "state": "draft" + }, + { + "at": 1789474140000, + "state": "published" + } + ] + } + } + ], + "events": [ + { + "eventId": "ev-sleep-1", + "entryId": "entry-e1", + "audienceScope": "household", + "supersededBy": "ev-sleep-2", + "sourceExcerpt": { + "start": 41, + "end": 102 + }, + "wire": { + "_tag": "Event", + "category": "sleep", + "occurredAt": 1789406100000, + "confidence": 0.61, + "authorId": "elena", + "note": "afternoon nap (extraction guess — misread)" + } + }, + { + "eventId": "ev-sleep-2", + "entryId": "entry-e1", + "audienceScope": "household", + "corrects": "ev-sleep-1", + "endAt": 1789446600000, + "sourceExcerpt": { + "start": 41, + "end": 102 + }, + "wire": { + "_tag": "Event", + "category": "sleep", + "occurredAt": 1789441200000, + "confidence": 1, + "authorId": "elena", + "note": "night waking 23:00–00:30 — corrected from the afternoon-nap misread" + } + }, + { + "eventId": "ev-meal-1", + "entryId": "entry-e1", + "audienceScope": "household", + "sourceExcerpt": { + "start": 0, + "end": 40 + }, + "photoId": "media/breakfast-photo.png", + "wire": { + "_tag": "Event", + "category": "meal", + "occurredAt": 1789470600000, + "quantity": { + "value": 0.5, + "unit": "serving" + }, + "confidence": 0.88, + "authorId": "elena", + "note": "half the oatmeal, refused milk" + } + }, + { + "eventId": "ev-school-1", + "entryId": "entry-e1", + "audienceScope": "parents", + "sourceExcerpt": { + "start": 103, + "end": 183 + }, + "wire": { + "_tag": "Event", + "category": "school", + "occurredAt": 1789471800000, + "confidence": 0.83, + "authorId": "elena", + "note": "hard drop-off — about five minutes of crying, then she settled" + } + }, + { + "eventId": "ev-potty-1", + "entryId": "entry-e1", + "audienceScope": "household", + "sourceExcerpt": { + "start": 184, + "end": 246 + }, + "wire": { + "_tag": "Event", + "category": "potty", + "occurredAt": 1789469400000, + "quantity": { + "value": 2, + "unit": "successes" + }, + "confidence": 0.9, + "authorId": "elena", + "note": "two successes before breakfast" + } + }, + { + "eventId": "ev-milestone-1", + "entryId": "entry-e1", + "audienceScope": "household", + "sourceExcerpt": { + "start": 247, + "end": 307 + }, + "wire": { + "_tag": "Event", + "category": "milestone", + "occurredAt": 1789471500000, + "confidence": 0.88, + "authorId": "elena", + "note": "pedaled the balance bike halfway down the block — first time" + } + }, + { + "eventId": "ev-mood-1", + "entryId": "entry-e1", + "audienceScope": "household", + "sourceExcerpt": { + "start": 308, + "end": 345 + }, + "wire": { + "_tag": "Event", + "category": "mood", + "occurredAt": 1789414200000, + "confidence": 1, + "authorId": "elena", + "note": "teary after preschool quiet time yesterday; wanted to keep playing; calmed quickly" + } + }, + { + "eventId": "ev-potty-2", + "entryId": "entry-e2", + "audienceScope": "household", + "sourceExcerpt": { + "start": 0, + "end": 129 + }, + "wire": { + "_tag": "Event", + "category": "potty", + "occurredAt": 1789469700000, + "quantity": { + "value": 1, + "unit": "accident" + }, + "confidence": 1, + "authorId": "elena", + "note": "one accident at home before breakfast — typed manually after extraction timed out" + } + } + ], + "audienceRestrictions": [ + { + "eventId": "ev-school-1", + "scope": "parents", + "grantedBy": "elena", + "grantedAt": 1789472700000, + "note": "S1-B: restrict the drop-off meltdown event to parents only, per the grants model" + } + ], + "reviewSessions": [ + { + "at": 1789472640000, + "entryId": "entry-e1", + "seenState": "draft", + "caption": "S1-B (07:44): extraction finished server-side during the call; Elena inspects the draft, corrects the nap misread with a preview, restricts the drop-off event, and attaches the breakfast photo. Full review-card flow = slots 11–14 (out of scope) — this is the one representative doorway.", + "actions": [ + { + "kind": "correct", + "at": 1789472640000, + "detail": "ev-sleep-1 (afternoon nap, 0.61) → ev-sleep-2 (night waking 23:00–00:30, confirmed 1.0); preview shown before confirm" + }, + { + "kind": "restrict-audience", + "at": 1789472700000, + "detail": "ev-school-1 → parents only" + }, + { + "kind": "attach-photo", + "at": 1789472760000, + "detail": "breakfast photo attached to ev-meal-1" + } + ] + } + ], + "readOnlyQuestions": [ + { + "question": "Did she nap?", + "askedBy": "marco", + "askedAt": 1789510260000, + "answer": "No nap recorded today. The only sleep event is the corrected night waking (23:00–00:30) — first misread as an afternoon nap, corrected by Elena at 07:44.", + "sources": [ + { + "kind": "correction", + "ref": "ev-sleep-2", + "excerpt": "night waking 23:00–00:30 — corrected from the afternoon-nap misread" + }, + { + "kind": "event", + "ref": "ev-sleep-2" + }, + { + "kind": "fixture", + "ref": "coverage: no nap event in today's log — absence of record, not a confirmed absence" + } + ] + } + ], + "takeover": { + "confirmedBy": "marco", + "confirmedAt": 1789510320000, + "plan": { + "note": "No nap recorded in today's log. Bedtime plan is the parents' call; no behavioral prediction is offered without a supported source.", + "basis": [ + "ev-sleep-2" + ] + }, + "fiveFacts": [ + { + "headline": "Night waking 23:00–00:30 last night", + "detail": "Corrected at 07:44 — extraction first read it as an afternoon nap.", + "refs": [ + { + "kind": "event", + "ref": "ev-sleep-2" + }, + { + "kind": "correction", + "ref": "ev-sleep-1 → ev-sleep-2" + } + ] + }, + { + "headline": "Ate half the oatmeal, refused milk", + "refs": [ + { + "kind": "event", + "ref": "ev-meal-1" + }, + { + "kind": "transcript-excerpt", + "ref": "entry-e1", + "excerpt": "Breakfast was half the oatmeal, no milk." + } + ] + }, + { + "headline": "Hard drop-off — settled after about five minutes", + "detail": "Parents only (Elena restricted this at 07:45) — Marco sees it; Rosa does not.", + "refs": [ + { + "kind": "event", + "ref": "ev-school-1" + } + ] + }, + { + "headline": "No nap recorded", + "detail": "Reads from the correction: what looked like a nap was the night waking.", + "refs": [ + { + "kind": "correction", + "ref": "ev-sleep-1 → ev-sleep-2" + }, + { + "kind": "fixture", + "ref": "coverage: no nap event in today's log (absence of record, not a confirmed absence)" + } + ] + }, + { + "headline": "Pedaled the balance bike halfway down the block — worth celebrating", + "refs": [ + { + "kind": "event", + "ref": "ev-milestone-1" + }, + { + "kind": "transcript-excerpt", + "ref": "entry-e1", + "excerpt": "She finally pedaled the balance bike halfway down the block." + } + ] + } + ], + "pendingItems": [ + { + "label": "Clarification answered", + "detail": "\"upset again after quiet time\" — Elena confirmed: teary after preschool quiet time yesterday; calmed quickly.", + "state": "resolved", + "at": 1789473240000 + }, + { + "label": "Failed extraction resolved by hand", + "detail": "Potty-accident event timed out on a provider timeout; Elena typed it manually. Failed attempt visible in lineage; nothing lost.", + "state": "resolved", + "at": 1789474080000 + } + ] + } +} diff --git a/spikes/home-c-handoff/package.json b/spikes/home-c-handoff/package.json new file mode 100644 index 0000000..b436007 --- /dev/null +++ b/spikes/home-c-handoff/package.json @@ -0,0 +1,15 @@ +{ + "name": "@journal/spike-home-c-handoff", + "version": "0.1.0", + "private": true, + "description": "Parent home candidate C — handoff-first home lens prototype (rubric art_VyNYOggs, candidate 3 / todo_wZdouzJU). Standalone spike: bun tests decode synthetic S1 fixtures through the contract schemas; RN screens are typechecked, not executed.", + "scripts": { + "test": "bun test", + "typecheck": "tsc -p tsconfig.json --noEmit", + "gen": "bun scripts/generate-fixtures.ts" + }, + "devDependencies": {}, + "notes": { + "dependencies": "Intentionally empty. The repo uses a hoisted pnpm layout (.npmrc node-linker=hoisted), so react, react-native, and effect resolve from the workspace root while typechecking (moduleResolution walks up). This keeps the spike outside pnpm-workspace.yaml globs, exactly like security/ and evaluation/." + } +} diff --git a/spikes/home-c-handoff/scripts/generate-fixtures.ts b/spikes/home-c-handoff/scripts/generate-fixtures.ts new file mode 100644 index 0000000..2924e16 --- /dev/null +++ b/spikes/home-c-handoff/scripts/generate-fixtures.ts @@ -0,0 +1,628 @@ +/** + * Deterministic synthetic fixture generator — Parent Home candidate C + * (handoff-first), rubric art_VyNYOggs v1.0, canonical scenario S1. + * + * Ground rule 1: identical scenario S1, identical data. Ground rule 2: the + * contract vocabulary (art_I2TCG08V v0.2) and repo naming are the authority. + * Ground rule 4: authored independently — all data here is synthetic; no + * person, photo, or device data is real. + * + * Run: bun scripts/generate-fixtures.ts (from spikes/home-c-handoff/) + * Re-running must be a no-op — tests assert committed JSON equals regenerated + * JSON (determinism proof). + * + * Scenario-day derivation: the rubric fixes S1 on a Tuesday. 2026-09-15 is a + * real Tuesday (asserted below); the 30-day history ends on that day so the + * month strip and the S1 day are consistent by construction — the last row of + * month-history is set FROM the S1 data, never generated. + */ +import { createHash } from "node:crypto" +import { mkdirSync, writeFileSync } from "node:fs" +import { dirname, join } from "node:path" + +const OUT = join(import.meta.dir, "..", "fixtures") + +/** America/New_York is UTC-4 (EDT) on every date this fixture uses. */ +const ET = (month: 8 | 7, day: number, h: number, m = 0): number => + Date.UTC(2026, month, day, h + 4, m, 0) + +const etLabel = (ms: number): string => { + const d = new Date(ms) + const hh = d.getUTCHours() - 4 + const hh2 = hh < 0 ? hh + 24 : hh + return `${String(hh2).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}` +} + +const sha256 = (s: string): string => createHash("sha256").update(s, "utf8").digest("hex") + +// --------------------------------------------------------------------------- +// Personas and household (rubric: binding). Repo evaluation fixtures use the +// role-style id `caregiver-1`; we map scenario roles onto that naming style: +// person slugs as authorIds, roles from the grants model. +// --------------------------------------------------------------------------- +const household = { + householdId: "hh_rivera", + name: "The Riveras", + members: [ + { userId: "elena", displayName: "Elena (mom, primary logger)", role: "parent" }, + { userId: "marco", displayName: "Marco (dad, takes over bedtime)", role: "parent" }, + { userId: "rosa", displayName: "Rosa (invited grandmother, weekday afternoons)", role: "caregiver" }, + ], + child: { childId: "child_sofia", name: "Sofia", ageYears: 3 }, +} as const + +// --------------------------------------------------------------------------- +// S1-A — capture with interruption, Tuesday 07:38, Elena, voice. +// Interruption is a CAPTURE-SESSION fact, never transcript bytes +// (byte-faithfulness, art_rBKvvzIa §2.1): the transcript is exactly what was +// dictated; the call inserted no bytes. +// --------------------------------------------------------------------------- +const E1_TOPICS = [ + { text: "Breakfast was half the oatmeal, no milk.", mode: "voice" }, + { text: "She woke at eleven last night and was up until twelve thirty.", mode: "voice" }, + { text: "Drop-off at preschool was hard — about five minutes of crying, then she settled.", mode: "voice" }, + { text: "Two potty successes and one accident at home before breakfast.", mode: "text" }, + { text: "She finally pedaled the balance bike halfway down the block.", mode: "text" }, + { text: "She was upset again after quiet time.", mode: "text" }, +] as const + +const E1_TRANSCRIPT = E1_TOPICS.map((t) => t.text).join(" ") +const topicExcerpt = (i: number) => { + const text = E1_TOPICS[i]!.text + const start = E1_TRANSCRIPT.indexOf(text) + return { start, end: start + text.length } +} + +const E2_TRANSCRIPT = + "Follow-up from this morning — she had the one accident at home before breakfast. Wet underwear, I changed her clothes right away." + +// Timestamps (ET labels are the display truth; ms is the wire truth). +const T = { + nightWakingStart: ET(8, 14, 23, 0), // Sep 14 23:00 ET + nightWakingEnd: ET(8, 15, 0, 30), // Sep 15 00:30 ET + pottySuccesses: ET(8, 15, 6, 50), + pottyAccident: ET(8, 15, 6, 55), + breakfast: ET(8, 15, 7, 10), + bike: ET(8, 15, 7, 25), + dropoff: ET(8, 15, 7, 30), + quietTimeYesterday: ET(8, 14, 15, 30), + misreadNapStart: ET(8, 14, 13, 15), // the extractor's "afternoon nap" + e1Created: ET(8, 15, 7, 38), + e1Interrupted: ET(8, 15, 7, 41), // after the third topic — preschool calls + attempt0Start: ET(8, 15, 7, 39), + attempt0End: ET(8, 15, 7, 42), // completed server-side during the call + s1bCorrect: ET(8, 15, 7, 44), + s1bRestrict: ET(8, 15, 7, 45), + s1bPhoto: ET(8, 15, 7, 46), + e1Resumed: ET(8, 15, 7, 51), // 10 minutes later, typing while holding Sofia + attempt1Start: ET(8, 15, 7, 51), + attempt1End: ET(8, 15, 7, 53), + e1Published: ET(8, 15, 7, 55), + clarifyAsked: ET(8, 15, 7, 53), + clarifyAnswered: ET(8, 15, 7, 54), + e2Created: ET(8, 15, 8, 5), // S1-D failed state + e2AttemptStart: ET(8, 15, 8, 5), + e2AttemptEnd: ET(8, 15, 8, 6), + e2Manual: ET(8, 15, 8, 8), + e2Published: ET(8, 15, 8, 9), + marcoOpened: ET(8, 15, 18, 10), // S1-E + marcoAsked: ET(8, 15, 18, 11), + marcoConfirmed: ET(8, 15, 18, 12), + rosaOpened: ET(8, 16, 14, 0), // S1-F, next day +} as const + +// --------------------------------------------------------------------------- +// Wire events (contract v0.2 shapes) + presentation projection. +// --------------------------------------------------------------------------- +type WireEvent = { + _tag: "Event" + category: "potty" | "meal" | "sleep" | "mood" | "milestone" | "school" + occurredAt: number + quantity?: { value: number; unit?: string } + confidence: number + authorId: string + note?: string +} + +const wire = (e: WireEvent): WireEvent => { + const out: Record = { ...e } + if (out.quantity === undefined) delete out.quantity // absent, never null + if (out.note === undefined) delete out.note + return out as WireEvent +} + +const events = [ + { + eventId: "ev-sleep-1", + entryId: "entry-e1", + audienceScope: "household", + supersededBy: "ev-sleep-2", + sourceExcerpt: topicExcerpt(1), + wire: wire({ + _tag: "Event", + category: "sleep", + occurredAt: T.misreadNapStart, + confidence: 0.61, + authorId: "elena", + note: "afternoon nap (extraction guess — misread)", + }), + }, + { + eventId: "ev-sleep-2", + entryId: "entry-e1", + audienceScope: "household", + corrects: "ev-sleep-1", + endAt: T.nightWakingEnd, + sourceExcerpt: topicExcerpt(1), + wire: wire({ + _tag: "Event", + category: "sleep", + occurredAt: T.nightWakingStart, + confidence: 1, // caregiver-confirmed (S1-B correction, 07:44) — pinned + authorId: "elena", + note: "night waking 23:00–00:30 — corrected from the afternoon-nap misread", + }), + }, + { + eventId: "ev-meal-1", + entryId: "entry-e1", + audienceScope: "household", + sourceExcerpt: topicExcerpt(0), + photoId: "media/breakfast-photo.png", + wire: wire({ + _tag: "Event", + category: "meal", + occurredAt: T.breakfast, + quantity: { value: 0.5, unit: "serving" }, + confidence: 0.88, + authorId: "elena", + note: "half the oatmeal, refused milk", + }), + }, + { + eventId: "ev-school-1", + entryId: "entry-e1", + audienceScope: "parents", // S1-B restriction at 07:45 + sourceExcerpt: topicExcerpt(2), + wire: wire({ + _tag: "Event", + category: "school", + occurredAt: T.dropoff, + confidence: 0.83, + authorId: "elena", + note: "hard drop-off — about five minutes of crying, then she settled", + }), + }, + { + eventId: "ev-potty-1", + entryId: "entry-e1", + audienceScope: "household", + sourceExcerpt: topicExcerpt(3), + wire: wire({ + _tag: "Event", + category: "potty", + occurredAt: T.pottySuccesses, + quantity: { value: 2, unit: "successes" }, + confidence: 0.9, + authorId: "elena", + note: "two successes before breakfast", + }), + }, + { + eventId: "ev-milestone-1", + entryId: "entry-e1", + audienceScope: "household", + sourceExcerpt: topicExcerpt(4), + wire: wire({ + _tag: "Event", + category: "milestone", + occurredAt: T.bike, + confidence: 0.88, + authorId: "elena", + note: "pedaled the balance bike halfway down the block — first time", + }), + }, + { + eventId: "ev-mood-1", + entryId: "entry-e1", + audienceScope: "household", + sourceExcerpt: topicExcerpt(5), + wire: wire({ + _tag: "Event", + category: "mood", + occurredAt: T.quietTimeYesterday, + confidence: 1, // confirmed through the one clarification exchange + authorId: "elena", + note: "teary after preschool quiet time yesterday; wanted to keep playing; calmed quickly", + }), + }, + { + eventId: "ev-potty-2", + entryId: "entry-e2", + audienceScope: "household", + sourceExcerpt: { start: 0, end: E2_TRANSCRIPT.length }, + wire: wire({ + _tag: "Event", + category: "potty", + occurredAt: T.pottyAccident, + quantity: { value: 1, unit: "accident" }, + confidence: 1, // typed manually by Elena after the failed attempt (S1-D) + authorId: "elena", + note: "one accident at home before breakfast — typed manually after extraction timed out", + }), + }, +] + +// --------------------------------------------------------------------------- +// Entries (contract v0.2 wire) + capture sessions (envelope semantics). +// The contract Entry.events carries the CURRENT event set per entry. +// --------------------------------------------------------------------------- +const e1Current = events.filter((e) => e.entryId === "entry-e1" && e.eventId !== "ev-sleep-1") +const e2Current = events.filter((e) => e.entryId === "entry-e2") + +const entries = [ + { + captureId: "cap-e1-morning", + entryId: "entry-e1", + wire: { + _tag: "Entry", + transcript: E1_TRANSCRIPT, + authorId: "elena", + createdAt: T.e1Created, + visibility: "published", + events: e1Current.map((e) => e.wire), + }, + capture: { + mode: "mixed", + voiceTopics: [0, 1, 2], + typedTopics: [3, 4, 5], + interruptedAt: T.e1Interrupted, + resumedAt: T.e1Resumed, + interruptionNote: + "Incoming call from the preschool after the third topic; Elena returned 10 minutes later and finished by typing while holding Sofia (quiet-input path). Server extraction (attempt 0) was NOT cancelled by the disconnect — envelope rule (a).", + attempts: [ + { + attempt: 0, + startedAt: T.attempt0Start, + finishedAt: T.attempt0End, + outcome: "succeeded", + note: "ran server-side over the partial transcript (topics 1–3) while the client was interrupted", + }, + { + attempt: 1, + startedAt: T.attempt1Start, + finishedAt: T.attempt1End, + outcome: "succeeded", + note: "full transcript after typed completion; stale attempt 0 discarded, never merged (rule 2); the extractor again proposed an afternoon nap — suppressed because the caregiver-confirmed correction is pinned (art_rBKvvzIa §3.2)", + suppressedConflicts: [ + { category: "sleep", reason: "caregiver-confirmed correction ev-sleep-2 is pinned; rerun never downgrades it" }, + ], + }, + ], + clarification: { + question: + "\"She was upset again after quiet time\" — when was that, and what happened?", + answer: + "Yesterday at preschool, after quiet time — she got teary because she wanted to keep playing; she calmed after a few minutes.", + askedAt: T.clarifyAsked, + answeredAt: T.clarifyAnswered, + }, + visibilityTimeline: [ + { at: T.e1Created, state: "draft" }, + { at: T.e1Published, state: "published" }, + ], + }, + }, + { + captureId: "cap-e2-accident", + entryId: "entry-e2", + wire: { + _tag: "Entry", + transcript: E2_TRANSCRIPT, + authorId: "elena", + createdAt: T.e2Created, + visibility: "published", + events: e2Current.map((e) => e.wire), + }, + capture: { + mode: "text", + voiceTopics: [], + typedTopics: [0], + attempts: [ + { + attempt: 0, + startedAt: T.e2AttemptStart, + finishedAt: T.e2AttemptEnd, + outcome: "failed", + failureReason: "Timeout — provider/network timeout (retryable)", + note: "visible failed state offered retry; Elena typed the event manually instead. The failed attempt stays in lineage; the raw transcript is preserved — no data loss (S1-D).", + }, + ], + visibilityTimeline: [ + { at: T.e2Created, state: "draft" }, + { at: T.e2Published, state: "published" }, + ], + }, + }, +] + +const audienceRestrictions = [ + { + eventId: "ev-school-1", + scope: "parents", + grantedBy: "elena", + grantedAt: T.s1bRestrict, + note: "S1-B: restrict the drop-off meltdown event to parents only, per the grants model", + }, +] + +const reviewSessions = [ + { + at: T.s1bCorrect, + entryId: "entry-e1", + seenState: "draft", + caption: + "S1-B (07:44): extraction finished server-side during the call; Elena inspects the draft, corrects the nap misread with a preview, restricts the drop-off event, and attaches the breakfast photo. Full review-card flow = slots 11–14 (out of scope) — this is the one representative doorway.", + actions: [ + { kind: "correct", at: T.s1bCorrect, detail: "ev-sleep-1 (afternoon nap, 0.61) → ev-sleep-2 (night waking 23:00–00:30, confirmed 1.0); preview shown before confirm" }, + { kind: "restrict-audience", at: T.s1bRestrict, detail: "ev-school-1 → parents only" }, + { kind: "attach-photo", at: T.s1bPhoto, detail: "breakfast photo attached to ev-meal-1" }, + ], + }, +] + +// Product-owner ruling (binding): missing data reads "No nap recorded" — +// absence of record is never phrased as a confirmed absence, and no +// behavioral prediction is shown without a supported source event. +// Citation refs for absence-of-record use the "coverage:" prefix. +const readOnlyQuestions = [ + { + question: "Did she nap?", + askedBy: "marco", + askedAt: T.marcoAsked, + answer: + "No nap recorded today. The only sleep event is the corrected night waking (23:00–00:30) — first misread as an afternoon nap, corrected by Elena at 07:44.", + sources: [ + { kind: "correction", ref: "ev-sleep-2", excerpt: "night waking 23:00–00:30 — corrected from the afternoon-nap misread" }, + { kind: "event", ref: "ev-sleep-2" }, + { kind: "fixture", ref: "coverage: no nap event in today's log — absence of record, not a confirmed absence" }, + ], + }, +] + +const takeover = { + confirmedBy: "marco", + confirmedAt: T.marcoConfirmed, + plan: { + note: "No nap recorded in today's log. Bedtime plan is the parents' call; no behavioral prediction is offered without a supported source.", + basis: ["ev-sleep-2"], + }, + fiveFacts: [ + { + headline: "Night waking 23:00–00:30 last night", + detail: "Corrected at 07:44 — extraction first read it as an afternoon nap.", + refs: [{ kind: "event", ref: "ev-sleep-2" }, { kind: "correction", ref: "ev-sleep-1 → ev-sleep-2" }], + }, + { + headline: "Ate half the oatmeal, refused milk", + refs: [{ kind: "event", ref: "ev-meal-1" }, { kind: "transcript-excerpt", ref: "entry-e1", excerpt: E1_TOPICS[0]!.text }], + }, + { + headline: "Hard drop-off — settled after about five minutes", + detail: "Parents only (Elena restricted this at 07:45) — Marco sees it; Rosa does not.", + refs: [{ kind: "event", ref: "ev-school-1" }], + }, + { + headline: "No nap recorded", + detail: "Reads from the correction: what looked like a nap was the night waking.", + refs: [{ kind: "correction", ref: "ev-sleep-1 → ev-sleep-2" }, { kind: "fixture", ref: "coverage: no nap event in today's log (absence of record, not a confirmed absence)" }], + }, + { + headline: "Pedaled the balance bike halfway down the block — worth celebrating", + refs: [{ kind: "event", ref: "ev-milestone-1" }, { kind: "transcript-excerpt", ref: "entry-e1", excerpt: E1_TOPICS[4]!.text }], + }, + ], + pendingItems: [ + { + label: "Clarification answered", + detail: "\"upset again after quiet time\" — Elena confirmed: teary after preschool quiet time yesterday; calmed quickly.", + state: "resolved", + at: T.clarifyAnswered, + }, + { + label: "Failed extraction resolved by hand", + detail: "Potty-accident event timed out on a provider timeout; Elena typed it manually. Failed attempt visible in lineage; nothing lost.", + state: "resolved", + at: T.e2Manual, + }, + ], +} + +const s1Day = { + fixtureId: "HOME-C-S1-DAY", + scenario: "Canonical scenario S1 — rubric art_VyNYOggs v1.0 (binding)", + candidate: "3 — handoff-first (direct worker assignment, thread th_wkbO7wK7, root todo_IpkisZRm)", + timezone: "America/New_York", + dayLabel: "Tuesday", + day: "2026-09-15", + renderedMoment: "S1-E 18:10 — Marco opens cold, takeover brief is the home", + household, + entries, + events, + audienceRestrictions, + reviewSessions, + readOnlyQuestions, + takeover, +} + +// --------------------------------------------------------------------------- +// 30-day month history — deterministic, seeded; last day set FROM S1 data. +// --------------------------------------------------------------------------- +function mulberry32(seed: number): () => number { + let a = seed + return () => { + a |= 0 + a = (a + 0x6d2b79f5) | 0 + let t = Math.imul(a ^ (a >>> 15), 1 | a) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +const MILESTONE_POOL = [ + "told a full story about her day", + "washed hands without being asked", + "first two-wheel scooter attempt", + "used the big slide alone", + "built a tower of ten blocks", + "called grandma Rosa by herself", +] + +const monthDays: Array> = [] +const rand = mulberry32(20260915) +let milestoneCursor = 0 +for (let i = 0; i < 30; i++) { + const dayMs = Date.UTC(2026, 7, 17 + i) // Aug 17 + i days + const d = new Date(dayMs) + const date = d.toISOString().slice(0, 10) + const weekday = d.getUTCDay() + const dayLabel = WEEKDAYS[weekday]! + const isSep15 = date === "2026-09-15" + + if (isSep15) { + // Last row: set FROM the S1 fixture — never generated (consistency by + // construction; the evaluator compares candidates on this row). + monthDays.push({ + date, + dayLabel, + captures: 2, + eventsByCategory: { meal: 1, sleep: 1, school: 1, potty: 2, milestone: 1, mood: 1 }, + nightWakings: 1, + napMinutes: 0, + pottySuccesses: 2, + pottyAccidents: 1, + milestones: ["balance bike — pedaled half a block for the first time"], + coverage: "partial", + gapNotes: ["day in progress — captures through 08:09"], + source: "set from HOME-C-S1-DAY (not generated)", + }) + continue + } + + const preschool = weekday >= 1 && weekday <= 5 + const noCapture = date === "2026-08-23" || date === "2026-09-06" // Sundays out + if (noCapture) { + monthDays.push({ + date, + dayLabel, + captures: 0, + eventsByCategory: {}, + nightWakings: 0, + napMinutes: 0, + pottySuccesses: 0, + pottyAccidents: 0, + milestones: [], + coverage: "none", + gapNotes: ["no capture — family day out"], + source: "generated", + }) + continue + } + + const captures = 1 + Math.floor(rand() * 3) + const napMinutes = rand() < 0.75 ? 45 + 15 * Math.floor(rand() * 4) : 0 + const pottySuccesses = 2 + Math.floor(rand() * 4) + const pottyAccidents = rand() < 0.35 ? 1 + Math.floor(rand() * 2) : 0 + const nightWakings = rand() < 0.18 ? 1 : 0 + const hasMilestone = rand() < 0.14 + const partial = !preschool ? rand() < 0.2 : rand() < 0.3 + const eventsByCategory: Record = { + meal: 2 + Math.floor(rand() * 2), + sleep: 1 + nightWakings + (napMinutes > 0 ? 1 : 0), + potty: (1 + Math.floor(rand() * 2)) + (pottyAccidents > 0 ? 1 : 0), + mood: rand() < 0.5 ? 1 : 0, + school: preschool ? 1 : 0, + milestone: hasMilestone ? 1 : 0, + } + const gapNotes = partial ? ["no evening capture"] : [] + monthDays.push({ + date, + dayLabel, + captures, + eventsByCategory, + nightWakings, + napMinutes, + pottySuccesses, + pottyAccidents, + milestones: hasMilestone ? [MILESTONE_POOL[milestoneCursor++ % MILESTONE_POOL.length]!] : [], + coverage: partial ? "partial" : "full", + gapNotes, + source: "generated", + }) +} + +const monthHistory = { + fixtureId: "HOME-C-MONTH-HISTORY", + window: { start: "2026-08-17", end: "2026-09-15", days: 30 }, + deterministic: { seed: 20260915, generator: "scripts/generate-fixtures.ts", prng: "mulberry32" }, + note: "The final row is set from the S1 day so month history and scenario can never diverge.", + days: monthDays, +} + +// --------------------------------------------------------------------------- +// Media + manifest. +// --------------------------------------------------------------------------- +const BREAKFAST_PNG_BASE64 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" +const pngBytes = Buffer.from(BREAKFAST_PNG_BASE64, "base64") +const pngSha = createHash("sha256").update(pngBytes).digest("hex") + +const manifest = { + manifestVersion: "0.1.0", + rubric: { + artifactId: "art_VyNYOggs", + version: "1.0 (frozen 2026-09-17)", + candidate: "3 — handoff-first", + registryTask: "todo_wZdouzJU (folio version superseded by direct worker assignment)", + executingThread: "th_wkbO7wK7", + rootTask: "todo_IpkisZRm", + }, + contract: { + artifactId: "art_I2TCG08V", + version: "0.2", + effectPin: "4.0.0-rc.115", + note: "Wire shapes follow the contract document (and the evaluation corpus adapter); the merged packages/domain implementation diverges (timestamp/payload vs occurredAt/quantity) — flagged in the evidence document.", + }, + scenario: { scenarioId: "S1", personas: ["elena", "marco", "rosa", "sofia"], binding: true }, + fixtures: [ + { id: "HOME-C-S1-DAY", file: "s1-day.json", kind: "scenario", beats: ["S1-A", "S1-B", "S1-C", "S1-D", "S1-E", "S1-F"] }, + { id: "HOME-C-MONTH-HISTORY", file: "month-history.json", kind: "history", days: 30 }, + { id: "HOME-C-BREAKFAST-PHOTO", file: "media/breakfast-photo.png", kind: "media", bytes: pngBytes.length, sha256: pngSha, note: "synthetic placeholder image (1×1 PNG)" }, + ], + transcripts: { + sha256: { "entry-e1": sha256(E1_TRANSCRIPT), "entry-e2": sha256(E2_TRANSCRIPT) }, + byteFidelityRule: "transcript bytes are exactly what was dictated; interruption markers are session facts, never transcript bytes", + }, + allSynthetic: true, +} + +// --------------------------------------------------------------------------- +// Emit. +// --------------------------------------------------------------------------- +const dayCheck = new Date(ET(8, 15, 7, 38)).toUTCString().slice(0, 3) +if (dayCheck !== "Tue") throw new Error(`scenario day must be Tuesday, got ${dayCheck}`) + +const write = (rel: string, content: string | Buffer): void => { + const p = join(OUT, rel) + mkdirSync(dirname(p), { recursive: true }) + writeFileSync(p, content) + console.log(`wrote ${rel} (${typeof content === "string" ? content.length : content.length} bytes)`) +} + +write("s1-day.json", `${JSON.stringify(s1Day, null, 2)}\n`) +write("month-history.json", `${JSON.stringify(monthHistory, null, 2)}\n`) +write("media/breakfast-photo.png", pngBytes) +write("manifest.json", `${JSON.stringify(manifest, null, 2)}\n`) +console.log(`\nscenario-day sanity: 2026-09-15 is Tuesday (dayCheck=${dayCheck}); ET label for e1Created: ${etLabel(T.e1Created)} (expect 07:38)`) +console.log(`night waking: ${etLabel(T.nightWakingStart)} → ${etLabel(T.nightWakingEnd)} (expect 23:00 → 00:30)`) diff --git a/spikes/home-c-handoff/src/App.tsx b/spikes/home-c-handoff/src/App.tsx new file mode 100644 index 0000000..c90ce16 --- /dev/null +++ b/spikes/home-c-handoff/src/App.tsx @@ -0,0 +1,65 @@ +import { useState } from "react" +import { Pressable, StyleSheet, Text, View } from "react-native" + +import { CaptureScreen } from "./screens/CaptureScreen" +import { HomeScreen } from "./screens/HomeScreen" +import { InspectScreen } from "./screens/InspectScreen" +import { MonthScreen } from "./screens/MonthScreen" +import { ReviewDoorwayScreen } from "./screens/ReviewDoorwayScreen" +import { RosaScreen } from "./screens/RosaScreen" +import { C } from "./ui" + +/** + * Candidate C — handoff-first parent home (prototype). + * Plain state routing: the point under test is the home LENS and the S1 beat + * reachability, not a navigation library. + */ +type Route = + | { name: "home" } + | { name: "capture" } + | { name: "inspect"; eventId: string } + | { name: "month" } + | { name: "review" } + | { name: "rosa" } + +export default function App() { + const [viewer, setViewer] = useState("marco") + const [route, setRoute] = useState({ name: "home" }) + const home = (): void => setRoute({ name: "home" }) + + return ( + + {route.name !== "home" && ( + + ‹ Home + + )} + {route.name === "home" && ( + setRoute({ name: "capture" })} + onOpenReview={() => setRoute({ name: "review" })} + onOpenMonth={() => setRoute({ name: "month" })} + onOpenEvent={(eventId) => setRoute({ name: "inspect", eventId })} + onOpenRosa={() => setRoute({ name: "rosa" })} + /> + )} + {route.name === "capture" && } + {route.name === "inspect" && } + {route.name === "month" && } + {route.name === "review" && ( + setRoute({ name: "inspect", eventId })} + onDone={home} + /> + )} + {route.name === "rosa" && } + + ) +} + +const styles = StyleSheet.create({ + app: { backgroundColor: C.bg, flex: 1, paddingTop: 8 }, + back: { color: C.accent, fontSize: 14, fontWeight: "700", paddingHorizontal: 16, paddingVertical: 6 }, +}) diff --git a/spikes/home-c-handoff/src/contract.ts b/spikes/home-c-handoff/src/contract.ts new file mode 100644 index 0000000..efe85db --- /dev/null +++ b/spikes/home-c-handoff/src/contract.ts @@ -0,0 +1,121 @@ +import { Schema } from "effect" + +/** + * Contract mirror — art_I2TCG08V (Shared Child Journal — Effect v4 Schema + * Contract v0.2), the rubric's declared vocabulary authority + * (art_VyNYOggs, ground rule 2). Shapes are copied field-for-field; every + * fixture in ./fixtures and every event the prototype renders decodes + * through these schemas on the pinned effect@4.0.0-rc.115. + * + * Known divergence vs the merged repo implementation (packages/domain): + * the merged Event uses `timestamp: Schema.Number` + `payload: Record` and + * has no `_tag`/`occurredAt`/`quantity`/`authorId`/`note`. The evaluation + * corpus adapter (evaluation/src/adapter.ts) and this prototype follow the + * contract document instead. The mismatch is already flagged for the v0.3 + * contract fold (Event.authorId open); the home candidates are not the + * reconciliation owner — see the evidence document, "Contract divergences". + * + * Wire format rules binding on fixtures (contract doc §validation): + * - `_tag` literals present on the wire. + * - Timestamps are unix-ms numbers on the wire (Date in domain code via + * Schema.DateFromMillis). + * - Optional fields are absent — never explicitly `null`. + * - `quantity`: absent key OR explicit undefined both valid; explicit null + * is NOT in contract. + * - `note`: `optionalKey` — missing key only; explicit undefined fails + * decode; non-empty when present. + */ + +/** Exactly six categories (contract: category literals). */ +export const EventCategory = Schema.Literals(["potty", "meal", "sleep", "mood", "milestone", "school"]) +export type EventCategory = typeof EventCategory["Type"] + +/** Quantitative payload. */ +export const Quantity = Schema.Struct({ + value: Schema.Number, + unit: Schema.optional(Schema.String), +}) +export type Quantity = typeof Quantity["Type"] + +/** Extraction target (contract v0.2 "Event"). */ +export const EventFields = { + _tag: Schema.Literal("Event"), + category: EventCategory, + /** Unix ms on the wire; `Date` in domain code. */ + occurredAt: Schema.DateFromMillis, + quantity: Schema.optional(Quantity), + /** 1 = caregiver-confirmed; lower = raw extractor guess. */ + confidence: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 })), + /** Attribution: caregiver who dictated/confirmed. */ + authorId: Schema.NonEmptyString, + note: Schema.optionalKey(Schema.NonEmptyString), +} satisfies Schema.Struct.Fields +export const Event = Schema.Struct(EventFields) +export type Event = typeof Event["Type"] + +/** Capture record (contract v0.2 "Entry"). Raw transcript always preserved. */ +export const EntryFields = { + _tag: Schema.Literal("Entry"), + transcript: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, + createdAt: Schema.DateFromMillis, + /** Per-entry publication state ONLY (v0.2 decision 1). */ + visibility: Schema.Literals(["draft", "published"]), + /** May be empty — extraction failure never blocks capture. */ + events: Schema.Array(Event), +} satisfies Schema.Struct.Fields +export const Entry = Schema.Struct(EntryFields) +export type Entry = typeof Entry["Type"] + +/** Correlation envelope (v0.2 interruption semantics). */ +export const CaptureId = Schema.NonEmptyString +export type CaptureId = typeof CaptureId["Type"] +/** Monotonic per capture, starting at 0. */ +export const ExtractionAttempt = Schema.Int +export type ExtractionAttempt = typeof ExtractionAttempt["Type"] + +export const ExtractionRequest = Schema.Struct({ + captureId: CaptureId, + attempt: ExtractionAttempt, + transcript: Schema.NonEmptyString, +}) +export type ExtractionRequest = typeof ExtractionRequest["Type"] + +export const ExtractionResult = Schema.Struct({ + captureId: CaptureId, + attempt: ExtractionAttempt, + events: Schema.Array(Event), +}) +export type ExtractionResult = typeof ExtractionResult["Type"] + +/** Stale-result suppression + idempotent completion (v0.2 rules 2 and 3). */ +export const applyExtractionResult = ( + applied: ReadonlyArray, + result: ExtractionResult, +): ReadonlyArray => { + // Rule 3: applying the same (captureId, attempt) twice is a no-op. + if ( + applied.some( + (a) => a.captureId === result.captureId && a.attempt === result.attempt, + ) + ) { + return applied + } + // Rule 2: superseded attempts are discarded, never merged. + const others = applied.filter((a) => a.captureId !== result.captureId) + const previous = applied.find( + (a) => a.captureId === result.captureId, + ) + if (previous && previous.attempt > result.attempt) return applied + return [...others, previous].filter((a): a is ExtractionResult => a !== undefined).concat([result]) +} + +/** The latest applied attempt per capture is the current event set. */ +export const currentEvents = ( + applied: ReadonlyArray, + captureId: string, +): ReadonlyArray => + applied + .filter((a) => a.captureId === captureId) + .sort((a, b) => a.attempt - b.attempt) + .at(-1)?.events ?? [] diff --git a/spikes/home-c-handoff/src/data.ts b/spikes/home-c-handoff/src/data.ts new file mode 100644 index 0000000..f4931c6 --- /dev/null +++ b/spikes/home-c-handoff/src/data.ts @@ -0,0 +1,269 @@ +/** + * Typed data layer — loads the synthetic S1 fixtures and decodes EVERYTHING + * through Effect v4 schemas: contract wire shapes (art_I2TCG08V v0.2) plus + * presentation projections defined here. Decode-through is the contract's + * first rule ("never hand-roll a second domain model") — the prototype holds + * itself to it for its own view layer too. + * + * The merged packages/domain Event diverges from the contract document + * (timestamp/payload vs occurredAt/quantity — see src/contract.ts); this file + * follows the contract document, matching the evaluation corpus adapter. + */ +import { Schema } from "effect" + +import { EventFields, EntryFields, EventCategory, type Event, type Entry } from "./contract" +import type { AudienceRestriction, Cue, HouseholdMember, ReadOnlyAnswer } from "./grants" +import { eventCue, canSeeEntry } from "./grants" + +import dayJson from "../fixtures/s1-day.json" +import monthJson from "../fixtures/month-history.json" + +const RoleLiteral = Schema.Literals(["parent", "caregiver"]) +const ScopeLiteral = Schema.Literals(["household", "parents"]) + +/** Presentation projection of a contract Event plus prototype fields. */ +export const EventView = Schema.Struct({ + eventId: Schema.NonEmptyString, + entryId: Schema.NonEmptyString, + audienceScope: ScopeLiteral, + /** Sleep spans: night waking end (prototype field, derived content). */ + endAt: Schema.optional(Schema.DateFromMillis), + corrects: Schema.optional(Schema.NonEmptyString), + supersededBy: Schema.optional(Schema.NonEmptyString), + /** Character offsets into the source transcript (S1-C source links). */ + sourceExcerpt: Schema.Struct({ start: Schema.Int, end: Schema.Int }), + photoId: Schema.optional(Schema.String), + /** Contract v0.2 Event — decodes through the canonical schema. */ + wire: Schema.Struct(EventFields), +}) +export type EventView = typeof EventView["Type"] + +const Attempt = Schema.Struct({ + attempt: Schema.Int, + startedAt: Schema.DateFromMillis, + finishedAt: Schema.optional(Schema.DateFromMillis), + outcome: Schema.Literals(["succeeded", "failed"]), + failureReason: Schema.optionalKey(Schema.NonEmptyString), + note: Schema.optionalKey(Schema.NonEmptyString), + suppressedConflicts: Schema.optional( + Schema.Array(Schema.Struct({ category: EventCategory, reason: Schema.NonEmptyString })), + ), +}) + +const CaptureSession = Schema.Struct({ + mode: Schema.Literals(["voice", "text", "mixed"]), + voiceTopics: Schema.Array(Schema.Int), + typedTopics: Schema.Array(Schema.Int), + interruptedAt: Schema.optional(Schema.DateFromMillis), + resumedAt: Schema.optional(Schema.DateFromMillis), + interruptionNote: Schema.optionalKey(Schema.NonEmptyString), + attempts: Schema.Array(Attempt), + clarification: Schema.optional( + Schema.Struct({ + question: Schema.NonEmptyString, + answer: Schema.NonEmptyString, + askedAt: Schema.DateFromMillis, + answeredAt: Schema.DateFromMillis, + }), + ), + visibilityTimeline: Schema.Array( + Schema.Struct({ at: Schema.DateFromMillis, state: Schema.Literals(["draft", "published"]) }), + ), +}) + +export const EntryView = Schema.Struct({ + captureId: Schema.NonEmptyString, + entryId: Schema.NonEmptyString, + /** Contract v0.2 Entry — decodes through the canonical schema. */ + wire: Schema.Struct(EntryFields), + capture: CaptureSession, +}) +export type EntryView = typeof EntryView["Type"] + +const Ref = Schema.Struct({ + kind: Schema.Literals(["transcript-excerpt", "event", "correction", "fixture"]), + ref: Schema.NonEmptyString, + excerpt: Schema.optional(Schema.NonEmptyString), +}) + +const Takeover = Schema.Struct({ + confirmedBy: Schema.NonEmptyString, + confirmedAt: Schema.DateFromMillis, + plan: Schema.Struct({ note: Schema.NonEmptyString, basis: Schema.Array(Schema.NonEmptyString) }), + fiveFacts: Schema.Array( + Schema.Struct({ + headline: Schema.NonEmptyString, + detail: Schema.optionalKey(Schema.NonEmptyString), + refs: Schema.Array(Ref), + }), + ), + pendingItems: Schema.Array( + Schema.Struct({ + label: Schema.NonEmptyString, + detail: Schema.NonEmptyString, + state: Schema.Literals(["open", "resolved"]), + at: Schema.DateFromMillis, + }), + ), +}) + +export const Day = Schema.Struct({ + fixtureId: Schema.NonEmptyString, + scenario: Schema.NonEmptyString, + candidate: Schema.NonEmptyString, + timezone: Schema.NonEmptyString, + dayLabel: Schema.NonEmptyString, + day: Schema.NonEmptyString, + renderedMoment: Schema.NonEmptyString, + household: Schema.Struct({ + householdId: Schema.NonEmptyString, + name: Schema.NonEmptyString, + members: Schema.Array( + Schema.Struct({ userId: Schema.NonEmptyString, displayName: Schema.NonEmptyString, role: RoleLiteral }), + ), + child: Schema.Struct({ childId: Schema.NonEmptyString, name: Schema.NonEmptyString, ageYears: Schema.Int }), + }), + entries: Schema.Array(EntryView), + events: Schema.Array(EventView), + audienceRestrictions: Schema.Array( + Schema.Struct({ + eventId: Schema.NonEmptyString, + scope: ScopeLiteral, + grantedBy: Schema.NonEmptyString, + grantedAt: Schema.DateFromMillis, + note: Schema.optionalKey(Schema.NonEmptyString), + }), + ), + reviewSessions: Schema.Array( + Schema.Struct({ + at: Schema.DateFromMillis, + entryId: Schema.NonEmptyString, + seenState: Schema.Literals(["draft", "published"]), + caption: Schema.NonEmptyString, + actions: Schema.Array( + Schema.Struct({ kind: Schema.NonEmptyString, at: Schema.DateFromMillis, detail: Schema.NonEmptyString }), + ), + }), + ), + readOnlyQuestions: Schema.Array( + Schema.Struct({ + question: Schema.NonEmptyString, + askedBy: Schema.NonEmptyString, + askedAt: Schema.DateFromMillis, + answer: Schema.NonEmptyString, + sources: Schema.Array(Ref), + }), + ), + takeover: Takeover, +}) +export type Day = typeof Day["Type"] + +export const MonthDay = Schema.Struct({ + date: Schema.NonEmptyString, + dayLabel: Schema.NonEmptyString, + captures: Schema.Int, + eventsByCategory: Schema.Record(Schema.String, Schema.Int), + nightWakings: Schema.Int, + napMinutes: Schema.Int, + pottySuccesses: Schema.Int, + pottyAccidents: Schema.Int, + milestones: Schema.Array(Schema.NonEmptyString), + coverage: Schema.Literals(["full", "partial", "none"]), + gapNotes: Schema.Array(Schema.NonEmptyString), + source: Schema.NonEmptyString, +}) +export type MonthDay = typeof MonthDay["Type"] + +export const Month = Schema.Struct({ + fixtureId: Schema.NonEmptyString, + window: Schema.Struct({ start: Schema.NonEmptyString, end: Schema.NonEmptyString, days: Schema.Int }), + deterministic: Schema.Struct({ + seed: Schema.Int, + generator: Schema.NonEmptyString, + prng: Schema.NonEmptyString, + }), + note: Schema.NonEmptyString, + days: Schema.Array(MonthDay), +}) +export type Month = typeof Month["Type"] + +/** Decode at module load — a fixture that fails the contract fails loud. */ +export const day: Day = Schema.decodeUnknownSync(Day)(dayJson) +export const month: Month = Schema.decodeUnknownSync(Month)(monthJson) + +// --------------------------------------------------------------------------- +// Lookups and viewer filtering. +// --------------------------------------------------------------------------- +export const memberByUserId = (userId: string): HouseholdMember | undefined => + day.household.members.find((m) => m.userId === userId) + +export const entryById = (entryId: string): EntryView | undefined => + day.entries.find((e) => e.entryId === entryId) + +export const eventById = (eventId: string): EventView | undefined => + day.events.find((e) => e.eventId === eventId) + +/** Current = not superseded by a correction (append-only lineage). */ +export const currentEvents = (): Array => day.events.filter((e) => e.supersededBy === undefined) + +export const supersededEvents = (): Array => day.events.filter((e) => e.supersededBy !== undefined) + +/** Decoded wire → grants-layer shape (grantedAt as unix ms; note carried). */ +const restrictions: Array = day.audienceRestrictions.map((r) => ({ + eventId: r.eventId, + scope: r.scope, + grantedBy: r.grantedBy, + grantedAt: r.grantedAt.getTime(), + note: r.note, +})) + +export const restrictionFor = (eventId: string): AudienceRestriction | undefined => + restrictions.find((r) => r.eventId === eventId) + +export const cueFor = (member: HouseholdMember | undefined, event: EventView): Cue => { + if (member === undefined) return "locked" // fail-closed for unknown viewers + const entry = entryById(event.entryId) + if (entry === undefined) return "locked" + return eventCue(member, entry.wire, restrictionFor(event.eventId)) +} + +export const feedForMember = (userId: string): Array<{ event: EventView; cue: Cue }> => { + const member = memberByUserId(userId) + if (member === undefined) return [] + return day.events + .map((event) => ({ event, cue: cueFor(member, event) })) + .filter((x) => x.cue === "visible" || (x.cue === "locked" && member.role === "caregiver")) + .sort((a, b) => (a.event.wire.occurredAt as unknown as number) - (b.event.wire.occurredAt as unknown as number)) +} + +/** Draft-visibility rule chosen for this prototype (see grants.ts). */ +export const draftVisibleTo = (member: HouseholdMember, entry: EntryView): boolean => + canSeeEntry(member, entry.wire) + +/** Fixed-offset ET clock label for prototype determinism (EDT = UTC−4). */ +export const etTime = (date: Date): string => { + const hh = date.getUTCHours() - 4 + const label = hh < 0 ? hh + 24 : hh + return `${String(label).padStart(2, "0")}:${String(date.getUTCMinutes()).padStart(2, "0")}` +} + +export const eventTime = (event: EventView): string => etTime(event.wire.occurredAt) + +export const CATEGORY_GLYPH: Record = { + potty: "🚽", + meal: "🍽", + sleep: "😴", + mood: "💛", + milestone: "🌟", + school: "🎒", +} + +export const confidenceLabel = (event: Event): string => + event.confidence === 1 ? "Confirmed" : `AI guess ${event.confidence.toFixed(2)}` + +/** Transcript excerpt for a source link (S1-C): verbatim slice, no reflow. */ +export const excerptFor = (event: EventView): string => { + const entry = entryById(event.entryId) + if (entry === undefined) return "" + return entry.wire.transcript.slice(event.sourceExcerpt.start, event.sourceExcerpt.end) +} diff --git a/spikes/home-c-handoff/src/grants.ts b/spikes/home-c-handoff/src/grants.ts new file mode 100644 index 0000000..32d3e71 --- /dev/null +++ b/spikes/home-c-handoff/src/grants.ts @@ -0,0 +1,81 @@ +/** + * Audience model for the handoff-first home prototype. + * + * Contract v0.2 (art_I2TCG08V): Entry.visibility (`draft | published`) is the + * PER-ENTRY publication state ONLY; WHO may see a published entry is resolved + * from household/relationship grants — "keyed by household/relationship, not + * by entry". No audience field on Entry, no fused status enum. + * + * The rubric scenario (art_VyNYOggs, S1-B) additionally requires Elena to + * "restrict the drop-off meltdown event to parents only (per the grants + * model)", i.e. a per-EVENT restriction. Contract v0.2 has no home for a + * per-event restriction yet, so this prototype models it as an explicit, + * additive AudienceRestriction record in the PROTOTYPE data layer only — + * nothing in packages/domain is touched. Flagged as a contract question in + * the evidence document. Restrictions narrow; they never widen. + * + * Draft visibility is the contract's own open question ("who inside a + * household sees a draft" — art_rBKvvzIa §7 open question 2). This prototype + * picks: drafts are visible to their author and to parent-role members, + * never to caregiver-role members. Stated here so the evaluator can score + * the choice. + */ + +export type Role = "parent" | "caregiver" + +export interface HouseholdMember { + readonly userId: string + readonly displayName: string + readonly role: Role +} + +/** PROPOSED extension (not in contract v0.2) — see module doc. */ +export type EventAudienceScope = "household" | "parents" + +export interface AudienceRestriction { + readonly eventId: string + readonly scope: EventAudienceScope + readonly grantedBy: string + readonly grantedAt: number + readonly note?: string +} + +export type Cue = "visible" | "locked" + +const isDraftVisible = ( + member: HouseholdMember, + authorId: string, +): boolean => member.role === "parent" || member.userId === authorId + +/** Entry-level: publication state + draft rule. */ +export const canSeeEntry = ( + member: HouseholdMember, + entry: { readonly authorId: string; readonly visibility: "draft" | "published" }, +): boolean => entry.visibility === "published" || isDraftVisible(member, entry.authorId) + +/** Event-level: entry gate plus audience restrictions (narrowing only). */ +export const eventCue = ( + member: HouseholdMember, + entry: { readonly authorId: string; readonly visibility: "draft" | "published" }, + restriction?: AudienceRestriction, +): Cue => { + if (!canSeeEntry(member, entry)) return "locked" + if (restriction?.scope === "parents" && member.role !== "parent") return "locked" + return "visible" +} + +/** + * Read-only questions never write (rubric hard requirement). The answer + * carries sources; there is no mutation path on this type by construction. + */ +export interface ReadOnlyAnswer { + readonly question: string + readonly askedBy: string + readonly askedAt: number + readonly answer: string + readonly sources: ReadonlyArray<{ + readonly kind: "transcript-excerpt" | "event" | "correction" | "fixture" + readonly ref: string + readonly excerpt?: string + }> +} diff --git a/spikes/home-c-handoff/src/screens/CaptureScreen.tsx b/spikes/home-c-handoff/src/screens/CaptureScreen.tsx new file mode 100644 index 0000000..497ff06 --- /dev/null +++ b/spikes/home-c-handoff/src/screens/CaptureScreen.tsx @@ -0,0 +1,168 @@ +import { useState } from "react" +import { ScrollView, StyleSheet, Text, View } from "react-native" + +import { currentEvents, entryById } from "../data" +import { Btn, C, Caption, Card, Chip, Screen } from "../ui" + +/** + * S1-A replay — capture with interruption, then quiet-input completion. + * Scripted off fixture HOME-C-S1-DAY: Elena dictates topics 1–3 by voice + * (07:38), the preschool calls (07:41), draft is saved untouched, server + * extraction completes during the call (envelope rule a), Elena returns at + * 07:51 and TYPES the remaining topics while holding Sofia, answers exactly + * one clarification, publishes at 07:55. + */ +const PHASES = [ + "intro", + "t1", + "t2", + "t3", + "interrupt", + "draftSaved", + "attempt0", + "resumed", + "t5", + "t6", + "clarify", + "published", +] as const +type Phase = (typeof PHASES)[number] + +const topicsShown: Record = { + intro: 0, + t1: 1, + t2: 2, + t3: 3, + interrupt: 3, + draftSaved: 3, + attempt0: 3, + resumed: 4, + t5: 5, + t6: 6, + clarify: 6, + published: 6, +} + +export const CaptureScreen = ({ onDone }: { onDone: () => void }) => { + const [phase, setPhase] = useState("intro") + const [clarifyAnswered, setClarifyAnswered] = useState(false) + const entry = entryById("entry-e1") + if (entry === undefined) return null + + // Current events sorted by excerpt offset == dictation order (topics 1–6). + const topics = currentEvents() + .filter((e) => e.entryId === "entry-e1") + .sort((a, b) => a.sourceExcerpt.start - b.sourceExcerpt.start) + const shown = topics.slice(0, topicsShown[phase]) + const modeFor = (i: number): "voice" | "text" => (i < 3 ? "voice" : "text") + + const next = (): void => { + const i = PHASES.indexOf(phase) + const nextPhase = PHASES[i + 1] + if (nextPhase !== undefined) setPhase(nextPhase) + } + + return ( + + + Speak an update — Tuesday 07:38, Elena + + Scripted replay of fixture HOME-C-S1-DAY (S1-A). Each tap counts as a real user action + (D1 is scored on taps and screens). + + + {phase === "intro" && ( + + One hand holding Sofia. Voice is primary; the text path always exists. + + + )} + + {shown.map((topic, i) => ( + + + + {modeFor(i) === "voice" ? `07:3${8 + i}` : "07:5x"} + + + “{entry.wire.transcript.slice(topic.sourceExcerpt.start, topic.sourceExcerpt.end)}” + + + ))} + + {(phase === "interrupt" || phase === "draftSaved") && ( + + + {phase === "interrupt" + ? "07:41 — after the third topic. Elena takes the call." + : "Draft saved — nothing lost. The transcript so far is preserved verbatim; the call inserts no bytes into it."} + + + + )} + + {phase === "attempt0" && ( + + + Attempt 0 (07:39–07:42) ran SERVER-SIDE over the partial transcript — the client + disconnect did not cancel it (contract v0.2 envelope rule a). Elena never waited on it. + + + + )} + + {phase === "resumed" && ( + + + Still holding Sofia — she switches to typing (the quiet-input demonstration, S1-A). + Remaining topics are typed, not lost. + + + )} + + {phase === "clarify" && ( + + {entry.capture.clarification?.question} + + Exactly one clarification round-trip (rubric target: 1). Ambiguous clause: + “She was upset again after quiet time.” + + {entry.capture.clarification?.answer} + {clarifyAnswered ? ( + Sent — the mood event becomes caregiver-confirmed (confidence 1.0). + ) : ( + setClarifyAnswered(true)} /> + )} + {clarifyAnswered && } + + )} + + {phase === "published" && ( + + + draft → published (per-entry lifecycle state, contract v0.2). Topics captured: 6/6, + dropped: 0. Extraction attempt 1 re-ran over the full transcript; the stale attempt 0 + was discarded, never merged (rule 2) — and the 07:44 correction survived it because + caregiver-confirmed events are pinned. + + + + )} + + {phase !== "intro" && phase !== "published" && ( + + + + )} + + + ) +} + +const local = StyleSheet.create({ + content: { paddingBottom: 32, gap: 4 }, + title: { color: C.text, fontSize: 19, fontWeight: "800", marginBottom: 4 }, + topicRow: { alignItems: "center", flexDirection: "row", gap: 8, marginBottom: 6 }, + topicText: { color: C.text, fontSize: 14, lineHeight: 20 }, + navRow: { marginTop: 8 }, +}) diff --git a/spikes/home-c-handoff/src/screens/HomeScreen.tsx b/spikes/home-c-handoff/src/screens/HomeScreen.tsx new file mode 100644 index 0000000..93cb4f1 --- /dev/null +++ b/spikes/home-c-handoff/src/screens/HomeScreen.tsx @@ -0,0 +1,200 @@ +import { useState } from "react" +import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native" + +import { + CATEGORY_GLYPH, + confidenceLabel, + currentEvents, + day, + eventTime, + feedForMember, + month, + restrictionFor, +} from "../data" +import { Btn, C, Caption, Card, Chip, FactRow, Screen, SectionTitle, styles as ui } from "../ui" + +/** + * THE CANDIDATE-C LENS: the home leads with the TAKEOVER BRIEF — what the + * on-duty caregiver needs to take over care right now. Capture and feed serve + * the brief. One-handed: capture (the most frequent action) sits in the + * bottom thumb zone; brief actions are full-width rows in the lower third. + */ +export const HomeScreen = ({ + viewer, + onSwitchViewer, + onOpenCapture, + onOpenReview, + onOpenMonth, + onOpenEvent, + onOpenRosa, +}: { + viewer: string + onSwitchViewer: (userId: string) => void + onOpenCapture: () => void + onOpenReview: () => void + onOpenMonth: () => void + onOpenEvent: (eventId: string) => void + onOpenRosa: () => void +}) => { + const [confirmed, setConfirmed] = useState(false) + const [showAnswer, setShowAnswer] = useState(false) + const question = day.readOnlyQuestions[0] + const feed = feedForMember(viewer) + + return ( + + + + + {day.household.child.name} · {day.household.child.ageYears} · {day.household.name} + + + {day.dayLabel} Sep 15 — 18:10 · last update 08:09 · 2 captures · 7 events + + + + + {day.household.members.map((m) => ( + onSwitchViewer(m.userId)} + /> + ))} + + + Take over Sofia's care + + {day.takeover.fiveFacts.map((fact, i) => { + const eventRef = fact.refs.find((r) => r.kind === "event") + return ( + onOpenEvent(eventRef.ref) : undefined} + /> + ) + })} + + {day.takeover.pendingItems.map((p) => ( + + ✓ {p.label} — {p.detail} + + ))} + + Tonight's plan: {day.takeover.plan.note} + setConfirmed(true)} + /> + + + {question !== undefined && ( + + setShowAnswer(true)} /> + {showAnswer && ( + + {question.answer} + {question.sources.map((s, i) => ( + + • [{s.kind}] {s.ref} + {s.excerpt !== undefined ? ` — “${s.excerpt}”` : ""} + + ))} + Questions never write — hard requirement (S1-E). + + )} + + )} + + Today's feed — per-event audience cues + {feed.map(({ event, cue }) => { + const restriction = restrictionFor(event.eventId) + if (cue === "locked") { + return ( + + 🔒 Parents only — locked for this viewer + {restriction?.note} + + ) + } + return ( + + + {CATEGORY_GLYPH[event.wire.category] ?? "•"} + + {event.wire.note} + + {eventTime(event)} · {confidenceLabel(event.wire)} + {event.audienceScope === "parents" ? " · 🔒 parents only" : ""} + {event.corrects !== undefined ? " · corrected (original preserved)" : ""} + + + onOpenEvent(event.eventId)} hitSlop={8}> + source ↗ + + + + ) + })} + + Month history (30 days) + + + {month.days.map((d) => ( + + ))} + + Green = full capture, amber = gaps, dark = none. Tap for details. + + + + + + + + + + The full extraction-review card flow (slots 11–14), handoff implementation (slot 23), and + digest flow (slot 24) are out of scope — the home lens only (rubric ground rule 3). + + + + + + + Thumb zone: capture lives in the bottom third — one-handed (S1-A). + + + + ) +} + +const local = StyleSheet.create({ + content: { paddingBottom: 32 }, + header: { marginBottom: 10 }, + headerTitle: { color: C.text, fontSize: 19, fontWeight: "800" }, + chips: { flexDirection: "row", flexWrap: "wrap", gap: 8, marginBottom: 12 }, + pendingWrap: { marginTop: 4, marginBottom: 8 }, + pendingLine: { color: C.dim, fontSize: 12.5, lineHeight: 17 }, + planLine: { color: C.text, fontSize: 13.5, fontWeight: "600", marginBottom: 10 }, + answerWrap: { marginTop: 10, gap: 4 }, + answerText: { color: C.text, fontSize: 13.5, lineHeight: 19 }, + lockLine: { color: C.warn, fontSize: 14, fontWeight: "700", marginBottom: 4 }, + eventCard: { paddingVertical: 10 }, + eventRow: { alignItems: "flex-start", flexDirection: "row", gap: 10 }, + glyph: { fontSize: 18 }, + eventBody: { flex: 1 }, + eventNote: { color: C.text, fontSize: 14, lineHeight: 19 }, + strip: { flexDirection: "row", flexWrap: "wrap", gap: 3, marginBottom: 8 }, + stripCell: { backgroundColor: C.cardLine, borderRadius: 2, height: 14, width: 9 }, + captureBar: { gap: 8, marginTop: 4 }, +}) diff --git a/spikes/home-c-handoff/src/screens/InspectScreen.tsx b/spikes/home-c-handoff/src/screens/InspectScreen.tsx new file mode 100644 index 0000000..3bb80d1 --- /dev/null +++ b/spikes/home-c-handoff/src/screens/InspectScreen.tsx @@ -0,0 +1,123 @@ +import { useState } from "react" +import { ScrollView, StyleSheet, Text, View } from "react-native" + +import { confidenceLabel, etTime, eventById } from "../data" +import { Btn, C, Caption, Card, Chip, Screen } from "../ui" + +/** + * S1-B / S1-C — inspect and correct. Three bundled actions, each with a + * preview before confirm (D2: change previewed, source excerpt visible while + * correcting, append-only lineage — the original is never erased). + */ +type Tab = "sleep" | "audience" | "photo" + +export const InspectScreen = ({ eventId, onDone }: { eventId: string; onDone: () => void }) => { + const [tab, setTab] = useState("sleep") + const [step, setStep] = useState(0) + const misread = eventById("ev-sleep-1") + const corrected = eventById("ev-sleep-2") + const school = eventById("ev-school-1") + const meal = eventById("ev-meal-1") + const opened = eventById(eventId) + + return ( + + + Inspect event + {opened !== undefined && ( + + “{opened.wire.note}” + + {etTime(opened.wire.occurredAt)} · {confidenceLabel(opened.wire)} · transcript excerpt is + one tap away — every fact links back to the raw capture. + + + )} + + + { setTab("sleep"); setStep(0) }} /> + { setTab("audience"); setStep(0) }} /> + { setTab("photo"); setStep(0) }} /> + + + {tab === "sleep" && misread !== undefined && corrected !== undefined && ( + <> + + + {etTime(misread.wire.occurredAt)} · {confidenceLabel(misread.wire)} — low confidence is + the tell. Elena corrects it at 07:44 (S1-B). + + {step === 0 && setStep(1)} />} + + {step >= 1 && ( + + Night waking · 23:00 → 00:30 (90 min) + {step === 1 && setStep(2)} />} + + )} + {step >= 2 && ( + + — {misread.wire.note} ({etTime(misread.wire.occurredAt)}, confidence 0.61) + + {corrected.wire.note} (23:00–00:30, caregiver-confirmed 1.0) + + Source excerpt stays visible while correcting: “She woke at eleven last night and + was up until twelve thirty.” + + {step === 2 && setStep(3)} />} + + )} + {step >= 3 && ( + + + ev-sleep-2 supersedes ev-sleep-1; the original stays inspectable. Confidence 1.0 + pins it: a rerun never downgrades a caregiver-confirmed event — this is what makes + the correction survive attempt 1 at 07:53. + + + )} + + )} + + {tab === "audience" && school !== undefined && ( + + “{school.wire.note}” + + + + + + Restricted at 07:45, per the grants model. Audience is a separate dimension from + publication state (contract v0.2 decision 1); per-event restriction is a PROPOSED + extension in this prototype's data layer — flagged in the evidence document. + + + )} + + {tab === "photo" && meal !== undefined && ( + + “{meal.wire.note}” + + + Photo rides the entry (photoId, contract v0.2 Entry.photoId); the source link from the + meal event opens transcript excerpt + photo together (S1-C). + + + )} + + + + + + + ) +} + +const local = StyleSheet.create({ + content: { paddingBottom: 32, gap: 4 }, + title: { color: C.text, fontSize: 19, fontWeight: "800", marginBottom: 4 }, + body: { color: C.text, fontSize: 14, lineHeight: 20, marginBottom: 6 }, + tabs: { flexDirection: "row", flexWrap: "wrap", gap: 8, marginVertical: 8 }, + diffOld: { color: C.dim, fontSize: 13.5, lineHeight: 19, textDecorationLine: "line-through" }, + diffNew: { color: C.ok, fontSize: 13.5, fontWeight: "600", lineHeight: 19 }, + navRow: { marginTop: 8 }, +}) diff --git a/spikes/home-c-handoff/src/screens/MonthScreen.tsx b/spikes/home-c-handoff/src/screens/MonthScreen.tsx new file mode 100644 index 0000000..b1983d6 --- /dev/null +++ b/spikes/home-c-handoff/src/screens/MonthScreen.tsx @@ -0,0 +1,83 @@ +import { useState } from "react" +import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native" + +import { month } from "../data" +import { C, Caption, Card, Screen } from "../ui" + +/** + * Month history — the same 30-day window every candidate shows (rubric ground + * rule 1). The handoff lens reads it as context for takeover: patterns and + * COVERAGE GAPS are disclosed, never smoothed over. + */ +export const MonthScreen = ({ onDone }: { onDone: () => void }) => { + const [selected, setSelected] = useState("2026-09-15") + const selectedDay = month.days.find((d) => d.date === selected) + + return ( + + + Last 30 days — Sofia + {month.note} + + + + {month.days.map((d) => ( + setSelected(d.date)} + style={[local.cell, d.coverage === "full" && { backgroundColor: C.ok }, d.coverage === "partial" && { backgroundColor: C.warn }]} + /> + ))} + + + ■ full ■ gaps ■ no capture — tap a day + + + + {selectedDay !== undefined && ( + + + {selectedDay.captures} captures ·{" "} + {Object.entries(selectedDay.eventsByCategory) + .map(([k, v]) => `${k}: ${v}`) + .join(", ") || "no events"} + + + Night wakings: {selectedDay.nightWakings} · nap: {selectedDay.napMinutes} min · + potty: {selectedDay.pottySuccesses}✓/{selectedDay.pottyAccidents}✗ + + {selectedDay.milestones.map((m) => ( + 🌟 {m} + ))} + {selectedDay.gapNotes.length > 0 && ( + ⚠ {selectedDay.gapNotes.join("; ")} — shown as-is, not smoothed + )} + + {selectedDay.date === "2026-09-15" + ? "This row is SET from the S1 fixture — month history and scenario cannot diverge (evaluator consistency check)." + : "Generated deterministically (seed 20260915); committed JSON is byte-identical on regeneration."} + + + )} + + + + Glanceable pattern: sleep is the wobbly column this month — one night waking trend line, + zero naps today. The brief above the fold carries today's copy of that pattern. + + + + + ) +} + +const local = StyleSheet.create({ + content: { paddingBottom: 32, gap: 4 }, + title: { color: C.text, fontSize: 19, fontWeight: "800", marginBottom: 4 }, + grid: { flexDirection: "row", flexWrap: "wrap", gap: 5, marginVertical: 10 }, + cell: { backgroundColor: C.cardLine, borderRadius: 4, height: 26, width: 26 }, + legend: { marginBottom: 6 }, + line: { color: C.text, fontSize: 13.5, lineHeight: 19 }, + milestone: { color: C.text, fontSize: 13.5, lineHeight: 19 }, + gap: { color: C.warn, fontSize: 12.5, lineHeight: 17, marginTop: 4 }, +}) diff --git a/spikes/home-c-handoff/src/screens/ReviewDoorwayScreen.tsx b/spikes/home-c-handoff/src/screens/ReviewDoorwayScreen.tsx new file mode 100644 index 0000000..9eae0d8 --- /dev/null +++ b/spikes/home-c-handoff/src/screens/ReviewDoorwayScreen.tsx @@ -0,0 +1,56 @@ +import { ScrollView, StyleSheet, Text, View } from "react-native" + +import { day, etTime } from "../data" +import { Btn, C, Caption, Card, Screen } from "../ui" + +/** + * The ONE representative review screen the rubric allows (badge or doorway — + * ground rule 3). Shows the 07:44 draft-review state from the fixture's + * reviewSession; the full extraction-review card flow belongs to slots 11–14. + */ +export const ReviewDoorwayScreen = ({ + onOpenEvent, + onDone, +}: { + onOpenEvent: (eventId: string) => void + onDone: () => void +}) => { + const session = day.reviewSessions[0] + if (session === undefined) return null + + return ( + + + Review — draft entry (07:44) + + + Extraction finished server-side while Elena was on the call. She inspects BEFORE + publishing: correct, restrict, attach — the three actions below, each previewed. + + {session.actions.map((a, i) => ( + + + {etTime(a.at)} · {a.kind} + + {a.detail} + + ))} + + + onOpenEvent("ev-sleep-2")} /> + + + {session.caption} + + + + + ) +} + +const local = StyleSheet.create({ + content: { paddingBottom: 32, gap: 8 }, + title: { color: C.text, fontSize: 19, fontWeight: "800", marginBottom: 4 }, + action: { marginTop: 8 }, + actionLine: { color: C.text, fontSize: 13.5, fontWeight: "700" }, +}) diff --git a/spikes/home-c-handoff/src/screens/RosaScreen.tsx b/spikes/home-c-handoff/src/screens/RosaScreen.tsx new file mode 100644 index 0000000..5d0b75a --- /dev/null +++ b/spikes/home-c-handoff/src/screens/RosaScreen.tsx @@ -0,0 +1,77 @@ +import { ScrollView, StyleSheet, Text, View } from "react-native" + +import { CATEGORY_GLYPH, confidenceLabel, currentEvents, cueFor, day, entryById, eventTime, memberByUserId } from "../data" +import { Btn, C, Caption, Card, Screen, SectionTitle } from "../ui" + +/** + * S1-F — caregiver awareness. Rosa (invited grandmother, caregiver role) sees + * what her grants allow: the parents-only meltdown event shows as a locked + * tile (visibly locked, not silently hidden), drafts never reach her, and + * today's plan is visible so she can actually help. + */ +export const RosaScreen = ({ onDone }: { onDone: () => void }) => { + const rosa = memberByUserId("rosa") + if (rosa === undefined) return null + + return ( + + + What Rosa sees — Wednesday 14:00 + + Rosa's grants: caregiver role, weekday afternoons. Everything below is resolved from + household/relationship grants — never from a per-entry audience field (contract v0.2). + + + Today's plan (visible) + + {day.takeover.plan.note} + + + Sofia's day (grants-filtered) + {currentEvents().map((event) => { + const cue = cueFor(rosa, event) + const entry = entryById(event.entryId) + if (entry === undefined) return null + if (cue === "locked") { + return ( + + 🔒 Parents only — locked + This event is restricted; Rosa sees the lock, not silence. + + ) + } + return ( + + + {CATEGORY_GLYPH[event.wire.category] ?? "•"} + + {event.wire.note} + + {eventTime(event)} · {confidenceLabel(event.wire)} · by {event.wire.authorId} + + + + + ) + })} + + + + Prototype rule (stated, because the contract leaves draft visibility open): drafts are + visible to their author and to parent-role members only. + + + + + + ) +} + +const local = StyleSheet.create({ + content: { paddingBottom: 32, gap: 4 }, + title: { color: C.text, fontSize: 19, fontWeight: "800", marginBottom: 4 }, + line: { color: C.text, fontSize: 14, lineHeight: 20 }, + lock: { color: C.warn, fontSize: 14, fontWeight: "700", marginBottom: 4 }, + row: { alignItems: "flex-start", flexDirection: "row", gap: 10 }, + glyph: { fontSize: 18 }, +}) diff --git a/spikes/home-c-handoff/src/ui.tsx b/spikes/home-c-handoff/src/ui.tsx new file mode 100644 index 0000000..0bf7af6 --- /dev/null +++ b/spikes/home-c-handoff/src/ui.tsx @@ -0,0 +1,137 @@ +import type { ReactNode } from "react" +import { Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from "react-native" + +/** + * Shared presentation primitives for the candidate-C prototype screens. + * Everything is plain react-native — the point of candidate C is the home + * LENS (what the screen leads with), not a navigation library. + */ + +export const C = { + bg: "#0B1220", + card: "#111C2E", + cardLine: "#24344F", + text: "#EAF2FF", + dim: "#8FA3BF", + accent: "#5AC8FA", + accentSoft: "#12314A", + ok: "#34C77B", + okSoft: "#0F2E20", + warn: "#FFB020", + warnSoft: "#33270D", + danger: "#FF5D5D", + dangerSoft: "#331414", +} as const + +export const Screen = ({ children }: { children: ReactNode }) => ( + {children} +) + +export const Card = ({ + title, + tone, + children, + style, +}: { + title?: string + tone?: "default" | "ok" | "warn" | "danger" + children: ReactNode + style?: StyleProp +}) => ( + + {title !== undefined && {title}} + {children} + +) + +export const Btn = ({ + label, + onPress, + primary = false, + tone, +}: { + label: string + onPress?: () => void + primary?: boolean + tone?: "ok" | "danger" +}) => ( + + {label} + +) + +export const Chip = ({ label, tone = "default", onPress }: { label: string; tone?: "default" | "accent" | "ok" | "warn" | "danger"; onPress?: () => void }) => ( + + {label} + +) + +export const SectionTitle = ({ children }: { children: ReactNode }) => ( + {children} +) + +export const Caption = ({ children }: { children: ReactNode }) => ( + {children} +) + +export const FactRow = ({ + index, + headline, + detail, + onOpenSource, +}: { + index: number + headline: string + detail?: string + onOpenSource?: () => void +}) => ( + + {index} + + {headline} + {detail !== undefined && detail !== "" && {detail}} + + {onOpenSource !== undefined && ( + + source ↗ + + )} + +) + +export const styles = StyleSheet.create({ + screen: { backgroundColor: C.bg, flex: 1, paddingBottom: 24, paddingHorizontal: 16, paddingTop: 48 }, + card: { backgroundColor: C.card, borderColor: C.cardLine, borderRadius: 14, borderWidth: 1, marginBottom: 12, padding: 14 }, + cardTitle: { color: C.text, fontSize: 15, fontWeight: "700", marginBottom: 8 }, + btn: { backgroundColor: C.accentSoft, borderColor: C.accent, borderRadius: 12, borderWidth: 1, paddingVertical: 12, paddingHorizontal: 16 }, + btnPrimary: { backgroundColor: C.accent }, + btnOk: { backgroundColor: C.okSoft, borderColor: C.ok }, + btnDanger: { backgroundColor: C.dangerSoft, borderColor: C.danger }, + btnLabel: { color: C.accent, fontSize: 15, fontWeight: "600", textAlign: "center" }, + btnLabelPrimary: { color: "#04121E" }, + chip: { backgroundColor: C.card, borderColor: C.cardLine, borderRadius: 999, borderWidth: 1, paddingHorizontal: 10, paddingVertical: 5 }, + chipAccent: { backgroundColor: C.accentSoft, borderColor: C.accent }, + chipOk: { backgroundColor: C.okSoft, borderColor: C.ok }, + chipWarn: { backgroundColor: C.warnSoft, borderColor: C.warn }, + chipDanger: { backgroundColor: C.dangerSoft, borderColor: C.danger }, + chipLabel: { color: C.text, fontSize: 12 }, + sectionTitle: { color: C.dim, fontSize: 12, fontWeight: "700", letterSpacing: 1.2, marginBottom: 6, textTransform: "uppercase" }, + caption: { color: C.dim, fontSize: 12, lineHeight: 17 }, + factRow: { alignItems: "flex-start", flexDirection: "row", gap: 10, marginBottom: 10 }, + factIndex: { color: C.accent, fontSize: 14, fontWeight: "800", marginTop: 1 }, + factBody: { flex: 1 }, + factHeadline: { color: C.text, fontSize: 14, fontWeight: "600", lineHeight: 19 }, + factDetail: { color: C.dim, fontSize: 12.5, lineHeight: 17, marginTop: 2 }, + sourceLink: { color: C.accent, fontSize: 12, fontWeight: "600", marginTop: 2 }, +}) diff --git a/spikes/home-c-handoff/test/contract.test.ts b/spikes/home-c-handoff/test/contract.test.ts new file mode 100644 index 0000000..bab3d37 --- /dev/null +++ b/spikes/home-c-handoff/test/contract.test.ts @@ -0,0 +1,130 @@ +import { createHash } from "node:crypto" +import { readFileSync } from "node:fs" +import { join } from "node:path" +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" + +import { Entry, Event } from "../src/contract" +import { currentEvents, day, month, supersededEvents } from "../src/data" +import manifest from "../fixtures/manifest.json" +import dayJson from "../fixtures/s1-day.json" +import monthJson from "../fixtures/month-history.json" + +const sha256 = (s: string): string => createHash("sha256").update(s, "utf8").digest("hex") + +describe("fixture → contract decode (art_I2TCG08V v0.2)", () => { + test("every Entry wire payload decodes through the canonical Entry schema", () => { + const fixture = dayJson as unknown as { entries: Array<{ entryId: string; wire: unknown }> } + for (const entry of fixture.entries) { + const decoded = Schema.decodeUnknownSync(Entry)(entry.wire) + expect(decoded._tag).toBe("Entry") + expect(decoded.transcript.length).toBeGreaterThan(0) + } + }) + + test("every Event wire payload decodes through the canonical Event schema", () => { + const fixture = dayJson as unknown as { events: Array<{ eventId: string; wire: { category: "potty" | "meal" | "sleep" | "mood" | "milestone" | "school" } }> } + for (const event of fixture.events) { + const decoded = Schema.decodeUnknownSync(Event)(event.wire) + expect(decoded.category).toBe(event.wire.category) + } + }) + + test("transcripts round-trip byte-identical (sha256 in manifest)", () => { + const hashes = manifest.transcripts.sha256 as Record + for (const entry of day.entries) { + expect(sha256(entry.wire.transcript)).toBe(hashes[entry.entryId] as string) + } + }) + + test("wire format: no explicit nulls anywhere; timestamps are integer unix-ms", () => { + const walk = (node: unknown): void => { + if (node === null) throw new Error("explicit null in fixture — not in contract") + if (Array.isArray(node)) return node.forEach(walk) + if (typeof node === "object" && node !== undefined) { + for (const value of Object.values(node as Record)) walk(value) + } + } + walk(dayJson) + walk(monthJson) + for (const event of day.events) { + expect(Number.isInteger(event.wire.occurredAt.getTime())).toBe(true) + } + }) + + test("regenerating fixtures is a byte-level no-op (determinism proof)", () => { + const spikeDir = join(import.meta.dir, "..") + const files = ["s1-day.json", "month-history.json", "manifest.json"] as const + const before = files.map((f) => createHash("sha256").update(readFileSync(join(spikeDir, "fixtures", f))).digest("hex")) + const run = Bun.spawnSync(["bun", "scripts/generate-fixtures.ts"], { cwd: spikeDir }) + expect(run.exitCode).toBe(0) + const after = files.map((f) => createHash("sha256").update(readFileSync(join(spikeDir, "fixtures", f))).digest("hex")) + expect(after).toEqual(before) + }) +}) + +describe("scenario integrity (rubric ground rule 1 — identical S1, binding)", () => { + test("exactly one clarification round-trip, answered", () => { + const entry = day.entries[0] + expect(entry?.capture.clarification).toBeDefined() + expect(entry?.capture.attempts.length).toBe(2) + const clarify = entry?.capture.clarification + expect(clarify !== undefined && clarify.answeredAt > clarify.askedAt).toBe(true) + // ...and the other capture has none: + expect(day.entries[1]?.capture.clarification).toBeUndefined() + }) + + test("interruption is a session fact, never transcript bytes", () => { + const entry = day.entries[0] + expect(entry?.capture.interruptedAt).toBeDefined() + expect(entry?.wire.transcript.includes("call")).toBe(false) + expect(entry?.wire.transcript.includes("interrupt")).toBe(false) + }) + + test("takeover brief: five facts, each with at least one source; pending items resolved", () => { + expect(day.takeover.fiveFacts.length).toBe(5) + for (const fact of day.takeover.fiveFacts) { + expect(fact.refs.length).toBeGreaterThan(0) + } + expect(day.takeover.pendingItems.every((p) => p.state === "resolved")).toBe(true) + expect(day.takeover.pendingItems.length).toBe(2) + }) + + test("failed extraction (S1-D): failed attempt visible, transcript preserved, no data loss", () => { + const e2 = day.entries[1] + expect(e2?.capture.attempts[0]?.outcome).toBe("failed") + expect(e2?.capture.attempts[0]?.failureReason?.toLowerCase()).toContain("timeout") + expect(e2?.wire.transcript.length).toBeGreaterThan(0) + // The manual event coexists with the failed attempt: + const manual = e2?.wire.events.find((e) => e.category === "potty" && e.note?.includes("typed manually")) + expect(manual?.confidence).toBe(1) + }) + + test("entry.wire.events equals the entry's current (non-superseded) event set", () => { + for (const entry of day.entries) { + const current = currentEvents().filter((e) => e.entryId === entry.entryId) + expect(entry.wire.events.length).toBe(current.length) + } + expect(supersededEvents().length).toBe(1) // ev-sleep-1 + }) +}) + +describe("month history consistency", () => { + test("30 days, deterministic metadata", () => { + expect(month.days.length).toBe(30) + expect(month.deterministic.seed).toBe(20260915) + expect(month.window.end).toBe("2026-09-15") + }) + + test("final row is set from the S1 day, never generated (no divergence by construction)", () => { + const last = month.days.at(-1) + expect(last?.source).toContain("HOME-C-S1-DAY") + expect(last?.nightWakings).toBe(1) + expect(last?.napMinutes).toBe(0) // fact 4: "No nap recorded" — napMinutes is internal state; the brief text must not claim a confirmed absence + expect(last?.pottySuccesses).toBe(2) + expect(last?.pottyAccidents).toBe(1) + expect(last?.captures).toBe(2) + expect(last?.milestones[0]).toContain("balance bike") + expect(last?.eventsByCategory).toEqual({ meal: 1, sleep: 1, school: 1, potty: 2, milestone: 1, mood: 1 }) + }) +}) diff --git a/spikes/home-c-handoff/test/semantics.test.ts b/spikes/home-c-handoff/test/semantics.test.ts new file mode 100644 index 0000000..d6b3123 --- /dev/null +++ b/spikes/home-c-handoff/test/semantics.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" + +import { ExtractionResult, type ExtractionResult as TExtractionResult } from "../src/contract" +import { applyExtractionResult, currentEvents as contractCurrentEvents } from "../src/contract" +import { canSeeEntry, eventCue, type HouseholdMember } from "../src/grants" +import { cueFor, currentEvents, day, eventById, feedForMember, memberByUserId, restrictionFor, supersededEvents } from "../src/data" +import dayJson from "../fixtures/s1-day.json" + +const parent = (userId: string): HouseholdMember | undefined => memberByUserId(userId) +const rosa = (): HouseholdMember | undefined => memberByUserId("rosa") + +describe("audience grants (contract v0.2: visibility vs audience are separate dimensions)", () => { + test("parents-only event: Marco and Elena see it, Rosa gets a locked cue (not silence)", () => { + const school = eventById("ev-school-1") + expect(school).toBeDefined() + const entry = day.entries[0] + if (school === undefined || entry === undefined) throw new Error("fixture missing") + expect(eventCue(parent("marco")!, entry.wire, undefined)).toBe("visible") + expect(eventCue(rosa()!, entry.wire, undefined)).toBe("visible") + const restriction = restrictionFor("ev-school-1") + expect(restriction?.scope).toBe("parents") + expect(eventCue(rosa()!, entry.wire, restriction)).toBe("locked") + }) + + test("restrictions narrow, never widen: a parents-scoped event never shows to caregivers", () => { + const school = eventById("ev-school-1") + const entry = day.entries[0] + if (school === undefined || entry === undefined) throw new Error("fixture missing") + const restriction = { eventId: school.eventId, scope: "parents" as const, grantedBy: "elena", grantedAt: 0 } + expect(cueFor(rosa(), school)).toBe("locked") + expect(cueFor(parent("marco"), school)).toBe("visible") + void restriction + }) + + test("drafts: visible to author and parents, never to caregiver role (stated prototype rule)", () => { + const draft = { authorId: "elena", visibility: "draft" as const } + expect(canSeeEntry(rosa()!, draft)).toBe(false) + expect(canSeeEntry(parent("marco")!, draft)).toBe(true) + expect(canSeeEntry(parent("elena")!, draft)).toBe(true) + }) + + test("feedForMember: caregiver sees the lock tile; parents see the event", () => { + const rosaFeed = feedForMember("rosa") + const locked = rosaFeed.find((x) => x.event.eventId === "ev-school-1") + expect(locked?.cue).toBe("locked") + const marcoFeed = feedForMember("marco") + const visible = marcoFeed.find((x) => x.event.eventId === "ev-school-1") + expect(visible?.cue).toBe("visible") + }) +}) + +describe("extraction envelope semantics (contract v0.2 rules 1–3)", () => { + const decode = Schema.decodeUnknownSync(ExtractionResult) + const result = (captureId: string, attempt: number, category: string): TExtractionResult => + decode({ + _tag: "ExtractionResult", + captureId, + attempt, + events: [ + { _tag: "Event", category, occurredAt: 1_757_900_000_000 + attempt, confidence: 0.7, authorId: "elena" }, + ], + }) + + test("stale-result suppression: a superseded attempt is discarded, never merged", () => { + const applied = applyExtractionResult([], result("cap-x", 1, "meal")) + const stale = applyExtractionResult(applied, result("cap-x", 0, "potty")) + expect(contractCurrentEvents(stale, "cap-x").length).toBe(1) + expect(contractCurrentEvents(stale, "cap-x")[0]?.category).toBe("meal") + }) + + test("idempotent completion: applying the same (captureId, attempt) twice is a no-op", () => { + const once = applyExtractionResult([], result("cap-y", 0, "sleep")) + const twice = applyExtractionResult(once, result("cap-y", 0, "sleep")) + expect(twice.length).toBe(once.length) + }) + + test("captures are independent", () => { + const a = applyExtractionResult([], result("cap-a", 0, "meal")) + const b = applyExtractionResult(a, result("cap-b", 0, "mood")) + expect(contractCurrentEvents(b, "cap-a")[0]?.category).toBe("meal") + expect(contractCurrentEvents(b, "cap-b")[0]?.category).toBe("mood") + }) +}) + +describe("corrections and pinning (art_rBKvvzIa §3.2 semantics in the home lens)", () => { + test("the corrected night waking is caregiver-confirmed (pinned) and survives attempt 1", () => { + const corrected = eventById("ev-sleep-2") + expect(corrected?.wire.confidence).toBe(1) + expect(corrected?.corrects).toBe("ev-sleep-1") + const entry = day.entries[0] + const attempt1 = entry?.capture.attempts.find((a) => a.attempt === 1) + expect(attempt1?.suppressedConflicts?.[0]?.category).toBe("sleep") + expect(attempt1?.suppressedConflicts?.[0]?.reason).toContain("pinned") + }) + + test("the misread original is never erased (append-only lineage)", () => { + const misread = eventById("ev-sleep-1") + expect(misread?.supersededBy).toBe("ev-sleep-2") + expect(misread?.wire.note).toContain("misread") + expect(currentEvents().find((e) => e.eventId === "ev-sleep-1")).toBeUndefined() + }) + + test("the correction is what makes five-fact #4 true (No nap recorded — absence of record, not a confirmed absence)", () => { + const fact4 = day.takeover.fiveFacts[3] + expect(fact4?.headline).toBe("No nap recorded") + expect(fact4?.refs.some((r) => r.kind === "correction")).toBe(true) + expect(fact4?.refs.some((r) => r.kind === "fixture" && r.ref.startsWith("coverage:"))).toBe(true) + }) +}) + +describe("read-only questions never write", () => { + test("Marco's 'Did she nap?' answer is source-linked and carries no mutation path", () => { + const q = day.readOnlyQuestions[0] + expect(q?.question).toBe("Did she nap?") + expect(q?.askedBy).toBe("marco") + expect(q?.sources.length).toBeGreaterThanOrEqual(2) + expect(q?.sources.some((s) => s.kind === "fixture" && s.ref.startsWith("coverage:"))).toBe(true) + expect(q?.answer).toContain("No nap recorded today") + }) +}) + +describe("missing-data semantics (product-owner ruling: absence of record ≠ confirmed absence)", () => { + // The ruling: missing data reads "No nap recorded" — it may never imply a + // confirmed absence, and no behavioral prediction may be shown without a + // supported source event. Negative control: fails if any prediction-capable + // surface (brief headlines/details, plan note, Q&A answer) starts + // forecasting behavior from missing data again. + test("no behavioral prediction appears in the brief, plan, or answers without a supported source event", () => { + const fact4 = day.takeover.fiveFacts[3] + const plan = day.takeover.plan + const answer = day.readOnlyQuestions[0]?.answer ?? "" + const surfaces = [fact4?.headline, fact4?.detail, plan?.note, answer].filter( + (s): s is string => s !== undefined, + ) + + for (const text of surfaces) { + expect(text).not.toMatch(/no nap today/i) // confirmed-absence phrasing is banned + expect(text).not.toMatch(/meltdown/i) // forecast vocabulary is banned on missing data + expect(text).not.toMatch(/expect an early/i) + expect(text).not.toMatch(/consider an early/i) + } + expect(fact4?.headline).toBe("No nap recorded") + expect(plan?.note).toContain("no behavioral prediction is offered without a supported source") + expect(answer).toContain("No nap recorded today") + + // Sweep the WHOLE fixture: every "meltdown" mention must sit in the + // drop-off event's own context (its parents-only restriction note) — a + // recorded event, never a prediction about missing data: + const meltdownPaths: Array = [] + const walk = (node: unknown, path: string): void => { + if (typeof node === "string") { + if (node.toLowerCase().includes("meltdown")) meltdownPaths.push(path) + return + } + if (Array.isArray(node)) return node.forEach((v, i) => walk(v, `${path}[${i}]`)) + if (typeof node === "object" && node !== null) { + for (const [k, v] of Object.entries(node)) walk(v, path === "" ? k : `${path}.${k}`) + } + } + walk(dayJson, "") + expect(meltdownPaths.length).toBeGreaterThan(0) + for (const path of meltdownPaths) { + expect(path.startsWith("audienceRestrictions")).toBe(true) + } + expect( + day.audienceRestrictions.some( + (r) => r.eventId === "ev-school-1" && r.note?.toLowerCase().includes("meltdown"), + ), + ).toBe(true) + + // The plan's basis is non-empty and every id resolves to a real source event: + expect((plan?.basis ?? []).length).toBeGreaterThan(0) + for (const id of plan?.basis ?? []) { + expect(eventById(id)).toBeDefined() + } + }) +}) diff --git a/spikes/home-c-handoff/tsconfig.json b/spikes/home-c-handoff/tsconfig.json new file mode 100644 index 0000000..9ebe510 --- /dev/null +++ b/spikes/home-c-handoff/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "jsx": "react-jsx", + "resolveJsonModule": true, + "types": ["node", "bun"] + }, + "include": ["src", "test", "scripts"] +}