From 9e7ce7325e17e8082bb897b3318a50168b7e3502 Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 19:48:58 +0000 Subject: [PATCH 1/2] =?UTF-8?q?feat(catch-up):=20since-last-seen=20caregiv?= =?UTF-8?q?er=20catch-up=20=E2=80=94=20contract=20delta=20v0.1=20+=20deter?= =?UTF-8?q?ministic=20acceptance=20cases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the catch-up slice per the published design (art_6qhBut41): - packages/domain: additive Effect v4 contracts (CaregiverReadStateFields, CatchUpQueryInput/Source/Item, CoverageDay, CatchUpReport, AdvanceReadStateInput, EventRevision proposal) + deterministic computeCatchUp reducer (fail-closed grants, horizon clip, strict-after watermark, late/corrected projection, coverage days, gap disclosure, confirmation counts) + monotonic advanceReadState + utcDayKey. - backend/convex: additive caregiverReadState table with by_caregiver_child index, getCatchUp query and advanceReadState mutation (fail-closed allowlist placeholder pending membership slot 19; corrected path TODO pending eventRevisions slot 10). Regenerated _generated/api.d.ts. - apps/mobile: presentational CatchUpView prototype (typecheck-verified only, not device-verified); links @journal/domain (lockfile importers entry only — no new npm dependencies). - evaluation/fixtures/agent-experience/catchup: synthetic two-household fixtures + AC-01..AC-14 cases (no real names/ids/medical content). Co-authored-by: Gilbert Polanco --- apps/mobile/package.json | 1 + apps/mobile/src/catchup/CatchUpView.tsx | 125 +++++ backend/convex/convex/_generated/api.d.ts | 2 + backend/convex/convex/catchup.ts | 184 +++++++ backend/convex/convex/schema.ts | 15 +- .../agent-experience/catchup/cases.json | 235 ++++++++ .../agent-experience/catchup/grants.json | 8 + .../agent-experience/catchup/history.json | 291 ++++++++++ packages/domain/src/catchup.ts | 379 +++++++++++++ packages/domain/src/index.ts | 28 + packages/domain/test/catchup.test.ts | 517 ++++++++++++++++++ pnpm-lock.yaml | 3 + 12 files changed, 1787 insertions(+), 1 deletion(-) create mode 100644 apps/mobile/src/catchup/CatchUpView.tsx create mode 100644 backend/convex/convex/catchup.ts create mode 100644 evaluation/fixtures/agent-experience/catchup/cases.json create mode 100644 evaluation/fixtures/agent-experience/catchup/grants.json create mode 100644 evaluation/fixtures/agent-experience/catchup/history.json create mode 100644 packages/domain/src/catchup.ts create mode 100644 packages/domain/test/catchup.test.ts diff --git a/apps/mobile/package.json b/apps/mobile/package.json index cc6f060..61c379f 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -10,6 +10,7 @@ "ios": "expo start --ios" }, "dependencies": { + "@journal/domain": "workspace:*", "@journal/month-history": "workspace:*", "@journal/ui": "workspace:*", "convex": "^1.46.0", diff --git a/apps/mobile/src/catchup/CatchUpView.tsx b/apps/mobile/src/catchup/CatchUpView.tsx new file mode 100644 index 0000000..ac10a73 --- /dev/null +++ b/apps/mobile/src/catchup/CatchUpView.tsx @@ -0,0 +1,125 @@ +/** + * PROTOTYPE — typecheck-verified only, NOT device-verified. + * + * Since-last-seen catch-up view (contract delta v0.1, art_6qhBut41). + * Presentational: renders a validated domain `CatchUpReport`. The caller owns + * fetching (`getCatchUp`) and watermark advance (`advanceReadState`); this + * component holds no data access, no navigation, no provider wiring, and no + * new dependencies. Disclosure discipline mirrors the domain contract: gaps + * are phrased only as missing recordings — never as "nothing happened" — the + * transcript is shown verbatim (excerpted, never paraphrased), and events + * with confidence below 1 are always marked inferred. + */ +import { ScrollView, StyleSheet, View } from "react-native" + +import { gapDisclosure, type CatchUpItem, type CatchUpReport } from "@journal/domain" +import { Text } from "@journal/ui" + +const TRANSCRIPT_EXCERPT_MAX = 140 + +const isoDay = (epochMs: number): string => new Date(epochMs).toISOString().slice(0, 10) + +const excerptOf = (transcript: string): string => + transcript.length <= TRANSCRIPT_EXCERPT_MAX + ? transcript + : `${transcript.slice(0, TRANSCRIPT_EXCERPT_MAX)}…` + +/** Kind badge; late items name both ends of the delay (happened vs recorded). */ +const kindBadgeText = (item: CatchUpItem): string => { + if (item.kind === "late" && item.daysLate !== undefined) { + return `late: happened ${isoDay(item.occurredAt ?? item.entryCreatedAt)}, recorded ${isoDay(item.entryCreatedAt)}` + } + return item.kind +} + +/** One canonical event line; confidence below 1 is always disclosed. */ +const eventLine = (category: string, payload: Record | undefined, confidence: number): string => { + const values = + payload === undefined + ? "" + : Object.entries(payload) + .map(([key, value]) => `${key}: ${value}`) + .join(", ") + const summary = values.length > 0 ? `${category} (${values})` : category + return confidence < 1 ? `${summary} — inferred` : summary +} + +/** Typecheck-only usage example: proves the props contract, routes nothing. */ +export function CatchUpViewUsageExample({ report }: { report: CatchUpReport }) { + return +} + +export function CatchUpView({ report }: { report: CatchUpReport }) { + const disclosure = gapDisclosure(report.coverageDays) + const confirmed = report.confirmation.confirmedEvents + const total = confirmed + report.confirmation.inferredEvents + const newItems = report.items.filter((item) => item.kind !== "corrected") + const correctedItems = report.items.filter((item) => item.kind === "corrected") + + return ( + + + + Catch-up {isoDay(report.windowStart)} – {isoDay(report.windowEnd)} + + + {report.allCaughtUp ? "You're all caught up." : "Here's what was recorded while you were away."} + + + + {newItems.length > 0 && ( + + New while you were away + {newItems.map((item) => ( + + {kindBadgeText(item)} + Recorded by {item.source.authorId} + "{excerptOf(item.source.rawTranscript)}" + {item.events.map((event, index) => ( + {`${eventLine(event.category, event.payload, event.confidence)} · ${isoDay(event.timestamp)}`} + ))} + + ))} + + )} + + {correctedItems.length > 0 && ( + + Corrected + {correctedItems.map((item) => ( + + {/* The report carries the revised (canonical) value and the + original's citation — never an invented original value. */} + {item.events.map((event, index) => ( + {`Corrected: ${eventLine(event.category, event.payload, event.confidence)} · ${isoDay(event.timestamp)}`} + ))} + + {`Revised by ${item.correctedBy ?? "unknown"} · original event ${item.originalEventId ?? "unknown"}${item.revisionIds.length > 0 ? ` · ${item.revisionIds.length} revision(s)` : ""}`} + + "{excerptOf(item.source.rawTranscript)}" + + ))} + + )} + + + {disclosure.length > 0 && {disclosure}} + {`${confirmed} of ${total} events caregiver-confirmed`} + + + ) +} + +const styles = StyleSheet.create({ + container: { flex: 1 }, + header: { padding: 16, gap: 4 }, + section: { padding: 16, paddingTop: 0, gap: 8 }, + sectionTitle: { fontSize: 18, fontWeight: "600" }, + card: { padding: 12, borderWidth: StyleSheet.hairlineWidth, borderRadius: 8, gap: 4 }, + badge: { fontWeight: "600" }, + footer: { padding: 16, gap: 4 }, +}) diff --git a/backend/convex/convex/_generated/api.d.ts b/backend/convex/convex/_generated/api.d.ts index 8d94d4a..f31ccfb 100644 --- a/backend/convex/convex/_generated/api.d.ts +++ b/backend/convex/convex/_generated/api.d.ts @@ -8,6 +8,7 @@ * @module */ +import type * as catchup from "../catchup.js"; import type * as children from "../children.js"; import type * as entries from "../entries.js"; import type * as households from "../households.js"; @@ -23,6 +24,7 @@ import type { } from "convex/server"; declare const fullApi: ApiFromModules<{ + catchup: typeof catchup; children: typeof children; entries: typeof entries; households: typeof households; diff --git a/backend/convex/convex/catchup.ts b/backend/convex/convex/catchup.ts new file mode 100644 index 0000000..14c692c --- /dev/null +++ b/backend/convex/convex/catchup.ts @@ -0,0 +1,184 @@ +import { Schema } from "effect" + +import { + AdvanceReadStateInput, + CatchUpQueryInput, + CatchUpReport, + EntryDocument, + EventDocument, + computeCatchUp, +} from "@journal/domain" +import { convexFields } from "@journal/domain/convex" + +import { mutation, query } from "./_generated/server" +import { ConvexError } from "convex/values" + +import { errorText, stripUndefined } from "./lib" + +/** + * Since-last-seen caregiver catch-up (contract delta v0.1, art_6qhBut41). + * + * `getCatchUp` derives the report from the flat model through the + * deterministic domain reducer; `advanceReadState` upserts the monotonic + * per-(caregiver, child) watermark. `now` is part of the decoded contract + * input (the reducer stays pure — no wall clock inside domain code). + * + * Corrected path NOT wired: `eventRevisions` has no table on master — the + * v0.3 fold (slot 10) owns revision persistence and will pass revisions into + * the reducer here. Until then the corrected path stays silent on the + * backend; the reducer's corrected logic is exercised by the domain tests. + */ + +// PLACEHOLDER grants pending slot 19 (household members/grants): the flat +// model has no membership table, so the grant is a named allowlist and the +// default is DENY. Replace with the real membership check the moment slot 19 +// lands — this list must never graduate to a config surface. +const knownReaders: ReadonlyArray = ["reader_mom", "reader_dad"] + +const grantsFor = { + canRead: (readerId: string, _householdId: string): boolean => knownReaders.includes(readerId), +} + +/** + * Catch-up report for one (reader, child) pair. Rows are read per-child via + * the canonical indexes; events are joined through each entry's + * structuredEventIds (entries carry no event payloads). Authorization fails + * closed: an unlisted reader is an error, never a partial report. + */ +export const getCatchUp = query({ + args: convexFields(CatchUpQueryInput), + handler: async (ctx, rawArgs): Promise => { + let args: typeof CatchUpQueryInput["Type"] + try { + args = Schema.decodeUnknownSync(CatchUpQueryInput)(stripUndefined(rawArgs)) + } catch (err) { + throw new ConvexError({ code: "INVALID_CATCHUP_INPUT", message: errorText(err) }) + } + + // Fail-closed referential check (same shape as entries.createEntry). + const childId = ctx.db.normalizeId("children", args.childId) + if (childId === null) { + throw new ConvexError({ + code: "CHILD_NOT_FOUND", + message: `child ${args.childId} does not exist`, + }) + } + const child = await ctx.db.get(childId) + if (child === null) { + throw new ConvexError({ + code: "CHILD_NOT_FOUND", + message: `child ${args.childId} does not exist`, + }) + } + + // Watermark: absent row = first-time reader (the reducer treats it as 0). + const readState = await ctx.db + .query("caregiverReadState") + .withIndex("by_caregiver_child", (q) => + q.eq("caregiverId", args.readerId).eq("childId", args.childId), + ) + .first() + + const [entryRows, eventRows] = await Promise.all([ + ctx.db + .query("entries") + .withIndex("by_child", (q) => q.eq("childId", args.childId)) + .collect(), + ctx.db + .query("events") + .withIndex("by_child", (q) => q.eq("childId", args.childId)) + .collect(), + ]) + + // Rows decode through the *_Document contracts (system fields included — + // the reducer cites entry._id and event._id). + const decodeEntry = Schema.decodeUnknownSync(EntryDocument) + const decodeEvent = Schema.decodeUnknownSync(EventDocument) + // Domain ids are plain strings (convexId is an annotated Schema.String); + // the generated doc type brands them. Key the join by the plain-string view. + const eventsById = new Map(eventRows.map((event) => [event._id as string, event])) + + const catchUpEntries = entryRows.map((row) => { + const entry = decodeEntry(row) + return { + entry, + events: entry.structuredEventIds.flatMap((eventId) => { + const found = eventsById.get(eventId) + if (found === undefined) return [] + return [decodeEvent(found)] + }), + } + }) + + // TODO(v0.3 fold / slot 10): load eventRevisions for this child and pass + // them through so in-window corrections surface from the backend. + const result = computeCatchUp( + args, + { + householdId: child.householdId, + readerLastSeenAt: readState?.lastSeenAt, + entries: catchUpEntries, + revisions: [], + }, + grantsFor, + ) + + if ("_tag" in result) { + throw new ConvexError({ + code: result._tag === "UnauthorizedReader" ? "UNAUTHORIZED_READER" : "HORIZON_EXCEEDED", + message: + result._tag === "UnauthorizedReader" + ? `reader ${args.readerId} is not authorized for this child's household` + : "horizonDays exceeds the 30-day maximum", + }) + } + return result + }, +}) + +/** + * Monotonic watermark advance: max(existing, at) — a stale client or a replay + * can never move the reader backwards. Upsert keyed on by_caregiver_child; + * the first write creates the row (undefined -> at). + */ +export const advanceReadState = mutation({ + args: convexFields(AdvanceReadStateInput), + handler: async (ctx, rawArgs): Promise<{ lastSeenAt: number }> => { + let args: typeof AdvanceReadStateInput["Type"] + try { + args = Schema.decodeUnknownSync(AdvanceReadStateInput)(stripUndefined(rawArgs)) + } catch (err) { + throw new ConvexError({ code: "INVALID_ADVANCE_INPUT", message: errorText(err) }) + } + + const childId = ctx.db.normalizeId("children", args.childId) + if (childId === null) { + throw new ConvexError({ + code: "CHILD_NOT_FOUND", + message: `child ${args.childId} does not exist`, + }) + } + + const existing = await ctx.db + .query("caregiverReadState") + .withIndex("by_caregiver_child", (q) => + q.eq("caregiverId", args.caregiverId).eq("childId", args.childId), + ) + .first() + + if (existing === null) { + await ctx.db.insert("caregiverReadState", { + caregiverId: args.caregiverId, + childId: args.childId, + lastSeenAt: args.at, + }) + return { lastSeenAt: args.at } + } + // Same-value advance is a no-op (idempotent by construction). + if (args.at > existing.lastSeenAt) { + await ctx.db.patch(existing._id, { lastSeenAt: args.at }) + return { lastSeenAt: args.at } + } + return { lastSeenAt: existing.lastSeenAt } + }, +}) diff --git a/backend/convex/convex/schema.ts b/backend/convex/convex/schema.ts index 6061291..51d2f3a 100644 --- a/backend/convex/convex/schema.ts +++ b/backend/convex/convex/schema.ts @@ -1,7 +1,14 @@ import { defineSchema, defineTable } from "convex/server" import { Schema } from "effect" -import { ChildFields, EntryFields, EventFields, HouseholdFields, KnowledgeFields } from "@journal/domain" +import { + CaregiverReadStateFields, + ChildFields, + EntryFields, + EventFields, + HouseholdFields, + KnowledgeFields, +} from "@journal/domain" import { convexFields } from "@journal/domain/convex" /** @@ -31,4 +38,10 @@ export default defineSchema({ .index("by_household", ["householdId"]) .index("by_child_topic", ["childId", "topic"]) .index("by_supersedes", ["supersedes"]), + // Since-last-seen read state (catch-up contract delta v0.1, art_6qhBut41): + // one monotonic watermark row per (caregiver, child). Additive only. + caregiverReadState: tableFrom(CaregiverReadStateFields).index("by_caregiver_child", [ + "caregiverId", + "childId", + ]), }) diff --git a/evaluation/fixtures/agent-experience/catchup/cases.json b/evaluation/fixtures/agent-experience/catchup/cases.json new file mode 100644 index 0000000..f26f16a --- /dev/null +++ b/evaluation/fixtures/agent-experience/catchup/cases.json @@ -0,0 +1,235 @@ +{ + "cases": [ + { + "caseId": "AC-01", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": null, + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "windowStartIso": "2026-09-01T12:00:00Z", + "horizonClipped": true, + "allCaughtUp": false, + "kinds": ["new", "new", "new", "new", "late", "new"], + "expectedItemEntryIds": [ + "entries_test_2", + "entries_test_4", + "entries_test_3", + "entries_test_5", + "entries_test_6", + "entries_test_7" + ], + "counts": { "gapDays": 9, "confirmedEvents": 2, "inferredEvents": 3 }, + "notes": "First-time reader, 20d history, horizon 14: windowStart = now-14d, horizonClipped, every item new/late, every source.rawTranscript verbatim non-empty, coverage + confirmation present." + } + }, + { + "caseId": "AC-02", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-05T00:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": ["new", "late", "new", "corrected"], + "expectedItemEntryIds": [ + "entries_test_5", + "entries_test_6", + "entries_test_7", + "entries_test_2" + ], + "boundaryExcludedEntryId": "entries_test_3", + "notes": "Strictly-after rule for new items: entry at exactly W (entries_test_3) and before W (entries_test_2, entries_test_4) are not new items; entries after W are. entries_test_2 appears only as a CORRECTED item (its revision landed after W) — never as new." + } + }, + { + "caseId": "AC-03", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-01T00:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": ["new", "new", "new", "new", "late", "new"], + "lateSpec": { + "entryId": "entries_test_6", + "daysLate": 2, + "occurredAtIso": "2026-09-08T19:30:00Z", + "recordedAtIso": "2026-09-10T16:00:00Z" + }, + "notes": "Entry captured Sep 10 with event timestamped Sep 8: kind late, daysLate 2, occurredAt = the Sep 8 event timestamp." + } + }, + { + "caseId": "AC-04", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-05T00:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "correctedSpec": { + "entryId": "entries_test_2", + "originalEventId": "events_test_2", + "revisionIds": ["revisions_test_1"], + "correctedBy": "reader_dad", + "revisedPayload": { "portions": 3 }, + "revisedConfidence": 0.95 + }, + "notes": "Event E existed at W, revision R (Sep 8) lands after W: corrected item on the ORIGINAL entry, revisionIds [R], correctedBy R.actorId, events show revised values, source keeps the original entry + verbatim transcript." + } + }, + { + "caseId": "AC-05", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-12T00:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": ["new"], + "expectedItemEntryIds": ["entries_test_7"], + "correctedItemCount": 0, + "absentFromOutput": ["revisions_test_1", "entries_test_2", "events_test_2"], + "notes": "Same correction but R (Sep 8) landed before W (Sep 12): NO corrected item — already seen." + } + }, + { + "caseId": "AC-06", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-01T00:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": ["new", "new", "new", "new", "late", "new"], + "draftEntryIds": ["entries_test_8", "entries_test_9"], + "notes": "Drafts sit inside the window: zero draft items anywhere in the report." + } + }, + { + "caseId": "AC-07", + "readerId": "reader_stranger", + "childId": "child_alpha", + "watermarkIso": null, + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "errorTag": "UnauthorizedReader", + "notes": "Reader has no grant on the child's household; hh_beta data is present in history. Result is { _tag: 'UnauthorizedReader' } and NOTHING else." + } + }, + { + "caseId": "AC-08", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": null, + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": ["new", "new", "new", "new", "late", "new"], + "absentFromOutput": ["entries_test_11", "events_test_11", "child_beta", "hh_beta"], + "notes": "Authorized reader with a cross-household entry present in history: every source.entryId belongs to a reader-visible entry; the cross-household entry appears nowhere." + } + }, + { + "caseId": "AC-09", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-04T00:00:00Z", + "nowIso": "2026-09-08T00:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": ["new", "new"], + "expectedItemEntryIds": ["entries_test_3", "entries_test_5"], + "gapDayCount": 3, + "gapDayKeys": ["2026-09-04", "2026-09-07", "2026-09-08"], + "coverageDayCount": 5, + "disclosure": "No entries recorded for 2026-09-04, 2026-09-07, 2026-09-08", + "notes": "Window with zero-entry days: gapDays correct, coverageDays lists them, disclosure string is exactly 'No entries recorded for ' + the day list." + } + }, + { + "caseId": "AC-10", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": null, + "nowIso": "2026-11-02T12:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": ["new", "new"], + "expectedItemEntryIds": ["entries_test_12", "entries_test_13"], + "dayKeyPolicy": "america-new-york-fallback", + "singleBucketDay": "2026-11-01", + "singleBucketCount": 2, + "coverageDayCount": 15, + "notes": "DST fall-back day key (offset -240 before 2026-11-01T06:00:00Z, then -300): the 05:00Z and 06:00Z entries both bucket to local day 2026-11-01; exactly one bucket for that day; no 23/25h skew." + } + }, + { + "caseId": "AC-11", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-15T12:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "kinds": [], + "expectedItemEntryIds": [], + "allCaughtUp": true, + "coverageDayCount": 1, + "notes": "No items after W: items [], allCaughtUp true, coverageDays still non-empty." + } + }, + { + "caseId": "AC-12", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": null, + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "advanceSpec": { + "t1Iso": "2026-09-10T00:00:00Z", + "t2Iso": "2026-09-12T00:00:00Z" + }, + "notes": "advanceReadState(undefined, t2) = t2; advance(t2, t1) with t1 < t2 stays t2; advancing twice with the same at is a no-op." + } + }, + { + "caseId": "AC-13", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-08-25T00:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "windowStartIso": "2026-09-01T12:00:00Z", + "horizonClipped": true, + "kinds": ["new", "new", "new", "new", "late", "new"], + "expectedItemEntryIds": [ + "entries_test_2", + "entries_test_4", + "entries_test_3", + "entries_test_5", + "entries_test_6", + "entries_test_7" + ], + "absentFromOutput": ["revisions_test_2", "entries_test_10"], + "notes": "Watermark older than horizon: windowStart = now - horizon (not the watermark), horizonClipped true, corrections to pre-window events (revisions_test_2 on the Aug 20 entry) do not surface. The Aug 26 entry (after the watermark but pre-windowStart) is clipped too." + } + }, + { + "caseId": "AC-14", + "readerId": "reader_mom", + "childId": "child_alpha", + "watermarkIso": "2026-09-05T00:00:00Z", + "nowIso": "2026-09-15T12:00:00Z", + "horizonDays": 14, + "expected": { + "notes": "Report -> encodeSync(CatchUpReport) -> decodeUnknownSync -> deep-equal the original (lossless). Runs on the AC-04-shaped report (corrected + late + eventless + photo) so every optional field round-trips." + } + } + ] +} diff --git a/evaluation/fixtures/agent-experience/catchup/grants.json b/evaluation/fixtures/agent-experience/catchup/grants.json new file mode 100644 index 0000000..ce970c7 --- /dev/null +++ b/evaluation/fixtures/agent-experience/catchup/grants.json @@ -0,0 +1,8 @@ +{ + "memberships": { + "reader_mom": ["hh_alpha"], + "reader_dad": ["hh_alpha"], + "reader_sitter": ["hh_alpha"], + "reader_stranger": ["hh_beta"] + } +} diff --git a/evaluation/fixtures/agent-experience/catchup/history.json b/evaluation/fixtures/agent-experience/catchup/history.json new file mode 100644 index 0000000..4a9b7ce --- /dev/null +++ b/evaluation/fixtures/agent-experience/catchup/history.json @@ -0,0 +1,291 @@ +{ + "households": [ + { "_id": "hh_alpha", "name": "Synthetic household alpha", "createdAt": "2026-08-01T00:00:00Z", "_creationTime": "2026-08-01T00:00:00Z" }, + { "_id": "hh_beta", "name": "Synthetic household beta", "createdAt": "2026-08-01T00:00:00Z", "_creationTime": "2026-08-01T00:00:00Z" } + ], + "children": [ + { "_id": "child_alpha", "householdId": "hh_alpha", "name": "Synthetic child A", "createdAt": "2026-08-01T00:00:00Z", "_creationTime": "2026-08-01T00:00:00Z" }, + { "_id": "child_beta", "householdId": "hh_beta", "name": "Synthetic child B", "createdAt": "2026-08-01T00:00:00Z", "_creationTime": "2026-08-01T00:00:00Z" } + ], + "entries": [ + { + "_id": "entries_test_1", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: morning nap, logged late.", + "structuredEventIds": ["events_test_1"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-08-26T15:00:00Z", + "_creationTime": "2026-08-26T15:00:00Z" + }, + { + "_id": "entries_test_2", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_dad", + "rawTranscript": "Synthetic: solid lunch, ate well.", + "structuredEventIds": ["events_test_2"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-09-02T09:00:00Z", + "_creationTime": "2026-09-02T09:00:00Z" + }, + { + "_id": "entries_test_3", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: quick note, no events extracted.", + "structuredEventIds": [], + "extractionStatus": "pending", + "visibility": "published", + "createdAt": "2026-09-05T00:00:00Z", + "_creationTime": "2026-09-05T00:00:00Z" + }, + { + "_id": "entries_test_4", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_dad", + "rawTranscript": "Synthetic: cheerful after the park.", + "structuredEventIds": ["events_test_4"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-09-03T10:00:00Z", + "_creationTime": "2026-09-03T10:00:00Z" + }, + { + "_id": "entries_test_5", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: first independent steps in the park.", + "structuredEventIds": ["events_test_5"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-09-06T08:00:00Z", + "_creationTime": "2026-09-06T08:00:00Z" + }, + { + "_id": "entries_test_6", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: bedtime story and lights out.", + "structuredEventIds": ["events_test_6"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-09-10T16:00:00Z", + "_creationTime": "2026-09-10T16:00:00Z" + }, + { + "_id": "entries_test_7", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_sitter", + "rawTranscript": "Synthetic: midday bottle, finished most of it.", + "structuredEventIds": ["events_test_7"], + "extractionStatus": "structured", + "visibility": "published", + "photoId": "photos_test_1", + "createdAt": "2026-09-12T09:30:00Z", + "_creationTime": "2026-09-12T09:30:00Z" + }, + { + "_id": "entries_test_8", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_dad", + "rawTranscript": "Synthetic: private draft, not published.", + "structuredEventIds": [], + "extractionStatus": "pending", + "visibility": "draft", + "createdAt": "2026-09-07T11:00:00Z", + "_creationTime": "2026-09-07T11:00:00Z" + }, + { + "_id": "entries_test_9", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: second draft, not published.", + "structuredEventIds": [], + "extractionStatus": "pending", + "visibility": "draft", + "createdAt": "2026-09-13T14:00:00Z", + "_creationTime": "2026-09-13T14:00:00Z" + }, + { + "_id": "entries_test_10", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: splashing at the pool.", + "structuredEventIds": ["events_test_10"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-08-20T12:00:00Z", + "_creationTime": "2026-08-20T12:00:00Z" + }, + { + "_id": "entries_test_11", + "householdId": "hh_beta", + "childId": "child_beta", + "authorId": "reader_stranger", + "rawTranscript": "Synthetic: cross-household entry that must never leak.", + "structuredEventIds": ["events_test_11"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-09-08T10:00:00Z", + "_creationTime": "2026-09-08T10:00:00Z" + }, + { + "_id": "entries_test_12", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: daylight-saving probe, first bucket.", + "structuredEventIds": ["events_test_12"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-11-01T05:00:00Z", + "_creationTime": "2026-11-01T05:00:00Z" + }, + { + "_id": "entries_test_13", + "householdId": "hh_alpha", + "childId": "child_alpha", + "authorId": "reader_mom", + "rawTranscript": "Synthetic: daylight-saving probe, second bucket.", + "structuredEventIds": ["events_test_13"], + "extractionStatus": "structured", + "visibility": "published", + "createdAt": "2026-11-01T06:00:00Z", + "_creationTime": "2026-11-01T06:00:00Z" + } + ], + "events": [ + { + "_id": "events_test_1", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "sleep", + "timestamp": "2026-08-26T14:00:00Z", + "payload": { "minutes": 45 }, + "confidence": 1.0, + "_creationTime": "2026-08-26T15:00:00Z" + }, + { + "_id": "events_test_2", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "meal", + "timestamp": "2026-09-02T12:30:00Z", + "payload": { "portions": 3 }, + "confidence": 0.95, + "_creationTime": "2026-09-02T09:00:00Z" + }, + { + "_id": "events_test_4", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "mood", + "timestamp": "2026-09-03T15:00:00Z", + "confidence": 0.8, + "_creationTime": "2026-09-03T10:00:00Z" + }, + { + "_id": "events_test_5", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "milestone", + "timestamp": "2026-09-06T08:00:00Z", + "confidence": 1.0, + "_creationTime": "2026-09-06T08:00:00Z" + }, + { + "_id": "events_test_6", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "sleep", + "timestamp": "2026-09-08T19:30:00Z", + "payload": { "minutes": 40 }, + "confidence": 0.9, + "_creationTime": "2026-09-10T16:00:00Z" + }, + { + "_id": "events_test_7", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "meal", + "timestamp": "2026-09-12T09:15:00Z", + "confidence": 1.0, + "_creationTime": "2026-09-12T09:30:00Z" + }, + { + "_id": "events_test_10", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "mood", + "timestamp": "2026-08-20T11:00:00Z", + "confidence": 1.0, + "_creationTime": "2026-08-20T12:00:00Z" + }, + { + "_id": "events_test_11", + "householdId": "hh_beta", + "childId": "child_beta", + "category": "meal", + "timestamp": "2026-09-08T09:00:00Z", + "confidence": 1.0, + "_creationTime": "2026-09-08T10:00:00Z" + }, + { + "_id": "events_test_12", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "sleep", + "timestamp": "2026-11-01T05:00:00Z", + "confidence": 1.0, + "_creationTime": "2026-11-01T05:00:00Z" + }, + { + "_id": "events_test_13", + "householdId": "hh_alpha", + "childId": "child_alpha", + "category": "sleep", + "timestamp": "2026-11-01T06:00:00Z", + "confidence": 1.0, + "_creationTime": "2026-11-01T06:00:00Z" + } + ], + "revisions": [ + { + "id": "revisions_test_1", + "householdId": "hh_alpha", + "childId": "child_alpha", + "supersedesEventId": "events_test_2", + "category": "meal", + "timestamp": "2026-09-02T12:30:00Z", + "payload": { "portions": 3 }, + "confidence": 0.95, + "actorId": "reader_dad", + "note": "Synthetic correction: three portions, not two.", + "createdAt": "2026-09-08T10:00:00Z" + }, + { + "id": "revisions_test_2", + "householdId": "hh_alpha", + "childId": "child_alpha", + "supersedesEventId": "events_test_10", + "category": "mood", + "timestamp": "2026-08-20T11:00:00Z", + "confidence": 0.85, + "actorId": "reader_mom", + "note": "Synthetic correction landing in the clipped region.", + "createdAt": "2026-08-28T00:00:00Z" + } + ] +} diff --git a/packages/domain/src/catchup.ts b/packages/domain/src/catchup.ts new file mode 100644 index 0000000..b5fee27 --- /dev/null +++ b/packages/domain/src/catchup.ts @@ -0,0 +1,379 @@ +import { Schema } from "effect" + +import { EventCategory, EventFields } from "./event.js" +import { convexId } from "./ids.js" +import type { EntryDocument } from "./entry.js" +import type { Event, EventDocument } from "./event.js" + +/** + * Since-last-seen caregiver catch-up — contract delta v0.1 (additive). + * + * Design, rationale, and acceptance cases: art_6qhBut41 ("Since-Last-Seen + * Catch-Up — Design, Contract Delta v0.1, Acceptance Cases v1"). This file + * implements the published delta; no existing schema file changes. + * + * Conventions (merged codebase): unix-ms numbers on the wire, convexId(table) + * annotations for the Convex adapter, Schema.optionalKey for absent-key + * optionals, types inferred via Schema.Schema.Type. Domain code never imports + * Convex validators and never reads the wall clock — `now` is injected. + */ + +// --- reader read state (watermark) ----------------------------------------- + +export const CaregiverReadStateFields = { + caregiverId: Schema.NonEmptyString, // external identity (flat model — no members table until slot 19) + childId: convexId("children"), + lastSeenAt: Schema.Number, // unix ms; monotonic, never decreases +} satisfies Schema.Struct.Fields + +// --- query ------------------------------------------------------------------ + +export const CatchUpQueryInput = Schema.Struct({ + childId: convexId("children"), + readerId: Schema.NonEmptyString, + now: Schema.Number, // injected clock — no Date.now() inside the reducer + horizonDays: Schema.optionalKey(Schema.Int), // default 14, max 30 +}) +export type CatchUpQueryInput = typeof CatchUpQueryInput["Type"] + +// --- report ----------------------------------------------------------------- + +export type CatchUpItemKind = "new" | "late" | "corrected" + +export const CatchUpSource = Schema.Struct({ + entryId: convexId("entries"), + rawTranscript: Schema.NonEmptyString, // verbatim, preserved + photoId: Schema.optionalKey(Schema.String), + eventIds: Schema.Array(convexId("events")), + revisionIds: Schema.Array(convexId("eventRevisions")), // empty except kind "corrected" + authorId: Schema.String, +}) +export type CatchUpSource = typeof CatchUpSource["Type"] + +export const CatchUpItem = Schema.Struct({ + kind: Schema.Literals(["new", "late", "corrected"]), + entryId: convexId("entries"), + entryCreatedAt: Schema.Number, // = recordedAt on the wire + occurredAt: Schema.optionalKey(Schema.Number), // earliest event timestamp in the entry; absent for eventless entries + daysLate: Schema.optionalKey(Schema.Int), // present iff kind "late" (local-day difference) + originalEventId: Schema.optionalKey(convexId("events")), // present iff kind "corrected" + revisionIds: Schema.Array(convexId("eventRevisions")), + correctedBy: Schema.optionalKey(Schema.String), // actorId of the supersession + events: Schema.Array(Schema.Struct(EventFields)), // decoded canonical events as they stand now + source: CatchUpSource, +}) +export type CatchUpItem = typeof CatchUpItem["Type"] + +export const CoverageDay = Schema.Struct({ + day: Schema.String, // "YYYY-MM-DD" local-day key + publishedEntryCount: Schema.Number, +}) +export type CoverageDay = typeof CoverageDay["Type"] + +export const CatchUpReport = Schema.Struct({ + childId: convexId("children"), + readerId: Schema.NonEmptyString, + generatedAt: Schema.Number, + windowStart: Schema.Number, // max(watermark, now − horizon) + windowEnd: Schema.Number, // now + watermark: Schema.Number, // the lastSeenAt the report was computed from (0 for a first-time reader) + allCaughtUp: Schema.Boolean, + items: Schema.Array(CatchUpItem), + coverageDays: Schema.Array(CoverageDay), // every local day in window, zero-entry days included + gapDays: Schema.Number, // count of coverageDays with publishedEntryCount === 0 + horizonClipped: Schema.Boolean, + confirmation: Schema.Struct({ + confirmedEvents: Schema.Number, // confidence === 1 (caregiver-confirmed per contract v0.2) + inferredEvents: Schema.Number, // confidence < 1 (extractor guess) + }), +}) +export type CatchUpReport = typeof CatchUpReport["Type"] + +// --- watermark advance -------------------------------------------------------- + +export const AdvanceReadStateInput = Schema.Struct({ + caregiverId: Schema.NonEmptyString, + childId: convexId("children"), + at: Schema.Number, +}) +export type AdvanceReadStateInput = typeof AdvanceReadStateInput["Type"] + +// --- EventRevision (proposal, coordinated — not landed as a table here) ------ + +/** + * PROPOSAL for the v0.3-fold owner (slot 10) to reconcile — fixtures and the + * reducer consume this shape in this slice; there is NO eventRevisions table + * and no Convex persistence. Corrected-item persistence waits for that fold + * (see the TODO in backend/convex/convex/catchup.ts). + */ +export const EventRevisionFields = { + householdId: convexId("households"), + childId: convexId("children"), + supersedesEventId: convexId("events"), + category: EventCategory, + timestamp: Schema.Number, + payload: Schema.optionalKey(Schema.Record(Schema.String, Schema.Number)), + confidence: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 })), + actorId: Schema.String, // who corrected (attribution) + note: Schema.optionalKey(Schema.NonEmptyString), + createdAt: Schema.Number, +} satisfies Schema.Struct.Fields +export const EventRevisionStruct = Schema.Struct(EventRevisionFields) +export type EventRevision = typeof EventRevisionStruct["Type"] + +// --- deterministic reducer ------------------------------------------------------ + +const DEFAULT_HORIZON_DAYS = 14 +const MAX_HORIZON_DAYS = 30 +const DAY_MS = 24 * 60 * 60 * 1000 + +/** Local-day policy injected by the caller; the default is the UTC day key. */ +export type DayKeyOf = (epochMs: number) => string + +export const utcDayKey: DayKeyOf = (epochMs) => new Date(epochMs).toISOString().slice(0, 10) + +/** Calendar-day difference between two "YYYY-MM-DD" keys (offset-independent). */ +const dayKeyDiff = (from: string, to: string): number => + Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY_MS) + +const nextDayKey = (day: string): string => + new Date(Date.parse(`${day}T00:00:00Z`) + DAY_MS).toISOString().slice(0, 10) + +/** One entry plus the event documents linked to it (its structuredEventIds resolved). */ +export interface CatchUpEntry { + entry: EntryDocument + events: EventDocument[] +} + +/** + * Fixture/reducer-level revision record: the EventRevision proposal plus its + * table id (which only exists once the eventRevisions table lands at the fold). + */ +export type CatchUpRevision = EventRevision & { id: string } + +export interface CatchUpHistory { + /** The child's householdId — scope of the fail-closed grant check (history may span households defensively). */ + householdId: string + /** The reader's stored watermark for this child; undefined for a first-time reader (treated as 0). */ + readerLastSeenAt: number | undefined + entries: CatchUpEntry[] + /** Supersession proposals — no backend table in this slice (v0.3 fold / slot 10 owns it). */ + revisions: CatchUpRevision[] +} + +export interface CatchUpGrants { + canRead: (readerId: string, householdId: string) => boolean +} + +/** Fail-closed typed errors: no partial output rides on either tag. */ +export type CatchUpError = { _tag: "UnauthorizedReader" } | { _tag: "HorizonExceeded" } + +/** Canonical event value — system fields stripped to the EventFields contract. */ +const eventValueOf = (doc: EventDocument): Event => { + const { _id: _eventId, _creationTime: _eventCreationTime, ...value } = doc + return value +} + +/** The original entry's citations: verbatim transcript, events, photo, author. */ +const sourceOf = (entry: EntryDocument, events: EventDocument[], revisionIds: string[]): CatchUpSource => ({ + entryId: entry._id, + rawTranscript: entry.rawTranscript, + ...(entry.photoId !== undefined ? { photoId: entry.photoId } : {}), + eventIds: events.map((event) => event._id), + revisionIds, + authorId: entry.authorId, +}) + +/** New / late item: a published unseen entry with its events as they stand now. */ +const seenItemFor = (entry: EntryDocument, events: EventDocument[], dayKeyOf: DayKeyOf): CatchUpItem => { + const sorted = [...events].sort((a, b) => a.timestamp - b.timestamp) + const earliest = sorted[0] + const occurredAt = earliest?.timestamp + // Late: the earliest event's local day is before the capture day (AC-03). + const isLate = occurredAt !== undefined && dayKeyOf(occurredAt) < dayKeyOf(entry.createdAt) + return { + kind: isLate ? "late" : "new", + entryId: entry._id, + entryCreatedAt: entry.createdAt, + ...(occurredAt !== undefined ? { occurredAt } : {}), + ...(isLate && occurredAt !== undefined + ? { daysLate: dayKeyDiff(dayKeyOf(occurredAt), dayKeyOf(entry.createdAt)) } + : {}), + revisionIds: [], + events: sorted.map(eventValueOf), + source: sourceOf(entry, sorted, []), + } +} + +/** + * Corrected item: an in-window supersession of an event the reader already + * saw. `event` is the current canonical (post-revision) value as stored; the + * v0.3 fold (slot 10) owns applying revisions to stored events. + */ +const correctedItemFor = ( + entry: EntryDocument, + entryEvents: EventDocument[], + event: EventDocument, + revisions: CatchUpRevision[], +): CatchUpItem => { + const ordered = [...revisions].sort((a, b) => a.createdAt - b.createdAt) + const latest = ordered[ordered.length - 1] + if (latest === undefined) throw new Error("corrected item requires at least one revision") + return { + kind: "corrected", + entryId: entry._id, + entryCreatedAt: entry.createdAt, + occurredAt: event.timestamp, + originalEventId: event._id, + revisionIds: ordered.map((revision) => revision.id), + correctedBy: latest.actorId, + events: [eventValueOf(event)], + source: sourceOf(entry, entryEvents, ordered.map((revision) => revision.id)), + } +} + +/** + * Deterministic catch-up reducer. Pure: no clock, no randomness, no I/O. + * Item order: new/late by entryCreatedAt ascending, then corrected items by + * entryCreatedAt ascending — a pure function of the input sets. + */ +export function computeCatchUp( + input: CatchUpQueryInput, + history: CatchUpHistory, + grants: CatchUpGrants, + dayKeyOf: DayKeyOf = utcDayKey, +): CatchUpReport | CatchUpError { + // Fail closed FIRST: a reader without grants gets nothing at all — no items, + // no coverage, no shape that could leak household activity (AC-07, A8). + if (!grants.canRead(input.readerId, history.householdId)) { + return { _tag: "UnauthorizedReader" } + } + + const horizonDays = input.horizonDays ?? DEFAULT_HORIZON_DAYS + if (horizonDays > MAX_HORIZON_DAYS) { + return { _tag: "HorizonExceeded" } + } + + const now = input.now + const horizonStart = now - horizonDays * DAY_MS + const watermark = history.readerLastSeenAt ?? 0 + const windowStart = Math.max(watermark, horizonStart) + + // This child's rows only — cross-household entries are excluded everywhere, + // including the clip check and coverage (AC-08). + const childEntries = history.entries.filter( + ({ entry }) => entry.householdId === history.householdId && entry.childId === input.childId, + ) + + // Clipped: an existing watermark pushed before the horizon, or (first-time) + // history that reaches past the horizon (AC-01, AC-13). + const horizonClipped = + history.readerLastSeenAt === undefined + ? childEntries.some(({ entry }) => entry.createdAt < windowStart) + : history.readerLastSeenAt < windowStart + + const publishedEntries = childEntries.filter(({ entry }) => entry.visibility === "published") + + // New / late: published entries strictly after the watermark, inside the + // window [windowStart, now] (AC-01, AC-02 — boundary at exactly W excluded). + const seenItems = publishedEntries + .filter( + ({ entry }) => + entry.createdAt > watermark && entry.createdAt >= windowStart && entry.createdAt <= now, + ) + .sort((a, b) => a.entry.createdAt - b.entry.createdAt) + .map(({ entry, events }) => seenItemFor(entry, events, dayKeyOf)) + + // Corrected: supersessions that landed inside the window on events the + // reader already saw (their entry existed at/before the watermark and is + // visible). The horizon clips corrections exactly as it clips new entries: + // pre-window revisions never surface (AC-04, AC-05, AC-13). + const byEventId = new Map() + for (const { entry, events } of childEntries) { + for (const event of events) { + byEventId.set(event._id, { entry, events, event }) + } + } + const revisionsByEventId = new Map() + for (const revision of history.revisions) { + if (revision.createdAt < windowStart || revision.createdAt > now) continue + const group = revisionsByEventId.get(revision.supersedesEventId) + if (group === undefined) { + revisionsByEventId.set(revision.supersedesEventId, [revision]) + } else { + group.push(revision) + } + } + const correctedItems: CatchUpItem[] = [] + for (const [supersededEventId, revisions] of [...revisionsByEventId].sort(([a], [b]) => + a < b ? -1 : a > b ? 1 : 0, + )) { + const found = byEventId.get(supersededEventId) + if (found === undefined) continue // superseded event not in this child's history + const { entry, events, event } = found + if (entry.createdAt > watermark) continue // reader has not seen the original yet + if (entry.visibility !== "published") continue // drafts never surface + correctedItems.push(correctedItemFor(entry, events, event, revisions)) + } + correctedItems.sort( + (a, b) => + a.entryCreatedAt - b.entryCreatedAt || + (a.originalEventId ?? "").localeCompare(b.originalEventId ?? ""), + ) + + // Coverage: every local day from windowStart through now. Late events count + // on their CAPTURE day — coverage measures recording activity, not occurrence. + const publishedCountByDay = new Map() + for (const { entry } of publishedEntries) { + if (entry.createdAt < windowStart || entry.createdAt > now) continue + const day = dayKeyOf(entry.createdAt) + publishedCountByDay.set(day, (publishedCountByDay.get(day) ?? 0) + 1) + } + const coverageDays: CoverageDay[] = [] + const lastDay = dayKeyOf(now) + for (let day = dayKeyOf(windowStart); day <= lastDay; day = nextDayKey(day)) { + coverageDays.push({ day, publishedEntryCount: publishedCountByDay.get(day) ?? 0 }) + } + const gapDays = coverageDays.filter((day) => day.publishedEntryCount === 0).length + + // T2 disclosure: confidence split across the events that made the report. + let confirmedEvents = 0 + let inferredEvents = 0 + for (const item of [...seenItems, ...correctedItems]) { + for (const event of item.events) { + if (event.confidence === 1) confirmedEvents += 1 + else inferredEvents += 1 + } + } + + return { + childId: input.childId, + readerId: input.readerId, + generatedAt: now, + windowStart, + windowEnd: now, + watermark, + allCaughtUp: seenItems.length === 0 && correctedItems.length === 0, + items: [...seenItems, ...correctedItems], + coverageDays, + gapDays, + horizonClipped, + confirmation: { confirmedEvents, inferredEvents }, + } +} + +/** + * Exact disclosure string for zero-entry days (AC-09): "No entries recorded + * for " + the day list. Absence is phrased only as missing recordings — never + * as "nothing happened" and never as a welfare conclusion. Empty string when + * every day in the window has content. + */ +export function gapDisclosure(coverageDays: ReadonlyArray): string { + const gaps = coverageDays.filter((day) => day.publishedEntryCount === 0).map((day) => day.day) + return gaps.length === 0 ? "" : `No entries recorded for ${gaps.join(", ")}` +} + +/** Monotonic watermark advance: max(prev, at); undefined (first-time) -> at. Idempotent by construction (AC-12). */ +export function advanceReadState(prev: number | undefined, at: number): number { + return prev === undefined ? at : Math.max(prev, at) +} diff --git a/packages/domain/src/index.ts b/packages/domain/src/index.ts index 5ad6437..4931e8f 100644 --- a/packages/domain/src/index.ts +++ b/packages/domain/src/index.ts @@ -64,6 +64,23 @@ export { KnowledgeShapeError, assertKnowledgeInvariants, } from "./knowledge.js" +// Since-last-seen catch-up (art_6qhBut41): read-state + report contracts, +// deterministic reducer, watermark advance, EventRevision proposal. +export { + AdvanceReadStateInput, + CaregiverReadStateFields, + CatchUpItem, + CatchUpQueryInput, + CatchUpReport, + CatchUpSource, + CoverageDay, + EventRevisionFields, + EventRevisionStruct, + advanceReadState, + computeCatchUp, + gapDisclosure, + utcDayKey, +} from "./catchup.js" export { toolSchemaFor } from "./jsonSchema.js" export type { Child } from "./child.js" @@ -73,3 +90,14 @@ export type { Event, EventCategory } from "./event.js" // KnowledgeKind / KnowledgeStatus / KnowledgeProvenanceKind / KnowledgeSourceType // are merged value+type symbols — exported once by value above. export type { Knowledge } from "./knowledge.js" +// Catch-up pure types — schema constants above are merged value+type symbols. +export type { + CatchUpEntry, + CatchUpError, + CatchUpGrants, + CatchUpHistory, + CatchUpItemKind, + CatchUpRevision, + DayKeyOf, + EventRevision, +} from "./catchup.js" diff --git a/packages/domain/test/catchup.test.ts b/packages/domain/test/catchup.test.ts new file mode 100644 index 0000000..b9a544f --- /dev/null +++ b/packages/domain/test/catchup.test.ts @@ -0,0 +1,517 @@ +import { readFileSync } from "node:fs" +import { join } from "node:path" +import { fileURLToPath } from "node:url" + +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" + +import { + CatchUpQueryInput, + CatchUpReport, + ChildDocument, + EntryDocument, + EventDocument, + EventRevisionStruct, + advanceReadState, + computeCatchUp, + gapDisclosure, + utcDayKey, +} from "../src/index.js" +import type { + CatchUpEntry, + CatchUpError, + CatchUpGrants, + CatchUpHistory, + CatchUpItemKind, + CatchUpRevision, + DayKeyOf, +} from "../src/index.js" + +/** + * Since-last-seen catch-up acceptance cases (art_6qhBut41, AC-01…AC-14). + * + * Expectations live in evaluation/fixtures/agent-experience/catchup/ — + * history.json (synthetic two-household history), grants.json (reader + * memberships incl. one denied reader), cases.json (per-case inputs and + * expected kinds/ids/counts/disclosure). All fixture times are Z-suffixed ISO + * strings converted with Date.parse; no wall clock, no randomness. + */ + +const fixturesDir = fileURLToPath( + new URL("../../../evaluation/fixtures/agent-experience/catchup/", import.meta.url), +) + +interface RawEntry { + _id: string + householdId: string + childId: string + authorId: string + rawTranscript: string + structuredEventIds: string[] + extractionStatus: "pending" | "structured" | "failed" + visibility: "draft" | "published" + photoId?: string + createdAt: string + _creationTime: string +} + +interface RawEvent { + _id: string + householdId: string + childId: string + category: string + timestamp: string + payload?: Record + confidence: number + _creationTime: string +} + +interface RawRevision { + id: string + householdId: string + childId: string + supersedesEventId: string + category: string + timestamp: string + payload?: Record + confidence: number + actorId: string + note?: string + createdAt: string +} + +interface RawHistory { + children: Array<{ _id: string; householdId: string; name: string; createdAt: string; _creationTime: string }> + entries: RawEntry[] + events: RawEvent[] + revisions: RawRevision[] +} + +interface RawGrants { + memberships: Record +} + +interface CaseExpected { + windowStartIso?: string + horizonClipped?: boolean + allCaughtUp?: boolean + kinds?: CatchUpItemKind[] + expectedItemEntryIds?: string[] + boundaryExcludedEntryId?: string + lateSpec?: { entryId: string; daysLate: number; occurredAtIso: string; recordedAtIso: string } + correctedSpec?: { + entryId: string + originalEventId: string + revisionIds: string[] + correctedBy: string + revisedPayload: Record + revisedConfidence: number + } + correctedItemCount?: number + counts?: { gapDays: number; confirmedEvents: number; inferredEvents: number } + gapDayCount?: number + gapDayKeys?: string[] + coverageDayCount?: number + dayKeyPolicy?: string + singleBucketDay?: string + singleBucketCount?: number + disclosure?: string + errorTag?: "UnauthorizedReader" | "HorizonExceeded" + absentFromOutput?: string[] + draftEntryIds?: string[] + advanceSpec?: { t1Iso: string; t2Iso: string } +} + +interface CatchupCase { + caseId: string + readerId: string + childId: string + watermarkIso: string | null + nowIso: string + horizonDays: number + expected: CaseExpected +} + +const historyFixture = JSON.parse(readFileSync(join(fixturesDir, "history.json"), "utf8")) as RawHistory +const grantsFixture = JSON.parse(readFileSync(join(fixturesDir, "grants.json"), "utf8")) as RawGrants +const casesFixture = JSON.parse(readFileSync(join(fixturesDir, "cases.json"), "utf8")) as { + cases: CatchupCase[] +} + +/** Z-suffixed ISO only — anything else is a fixture bug, not a soft default. */ +const isoMs = (iso: string): number => { + if (!iso.endsWith("Z")) throw new Error(`fixture timestamp must be Z-suffixed ISO: ${iso}`) + const ms = Date.parse(iso) + if (Number.isNaN(ms)) throw new Error(`fixture timestamp is not parseable: ${iso}`) + return ms +} + +// Convert fixture rows to contract documents — decoding through the domain +// schemas validates the fixtures against the real contract, not a hand-copy. +const entryDocOf = (raw: RawEntry) => + Schema.decodeUnknownSync(EntryDocument)({ + householdId: raw.householdId, + childId: raw.childId, + authorId: raw.authorId, + rawTranscript: raw.rawTranscript, + structuredEventIds: raw.structuredEventIds, + extractionStatus: raw.extractionStatus, + visibility: raw.visibility, + ...(raw.photoId !== undefined ? { photoId: raw.photoId } : {}), + createdAt: isoMs(raw.createdAt), + _id: raw._id, + _creationTime: isoMs(raw._creationTime), + }) + +const eventDocOf = (raw: RawEvent) => + Schema.decodeUnknownSync(EventDocument)({ + householdId: raw.householdId, + childId: raw.childId, + category: raw.category, + timestamp: isoMs(raw.timestamp), + ...(raw.payload !== undefined ? { payload: raw.payload } : {}), + confidence: raw.confidence, + _id: raw._id, + _creationTime: isoMs(raw._creationTime), + }) + +const revisionDocOf = (raw: RawRevision): CatchUpRevision => ({ + ...Schema.decodeUnknownSync(EventRevisionStruct)({ + householdId: raw.householdId, + childId: raw.childId, + supersedesEventId: raw.supersedesEventId, + category: raw.category, + timestamp: isoMs(raw.timestamp), + ...(raw.payload !== undefined ? { payload: raw.payload } : {}), + confidence: raw.confidence, + actorId: raw.actorId, + ...(raw.note !== undefined ? { note: raw.note } : {}), + createdAt: isoMs(raw.createdAt), + }), + id: raw.id, +}) + +const entryDocs = historyFixture.entries.map(entryDocOf) +const eventDocs = historyFixture.events.map(eventDocOf) +const revisionDocs = historyFixture.revisions.map(revisionDocOf) + +// The child's householdId — scope of the fail-closed grant check. +const childDocs = historyFixture.children.map((child) => + Schema.decodeUnknownSync(ChildDocument)({ + householdId: child.householdId, + name: child.name, + createdAt: isoMs(child.createdAt), + _id: child._id, + _creationTime: isoMs(child._creationTime), + }), +) +const householdByChildId = new Map( + childDocs.map((child) => [child._id, child.householdId]), +) + +const eventsById = new Map(eventDocs.map((event) => [event._id, event])) + +const catchUpEntries: CatchUpEntry[] = entryDocs.map((entry) => ({ + entry, + events: entry.structuredEventIds.flatMap((eventId) => { + const event = eventsById.get(eventId) + if (event === undefined) throw new Error(`fixture event ${eventId} not found (entry ${entry._id})`) + return [event] + }), +})) + +const grants: CatchUpGrants = { + canRead: (readerId, householdId) => (grantsFixture.memberships[readerId] ?? []).includes(householdId), +} + +// Verbatim source of truth for AC-01's raw-transcript assertion. +const transcriptByEntryId = new Map( + historyFixture.entries.map((entry) => [entry._id, entry.rawTranscript]), +) + +/** AC-10's injected policy: America/New_York fall-back via fixed offsets (no tz database). */ +const dstFallbackDayKey: DayKeyOf = (epochMs) => { + const offsetMinutes = epochMs < Date.parse("2026-11-01T06:00:00Z") ? -240 : -300 + return new Date(epochMs + offsetMinutes * 60_000).toISOString().slice(0, 10) +} + +const dayKeyOfFor = (fixtureCase: CatchupCase): DayKeyOf => + fixtureCase.expected.dayKeyPolicy === "america-new-york-fallback" ? dstFallbackDayKey : utcDayKey + +const caseById = (caseId: string): CatchupCase => { + const found = casesFixture.cases.find((fixtureCase) => fixtureCase.caseId === caseId) + if (found === undefined) throw new Error(`fixture case ${caseId} not found in cases.json`) + return found +} + +/** Fixture expectations are heterogeneous per case — a referenced field must + * be present; never assert against undefined. */ +const req = (value: T | undefined, caseId: string, field: string): T => { + if (value === undefined) throw new Error(`${caseId} fixture is missing expected.${field}`) + return value +} + +const runCase = (fixtureCase: CatchupCase): CatchUpReport | CatchUpError => { + const householdId = householdByChildId.get(fixtureCase.childId) + if (householdId === undefined) throw new Error(`fixture child ${fixtureCase.childId} not found`) + const input = Schema.decodeUnknownSync(CatchUpQueryInput)({ + childId: fixtureCase.childId, + readerId: fixtureCase.readerId, + now: isoMs(fixtureCase.nowIso), + horizonDays: fixtureCase.horizonDays, + }) + const history: CatchUpHistory = { + householdId, + readerLastSeenAt: fixtureCase.watermarkIso === null ? undefined : isoMs(fixtureCase.watermarkIso), + entries: catchUpEntries, + revisions: revisionDocs, + } + return computeCatchUp(input, history, grants, dayKeyOfFor(fixtureCase)) +} + +const isReport = (result: CatchUpReport | CatchUpError): result is CatchUpReport => !("_tag" in result) + +const reportOf = (result: CatchUpReport | CatchUpError): CatchUpReport => { + if (!isReport(result)) throw new Error(`expected a CatchUpReport, got ${JSON.stringify(result)}`) + return result +} + +const errorOf = (result: CatchUpReport | CatchUpError): CatchUpError => { + if (isReport(result)) throw new Error("expected a CatchUpError, got a report") + return result +} + +const serializedOf = (value: unknown): string => JSON.stringify(value) + +describe("AC-01 first-time reader over 20d history clips to the horizon", () => { + test("windowStart = now−14d, clipped, all items new/late with verbatim sources, coverage + confirmation present", () => { + const fixtureCase = caseById("AC-01") + const report = reportOf(runCase(fixtureCase)) + expect(report.windowStart).toBe(isoMs(fixtureCase.expected.windowStartIso ?? "")) + expect(report.horizonClipped).toBe(true) + expect(report.allCaughtUp).toBe(false) + expect(report.items.map((item) => item.kind)).toEqual(req(fixtureCase.expected.kinds, "AC-01", "kinds")) + expect(report.items.map((item) => item.entryId)).toEqual( + req(fixtureCase.expected.expectedItemEntryIds, "AC-01", "expectedItemEntryIds"), + ) + for (const item of report.items) { + expect(item.source.rawTranscript.length).toBeGreaterThan(0) + // Verbatim: exactly the fixture transcript, never a paraphrase. + const expectedTranscript = transcriptByEntryId.get(item.entryId) + if (expectedTranscript === undefined) throw new Error(`no fixture transcript for ${item.entryId}`) + expect(item.source.rawTranscript).toBe(expectedTranscript) + } + expect(report.coverageDays.length).toBeGreaterThan(0) + const expectedCounts = req(fixtureCase.expected.counts, "AC-01", "counts") + expect(report.confirmation).toEqual({ + confirmedEvents: expectedCounts.confirmedEvents, + inferredEvents: expectedCounts.inferredEvents, + }) + expect(report.gapDays).toBe(expectedCounts.gapDays) + }) +}) + +describe("AC-02 strictly-after watermark rule", () => { + test("entries before/at W are not new items; the at-W boundary entry is excluded; after-W entries are included", () => { + const fixtureCase = caseById("AC-02") + const report = reportOf(runCase(fixtureCase)) + expect(report.items.map((item) => item.kind)).toEqual(req(fixtureCase.expected.kinds, "AC-02", "kinds")) + expect(report.items.map((item) => item.entryId)).toEqual( + req(fixtureCase.expected.expectedItemEntryIds, "AC-02", "expectedItemEntryIds"), + ) + const watermarkMs = isoMs(fixtureCase.watermarkIso ?? "") + for (const item of report.items) { + if (item.kind === "new" || item.kind === "late") { + expect(item.entryCreatedAt).toBeGreaterThan(watermarkMs) + } + } + expect(report.items.some((item) => item.entryId === fixtureCase.expected.boundaryExcludedEntryId)).toBe(false) + }) +}) + +describe("AC-03 late recording detection", () => { + test("event of Sep 8 recorded Sep 10: kind late, daysLate 2, occurredAt = Sep 8 event ts", () => { + const fixtureCase = caseById("AC-03") + const lateSpec = fixtureCase.expected.lateSpec + if (lateSpec === undefined) throw new Error("AC-03 fixture is missing lateSpec") + const report = reportOf(runCase(fixtureCase)) + const lateItem = report.items.find((item) => item.entryId === lateSpec.entryId) + expect(lateItem?.kind).toBe("late") + expect(lateItem?.daysLate).toBe(lateSpec.daysLate) + expect(lateItem?.occurredAt).toBe(isoMs(lateSpec.occurredAtIso)) + expect(lateItem?.entryCreatedAt).toBe(isoMs(lateSpec.recordedAtIso)) + }) +}) + +describe("AC-04 in-window correction surfaces on the original entry", () => { + test("kind corrected, originalEventId/revisionIds/correctedBy set, events show revised values, source keeps transcript", () => { + const fixtureCase = caseById("AC-04") + const spec = fixtureCase.expected.correctedSpec + if (spec === undefined) throw new Error("AC-04 fixture is missing correctedSpec") + const report = reportOf(runCase(fixtureCase)) + const corrected = report.items.find((item) => item.kind === "corrected") + expect(corrected?.entryId).toBe(spec.entryId) + expect(corrected?.originalEventId).toBe(spec.originalEventId) + expect(corrected?.revisionIds).toEqual(spec.revisionIds) + expect(corrected?.correctedBy).toBe(spec.correctedBy) + const revised = corrected?.events[0] + expect(revised?.payload).toEqual(spec.revisedPayload) + expect(revised?.confidence).toBe(spec.revisedConfidence) + expect(corrected?.source.entryId).toBe(spec.entryId) + expect(corrected?.source.rawTranscript).toBe(transcriptByEntryId.get(spec.entryId)) + }) +}) + +describe("AC-05 pre-watermark correction stays silent", () => { + test("same revision but R before W: no corrected item, referenced ids absent from output", () => { + const fixtureCase = caseById("AC-05") + const report = reportOf(runCase(fixtureCase)) + expect(report.items.filter((item) => item.kind === "corrected")).toHaveLength( + fixtureCase.expected.correctedItemCount ?? 0, + ) + expect(report.items.map((item) => item.entryId)).toEqual( + req(fixtureCase.expected.expectedItemEntryIds, "AC-05", "expectedItemEntryIds"), + ) + const serialized = serializedOf(report) + for (const absent of fixtureCase.expected.absentFromOutput ?? []) { + expect(serialized).not.toContain(absent) + } + }) +}) + +describe("AC-06 drafts never surface", () => { + test("draft entries inside the window appear nowhere in the report", () => { + const fixtureCase = caseById("AC-06") + const report = reportOf(runCase(fixtureCase)) + const serialized = serializedOf(report) + for (const draftId of fixtureCase.expected.draftEntryIds ?? []) { + expect(serialized).not.toContain(draftId) + } + // The published set is unaffected by the drafts' presence. + expect(report.items.map((item) => item.kind)).toEqual(req(fixtureCase.expected.kinds, "AC-06", "kinds")) + }) +}) + +describe("AC-07 fail-closed authorization", () => { + test("reader without a grant: { _tag: UnauthorizedReader } and NOTHING else", () => { + const fixtureCase = caseById("AC-07") + const error = errorOf(runCase(fixtureCase)) + expect(error._tag).toBe(req(fixtureCase.expected.errorTag, "AC-07", "errorTag")) + expect(Object.keys(error)).toEqual(["_tag"]) + }) +}) + +describe("AC-08 no cross-household leakage", () => { + test("every source.entryId resolves under the reader's grants; the foreign entry appears nowhere", () => { + const fixtureCase = caseById("AC-08") + const report = reportOf(runCase(fixtureCase)) + const householdId = householdByChildId.get(fixtureCase.childId) + if (householdId === undefined) throw new Error(`fixture child ${fixtureCase.childId} not found`) + const visibleEntryIds = new Set( + entryDocs + .filter((entry) => entry.householdId === householdId && entry.visibility === "published") + .map((entry) => entry._id), + ) + for (const item of report.items) { + expect(visibleEntryIds.has(item.source.entryId)).toBe(true) + } + const serialized = serializedOf(report) + for (const absent of fixtureCase.expected.absentFromOutput ?? []) { + expect(serialized).not.toContain(absent) + } + }) +}) + +describe("AC-09 gap disclosure", () => { + test("gapDays correct, coverageDays lists zero-entry days, exact disclosure string, no 'no care' phrasing", () => { + const fixtureCase = caseById("AC-09") + const report = reportOf(runCase(fixtureCase)) + expect(report.items.map((item) => item.entryId)).toEqual( + req(fixtureCase.expected.expectedItemEntryIds, "AC-09", "expectedItemEntryIds"), + ) + expect(report.gapDays).toBe(req(fixtureCase.expected.gapDayCount, "AC-09", "gapDayCount")) + expect(report.coverageDays.length).toBe(req(fixtureCase.expected.coverageDayCount, "AC-09", "coverageDayCount")) + for (const gapDay of fixtureCase.expected.gapDayKeys ?? []) { + const bucket = report.coverageDays.find((day) => day.day === gapDay) + expect(bucket?.publishedEntryCount).toBe(0) + } + expect(gapDisclosure(report.coverageDays)).toBe(req(fixtureCase.expected.disclosure, "AC-09", "disclosure")) + // Absence of logs never reads as absence of care. + const serialized = serializedOf(report).toLowerCase() + expect(serialized).not.toContain("no care") + expect(serialized).not.toContain("nothing happened") + }) +}) + +describe("AC-10 DST fall-back day bucketing", () => { + test("05:00Z and 06:00Z both bucket to 2026-11-01; single bucket, no 23/25h skew", () => { + const fixtureCase = caseById("AC-10") + expect(fixtureCase.expected.singleBucketDay).toBeDefined() + const singleBucketDay = req(fixtureCase.expected.singleBucketDay, "AC-10", "singleBucketDay") + const report = reportOf(runCase(fixtureCase)) + expect(report.items.map((item) => item.entryId)).toEqual( + req(fixtureCase.expected.expectedItemEntryIds, "AC-10", "expectedItemEntryIds"), + ) + // The injected policy buckets both instants to the same local day. + expect(dstFallbackDayKey(isoMs("2026-11-01T05:00:00Z"))).toBe(singleBucketDay) + expect(dstFallbackDayKey(isoMs("2026-11-01T06:00:00Z"))).toBe(singleBucketDay) + expect(report.coverageDays.length).toBe(req(fixtureCase.expected.coverageDayCount, "AC-10", "coverageDayCount")) + const buckets = report.coverageDays.filter((day) => day.day === singleBucketDay) + expect(buckets).toHaveLength(1) + expect(buckets[0]?.publishedEntryCount).toBe(req(fixtureCase.expected.singleBucketCount, "AC-10", "singleBucketCount")) + }) +}) + +describe("AC-11 fully caught up", () => { + test("items [], allCaughtUp true, coverageDays still non-empty", () => { + const fixtureCase = caseById("AC-11") + const report = reportOf(runCase(fixtureCase)) + expect(report.items).toHaveLength(0) + expect(report.allCaughtUp).toBe(true) + expect(report.coverageDays.length).toBe(req(fixtureCase.expected.coverageDayCount, "AC-11", "coverageDayCount")) + expect(report.coverageDays.length).toBeGreaterThan(0) + }) +}) + +describe("AC-12 monotonic idempotent watermark advance", () => { + test("advance(undefined, t2) = t2; advance(t2, t1 { + const spec = caseById("AC-12").expected.advanceSpec + if (spec === undefined) throw new Error("AC-12 fixture is missing advanceSpec") + const t1 = isoMs(spec.t1Iso) + const t2 = isoMs(spec.t2Iso) + const advanced = advanceReadState(undefined, t2) + expect(advanced).toBe(t2) + expect(advanceReadState(advanced, t1)).toBe(t2) + expect(advanceReadState(t2, t2)).toBe(t2) + }) +}) + +describe("AC-13 horizon clip suppresses pre-window corrections", () => { + test("windowStart = now−horizon (not the watermark), clipped, pre-window revisions absent", () => { + const fixtureCase = caseById("AC-13") + const expectedKinds = fixtureCase.expected.kinds + const expectedEntryIds = fixtureCase.expected.expectedItemEntryIds + if (expectedKinds === undefined || expectedEntryIds === undefined) { + throw new Error("AC-13 fixture is missing kinds/expectedItemEntryIds") + } + const report = reportOf(runCase(fixtureCase)) + expect(report.windowStart).toBe(isoMs(fixtureCase.expected.windowStartIso ?? "")) + expect(report.horizonClipped).toBe(true) + expect(report.items.map((item) => item.kind)).toEqual(expectedKinds) + expect(report.items.map((item) => item.entryId)).toEqual(expectedEntryIds) + expect(report.items.some((item) => item.kind === "corrected")).toBe(false) + const serialized = serializedOf(report) + for (const absent of fixtureCase.expected.absentFromOutput ?? []) { + expect(serialized).not.toContain(absent) + } + }) +}) + +describe("AC-14 contract round-trip", () => { + test("encodeSync(CatchUpReport) -> decodeUnknownSync -> deep-equal the original", () => { + const report = reportOf(runCase(caseById("AC-14"))) + const encoded = Schema.encodeSync(CatchUpReport)(report) + const decoded = Schema.decodeUnknownSync(CatchUpReport)(encoded) + expect(decoded).toEqual(report) + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c51d74..7e8ac79 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: apps/mobile: dependencies: + '@journal/domain': + specifier: workspace:* + version: link:../../packages/domain '@journal/month-history': specifier: workspace:* version: link:../../packages/month-history From 3e94820a96bcee9b063551380ac65ac4dd3d2f88 Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 20:14:18 +0000 Subject: [PATCH 2/2] feat(evaluation): register agent-experience/catchup fixture area Register the catch-up scenario-and-authorization area (cases.json, grants.json, history.json) in the fixture-area manifest with the loader-legal binding pair (bun-test-data), making it visible to the fail-fast registration path and listed by corpus runs. Update the manifest self-check's committed-shape pin to two areas (seed corpus + registered scenario area); all fail-fast rejection checks unchanged. Co-authored-by: Gilbert Polanco --- evaluation/fixtures/manifest.json | 5 +++++ evaluation/src/manifest-selfcheck.ts | 20 +++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/evaluation/fixtures/manifest.json b/evaluation/fixtures/manifest.json index a1584f0..2c5081a 100644 --- a/evaluation/fixtures/manifest.json +++ b/evaluation/fixtures/manifest.json @@ -5,6 +5,11 @@ "path": ".", "fixtureClass": "extraction-accuracy", "runnerBinding": "adapter-corpus" + }, + { + "path": "agent-experience/catchup", + "fixtureClass": "scenario-and-authorization", + "runnerBinding": "bun-test-data" } ] } diff --git a/evaluation/src/manifest-selfcheck.ts b/evaluation/src/manifest-selfcheck.ts index 1b4e6f7..7f1da89 100644 --- a/evaluation/src/manifest-selfcheck.ts +++ b/evaluation/src/manifest-selfcheck.ts @@ -51,11 +51,19 @@ async function checkSeedManifest(): Promise { const manifestUrl = pathToFileURL(join(fixturesDir, MANIFEST_FILENAME)) const manifest = await loadManifest(manifestUrl) assert.equal(manifest.version, 1) - assert.equal(manifest.areas.length, 1) + // Committed manifest shape: the flat seed corpus plus the registered + // scenario-and-authorization area consumed by the domain catch-up tests. + assert.equal(manifest.areas.length, 2) assert.deepEqual(manifest.areas[0], { path: '.', fixtureClass: 'extraction-accuracy', runnerBinding: 'adapter-corpus' }) + assert.deepEqual(manifest.areas[1], { + path: 'agent-experience/catchup', + fixtureClass: 'scenario-and-authorization', + runnerBinding: 'bun-test-data', + }) const resolved = await resolveFixtureAreas(manifestUrl) - const [area] = resolved.areas + assert.equal(resolved.areas.length, 2) + const [area, scenarioArea] = resolved.areas assert.ok(area, 'seed manifest must resolve one area') assert.equal(area.spec.id, 'extraction-accuracy') // The six seed fixtures are present, sorted, and the manifest never lists itself. @@ -64,7 +72,13 @@ async function checkSeedManifest(): Promise { } assert.ok(!area.files.includes(MANIFEST_FILENAME), 'manifest must never load as a fixture') assert.ok(area.files.every((f, i) => i === 0 || area.files[i - 1]! <= f), 'files must be sorted') - console.log(` ok seed manifest — 1 area (${area.files.length} corpus files, manifest excluded)`) + // Scenario areas resolve as data-only: files listed for the consumer, never executed here. + assert.ok(scenarioArea, 'registered scenario area must resolve') + assert.equal(scenarioArea.spec.id, 'scenario-and-authorization') + assert.deepEqual(scenarioArea.files, ['cases.json', 'grants.json', 'history.json']) + console.log( + ` ok committed manifest — 2 areas (${area.files.length} corpus + ${scenarioArea.files.length} scenario files, manifest excluded)`, + ) } async function checkRejections(tempRoot: string): Promise {