diff --git a/.obvious/obvious.md b/.obvious/obvious.md index abf57f5..16b52b9 100644 --- a/.obvious/obvious.md +++ b/.obvious/obvious.md @@ -28,6 +28,7 @@ apps/mobile Expo app; ConvexProvider reads EXPO_PUBLIC_CONVEX_URL backend/convex Convex schema + functions (children, households, entries, events) packages/domain Effect v4 schemas + Convex-validator adapter + JSON Schema (draft 2020-12) derivation packages/extraction Transcript → typed events pipeline (stub, no LLM call yet) +packages/month-history Deterministic month-history view model + executable journeys (28-check rubric, `bun src/run.ts`) packages/ui Shared RN primitives evaluation/ Acceptance corpus (6 fixtures) + candidate-agnostic cross-review harness security/ THREAT-MODEL.md + executable fail-closed access cases (17 tests) @@ -59,6 +60,7 @@ pnpm build # buildable packages bun test ./security # 17 fail-closed access cases (13 negative + 4 positive) cd evaluation && bun src/run.ts # corpus vs the worked example adapter bun src/run.ts --adapter=./src/example/broken-adapter.ts --expect-failure # negative control must fail +pnpm --filter @journal/month-history journeys # month-history 28-check rubric (runner + coverage both directions) ``` The security suite and evaluation harness are standalone (`security/` and diff --git a/README.md b/README.md index a7553e5..40fc176 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ apps/mobile Expo app; ConvexProvider reads EXPO_PUBLIC_CONVEX_URL backend/convex Convex schema + functions (children, households, entries, events) packages/domain Canonical Effect schemas + Convex-validator adapter + JSON Schema derivation packages/extraction Transcript -> typed events interface (stub) +packages/month-history Deterministic month-history view model + executable journeys (28-check rubric) packages/ui Shared RN primitives (placeholder) ``` diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx index 553d2d4..0387610 100644 --- a/apps/mobile/App.tsx +++ b/apps/mobile/App.tsx @@ -2,9 +2,8 @@ import { ConvexProvider, ConvexReactClient } from "convex/react" import { useMemo } from "react" import { StyleSheet, View } from "react-native" -import { Text } from "@journal/ui" - import { getConvexClientUrl } from "./src/lib/convex" +import { MonthHistoryScreen } from "./src/month/MonthHistoryScreen" export default function App() { const client = useMemo(() => new ConvexReactClient(getConvexClientUrl()), []) @@ -12,7 +11,7 @@ export default function App() { return ( - Shared Child Journal + ) @@ -20,8 +19,6 @@ export default function App() { const styles = StyleSheet.create({ container: { - alignItems: "center", flex: 1, - justifyContent: "center", }, }) diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 92ac6e9..cc6f060 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -10,6 +10,7 @@ "ios": "expo start --ios" }, "dependencies": { + "@journal/month-history": "workspace:*", "@journal/ui": "workspace:*", "convex": "^1.46.0", "effect": "4.0.0-rc.115", diff --git a/apps/mobile/src/month/MonthHistoryScreen.tsx b/apps/mobile/src/month/MonthHistoryScreen.tsx new file mode 100644 index 0000000..fa60002 --- /dev/null +++ b/apps/mobile/src/month/MonthHistoryScreen.tsx @@ -0,0 +1,267 @@ +/** + * Month-history prototype screen (RN). + * + * Deterministic prototype over the synthetic family fixture: it renders the + * SAME authorized view the executable journeys assert against, via + * buildAuthorizedView. Data discipline is one-to-one with the view contract: + * raw transcripts verbatim, capture attribution always visible, gaps honest, + * corrections disclosed with lineage, failed extraction never blocked, and + * every day cell screen-reader reachable (role/hint/label from the package). + * + * Wire-up to the Convex timeline (replacing the fixture input) is a follow-up; + * the view-input adapters in the package are the seam for that swap. + */ +import { useMemo, useState } from "react" +import { Pressable, ScrollView, StyleSheet, View } from "react-native" + +import { + FONT_SCALING, + GAP_DISCLAIMER, + HOUSEHOLD_ID, + HOUSEHOLD_ZONE, + MOM, + buildAuthorizedView, + type EntryCardView, + type EventCardView, +} from "@journal/month-history" +import { Text } from "@journal/ui" + +const PROTOTYPE_MONTH = "2026-09" + +export function MonthHistoryScreen() { + const [selectedDayKey, setSelectedDayKey] = useState("2026-09-12") + + const { access, view } = useMemo( + () => + buildAuthorizedView( + { kind: "caregiver", caregiverId: MOM, householdIds: [HOUSEHOLD_ID] }, + PROTOTYPE_MONTH, + HOUSEHOLD_ZONE, + ), + [], + ) + + if (access.outcome !== "allowed") { + return ( + + + You do not have access to this timeline. + + + ) + } + + const selectedDay = view.days.find((day) => day.dateKey === selectedDayKey) + + return ( + + + {view.monthLabel} + + + + {view.gap.message} {GAP_DISCLAIMER} + + + + {view.totalEntries} entries · {view.totalEvents} care events + + + + {view.days.map((day) => ( + setSelectedDayKey(day.dateKey)} + /> + ))} + + + {selectedDay ? ( + + + {selectedDay.dayLabel} + + {selectedDay.entries.map((entry) => ( + + ))} + {selectedDay.entries.length === 0 ? ( + + No entries recorded + + ) : null} + {selectedDay.events.map((event) => ( + + ))} + + ) : null} + + ) +} + +interface DayCellProps { + readonly dateKey: string + readonly dayLabel: string + readonly entryCount: number + readonly a11yRole: "button" + readonly a11yHint: string + readonly a11yLabel: string + readonly selected: boolean + readonly onPress: () => void +} + +function DayCell(props: DayCellProps) { + const dayOfMonth = Number(props.dateKey.slice(8, 10)) + return ( + + + {dayOfMonth} + + {props.entryCount > 0 ? : null} + + ) +} + +function EntryCard({ entry }: { entry: EntryCardView }) { + return ( + + + {entry.transcript} + + + {entry.authorName} · {entry.captureLabel} + + {entry.extractionStatusLabel ? ( + + {entry.extractionStatusLabel} + + ) : null} + {entry.correctionLineage ? ( + + {entry.correctionLineage.steps.map((step) => ( + + Corrected by {step.byName} — {step.createdAtLabel} + {step.reason ? ` · ${step.reason}` : ""} + + ))} + + {entry.correctionLineage.originalPreservedLabel} + + + ) : null} + + {entry.a11yLabel} + + + ) +} + +function EventLine({ event }: { event: EventCardView }) { + return ( + + + {event.category} — {event.localTimeLabel} + {event.isLate && event.lateLabel ? ` · ${event.lateLabel}` : ""} + + + ) +} + +const styles = StyleSheet.create({ + container: { flex: 1, padding: 16 }, + scroll: { flex: 1 }, + content: { padding: 16, paddingBottom: 48 }, + header: { fontSize: 24, fontWeight: "600", marginBottom: 8 }, + gapStatement: { marginBottom: 4 }, + totals: { fontSize: 13, opacity: 0.7, marginBottom: 12 }, + grid: { flexDirection: "row", flexWrap: "wrap", gap: 4 }, + cell: { + alignItems: "center", + borderRadius: 8, + flexGrow: 1, + flexBasis: "12%", + padding: 8, + minHeight: 40, + justifyContent: "center", + }, + cellSelected: { backgroundColor: "#dce9ff" }, + cellDay: { fontSize: 14 }, + cellDot: { width: 5, height: 5, borderRadius: 3, backgroundColor: "#2f6fed", marginTop: 3 }, + dayPanel: { marginTop: 16, gap: 8 }, + dayPanelHeader: { fontSize: 17, fontWeight: "600" }, + entryCard: { borderRadius: 10, borderWidth: StyleSheet.hairlineWidth, padding: 10, gap: 6 }, + entryTranscript: {}, + entryMeta: { fontSize: 12, opacity: 0.7 }, + entryFailed: { color: "#8a5a00" }, + lineage: { gap: 2 }, + lineageStep: { fontSize: 13 }, + lineagePreserved: { fontSize: 12, opacity: 0.7 }, + noEntries: { opacity: 0.7 }, + eventLine: { paddingLeft: 4 }, + eventText: {}, + srOnly: { height: 0, opacity: 0 }, +}) diff --git a/packages/month-history/package.json b/packages/month-history/package.json new file mode 100644 index 0000000..524214e --- /dev/null +++ b/packages/month-history/package.json @@ -0,0 +1,26 @@ +{ + "name": "@journal/month-history", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Deterministic month-history journeys (parent retrieval, correction, caregiver handoff): pure view model, timezone-correct month bucketing, synthetic fixtures, journey harness, and a machine-checked acceptance rubric. Proposal tier — canonical ownership is tracked in the 30-slot delivery map.", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "scripts": { + "test": "bun test", + "typecheck": "tsc -p tsconfig.json --noEmit", + "journeys": "bun src/run.ts" + }, + "dependencies": { + "@journal/domain": "workspace:*", + "effect": "4.0.0-rc.115" + }, + "devDependencies": { + "@types/bun": "^1.3.14", + "typescript": "~6.0.3" + } +} diff --git a/packages/month-history/rubric.json b/packages/month-history/rubric.json new file mode 100644 index 0000000..00a6e47 --- /dev/null +++ b/packages/month-history/rubric.json @@ -0,0 +1,174 @@ +{ + "version": "0.1", + "description": "Month-history journeys: every row MUST have an executing check with the same id, and every executed check MUST have a row here. The runner (src/run.ts) fails on either direction of the gap.", + "checks": [ + { + "id": "J1-A1", + "journey": "parent-retrieval", + "criterion": "A household member passes the one shared fail-closed access gate for a month-history read", + "measure": "monthAccess returns allowed for Mom on the fixture household; denial codes come from the security policy, not month-history" + }, + { + "id": "J1-A2", + "journey": "parent-retrieval", + "criterion": "A sparse month renders every calendar day explicitly, with honest gap copy and correct totals", + "measure": "September 2026 (Mom): 30 day cells, 25 gap days, message '25 of 30 days have no entries recorded.' + disclaimer; totals entries=5 events=6 late=1 corrected=1 orphans=0" + }, + { + "id": "J1-A3", + "journey": "parent-retrieval", + "criterion": "A late entry lands on the day the care HAPPENED, with explicit capture attribution", + "measure": "Sep 12 cell holds the nap event at 10:00 AM with capture label 'Captured September 20, 2026 at 8:14 AM' and the late label 'Recorded Sep 20 — about Sep 12'" + }, + { + "id": "J1-A4", + "journey": "parent-retrieval", + "criterion": "A failed extraction never blocks or hides the capture", + "measure": "Sep 20 cell shows the raw note with status failed and label 'Extraction failed — raw note preserved'; zero structured events that day" + }, + { + "id": "J1-A5", + "journey": "parent-retrieval", + "criterion": "Gap days never imply care did not happen", + "measure": "Sep 3 cell reads 'Thursday, September 3, 2026. No entries recorded.' and the month gap statement carries 'Gaps in the journal are not evidence about care.'" + }, + { + "id": "J1-A6", + "journey": "parent-retrieval", + "criterion": "Draft isolation inside the month view", + "measure": "Mom sees her own Sep 25 draft (and its mood event); Sep 26 shows no entries (Ana's draft is invisible to Mom)" + }, + { + "id": "J1-A7a", + "journey": "parent-retrieval", + "criterion": "Month boundaries bucket by the household timezone, both directions", + "measure": "In America/New_York the 23:50 EDT Sep 30 entry/event land on Sep 30 in the SEPTEMBER view and are absent from the October 2026 view (31 cells, exactly 1 event: Oct 1 00:10 EDT)" + }, + { + "id": "J1-A7b", + "journey": "parent-retrieval", + "criterion": "The same instant falls in different months under different household timezones", + "measure": "In Asia/Kolkata the same data puts both boundary events on 2026-10-01 (2 events, 31 cells)" + }, + { + "id": "J1-A8", + "journey": "parent-retrieval", + "criterion": "DST fall-back does not duplicate or lose a day", + "measure": "November 2026 (NY): both 1:30 AM events render on 2026-11-01 in timestamp order; month span is 721 hours; 30 cells" + }, + { + "id": "J1-A9", + "journey": "parent-retrieval", + "criterion": "A corrected entry shows corrected text WITH lineage, who/when/reason", + "measure": "Sep 2 card shows Dad's corrected text, lineage step 'Dad — Sunday, September 27, 2026 at 10:00 AM' with reason, and the original-preserved label" + }, + { + "id": "J1-A10", + "journey": "parent-retrieval", + "criterion": "Raw captures are immutable: projections never rewrite the dataset", + "measure": "Original tower transcript byte-identical after all view/digest builds; full JSON snapshot of entries+events unchanged" + }, + { + "id": "J1-A11", + "journey": "parent-retrieval", + "criterion": "Text input for corrections is quiet (never fights or startles the typist)", + "measure": "QUIET_TEXT_INPUT equals { autoCorrect:false, autoCapitalize:'none', spellCheck:false, autoFocus:false, keyboardType:'default', multiline:true, blurOnSubmit:false, textContentType:'none' }" + }, + { + "id": "J1-A12", + "journey": "parent-retrieval", + "criterion": "Large-text accessibility: body text scales uncapped, chrome capped, no fixed heights, no truncation", + "measure": "FONT_SCALING body max=null / chrome max=1.5; LAYOUT_POLICY fixedHeightsOnTextRows=false, truncatesEntryText=false, expand affordance 'Show full text'" + }, + { + "id": "J1-A13", + "journey": "parent-retrieval", + "criterion": "Every day cell is screen-reader reachable with role, hint, and label", + "measure": "All 30 cells expose a11yRole 'button', DAY_CELL_A11Y_HINT, non-empty label; header reads 'Month history: September 2026'" + }, + { + "id": "J1-A14", + "journey": "parent-retrieval", + "criterion": "An empty month is honest, never accusatory", + "measure": "Empty view: kind 'empty-month', message 'No entries were recorded this month.' + disclaimer, all 30 days listed as gaps" + }, + { + "id": "J2-B1", + "journey": "parent-correction", + "criterion": "Household members may correct published entries", + "measure": "correctionAccess(Dad, published tower entry) returns ALLOW via the shared policy" + }, + { + "id": "J2-B2", + "journey": "parent-correction", + "criterion": "Corrections form an append-only, deterministically ordered lineage", + "measure": "Two-step chain (Mom then Dad), listed out of order in input, sorts to [co_chain_1, co_chain_2]; supersedes must reference an earlier entry or construction throws" + }, + { + "id": "J2-B3", + "journey": "parent-correction", + "criterion": "Corrections are disclosed to screen readers on the entry and its events", + "measure": "Entry a11y label contains 'Corrected entry.'; each event of the corrected entry contains 'Includes a correction.'" + }, + { + "id": "J2-B4", + "journey": "parent-correction", + "criterion": "Drafts are author-only even for correction writes; anonymous principals denied", + "measure": "Ana on Mom's draft: DENY_DRAFT_AUTHOR_ONLY; anonymous on published: DENY_ANONYMOUS; Mom on her own draft: ALLOW" + }, + { + "id": "J2-B5", + "journey": "parent-correction", + "criterion": "Attribution is server-bound; claiming another author's id fails", + "measure": "Write action with asAuthorId=Mom from Dad's principal returns DENY_ATTRIBUTION_MISMATCH" + }, + { + "id": "J2-B6", + "journey": "parent-correction", + "criterion": "Non-members are denied the whole month view at the timeline gate", + "measure": "Outsider: DENY_NO_HOUSEHOLD_PATH; anonymous: DENY_ANONYMOUS — both before any entry-level filtering" + }, + { + "id": "J3-C1", + "journey": "caregiver-handoff", + "criterion": "The handoff digest is built from the RECEIVER's authorization, not the preparer's", + "measure": "Dad's view: 6 visible entries all 'published' (no draft content), 2 drafts excluded for principal; September view places 4 entries" + }, + { + "id": "J3-C2", + "journey": "caregiver-handoff", + "criterion": "Digest lines cover exactly the receiver-visible days with deterministic summaries", + "measure": "Lines for 2026-09-02/12/20/30 only; summaries '2× potty, 1× milestone', '1× sleep (45 min)', the failed-extraction note text, and '1× potty'" + }, + { + "id": "J3-C3", + "journey": "caregiver-handoff", + "criterion": "Every handoff line is source-linked", + "measure": "Each line has non-empty sourceEntryIds; Sep 12 links exactly to the late nap entry" + }, + { + "id": "J3-C4", + "journey": "caregiver-handoff", + "criterion": "Corrections surface in the handoff with attribution", + "measure": "Sep 2 line lists the tower entry as corrected; its authors include 'Mom'" + }, + { + "id": "J3-C5", + "journey": "caregiver-handoff", + "criterion": "Excluded drafts are disclosed as a count, never as content", + "measure": "excludedDraftCount=2 with note '2 draft entries are not included in this handoff (visible only to their authors).'" + }, + { + "id": "J3-C6", + "journey": "caregiver-handoff", + "criterion": "Gap disclosure in the handoff matches the receiver's view", + "measure": "26 gap days; statement '26 of 30 days have no entries recorded.' + disclaimer" + }, + { + "id": "J3-C7", + "journey": "caregiver-handoff", + "criterion": "The digest carries audience, preparer metadata, and source-preservation disclaimer", + "measure": "audience 'published-only', preparedByName 'Mom', preparedForName 'Dad', sourceDisclaimer includes verbatim-transcript preservation and the gap disclaimer" + } + ] +} diff --git a/packages/month-history/src/a11y.ts b/packages/month-history/src/a11y.ts new file mode 100644 index 0000000..a1b5de5 --- /dev/null +++ b/packages/month-history/src/a11y.ts @@ -0,0 +1,127 @@ +/** + * Accessibility contracts for the month-history surface, expressed as DATA. + * + * - Labels are deterministic strings built from the household-zone calendar; + * tests pin them exactly (en-US). + * - Text scaling: body text NEVER caps font scaling (large-text users get the + * full OS text size); chrome may cap at 1.5 so grids stay legible. Layout + * policy forbids fixed heights on text rows (no clipping at large type) + * and forbids truncating entry text (an explicit expand affordance instead). + * - Quiet text input: correction and note fields must not fight the person + * typing — no autocorrect/auto-capitalize/spellcheck mutations (child + * names, medications and dosages must survive verbatim), no focus steal, + * no submit-on-return surprise. + * + * These constants are the single source of truth for the RN prototype screen + * and for the rubric checks; the screen maps them onto TextInput/Text/ + * Pressable props one-to-one. + */ +import { localTimeLabel } from "./zone.js" + +export const QUIET_TEXT_INPUT = { + autoCorrect: false, + autoCapitalize: "none", + spellCheck: false, + autoFocus: false, + keyboardType: "default", + multiline: true, + blurOnSubmit: false, + textContentType: "none", +} as const + +export type QuietTextInput = typeof QUIET_TEXT_INPUT + +export const FONT_SCALING = { + /** Journal text scales with the user's OS text size, uncapped. */ + body: { allowFontScaling: true, maxFontSizeMultiplier: null }, + /** Day numerals and other chrome: capped so the grid stays legible. */ + chrome: { allowFontScaling: true, maxFontSizeMultiplier: 1.5 }, +} as const + +export const LAYOUT_POLICY = { + /** Text rows must not use fixed pixel heights (min-height only). */ + fixedHeightsOnTextRows: false, + /** Entry text is never truncated; an expand affordance reveals the rest. */ + truncatesEntryText: false, + expandAffordanceLabel: "Show full text", +} as const + +export const A11Y_ROLES = { + monthHeader: "header", + dayCell: "button", + entryText: "text", +} as const + +export const NO_ENTRIES_LABEL = "No entries recorded" +/** The product-honesty line: an unrecorded day says nothing about care. */ +export const GAP_DISCLAIMER = "Gaps in the journal are not evidence about care." +export const EXTRACTION_FAILED_LABEL = "Extraction failed — your original note is preserved verbatim." +export const CORRECTION_ORIGINAL_PRESERVED_LABEL = "The original note is preserved verbatim." +export const CORRECTION_INPUT_LABEL = "Correction text" +export const CORRECTION_INPUT_HINT = "Describe the correction. Your text is saved exactly as typed." +export const DAY_CELL_A11Y_HINT = "Opens the journal entries for this day." + +export function monthHeaderA11yLabel(month: string): string { + return `Month history: ${month}` +} + +export interface DayCellA11yInput { + readonly dayLabel: string + readonly entryCount: number + readonly eventCount: number + readonly correctedCount: number +} + +export function dayCellA11yLabel(input: DayCellA11yInput): string { + const recorded = + input.entryCount === 0 + ? `${NO_ENTRIES_LABEL}.` + : input.entryCount === 1 + ? "1 entry recorded." + : `${input.entryCount} entries recorded.` + const events = + input.eventCount > 0 ? (input.eventCount === 1 ? " 1 care event." : ` ${input.eventCount} care events.`) : "" + const corrected = input.correctedCount > 0 ? " Includes a corrected entry." : "" + return `${input.dayLabel}. ${recorded}${events}${corrected}` +} + +export interface EventA11yInput { + readonly category: string + readonly localTimeLabel: string + readonly authorName: string + readonly isLate: boolean + readonly captureLabel: string + readonly corrected: boolean +} + +export function eventA11yLabel(input: EventA11yInput): string { + const base = `${input.category}, ${input.localTimeLabel}, recorded by ${input.authorName}.` + const late = input.isLate ? ` ${input.captureLabel}.` : "" + const corrected = input.corrected ? " Includes a correction." : "" + return `${base}${late}${corrected}` +} + +export interface EntryA11yInput { + readonly authorName: string + readonly captureLabel: string + readonly transcript: string + readonly corrected: boolean +} + +export function entryA11yLabel(input: EntryA11yInput): string { + const corrected = input.corrected ? " Corrected entry." : "" + return `Note by ${input.authorName}. ${input.captureLabel}. ${previewForLabel(input.transcript)}${corrected}` +} + +/** Label previews cap at 100 chars so screen-reader summaries stay listenable. */ +export function previewForLabel(text: string): string { + return text.length <= 100 ? text : `${text.slice(0, 100)}…` +} + +export function captureLabel(instantMs: number, timeZone: string, fullDay: string): string { + return `Captured ${fullDay} at ${localTimeLabel(instantMs, timeZone)}` +} + +export function lateLabel(captureDayFull: string, occurrenceDayFull: string): string { + return `Recorded ${captureDayFull} — about ${occurrenceDayFull}` +} diff --git a/packages/month-history/src/access.ts b/packages/month-history/src/access.ts new file mode 100644 index 0000000..ddc23ed --- /dev/null +++ b/packages/month-history/src/access.ts @@ -0,0 +1,74 @@ +/** + * Authorization for month-history surfaces — a thin ADAPTER over the one + * fail-closed policy (security/access/policy.ts). No new rules are invented + * here: a month view is a child-timeline read, drafts are author-only, and + * writes are attribution-bound. Every decision cites the shared policy so + * month history can never open a path the rest of the product denies. + * + * Mapping note: the policy module's Entry shape is the contract v0.1 mock + * (transcript/status, createdAt as Date). The canonical domain EntryDocument + * (rawTranscript/visibility, createdAt as Unix ms) maps losslessly for the + * fields the policy reads. + */ +import type { EntryDocument } from "@journal/domain" +import { evaluateAccess } from "../../../security/access/policy" +import type { Entry as PolicyEntry } from "../../../security/access/schema-mock" +import type { ChildScope, Decision, DenyCode, Principal } from "../../../security/access/types" + +export type { ChildScope, Decision, DenyCode, Principal } + +/** Map a canonical domain EntryDocument onto the policy's Entry shape. */ +export function toPolicyEntry(entry: EntryDocument): PolicyEntry { + return { + _tag: "Entry", + transcript: entry.rawTranscript, + authorId: entry.authorId, + createdAt: new Date(entry.createdAt), + status: entry.visibility, + events: [], + } +} + +export type MonthAccessResult = + | { + readonly outcome: "allowed" + readonly visible: readonly EntryDocument[] + /** Entries in scope this principal may not see (e.g. another author's drafts). */ + readonly draftsExcludedForPrincipal: number + } + | { readonly outcome: "denied"; readonly code: DenyCode; readonly detail: string } + +/** + * Authorize a month-history read. The timeline-level gate decides first + * (anonymous / unknown scope / no household path are denials for the WHOLE + * view); then per-entry publication-state filtering applies (drafts are + * author-only). Other authors' drafts are INVISIBLE, not an error — the + * count of excluded drafts is disclosed so gap reporting stays honest. + */ +export function monthAccess(principal: Principal, scope: ChildScope, entries: readonly EntryDocument[]): MonthAccessResult { + const timeline = evaluateAccess(principal, { type: "read" }, { kind: "childTimeline", scope }) + if (timeline.outcome === "DENY") { + return { outcome: "denied", code: timeline.code, detail: timeline.detail } + } + const visible = entries.filter( + (entry) => evaluateAccess(principal, { type: "read" }, { kind: "entry", scope, entry: toPolicyEntry(entry) }).outcome === "ALLOW", + ) + return { + outcome: "allowed", + visible, + draftsExcludedForPrincipal: entries.length - visible.length, + } +} + +/** + * Who may file a correction against this entry? Same policy, write action, + * attribution-bound to the authenticated principal. Consequences (pinned by + * tests): any household member may correct a PUBLISHED entry; a DRAFT entry + * is author-only even for writes (DENY_DRAFT_AUTHOR_ONLY); an anonymous + * principal is DENY_ANONYMOUS; claiming someone else's authorship is + * DENY_ATTRIBUTION_MISMATCH. + */ +export function correctionAccess(principal: Principal, scope: ChildScope, entry: EntryDocument): Decision { + const asAuthorId = principal.kind === "caregiver" ? principal.caregiverId : "" + return evaluateAccess(principal, { type: "write", asAuthorId }, { kind: "entry", scope, entry: toPolicyEntry(entry) }) +} diff --git a/packages/month-history/src/corrections.ts b/packages/month-history/src/corrections.ts new file mode 100644 index 0000000..d333e03 --- /dev/null +++ b/packages/month-history/src/corrections.ts @@ -0,0 +1,65 @@ +/** + * Append-only correction lineage — PROPOSAL TIER (see CONTRACT-PROPOSAL.md; + * canonical adoption is owned by the contract v0.3 fold and slot 10). + * + * A correction never mutates or deletes the original entry: it is a new, + * attributed record that POINTS at the original and at the correction it + * supersedes. `buildLineage` is a pure projection — input data is treated as + * immutable and is never reordered in place. + */ + +export interface CorrectionRecord { + readonly correctionId: string + /** The entry being corrected. Never removed, never mutated. */ + readonly originalEntryId: string + /** Attributed author of the correction (server-bound to the principal). */ + readonly correctedBy: string + readonly createdAtMs: number + readonly reason?: string + /** Replacement raw text — stored as its own verbatim capture. */ + readonly replacementTranscript: string + /** Chain link: the earlier correction this one supersedes, if any. */ + readonly supersedesCorrectionId?: string +} + +export interface CorrectionLineage { + readonly originalEntryId: string + /** Ordered by (createdAtMs, correctionId) — deterministic under ties. */ + readonly chain: readonly CorrectionRecord[] +} + +export function buildLineage(corrections: readonly CorrectionRecord[]): ReadonlyMap { + const byOriginal = new Map() + for (const correction of corrections) { + const bucket = byOriginal.get(correction.originalEntryId) ?? [] + bucket.push(correction) + byOriginal.set(correction.originalEntryId, bucket) + } + const lineage = new Map() + for (const [originalEntryId, records] of byOriginal) { + // Chain integrity: every supersedesCorrectionId must point at an EARLIER + // correction of the SAME original — an append-only chain, no forks into + // other entries, no forward references. + const seen = new Set() + const ordered = [...records].sort( + (a, b) => a.createdAtMs - b.createdAtMs || (a.correctionId < b.correctionId ? -1 : a.correctionId > b.correctionId ? 1 : 0), + ) + for (const record of ordered) { + const supersedes = record.supersedesCorrectionId + if (supersedes !== undefined && !seen.has(supersedes)) { + throw new Error( + `correction ${record.correctionId} supersedes unknown or out-of-order correction ${supersedes}`, + ) + } + seen.add(record.correctionId) + } + lineage.set(originalEntryId, { originalEntryId, chain: ordered }) + } + return lineage +} + +export function latestCorrection(lineage: CorrectionLineage | undefined): CorrectionRecord | undefined { + const chain = lineage?.chain + if (!chain || chain.length === 0) return undefined + return chain[chain.length - 1] +} diff --git a/packages/month-history/src/fixtures/monthHistory.ts b/packages/month-history/src/fixtures/monthHistory.ts new file mode 100644 index 0000000..b1659f1 --- /dev/null +++ b/packages/month-history/src/fixtures/monthHistory.ts @@ -0,0 +1,310 @@ +/** + * Deterministic synthetic family dataset for the month-history journeys. + * + * All instants are fixed Date.UTC values (never `new Date()`); the household + * zone is America/New_York. Values pinned in tests were verified against + * full-ICU (bun 1.3.14 / node 20) on 2026-09-17: + * - Sep 30 2026 23:50 EDT = 1790826600000 -> local date 2026-09-30 + * - Oct 1 2026 00:10 EDT = 1790827800000 -> local date 2026-10-01 + * - Nov 1 2026 01:30 EDT = 1793511000000 and 01:30 EST = 1793514600000 + * BOTH map to local date 2026-11-01 (DST fall-back hour repeats) + * - Sep 2026 in NY spans 720h; Oct 744h; Nov 721h (fall-back) + * - instant 1790802000000 is 2026-10-01 in Asia/Kolkata but 2026-09-30 in NY + * + * The dataset is a CONTRACT fixture: entries/events are shaped as canonical + * domain documents and tests decode them through EntryDocument/EventDocument + * schemas before any view is built. + */ +import type { EntryDocument, EventDocument } from "@journal/domain" +import type { CorrectionRecord } from "../corrections.js" + +export const HOUSEHOLD_ZONE = "America/New_York" +export const HOUSEHOLD_ID = "hh_month_fixture_0000000000000000" +export const CHILD_ID = "ch_month_fixture_0000000000000000" + +export const MOM = "cg_mom" +export const DAD = "cg_dad" +export const ANA = "cg_ana" +export const AUTHORS: Readonly> = { [MOM]: "Mom", [DAD]: "Dad", [ANA]: "Ana" } + +// --- Fixed instants (September 2026, the sparse retrieval month) ---------- +export const SEP2_TOWER_CAPTURE = Date.UTC(2026, 8, 2, 22, 30, 0) // Sep 2, 6:30 PM EDT +export const SEP2_POTTY_1 = Date.UTC(2026, 8, 2, 19, 0, 0) // 3:00 PM EDT +export const SEP2_POTTY_2 = Date.UTC(2026, 8, 2, 20, 30, 0) // 4:30 PM EDT +export const SEP2_MILESTONE = Date.UTC(2026, 8, 2, 21, 45, 0) // 5:45 PM EDT +export const SEP12_NAP_CARE = Date.UTC(2026, 8, 12, 14, 0, 0) // 10:00 AM EDT (care date) +export const SEP20_LATE_CAPTURE = Date.UTC(2026, 8, 20, 12, 14, 0) // 8:14 AM EDT (capture date) +export const SEP20_FAILED_CAPTURE = Date.UTC(2026, 8, 21, 0, 5, 0) // Sep 20, 8:05 PM EDT +export const SEP25_DRAFT_CAPTURE = Date.UTC(2026, 8, 25, 21, 0, 0) // 5:00 PM EDT +export const SEP25_MOOD = Date.UTC(2026, 8, 25, 20, 30, 0) // 4:30 PM EDT +export const SEP26_DRAFT_CAPTURE = Date.UTC(2026, 8, 26, 13, 0, 0) // 9:00 AM EDT +export const SEP27_CORRECTION = Date.UTC(2026, 8, 27, 14, 0, 0) // 10:00 AM EDT + +// Month-boundary pair (NY): Sep 30 23:50 EDT vs Oct 1 00:10 EDT. +export const SEP30_2350_EVENT = 1790826600000 +export const OCT1_0010_EVENT = 1790827800000 + +// DST fall-back pair (NY): both are local 1:30 AM on Nov 1, 2026. +export const NOV1_0130_EDT = 1793511000000 +export const NOV1_0130_EST = 1793514600000 + +const ENTRY_TOWER_ID = "en_sep02_tower" +const ENTRY_NAP_LATE_ID = "en_sep12_nap_late" +const ENTRY_FAILED_ID = "en_sep20_failed" +const ENTRY_DRAFT_MOM_ID = "en_sep25_draft_mom" +const ENTRY_DRAFT_ANA_ID = "en_sep26_draft_ana" +const ENTRY_SEP30_BOUNDARY_ID = "en_sep30_boundary" +const ENTRY_OCT1_BOUNDARY_ID = "en_oct01_boundary" +const ENTRY_DST_ID = "en_nov01_dst" + +export const ORIGINAL_TOWER_TRANSCRIPT = + "Big day at preschool — Lena built a block tower taller than her. Two potty successes before pickup." +export const CORRECTED_TOWER_TRANSCRIPT = + "Lena built a 12-block tower at preschool today. Two potty successes before pickup." + +export const ENTRIES: readonly EntryDocument[] = [ + { + _id: ENTRY_TOWER_ID, + _creationTime: SEP2_TOWER_CAPTURE, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: MOM, + rawTranscript: ORIGINAL_TOWER_TRANSCRIPT, + structuredEventIds: ["ev_sep02_potty_1", "ev_sep02_potty_2", "ev_sep02_milestone"], + extractionStatus: "structured", + visibility: "published", + createdAt: SEP2_TOWER_CAPTURE, + }, + { + // LATE ENTRY: care happened Sep 12, captured Sep 20. The event belongs to + // Sep 12; the capture metadata travels with the card. + _id: ENTRY_NAP_LATE_ID, + _creationTime: SEP20_LATE_CAPTURE, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: MOM, + rawTranscript: "She napped 45 minutes after lunch on the 12th — forgot to log it.", + structuredEventIds: ["ev_sep12_nap"], + extractionStatus: "structured", + visibility: "published", + createdAt: SEP20_LATE_CAPTURE, + }, + { + // FAILED EXTRACTION: capture is never blocked; no structured events exist + // and the raw note must still surface on the capture day. + _id: ENTRY_FAILED_ID, + _creationTime: SEP20_FAILED_CAPTURE, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: DAD, + rawTranscript: "She napped 45 minutes after lunch.", + structuredEventIds: [], + extractionStatus: "failed", + visibility: "published", + createdAt: SEP20_FAILED_CAPTURE, + }, + { + // MOM'S DRAFT: visible to Mom only (author-only), even though extracted. + _id: ENTRY_DRAFT_MOM_ID, + _creationTime: SEP25_DRAFT_CAPTURE, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: MOM, + rawTranscript: "She seemed off after dinner — watching for a temperature tonight.", + structuredEventIds: ["ev_sep25_mood"], + extractionStatus: "structured", + visibility: "draft", + createdAt: SEP25_DRAFT_CAPTURE, + }, + { + // ANA'S DRAFT: invisible to both parents until published. + _id: ENTRY_DRAFT_ANA_ID, + _creationTime: SEP26_DRAFT_CAPTURE, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: ANA, + rawTranscript: "Morning walk to the corner library — pointed at every duck sticker.", + structuredEventIds: [], + extractionStatus: "pending", + visibility: "draft", + createdAt: SEP26_DRAFT_CAPTURE, + }, + { + // TIMEZONE BOUNDARY: care at 23:50 EDT on Sep 30 — NOT in the NY October + // view, but inside a Kolkata-October view of the same data. + _id: ENTRY_SEP30_BOUNDARY_ID, + _creationTime: SEP30_2350_EVENT, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: MOM, + rawTranscript: "One last potty before bed, right at the wire.", + structuredEventIds: ["ev_sep30_potty"], + extractionStatus: "structured", + visibility: "published", + createdAt: SEP30_2350_EVENT, + }, + { + // TIMEZONE BOUNDARY: care at 00:10 EDT on Oct 1 — the first minute of the + // NY October view. + _id: ENTRY_OCT1_BOUNDARY_ID, + _creationTime: OCT1_0010_EVENT, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: MOM, + rawTranscript: "Midnight snack raid — half a banana and all the cheerios.", + structuredEventIds: ["ev_oct01_meal"], + extractionStatus: "structured", + visibility: "published", + createdAt: OCT1_0010_EVENT, + }, + { + // DST FALL-BACK: two sleep events, both at local 1:30 AM on Nov 1 2026 — + // the wall-clock hour that happens twice. Both stay on Nov 1. + _id: ENTRY_DST_ID, + _creationTime: NOV1_0130_EDT, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: DAD, + rawTranscript: "Asleep again by 1:30 — before and after the clocks fell back.", + structuredEventIds: ["ev_nov01_sleep_edt", "ev_nov01_sleep_est"], + extractionStatus: "structured", + visibility: "published", + createdAt: NOV1_0130_EDT, + }, +] + +export const EVENTS: readonly EventDocument[] = [ + { + _id: "ev_sep02_potty_1", + _creationTime: SEP2_POTTY_1, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "potty", + timestamp: SEP2_POTTY_1, + confidence: 0.93, + }, + { + _id: "ev_sep02_potty_2", + _creationTime: SEP2_POTTY_2, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "potty", + timestamp: SEP2_POTTY_2, + confidence: 0.91, + }, + { + _id: "ev_sep02_milestone", + _creationTime: SEP2_MILESTONE, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "milestone", + timestamp: SEP2_MILESTONE, + confidence: 0.88, + }, + { + _id: "ev_sep12_nap", + _creationTime: SEP20_LATE_CAPTURE, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "sleep", + timestamp: SEP12_NAP_CARE, + payload: { minutes: 45 }, + confidence: 0.95, + }, + { + _id: "ev_sep25_mood", + _creationTime: SEP25_MOOD, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "mood", + timestamp: SEP25_MOOD, + confidence: 0.8, + }, + { + _id: "ev_sep30_potty", + _creationTime: SEP30_2350_EVENT, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "potty", + timestamp: SEP30_2350_EVENT, + confidence: 0.9, + }, + { + _id: "ev_oct01_meal", + _creationTime: OCT1_0010_EVENT, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "meal", + timestamp: OCT1_0010_EVENT, + confidence: 0.9, + }, + { + _id: "ev_nov01_sleep_edt", + _creationTime: NOV1_0130_EDT, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "sleep", + timestamp: NOV1_0130_EDT, + payload: { minutes: 30 }, + confidence: 0.85, + }, + { + _id: "ev_nov01_sleep_est", + _creationTime: NOV1_0130_EST, + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + category: "sleep", + timestamp: NOV1_0130_EST, + payload: { minutes: 90 }, + confidence: 0.85, + }, +] + +/** + * Dad corrects Mom's published entry (Sep 2): append-only, attributed, + * original preserved. A second correction supersedes the first in the + * lineage-chain test (not part of the default CORRECTIONS fixture). + */ +export const CORRECTIONS: readonly CorrectionRecord[] = [ + { + correctionId: "co_sep02_dad_1", + originalEntryId: ENTRY_TOWER_ID, + correctedBy: DAD, + createdAtMs: SEP27_CORRECTION, + reason: "Tower was 12 blocks — not taller than her. Grandpa exaggeration.", + replacementTranscript: CORRECTED_TOWER_TRANSCRIPT, + }, +] + +export const MONTH_FIXTURE = { + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + zone: HOUSEHOLD_ZONE, + entries: ENTRIES, + events: EVENTS, + corrections: CORRECTIONS, + authors: AUTHORS, +} as const + +export const ENTRY_IDS = { + tower: ENTRY_TOWER_ID, + napLate: ENTRY_NAP_LATE_ID, + failed: ENTRY_FAILED_ID, + draftMom: ENTRY_DRAFT_MOM_ID, + draftAna: ENTRY_DRAFT_ANA_ID, + sep30Boundary: ENTRY_SEP30_BOUNDARY_ID, + oct1Boundary: ENTRY_OCT1_BOUNDARY_ID, + dst: ENTRY_DST_ID, +} as const + +export const EVENT_IDS = { + potty1: "ev_sep02_potty_1", + potty2: "ev_sep02_potty_2", + milestone: "ev_sep02_milestone", + napLate: "ev_sep12_nap", + moodDraft: "ev_sep25_mood", + sep30Boundary: "ev_sep30_potty", + oct1Boundary: "ev_oct01_meal", + sleepEdt: "ev_nov01_sleep_edt", + sleepEst: "ev_nov01_sleep_est", +} as const diff --git a/packages/month-history/src/handoff.ts b/packages/month-history/src/handoff.ts new file mode 100644 index 0000000..a2ca8d6 --- /dev/null +++ b/packages/month-history/src/handoff.ts @@ -0,0 +1,113 @@ +/** + * Source-linked caregiver handoff digest — deterministic projection of a + * receiver-authorized month view. The digest is built from the RECEIVER'S + * view (run monthAccess for the receiving principal first): it can only ever + * contain what the receiver may see, and it DISCLOSES what was excluded + * (draft counts — never content) plus every day with nothing recorded. + */ +import type { EventCategory } from "@journal/domain" +import { GAP_DISCLAIMER } from "./a11y.js" +import type { MonthHistoryView } from "./types.js" + +const CATEGORY_ORDER: readonly EventCategory[] = ["potty", "meal", "sleep", "mood", "milestone", "school"] + +function payloadSummary(payload: Readonly>): string { + return Object.entries(payload) + .map(([key, value]) => (key === "minutes" ? `${value} min` : `${key} ${value}`)) + .join(", ") +} + +/** "2× potty, 1× sleep (45 min)" — canonical category order, view order within. */ +export function daySummary(events: readonly { readonly category: EventCategory; readonly payload?: Readonly> }[]): string { + const parts: string[] = [] + for (const category of CATEGORY_ORDER) { + const forCategory = events.filter((event) => event.category === category) + if (forCategory.length === 0) continue + const payloads = forCategory.filter((event) => event.payload !== undefined).map((event) => payloadSummary(event.payload as Readonly>)) + const payloadPart = payloads.length > 0 ? ` (${payloads.join(", ")})` : "" + parts.push(`${forCategory.length}× ${category}${payloadPart}`) + } + return parts.length > 0 ? parts.join(", ") : "No structured events." +} + +export interface HandoffDigestLine { + readonly dateKey: string + readonly dayLabel: string + readonly summary: string + /** Source entries behind this line — every claim links to its capture. */ + readonly sourceEntryIds: readonly string[] + readonly extractionFailedEntryIds: readonly string[] + readonly correctedEntryIds: readonly string[] + /** Display names of the authors recorded on this day, first-appearance order. */ + readonly authors: readonly string[] +} + +export interface HandoffDigest { + readonly monthKey: string + readonly monthLabel: string + readonly audience: "published-only" + readonly preparedByName?: string + readonly preparedForName?: string + readonly lines: readonly HandoffDigestLine[] + readonly gapDays: readonly string[] + readonly gapStatement: string + /** Drafts the receiver cannot see — disclosed as a count, never as content. */ + readonly excludedDraftCount: number + readonly excludedDraftNote: string + readonly sourceDisclaimer: string +} + +export function buildHandoffDigest( + view: MonthHistoryView, + options: { + readonly preparedByName?: string + readonly preparedForName?: string + /** Drafts in scope the receiving principal cannot see (access adapter's count). */ + readonly excludedDraftCount: number + }, +): HandoffDigest { + const lines: HandoffDigestLine[] = [] + for (const day of view.days) { + if (day.state !== "has-entries") continue + const extractionFailedEntryIds = day.entries.filter((entry) => entry.extractionStatus === "failed").map((entry) => entry.entryId) + let summary = daySummary(day.events) + if (day.events.length === 0) { + summary = `${day.entryCount} ${day.entryCount === 1 ? "note" : "notes"} recorded; no structured events.` + } + if (extractionFailedEntryIds.length > 0) { + summary += ` Extraction failed for ${extractionFailedEntryIds.length === 1 ? "1 note" : `${extractionFailedEntryIds.length} notes`} — raw text preserved.` + } + const authors: string[] = [] + for (const entry of day.entries) { + if (!authors.includes(entry.authorName)) authors.push(entry.authorName) + } + lines.push({ + dateKey: day.dateKey, + dayLabel: day.dayLabel, + summary, + sourceEntryIds: day.entries.map((entry) => entry.entryId), + extractionFailedEntryIds, + correctedEntryIds: day.entries.filter((entry) => entry.corrected).map((entry) => entry.entryId), + authors, + }) + } + const excludedDraftNote = + options.excludedDraftCount === 0 + ? "" + : options.excludedDraftCount === 1 + ? "1 draft entry is not included in this handoff (visible only to its author)." + : `${options.excludedDraftCount} draft entries are not included in this handoff (visible only to their authors).` + return { + monthKey: view.monthKey, + monthLabel: view.monthLabel, + audience: "published-only", + preparedByName: options.preparedByName, + preparedForName: options.preparedForName, + lines, + gapDays: view.gap.gapDays, + gapStatement: view.gap.message, + excludedDraftCount: options.excludedDraftCount, + excludedDraftNote, + sourceDisclaimer: `Every line links to its source entries; raw transcripts are preserved verbatim. ${GAP_DISCLAIMER}`, + } +} diff --git a/packages/month-history/src/index.ts b/packages/month-history/src/index.ts new file mode 100644 index 0000000..ccf0504 --- /dev/null +++ b/packages/month-history/src/index.ts @@ -0,0 +1,91 @@ +/** + * @journal/month-history — deterministic month-history surfaces for the + * Shared Child Journal: timezone-correct bucketing, one-policy + * authorization, append-only corrections, source-linked handoff digests, + * and accessibility contracts, with the three journeys as executable + * checks (src/run.ts + rubric.json). + */ +export { + DAY_CELL_A11Y_HINT, + CORRECTION_INPUT_HINT, + CORRECTION_INPUT_LABEL, + CORRECTION_ORIGINAL_PRESERVED_LABEL, + EXTRACTION_FAILED_LABEL, + FONT_SCALING, + GAP_DISCLAIMER, + LAYOUT_POLICY, + NO_ENTRIES_LABEL, + QUIET_TEXT_INPUT, + captureLabel, + dayCellA11yLabel, + entryA11yLabel, + eventA11yLabel, + lateLabel, + monthHeaderA11yLabel, + previewForLabel, +} from "./a11y.js" +export { + buildLineage, + latestCorrection, + type CorrectionLineage, + type CorrectionRecord, +} from "./corrections.js" +export { + correctionAccess, + monthAccess, + toPolicyEntry, + type ChildScope, + type Decision, + type DenyCode, + type MonthAccessResult, + type Principal, +} from "./access.js" +export { buildHandoffDigest, daySummary, type HandoffDigest, type HandoffDigestLine } from "./handoff.js" +export { + AUTHORS, + CHILD_ID, + CORRECTED_TOWER_TRANSCRIPT, + CORRECTIONS, + DAD, + ENTRIES, + ENTRY_IDS, + EVENTS, + EVENT_IDS, + HOUSEHOLD_ID, + HOUSEHOLD_ZONE, + MOM, + ANA, + MONTH_FIXTURE, + NOV1_0130_EDT, + NOV1_0130_EST, + OCT1_0010_EVENT, + ORIGINAL_TOWER_TRANSCRIPT, + SEP30_2350_EVENT, +} from "./fixtures/monthHistory.js" +export { + LABEL_LOCALE, + fullDayLabel, + isInstantInMonth, + localDateKey, + localDateKeysOfMonth, + localTimeLabel, + monthLabel, + nextMonthKey, + parseMonthKey, + zonedMonthBounds, + type LocalParts, + type ZonedMonthBounds, +} from "./zone.js" +export type { + BuildMonthHistoryInput, + CorrectionLineageView, + DayCellView, + EntryCardView, + EntryViewInput, + EventCardView, + EventViewInput, + MonthGapStatement, + MonthHistoryView, +} from "./types.js" +export { buildMonthHistoryView, entryViewInputFromDocument, eventViewInputFromDocument } from "./view.js" +export { JOURNEY_CHECKS, buildAuthorizedView, type CheckOutcome, type JourneyCheck, type JourneyKind } from "./journeys.js" diff --git a/packages/month-history/src/journeys.ts b/packages/month-history/src/journeys.ts new file mode 100644 index 0000000..2885c3f --- /dev/null +++ b/packages/month-history/src/journeys.ts @@ -0,0 +1,608 @@ +/** + * The three month-history journeys as EXECUTABLE checks. Each check is a + * deterministic claim about what a parent or invited caregiver can retrieve, + * correct, or hand off — pinned to exact strings and counts. run.ts executes + * these and validates rubric.json coverage; the bun test suite pins the same + * behavior at unit granularity. + * + * Journeys (synthetic family: Mom, Dad, and invited caregiver Ana): + * - parent-retrieval (J1) Mom retrieves September 2026 — a sparse month with + * a late entry, a failed extraction, two drafts, a correction, and month/ + * DST/timezone boundary cases; large-text, screen-reader and quiet-input + * contracts are part of the same retrieval surface. + * - parent-correction (J2) Dad corrects Mom's published entry; the original + * is preserved; drafts and attribution are protected by the one shared + * fail-closed policy. + * - caregiver-handoff (J3) Mom prepares a September handoff digest for Dad; + * it contains only what Dad may see, discloses excluded drafts as counts + * (never content), links every line to sources, and lists every day with + * nothing recorded. + */ +import { evaluateAccess } from "../../../security/access/policy" +import { + CORRECTION_ORIGINAL_PRESERVED_LABEL, + DAY_CELL_A11Y_HINT, + EXTRACTION_FAILED_LABEL, + FONT_SCALING, + GAP_DISCLAIMER, + LAYOUT_POLICY, + QUIET_TEXT_INPUT, +} from "./a11y.js" +import { correctionAccess, monthAccess, toPolicyEntry, type ChildScope, type MonthAccessResult, type Principal } from "./access.js" +import { + AUTHORS, + CHILD_ID, + CORRECTED_TOWER_TRANSCRIPT, + CORRECTIONS, + DAD, + ENTRIES, + ENTRY_IDS, + EVENT_IDS, + EVENTS, + HOUSEHOLD_ID, + HOUSEHOLD_ZONE, + MOM, + ORIGINAL_TOWER_TRANSCRIPT, + SEP27_CORRECTION, +} from "./fixtures/monthHistory.js" +import { buildLineage as buildLineageFrom, type CorrectionRecord } from "./corrections.js" +import { buildHandoffDigest } from "./handoff.js" +import type { DayCellView, MonthHistoryView } from "./types.js" +import { buildMonthHistoryView, entryViewInputFromDocument, eventViewInputFromDocument } from "./view.js" + +export type JourneyKind = "parent-retrieval" | "parent-correction" | "caregiver-handoff" + +export interface CheckOutcome { + readonly ok: boolean + readonly detail: string +} + +export interface JourneyCheck { + readonly id: string + readonly journey: JourneyKind + readonly claim: string + readonly run: () => CheckOutcome +} + +const check = (ok: boolean, detail: string): CheckOutcome => ({ ok, detail }) +const eq = (actual: T, expected: T, label: string): CheckOutcome => + check( + JSON.stringify(actual) === JSON.stringify(expected), + `${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`, + ) + +// --- Shared deterministic projections --------------------------------------- + +const SCOPE: ChildScope = { childId: CHILD_ID, householdId: HOUSEHOLD_ID } +const MOM_PRINCIPAL: Principal = { kind: "caregiver", caregiverId: MOM, householdIds: [HOUSEHOLD_ID] } +const DAD_PRINCIPAL: Principal = { kind: "caregiver", caregiverId: DAD, householdIds: [HOUSEHOLD_ID] } +const ANA_PRINCIPAL: Principal = { kind: "caregiver", caregiverId: "cg_ana", householdIds: [HOUSEHOLD_ID] } +const OUTSIDER_PRINCIPAL: Principal = { kind: "caregiver", caregiverId: "cg_outsider", householdIds: [] } +const ANON_PRINCIPAL: Principal = { kind: "anonymous" } + +/** Pristine-dataset fingerprint, captured BEFORE any projection runs. */ +const DATASET_SNAPSHOT = JSON.stringify({ entries: ENTRIES, events: EVENTS }) + +const SCOPE_ENTRIES = ENTRIES.map(entryViewInputFromDocument) +const ALL_EVENTS = EVENTS.map(eventViewInputFromDocument) + +export function buildAuthorizedView( + principal: Principal, + monthKey: string, + timeZone: string, + corrections: readonly CorrectionRecord[] = CORRECTIONS, +): { readonly access: MonthAccessResult; readonly view: MonthHistoryView } { + const access = monthAccess(principal, SCOPE, ENTRIES) + if (access.outcome !== "allowed") { + return { + access, + view: buildMonthHistoryView({ monthKey, timeZone, entries: [], events: [], corrections, authors: AUTHORS, scopeEntries: SCOPE_ENTRIES }), + } + } + return { + access, + view: buildMonthHistoryView({ + monthKey, + timeZone, + entries: access.visible.map(entryViewInputFromDocument), + events: ALL_EVENTS, + corrections, + authors: AUTHORS, + scopeEntries: SCOPE_ENTRIES, + }), + } +} + +const MOM_SEP = buildAuthorizedView(MOM_PRINCIPAL, "2026-09", HOUSEHOLD_ZONE) +const DAD_SEP = buildAuthorizedView(DAD_PRINCIPAL, "2026-09", HOUSEHOLD_ZONE) +const MOM_OCT_NY = buildAuthorizedView(MOM_PRINCIPAL, "2026-10", "America/New_York") +const MOM_OCT_IST = buildAuthorizedView(MOM_PRINCIPAL, "2026-10", "Asia/Kolkata") +const MOM_NOV_NY = buildAuthorizedView(MOM_PRINCIPAL, "2026-11", HOUSEHOLD_ZONE) + +const EMPTY_SEP = buildMonthHistoryView({ monthKey: "2026-09", timeZone: HOUSEHOLD_ZONE, entries: [], events: [], authors: AUTHORS }) + +const DAD_HANDOFF = buildHandoffDigest(DAD_SEP.view, { + preparedByName: "Mom", + preparedForName: "Dad", + excludedDraftCount: DAD_SEP.access.outcome === "allowed" ? DAD_SEP.access.draftsExcludedForPrincipal : 0, +}) + +function dayOf(view: MonthHistoryView, dateKey: string): DayCellView { + const day = view.days.find((candidate) => candidate.dateKey === dateKey) + if (!day) throw new Error(`view ${view.monthKey}/${view.timeZone} has no day ${dateKey}`) + return day +} + +const towerEntry = ENTRIES.find((entry) => entry._id === ENTRY_IDS.tower) +const momDraftEntry = ENTRIES.find((entry) => entry._id === ENTRY_IDS.draftMom) +if (!towerEntry || !momDraftEntry) throw new Error("fixture dataset is missing pinned entries") + +// Two-step correction chain (MOM then DAD), deliberately listed out of order +// to prove lineage ordering is deterministic. +const CHAIN_CORRECTIONS: readonly CorrectionRecord[] = [ + { + correctionId: "co_chain_2", + originalEntryId: ENTRY_IDS.tower, + correctedBy: DAD, + createdAtMs: SEP27_CORRECTION + 60_000, + replacementTranscript: "Second correction pass.", + supersedesCorrectionId: "co_chain_1", + }, + { + correctionId: "co_chain_1", + originalEntryId: ENTRY_IDS.tower, + correctedBy: MOM, + createdAtMs: SEP27_CORRECTION, + replacementTranscript: "First correction pass.", + }, +] + +// --- J1: parent-retrieval ---------------------------------------------------- + +const J1_CHECKS: readonly JourneyCheck[] = [ + { + id: "J1-A1", + journey: "parent-retrieval", + claim: "Household member passes the fail-closed timeline gate for the month view", + run: () => check(MOM_SEP.access.outcome === "allowed", `momAccess.outcome: ${MOM_SEP.access.outcome}`), + }, + { + id: "J1-A2", + journey: "parent-retrieval", + claim: "Sparse month: 30 explicit day cells, 25 gap days, honest gap copy and totals", + run: () => { + const view = MOM_SEP.view + const ok = + view.days.length === 30 && + view.gap.kind === "gaps" && + view.gap.gapDays.length === 25 && + view.gap.message === "25 of 30 days have no entries recorded. Gaps in the journal are not evidence about care." && + view.totalEntries === 5 && + view.totalEvents === 6 && + view.lateEvents === 1 && + view.correctedEntries === 1 && + view.orphanEventCount === 0 + return check( + ok, + `days=${view.days.length} gapDays=${view.gap.gapDays.length} kind=${view.gap.kind} entries=${view.totalEntries} events=${view.totalEvents} late=${view.lateEvents} corrected=${view.correctedEntries} orphans=${view.orphanEventCount} message="${view.gap.message}"`, + ) + }, + }, + { + id: "J1-A3", + journey: "parent-retrieval", + claim: "Late entry lands on the CARE day (Sep 12) with explicit capture attribution", + run: () => { + const day = dayOf(MOM_SEP.view, "2026-09-12") + const event = day.events[0] + if (!event) return check(false, "Sep 12 has no event card") + return check( + day.state === "has-entries" && + event.eventId === EVENT_IDS.napLate && + event.isLate === true && + event.localTimeLabel === "10:00 AM" && + event.captureDateKey === "2026-09-20" && + event.lateLabel === "Recorded Sunday, September 20, 2026 — about Saturday, September 12, 2026" && + event.captureLabel === "Captured Sunday, September 20, 2026 at 8:14 AM" && + event.authorName === "Mom" && + event.a11yLabel === + "sleep, 10:00 AM, recorded by Mom. Captured Sunday, September 20, 2026 at 8:14 AM.", + `day=${day.dateKey} state=${day.state} isLate=${event.isLate} lateLabel="${String(event.lateLabel)}" a11y="${event.a11yLabel}"`, + ) + }, + }, + { + id: "J1-A4", + journey: "parent-retrieval", + claim: "Failed extraction still surfaces on the capture day — raw note preserved, never blocked", + run: () => { + const day = dayOf(MOM_SEP.view, "2026-09-20") + const entry = day.entries[0] + if (!entry) return check(false, "Sep 20 has no entry card") + return check( + day.state === "has-entries" && + entry.entryId === ENTRY_IDS.failed && + entry.extractionStatus === "failed" && + entry.extractionStatusLabel === EXTRACTION_FAILED_LABEL && + entry.transcript === "She napped 45 minutes after lunch." && + day.events.length === 0, + `state=${day.state} status=${entry.extractionStatus} label="${String(entry.extractionStatusLabel)}" transcript="${entry.transcript}"`, + ) + }, + }, + { + id: "J1-A5", + journey: "parent-retrieval", + claim: "Gap-day copy says 'No entries recorded' and NEVER implies no care happened", + run: () => { + const day = dayOf(MOM_SEP.view, "2026-09-03") + return check( + day.state === "no-entries" && + day.a11yLabel === "Thursday, September 3, 2026. No entries recorded." && + MOM_SEP.view.gap.disclaimer === GAP_DISCLAIMER, + `label="${day.a11yLabel}" disclaimer="${MOM_SEP.view.gap.disclaimer}"`, + ) + }, + }, + { + id: "J1-A6", + journey: "parent-retrieval", + claim: "Draft isolation: Mom sees her own draft (and its event), never Ana's", + run: () => { + const momDraftDay = dayOf(MOM_SEP.view, "2026-09-25") + const anaDraftDay = dayOf(MOM_SEP.view, "2026-09-26") + const entry = momDraftDay.entries[0] + return check( + momDraftDay.state === "has-entries" && + entry?.entryId === ENTRY_IDS.draftMom && + entry?.visibility === "draft" && + momDraftDay.events[0]?.eventId === EVENT_IDS.moodDraft && + anaDraftDay.state === "no-entries", + `sep25=${momDraftDay.state}(${String(entry?.entryId)}) sep26=${anaDraftDay.state}`, + ) + }, + }, + { + id: "J1-A7a", + journey: "parent-retrieval", + claim: "Month boundary: 23:50 EDT stays in NY September, OUT of NY October, IN Kolkata October", + run: () => { + const view = MOM_OCT_NY.view + const allEvents = view.days.flatMap((day) => day.events) + const sep30 = dayOf(MOM_SEP.view, "2026-09-30") + const sep30Ok = + sep30.events.length === 1 && + sep30.events[0]?.eventId === EVENT_IDS.sep30Boundary && + sep30.entries[0]?.entryId === ENTRY_IDS.sep30Boundary + return check( + view.days.length === 31 && + view.days[0]?.dateKey === "2026-10-01" && + view.totalEvents === 1 && + allEvents.some((event) => event.eventId === EVENT_IDS.oct1Boundary) && + allViewsNoEvent(allEvents, EVENT_IDS.sep30Boundary) && + sep30Ok, + `octDays=${view.days.length} octEvents=${view.totalEvents} sep30HasBoundaryEvent=${sep30.events.length === 1} sep30HasBoundaryEntry=${sep30.entries[0]?.entryId === ENTRY_IDS.sep30Boundary}`, + ) + }, + }, + { + id: "J1-A7b", + journey: "parent-retrieval", + claim: "Timezone dependence: the SAME instant sits inside a Kolkata-October view", + run: () => { + const view = MOM_OCT_IST.view + const oct1 = dayOf(view, "2026-10-01") + const eventIds = oct1.events.map((event) => event.eventId) + return check( + view.days.length === 31 && view.totalEvents === 2 && eventIds.length === 2 && eventIds.includes(EVENT_IDS.sep30Boundary) && eventIds.includes(EVENT_IDS.oct1Boundary), + `days=${view.days.length} totalEvents=${view.totalEvents} oct1=[${eventIds.join(", ")}]`, + ) + }, + }, + { + id: "J1-A8", + journey: "parent-retrieval", + claim: "DST fall-back: both 1:30 AM events stay on Nov 1; the month is 721 hours long", + run: () => { + const view = MOM_NOV_NY.view + const day = dayOf(view, "2026-11-01") + const [first, second] = day.events + const hourSpan = view.bounds.endMsExclusive - view.bounds.startMs + return check( + day.events.length === 2 && + first?.localTimeLabel === "1:30 AM" && + second?.localTimeLabel === "1:30 AM" && + first?.eventId === EVENT_IDS.sleepEdt && + second?.eventId === EVENT_IDS.sleepEst && + first?.localDateKey === "2026-11-01" && + second?.localDateKey === "2026-11-01" && + hourSpan === 721 * 60 * 60_000 && + view.days.length === 30, + `events=${day.events.length} labels=[${String(first?.localTimeLabel)}, ${String(second?.localTimeLabel)}] hours=${hourSpan / (60 * 60_000)} days=${view.days.length}`, + ) + }, + }, + { + id: "J1-A9", + journey: "parent-retrieval", + claim: "Corrected entry shows the corrected text WITH lineage: who, when, reason, original preserved", + run: () => { + const day = dayOf(MOM_SEP.view, "2026-09-02") + const entry = day.entries[0] + if (!entry) return check(false, "Sep 2 has no entry card") + const step = entry.correctionLineage?.steps[0] + return check( + entry.corrected === true && + entry.transcript === CORRECTED_TOWER_TRANSCRIPT && + step?.byName === "Dad" && + step?.createdAtLabel === "Sunday, September 27, 2026 at 10:00 AM" && + typeof step?.reason === "string" && + step.reason.length > 0 && + entry.correctionLineage?.originalPreservedLabel === CORRECTION_ORIGINAL_PRESERVED_LABEL, + `corrected=${entry.corrected} by=${String(step?.byName)} when="${String(step?.createdAtLabel)}"`, + ) + }, + }, + { + id: "J1-A10", + journey: "parent-retrieval", + claim: "Raw capture preserved byte-for-byte in the dataset — projections never mutate it", + run: () => + check( + towerEntry.rawTranscript === ORIGINAL_TOWER_TRANSCRIPT && + JSON.stringify({ entries: ENTRIES, events: EVENTS }) === DATASET_SNAPSHOT, + `towerRawIntact=${towerEntry.rawTranscript === ORIGINAL_TOWER_TRANSCRIPT} datasetUnchanged=${JSON.stringify({ entries: ENTRIES, events: EVENTS }) === DATASET_SNAPSHOT}`, + ), + }, + { + id: "J1-A11", + journey: "parent-retrieval", + claim: "Quiet text input contract: correction fields never mutate or fight the typist", + run: () => + eq( + { ...QUIET_TEXT_INPUT }, + { + autoCorrect: false, + autoCapitalize: "none", + spellCheck: false, + autoFocus: false, + keyboardType: "default", + multiline: true, + blurOnSubmit: false, + textContentType: "none", + }, + "QUIET_TEXT_INPUT", + ), + }, + { + id: "J1-A12", + journey: "parent-retrieval", + claim: "Large text: body font scaling uncapped, chrome capped at 1.5, no fixed heights, no truncation", + run: () => + check( + FONT_SCALING.body.allowFontScaling === true && + FONT_SCALING.body.maxFontSizeMultiplier === null && + FONT_SCALING.chrome.allowFontScaling === true && + FONT_SCALING.chrome.maxFontSizeMultiplier === 1.5 && + LAYOUT_POLICY.fixedHeightsOnTextRows === false && + LAYOUT_POLICY.truncatesEntryText === false && + LAYOUT_POLICY.expandAffordanceLabel === "Show full text", + `body=${JSON.stringify(FONT_SCALING.body)} chrome=${JSON.stringify(FONT_SCALING.chrome)} layout=${JSON.stringify(LAYOUT_POLICY)}`, + ), + }, + { + id: "J1-A13", + journey: "parent-retrieval", + claim: "Every day cell exposes role=button, a hint, and a screen-reader label; month header labeled", + run: () => { + const structural = MOM_SEP.view.days.every( + (day) => day.a11yRole === "button" && day.a11yHint === DAY_CELL_A11Y_HINT && day.a11yLabel.length > 0, + ) + return check(structural && MOM_SEP.view.headerA11yLabel === "Month history: September 2026", `header="${MOM_SEP.view.headerA11yLabel}" allDaysLabeled=${structural}`) + }, + }, + { + id: "J1-A14", + journey: "parent-retrieval", + claim: "Empty month says 'no entries were recorded' + disclaimer — never 'no care'", + run: () => + check( + EMPTY_SEP.gap.kind === "empty-month" && + EMPTY_SEP.gap.message === `No entries were recorded this month. ${GAP_DISCLAIMER}` && + EMPTY_SEP.gap.gapDays.length === 30 && + EMPTY_SEP.totalEntries === 0, + `message="${EMPTY_SEP.gap.message}" gapDays=${EMPTY_SEP.gap.gapDays.length}`, + ), + }, +] + +// --- J2: parent-correction --------------------------------------------------- + +const J2_CHECKS: readonly JourneyCheck[] = [ + { + id: "J2-B1", + journey: "parent-correction", + claim: "Household member may correct a PUBLISHED entry (shared policy, write action)", + run: () => check(correctionAccess(DAD_PRINCIPAL, SCOPE, towerEntry).outcome === "ALLOW", `dadCorrection=${correctionAccess(DAD_PRINCIPAL, SCOPE, towerEntry).outcome}`), + }, + { + id: "J2-B2", + journey: "parent-correction", + claim: "Lineage is append-only and deterministic: sorted chain, supersedes must be ordered", + run: () => { + const lineage = buildLineageFrom(CHAIN_CORRECTIONS) + const chain = lineage.get(ENTRY_IDS.tower)?.chain ?? [] + return check( + chain.length === 2 && chain[0]?.correctionId === "co_chain_1" && chain[1]?.correctionId === "co_chain_2", + `chain=[${chain.map((c) => c.correctionId).join(", ")}]`, + ) + }, + }, + { + id: "J2-B3", + journey: "parent-correction", + claim: "Correction is disclosed to screen readers: on the entry and every event of it", + run: () => { + const day = dayOf(MOM_SEP.view, "2026-09-02") + const entry = day.entries[0] + return check( + typeof entry?.a11yLabel === "string" && + entry.a11yLabel.includes("Corrected entry.") && + day.events.every((event) => event.a11yLabel.includes("Includes a correction.")), + `entryA11y="${String(entry?.a11yLabel)}"`, + ) + }, + }, + { + id: "J2-B4", + journey: "parent-correction", + claim: "Drafts are author-only even for corrections; anonymous principals are denied outright", + run: () => { + const anaOnMomsDraft = correctionAccess(ANA_PRINCIPAL, SCOPE, momDraftEntry) + const anonOnPublished = correctionAccess(ANON_PRINCIPAL, SCOPE, towerEntry) + const momOwnDraft = correctionAccess(MOM_PRINCIPAL, SCOPE, momDraftEntry) + return check( + anaOnMomsDraft.outcome === "DENY" && + anaOnMomsDraft.code === "DENY_DRAFT_AUTHOR_ONLY" && + anonOnPublished.outcome === "DENY" && + anonOnPublished.code === "DENY_ANONYMOUS" && + momOwnDraft.outcome === "ALLOW", + `ana=${anaOnMomsDraft.outcome === "DENY" ? anaOnMomsDraft.code : "ALLOW"} anon=${anonOnPublished.outcome === "DENY" ? anonOnPublished.code : "ALLOW"} mom=${momOwnDraft.outcome}`, + ) + }, + }, + { + id: "J2-B5", + journey: "parent-correction", + claim: "Attribution is server-bound: a write claiming another author's id is denied", + run: () => { + const decision = evaluateAccess(DAD_PRINCIPAL, { type: "write", asAuthorId: MOM }, { kind: "entry", scope: SCOPE, entry: toPolicyEntry(towerEntry) }) + return check(decision.outcome === "DENY" && decision.code === "DENY_ATTRIBUTION_MISMATCH", `decision=${decision.outcome}${decision.outcome === "DENY" ? `/${decision.code}` : ""}`) + }, + }, + { + id: "J2-B6", + journey: "parent-correction", + claim: "Non-member is denied the whole month view at the timeline gate (fail-closed)", + run: () => { + const outsider = monthAccess(OUTSIDER_PRINCIPAL, SCOPE, ENTRIES) + const anon = monthAccess(ANON_PRINCIPAL, SCOPE, ENTRIES) + return check( + outsider.outcome === "denied" && outsider.code === "DENY_NO_HOUSEHOLD_PATH" && anon.outcome === "denied" && anon.code === "DENY_ANONYMOUS", + `outsider=${outsider.outcome === "denied" ? outsider.code : "allowed"} anon=${anon.outcome === "denied" ? anon.code : "allowed"}`, + ) + }, + }, +] + +// --- J3: caregiver-handoff --------------------------------------------------- + +const J3_CHECKS: readonly JourneyCheck[] = [ + { + id: "J3-C1", + journey: "caregiver-handoff", + claim: "Handoff is built from the RECEIVER's authorization: published-only for Dad", + run: () => { + const access = DAD_SEP.access + const allPublished = access.outcome === "allowed" && access.visible.every((entry) => entry.visibility === "published") + return check( + access.outcome === "allowed" && + access.visible.length === 6 && + allPublished && + access.draftsExcludedForPrincipal === 2 && + DAD_SEP.view.totalEntries === 4, + `visible=${access.outcome === "allowed" ? access.visible.length : "denied"} allPublished=${allPublished} excluded=${access.outcome === "allowed" ? access.draftsExcludedForPrincipal : "n/a"} sepEntries=${DAD_SEP.view.totalEntries}`, + ) + }, + }, + { + id: "J3-C2", + journey: "caregiver-handoff", + claim: "Digest lines cover exactly the receiver-visible days with deterministic summaries", + run: () => { + const dates = DAD_HANDOFF.lines.map((line) => line.dateKey) + const sep2 = DAD_HANDOFF.lines.find((line) => line.dateKey === "2026-09-02") + const sep12 = DAD_HANDOFF.lines.find((line) => line.dateKey === "2026-09-12") + const sep20 = DAD_HANDOFF.lines.find((line) => line.dateKey === "2026-09-20") + const sep30 = DAD_HANDOFF.lines.find((line) => line.dateKey === "2026-09-30") + return check( + eq(dates, ["2026-09-02", "2026-09-12", "2026-09-20", "2026-09-30"], "dates").ok && + sep2?.summary === "2× potty, 1× milestone" && + sep12?.summary === "1× sleep (45 min)" && + sep20?.summary === "1 note recorded; no structured events. Extraction failed for 1 note — raw text preserved." && + sep30?.summary === "1× potty", + `dates=${JSON.stringify(dates)} sep2="${String(sep2?.summary)}" sep12="${String(sep12?.summary)}" sep30="${String(sep30?.summary)}"`, + ) + }, + }, + { + id: "J3-C3", + journey: "caregiver-handoff", + claim: "Every handoff line is source-linked (no claim without its capture)", + run: () => { + const sep12 = DAD_HANDOFF.lines.find((line) => line.dateKey === "2026-09-12") + return check( + DAD_HANDOFF.lines.every((line) => line.sourceEntryIds.length > 0) && + eq(sep12?.sourceEntryIds, [ENTRY_IDS.napLate], "sep12.sources").ok, + `allLinked=${DAD_HANDOFF.lines.every((line) => line.sourceEntryIds.length > 0)} sep12=${JSON.stringify(sep12?.sourceEntryIds)}`, + ) + }, + }, + { + id: "J3-C4", + journey: "caregiver-handoff", + claim: "Corrections surface in the handoff with attribution to the correcting caregiver", + run: () => { + const sep2 = DAD_HANDOFF.lines.find((line) => line.dateKey === "2026-09-02") + return check( + eq(sep2?.correctedEntryIds, [ENTRY_IDS.tower], "sep2.corrected").ok && sep2?.authors.includes("Mom") === true, + `corrected=${JSON.stringify(sep2?.correctedEntryIds)} authors=${JSON.stringify(sep2?.authors)}`, + ) + }, + }, + { + id: "J3-C5", + journey: "caregiver-handoff", + claim: "Excluded drafts are disclosed as a COUNT, never as content", + run: () => + check( + DAD_HANDOFF.excludedDraftCount === 2 && + DAD_HANDOFF.excludedDraftNote === "2 draft entries are not included in this handoff (visible only to their authors).", + `note="${DAD_HANDOFF.excludedDraftNote}"`, + ), + }, + { + id: "J3-C6", + journey: "caregiver-handoff", + claim: "Gap disclosure: 26 of 30 days have nothing recorded, stated honestly", + run: () => + check( + DAD_HANDOFF.gapDays.length === 26 && + DAD_HANDOFF.gapStatement === "26 of 30 days have no entries recorded. Gaps in the journal are not evidence about care.", + `gapDays=${DAD_HANDOFF.gapDays.length} statement="${DAD_HANDOFF.gapStatement}"`, + ), + }, + { + id: "J3-C7", + journey: "caregiver-handoff", + claim: "Digest carries audience, preparer metadata, and the source-preservation disclaimer", + run: () => + check( + DAD_HANDOFF.audience === "published-only" && + DAD_HANDOFF.preparedByName === "Mom" && + DAD_HANDOFF.preparedForName === "Dad" && + DAD_HANDOFF.sourceDisclaimer === + "Every line links to its source entries; raw transcripts are preserved verbatim. Gaps in the journal are not evidence about care.", + `audience=${DAD_HANDOFF.audience} from=${String(DAD_HANDOFF.preparedByName)} to=${String(DAD_HANDOFF.preparedForName)}`, + ), + }, +] + +function allViewsHasEvent(events: readonly { readonly eventId: string }[], eventId: string): boolean { + return events.some((event) => event.eventId === eventId) +} +function allViewsNoEvent(events: readonly { readonly eventId: string }[], eventId: string): boolean { + return !allViewsHasEvent(events, eventId) +} + +export const JOURNEY_CHECKS: readonly JourneyCheck[] = [...J1_CHECKS, ...J2_CHECKS, ...J3_CHECKS] diff --git a/packages/month-history/src/run.ts b/packages/month-history/src/run.ts new file mode 100644 index 0000000..a473032 --- /dev/null +++ b/packages/month-history/src/run.ts @@ -0,0 +1,62 @@ +/** + * Journey harness: runs every journey check, validates that the machine + * rubric (rubric.json) and the executed checks cover each other, prints a + * per-journey table, and exits non-zero on any failure or coverage gap. + * Deterministic: no clock reads, no randomness, no network. + * + * Usage: + * bun src/run.ts (from packages/month-history) + * pnpm --filter @journal/month-history journeys + */ +import { JOURNEY_CHECKS } from "./journeys.js" +import rubricJson from "../rubric.json" + +interface RubricRow { + readonly id: string + readonly journey: string + readonly criterion: string + readonly measure: string +} +interface RubricFile { + readonly version: string + readonly checks: readonly RubricRow[] +} + +const rubric = rubricJson as RubricFile + +const results = JOURNEY_CHECKS.map((journeyCheck) => ({ + id: journeyCheck.id, + journey: journeyCheck.journey, + claim: journeyCheck.claim, + ...journeyCheck.run(), +})) +const failed = results.filter((result) => !result.ok) + +const rubricIds = new Set(rubric.checks.map((row) => row.id)) +const executedIds = new Set(results.map((result) => result.id)) +const uncovered = rubric.checks.filter((row) => !executedIds.has(row.id)).map((row) => row.id) +const unlisted = results.filter((result) => !rubricIds.has(result.id)).map((result) => result.id) + +const journeys = [...new Set(results.map((result) => result.journey))] +console.log(`\nMonth-history journeys — rubric v${rubric.version}\n`) +for (const journey of journeys) { + const rows = results.filter((result) => result.journey === journey) + const passed = rows.filter((row) => row.ok).length + console.log(`── ${journey} (${passed}/${rows.length})`) + const idWidth = Math.max(...rows.map((row) => row.id.length)) + for (const row of rows) { + console.log(` ${row.ok ? "PASS" : "FAIL"} ${row.id.padEnd(idWidth)} ${row.claim}`) + if (!row.ok) console.log(` ↳ ${row.detail}`) + } + console.log("") +} + +if (failed.length === 0) { + console.log(`All ${results.length} checks passed.`) +} else { + console.log(`FAILURES: ${failed.length} of ${results.length} — ${failed.map((row) => row.id).join(", ")}`) +} +if (uncovered.length > 0) console.log(`RUBRIC ROWS WITHOUT EXECUTING CHECKS: ${uncovered.join(", ")}`) +if (unlisted.length > 0) console.log(`EXECUTED CHECKS MISSING FROM RUBRIC: ${unlisted.join(", ")}`) + +if (failed.length > 0 || uncovered.length > 0 || unlisted.length > 0) process.exit(1) diff --git a/packages/month-history/src/types.ts b/packages/month-history/src/types.ts new file mode 100644 index 0000000..6880f4a --- /dev/null +++ b/packages/month-history/src/types.ts @@ -0,0 +1,152 @@ +/** + * View-model types for the month-history surface. UI-free and renderer-free: + * the React Native prototype (apps/mobile/src/month/MonthHistoryScreen.tsx) + * consumes these values and maps them onto RN accessibility, text-scaling, + * and input props one-to-one. Everything here is data — no effects, no + * clock, no I/O. + */ +import type { EventCategory } from "@journal/domain" +import type { ZonedMonthBounds } from "./zone.js" + +export type EntryVisibilityKind = "draft" | "published" +export type ExtractionStatusKind = "pending" | "structured" | "failed" + +/** Structural input — the canonical source is the domain EntryDocument. */ +export interface EntryViewInput { + readonly entryId: string + readonly householdId: string + readonly childId: string + readonly authorId: string + readonly rawTranscript: string + readonly structuredEventIds: readonly string[] + readonly extractionStatus: ExtractionStatusKind + readonly visibility: EntryVisibilityKind + readonly createdAt: number +} + +/** Structural input — the canonical source is the domain EventDocument. */ +export interface EventViewInput { + readonly eventId: string + readonly householdId: string + readonly childId: string + readonly category: EventCategory + readonly timestamp: number + readonly payload?: Readonly> + readonly confidence: number +} + +export interface EventCardView { + readonly eventId: string + readonly category: EventCategory + readonly occurredAtMs: number + /** Household-zone local date the event belongs to (the bucketing key). */ + readonly localDateKey: string + readonly localTimeLabel: string + readonly payload?: Readonly> + readonly confidence: number + readonly authorId: string + readonly authorName: string + readonly entryId: string + readonly captureDateKey: string + /** "Captured Sunday, September 20, 2026 at 8:14 AM" — always shown. */ + readonly captureLabel: string + /** Entry captured on a later local date than the event's care date. */ + readonly isLate: boolean + /** "Recorded Sunday, September 20, 2026 — about Saturday, September 12, 2026". */ + readonly lateLabel?: string + readonly corrected: boolean + readonly a11yLabel: string +} + +export interface CorrectionStepView { + readonly correctionId: string + readonly byName: string + readonly createdAtMs: number + readonly createdAtLabel: string + readonly reason?: string + readonly supersedesCorrectionId?: string +} + +export interface CorrectionLineageView { + readonly originalEntryId: string + readonly steps: readonly CorrectionStepView[] + readonly latestTranscript: string + /** Always carried by corrected entries — the original is never destroyed. */ + readonly originalPreservedLabel: string +} + +export interface EntryCardView { + readonly entryId: string + readonly authorId: string + readonly authorName: string + readonly visibility: EntryVisibilityKind + /** Verbatim raw transcript (the latest corrected text when a correction applies). */ + readonly transcript: string + readonly captureDateKey: string + readonly captureLabel: string + readonly extractionStatus: ExtractionStatusKind + /** Present when extraction failed — says the raw note is preserved, never blocks. */ + readonly extractionStatusLabel?: string + readonly corrected: boolean + readonly correctionLineage?: CorrectionLineageView + readonly a11yLabel: string +} + +export interface DayCellView { + readonly dateKey: string + readonly dayLabel: string + readonly entryCount: number + readonly eventCount: number + readonly state: "has-entries" | "no-entries" + readonly events: readonly EventCardView[] + readonly entries: readonly EntryCardView[] + readonly a11yLabel: string + readonly a11yRole: "button" + readonly a11yHint: string +} + +export interface MonthGapStatement { + readonly kind: "empty-month" | "gaps" | "no-gaps" + readonly message: string + readonly gapDays: readonly string[] + readonly disclaimer: string +} + +export interface MonthHistoryView { + readonly monthKey: string + readonly timeZone: string + readonly monthLabel: string + readonly headerA11yLabel: string + readonly bounds: ZonedMonthBounds + /** Every calendar day of the month, in order — gap days are explicit cells. */ + readonly days: readonly DayCellView[] + /** Entries the principal can see in this month's scope. */ + readonly totalEntries: number + readonly totalEvents: number + readonly lateEvents: number + readonly correctedEntries: number + /** Events in the month no entry in scope claims — surfaced, never hidden. */ + readonly orphanEventCount: number + readonly gap: MonthGapStatement +} + +export interface BuildMonthHistoryInput { + readonly monthKey: string + /** IANA zone of the household — the bucketing reference, never the viewer's device zone. */ + readonly timeZone: string + /** ALREADY AUTHORIZED entries — run the access filter before building a view. */ + readonly entries: readonly EntryViewInput[] + readonly events: readonly EventViewInput[] + readonly corrections?: readonly CorrectionInput[] + /** authorId → display name ("Mom", "Dad", "Ana"). Unmapped ids fall back to the id. */ + readonly authors: Readonly> + /** + * Every entry in the child's scope, visible or not — the claim universe. + * Events whose claiming entry is in scope but invisible to this principal + * are excluded from the view WITHOUT counting as orphans; orphans are + * events no entry in scope claims. Defaults to the authorized entries. + */ + readonly scopeEntries?: readonly EntryViewInput[] +} + +export type CorrectionInput = import("./corrections.js").CorrectionRecord diff --git a/packages/month-history/src/view.ts b/packages/month-history/src/view.ts new file mode 100644 index 0000000..a643f22 --- /dev/null +++ b/packages/month-history/src/view.ts @@ -0,0 +1,313 @@ +/** + * The month-history view builder: pure projection from authorized data to + * what the month surface shows. Deterministic by construction — no clock + * reads, no ambient state; the same (monthKey, timeZone, data) always + * produces the same view. + * + * Placement rules (pinned by tests): + * - Days are bucketed by the household-zone LOCAL calendar; the view contains + * every calendar day of the month, so gap days are explicit cells. + * - Events belong to the day their care happened (Event.timestamp); entries + * are attributed with capture metadata ("Captured Sep 20 … about Sep 12"). + * - An entry whose extraction produced no events (failed/pending) appears on + * its capture day — capture is never blocked, so its honesty matters. + * - A correction surfaces on the corrected entry's card with full lineage; + * the original text is preserved in the dataset and never destroyed. + */ +import { + A11Y_ROLES, + CORRECTION_ORIGINAL_PRESERVED_LABEL, + DAY_CELL_A11Y_HINT, + EXTRACTION_FAILED_LABEL, + GAP_DISCLAIMER, + captureLabel, + dayCellA11yLabel, + entryA11yLabel, + eventA11yLabel, + lateLabel, + monthHeaderA11yLabel, +} from "./a11y.js" +import { buildLineage, latestCorrection } from "./corrections.js" +import type { + BuildMonthHistoryInput, + CorrectionLineageView, + DayCellView, + EntryCardView, + EntryViewInput, + EventCardView, + EventViewInput, + MonthGapStatement, + MonthHistoryView, +} from "./types.js" +import { fullDayLabel, localDateKey, localDateKeysOfMonth, localTimeLabel, monthLabel, zonedMonthBounds } from "./zone.js" + +export { entryA11yLabel, eventA11yLabel } + +/** Adapt a canonical domain EntryDocument to the view input (field rename only). */ +export function entryViewInputFromDocument(document: { + readonly _id: string + readonly householdId: string + readonly childId: string + readonly authorId: string + readonly rawTranscript: string + readonly structuredEventIds: readonly string[] + readonly extractionStatus: "pending" | "structured" | "failed" + readonly visibility: "draft" | "published" + readonly createdAt: number +}): EntryViewInput { + return { + entryId: document._id, + householdId: document.householdId, + childId: document.childId, + authorId: document.authorId, + rawTranscript: document.rawTranscript, + structuredEventIds: document.structuredEventIds, + extractionStatus: document.extractionStatus, + visibility: document.visibility, + createdAt: document.createdAt, + } +} + +/** Adapt a canonical domain EventDocument to the view input (field rename only). */ +export function eventViewInputFromDocument(document: { + readonly _id: string + readonly householdId: string + readonly childId: string + readonly category: EventViewInput["category"] + readonly timestamp: number + readonly payload?: Readonly> + readonly confidence: number +}): EventViewInput { + return { + eventId: document._id, + householdId: document.householdId, + childId: document.childId, + category: document.category, + timestamp: document.timestamp, + payload: document.payload, + confidence: document.confidence, + } +} + +interface EntryCardCore { + readonly entry: EntryViewInput + readonly corrected: boolean + readonly transcript: string + readonly lineage?: CorrectionLineageView +} + +export function buildMonthHistoryView(input: BuildMonthHistoryInput): MonthHistoryView { + const { monthKey, timeZone } = input + const bounds = zonedMonthBounds(monthKey, timeZone) + const lineage = buildLineage(input.corrections ?? []) + const authorName = (authorId: string): string => input.authors[authorId] ?? authorId + + const entryById = new Map(input.entries.map((entry) => [entry.entryId, entry])) + const entryIdByEventId = new Map() + for (const entry of input.entries) { + for (const eventId of entry.structuredEventIds) entryIdByEventId.set(eventId, entry.entryId) + } + // Claim universe: every entry in scope (visible or not). Events claimed by + // in-scope-but-invisible entries are excluded without counting as orphans. + const scopeEntries = input.scopeEntries ?? input.entries + const scopeClaimedEventIds = new Set(scopeEntries.flatMap((entry) => entry.structuredEventIds)) + + const cardFor = (entry: EntryViewInput): EntryCardCore => { + const lin = lineage.get(entry.entryId) + const latest = latestCorrection(lin) + if (!lin || !latest) return { entry, corrected: false, transcript: entry.rawTranscript } + return { + entry, + corrected: true, + transcript: latest.replacementTranscript, + lineage: { + originalEntryId: entry.entryId, + steps: lin.chain.map((correction) => ({ + correctionId: correction.correctionId, + byName: authorName(correction.correctedBy), + createdAtMs: correction.createdAtMs, + createdAtLabel: `${fullDayLabel(localDateKey(correction.createdAtMs, timeZone))} at ${localTimeLabel(correction.createdAtMs, timeZone)}`, + reason: correction.reason, + supersedesCorrectionId: correction.supersedesCorrectionId, + })), + latestTranscript: latest.replacementTranscript, + originalPreservedLabel: CORRECTION_ORIGINAL_PRESERVED_LABEL, + }, + } + } + + // Events of the month, bucketed by household-zone local date. + const eventsInMonth = input.events + .filter((event) => event.timestamp >= bounds.startMs && event.timestamp < bounds.endMsExclusive) + .sort((a, b) => a.timestamp - b.timestamp || (a.eventId < b.eventId ? -1 : a.eventId > b.eventId ? 1 : 0)) + const eventsByDay = new Map() + let orphanEventCount = 0 + let hiddenEventCount = 0 + for (const event of eventsInMonth) { + if (!scopeClaimedEventIds.has(event.eventId)) orphanEventCount += 1 + else if (!entryIdByEventId.has(event.eventId)) hiddenEventCount += 1 + const key = localDateKey(event.timestamp, timeZone) + const bucket = eventsByDay.get(key) ?? [] + bucket.push(event) + eventsByDay.set(key, bucket) + } + + // Entries with in-month events appear on every day their care happened; + // entries with no in-month events appear on their capture day (if in-month). + const entryDays = new Map>() + for (const event of eventsInMonth) { + const entryId = entryIdByEventId.get(event.eventId) + if (entryId === undefined) continue + const days = entryDays.get(entryId) ?? new Set() + days.add(localDateKey(event.timestamp, timeZone)) + entryDays.set(entryId, days) + } + const dayKeySet = new Set(localDateKeysOfMonth(monthKey, timeZone)) + const entriesByDay = new Map() + const placeEntry = (core: EntryCardCore, dateKey: string): void => { + const bucket = entriesByDay.get(dateKey) ?? [] + if (!bucket.some((existing) => existing.entry.entryId === core.entry.entryId)) bucket.push(core) + entriesByDay.set(dateKey, bucket) + } + for (const entry of input.entries) { + const days = entryDays.get(entry.entryId) + if (days && days.size > 0) { + for (const dateKey of days) placeEntry(cardFor(entry), dateKey) + continue + } + const captureKey = localDateKey(entry.createdAt, timeZone) + if (dayKeySet.has(captureKey)) placeEntry(cardFor(entry), captureKey) + } + + const days: DayCellView[] = [] + const gapDays: string[] = [] + let lateEvents = 0 + for (const dateKey of localDateKeysOfMonth(monthKey, timeZone)) { + const dayEvents: EventCardView[] = [] + for (const event of eventsByDay.get(dateKey) ?? []) { + const entryId = entryIdByEventId.get(event.eventId) + if (entryId === undefined) continue // orphan: counted, never silently dropped + const entry = entryById.get(entryId) + if (entry === undefined) continue // event of an entry this principal cannot see + const core = cardFor(entry) + const captureKey = localDateKey(entry.createdAt, timeZone) + const isLate = captureKey !== dateKey + if (isLate) lateEvents += 1 + const day = fullDayLabel(dateKey) + const capturedAt = captureLabel(entry.createdAt, timeZone, fullDayLabel(captureKey)) + const time = localTimeLabel(event.timestamp, timeZone) + dayEvents.push({ + eventId: event.eventId, + category: event.category, + occurredAtMs: event.timestamp, + localDateKey: dateKey, + localTimeLabel: time, + payload: event.payload, + confidence: event.confidence, + authorId: entry.authorId, + authorName: authorName(entry.authorId), + entryId: entry.entryId, + captureDateKey: captureKey, + captureLabel: capturedAt, + isLate, + lateLabel: isLate ? lateLabel(fullDayLabel(captureKey), day) : undefined, + corrected: core.corrected, + a11yLabel: eventA11yLabel({ + category: event.category, + localTimeLabel: time, + authorName: authorName(entry.authorId), + isLate, + captureLabel: capturedAt, + corrected: core.corrected, + }), + }) + } + const dayEntries: EntryCardView[] = (entriesByDay.get(dateKey) ?? []).map((core) => { + const captureKey = localDateKey(core.entry.createdAt, timeZone) + const capturedAt = captureLabel(core.entry.createdAt, timeZone, fullDayLabel(captureKey)) + return { + entryId: core.entry.entryId, + authorId: core.entry.authorId, + authorName: authorName(core.entry.authorId), + visibility: core.entry.visibility, + transcript: core.transcript, + captureDateKey: captureKey, + captureLabel: capturedAt, + extractionStatus: core.entry.extractionStatus, + extractionStatusLabel: core.entry.extractionStatus === "failed" ? EXTRACTION_FAILED_LABEL : undefined, + corrected: core.corrected, + correctionLineage: core.lineage, + a11yLabel: entryA11yLabel({ + authorName: authorName(core.entry.authorId), + captureLabel: capturedAt, + transcript: core.transcript, + corrected: core.corrected, + }), + } + }) + const entryCount = dayEntries.length + const eventCount = dayEvents.length + const state = entryCount > 0 ? "has-entries" : "no-entries" + if (state === "no-entries") gapDays.push(dateKey) + const dayLabel = fullDayLabel(dateKey) + days.push({ + dateKey, + dayLabel, + entryCount, + eventCount, + state, + events: dayEvents, + entries: dayEntries, + a11yLabel: dayCellA11yLabel({ + dayLabel, + entryCount, + eventCount, + correctedCount: dayEntries.filter((entry) => entry.corrected).length, + }), + a11yRole: A11Y_ROLES.dayCell, + a11yHint: DAY_CELL_A11Y_HINT, + }) + } + + // Month-scoped totals: only entries actually placed in a day cell count. + const placedEntryIds = new Set(days.flatMap((day) => day.entries.map((entry) => entry.entryId))) + const correctedEntries = [...placedEntryIds].filter((entryId) => lineage.has(entryId)).length + const totalEntries = placedEntryIds.size + const totalEvents = eventsInMonth.length - orphanEventCount - hiddenEventCount + const gap: MonthGapStatement = + totalEntries === 0 + ? { + kind: "empty-month", + message: `No entries were recorded this month. ${GAP_DISCLAIMER}`, + gapDays: [...dayKeySet], + disclaimer: GAP_DISCLAIMER, + } + : gapDays.length === 0 + ? { + kind: "no-gaps", + message: "Every day this month has at least one entry recorded.", + gapDays: [], + disclaimer: GAP_DISCLAIMER, + } + : { + kind: "gaps", + message: `${gapDays.length} of ${days.length} days have no entries recorded. ${GAP_DISCLAIMER}`, + gapDays, + disclaimer: GAP_DISCLAIMER, + } + + return { + monthKey, + timeZone, + monthLabel: monthLabel(monthKey), + headerA11yLabel: monthHeaderA11yLabel(monthLabel(monthKey)), + bounds, + days, + totalEntries, + totalEvents, + lateEvents, + correctedEntries, + orphanEventCount, + gap, + } +} diff --git a/packages/month-history/src/zone.ts b/packages/month-history/src/zone.ts new file mode 100644 index 0000000..defab76 --- /dev/null +++ b/packages/month-history/src/zone.ts @@ -0,0 +1,217 @@ +/** + * Timezone-correct, deterministic calendar-month bucketing. + * + * Month history is bucketed by the household's LOCAL calendar — never by UTC, + * never by the viewer's device zone. Every function here is a pure function + * of its arguments: no `Date.now()`, no ambient timezone reads. Same inputs, + * same outputs, on every machine and every run. + * + * Implementation is Intl-based (full ICU). Formatters are cached per + * (locale, timeZone) and the locale is pinned to en-US so label strings are + * deterministic. Pinned values in test/zone.test.ts were computed and + * verified against bun 1.3.14 / node 20 full-ICU on 2026-09-17. + */ + +export const LABEL_LOCALE = "en-US" + +export interface ZonedMonthBounds { + /** First instant (Unix ms) whose local date is the 1st of the month. */ + readonly startMs: number + /** First instant (Unix ms) whose local date is the 1st of the NEXT month. */ + readonly endMsExclusive: number +} + +export interface LocalParts { + readonly year: string + readonly month: string + readonly day: string + readonly hour: string + readonly minute: string + readonly second: string +} + +const formatterCache = new Map() + +function partsFormatter(timeZone: string): Intl.DateTimeFormat { + const cacheKey = `${LABEL_LOCALE}|${timeZone}` + const cached = formatterCache.get(cacheKey) + if (cached) return cached + const formatter = new Intl.DateTimeFormat(LABEL_LOCALE, { + timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hourCycle: "h23", + }) + formatterCache.set(cacheKey, formatter) + return formatter +} + +function partsAt(instantMs: number, timeZone: string): LocalParts { + const collected = new Map() + for (const part of partsFormatter(timeZone).formatToParts(instantMs)) { + if (part.type !== "literal") collected.set(part.type, part.value) + } + const get = (kind: string): string => { + const value = collected.get(kind) + if (value === undefined) throw new Error(`Intl formatToParts missing "${kind}" for ${timeZone}`) + return value + } + return { + year: get("year"), + month: get("month"), + day: get("day"), + hour: get("hour"), + minute: get("minute"), + second: get("second"), + } +} + +function utcMsFromParts(parts: LocalParts): number { + return Date.UTC( + Number(parts.year), + Number(parts.month) - 1, + Number(parts.day), + Number(parts.hour), + Number(parts.minute), + Number(parts.second), + ) +} + +/** "YYYY-MM-DD" — the household-zone local calendar date of an instant. */ +export function localDateKey(instantMs: number, timeZone: string): string { + const parts = partsAt(instantMs, timeZone) + return `${parts.year}-${parts.month}-${parts.day}` +} + +const MONTH_KEY_PATTERN = /^\d{4}-\d{2}$/ + +export function parseMonthKey(monthKey: string): { readonly year: number; readonly month: number } { + if (!MONTH_KEY_PATTERN.test(monthKey)) { + throw new Error(`monthKey must be "YYYY-MM", got ${JSON.stringify(monthKey)}`) + } + const year = Number(monthKey.slice(0, 4)) + const month = Number(monthKey.slice(5, 7)) + if (month < 1 || month > 12) throw new Error(`monthKey month out of range: ${monthKey}`) + return { year, month } +} + +function parseDateKey(dateKey: string): { readonly year: number; readonly month: number; readonly day: number } { + if (!/^\d{4}-\d{2}-\d{2}$/.test(dateKey)) { + throw new Error(`dateKey must be "YYYY-MM-DD", got ${JSON.stringify(dateKey)}`) + } + return { year: Number(dateKey.slice(0, 4)), month: Number(dateKey.slice(5, 7)), day: Number(dateKey.slice(8, 10)) } +} + +export function nextMonthKey(monthKey: string): string { + const { year, month } = parseMonthKey(monthKey) + return month === 12 ? `${year + 1}-01` : `${year}-${String(month + 1).padStart(2, "0")}` +} + +const STEP_MS = 15 * 60_000 +const MAX_STEPS = 96 // > one day of walking; a correct zone resolves in a handful + +/** + * First instant whose local date is `year-month-day` in `timeZone`. + * + * Converges by shifting a UTC-midnight guess by the wall-clock offset it + * reads, then handles midnight-skipped DST days (e.g. America/Havana springs + * forward at 00:00): walk forward to the first instant that exists on the + * target local date, then back up to the earliest such instant. Defined + * semantics: a local date begins at the earliest instant that exists on it. + */ +function firstInstantOfLocalDate(year: number, month: number, day: number, timeZone: string): number { + const dateKey = `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}` + const utcMidnight = Date.UTC(year, month - 1, day) + let guess = utcMidnight + for (let i = 0; i < 6; i += 1) { + const diff = utcMidnight - utcMsFromParts(partsAt(guess, timeZone)) + if (diff === 0) break + guess += diff + } + let steps = 0 + while (localDateKey(guess, timeZone) !== dateKey) { + guess += STEP_MS + steps += 1 + if (steps > MAX_STEPS) throw new Error(`could not resolve local date ${dateKey} in ${timeZone}`) + } + while (localDateKey(guess - STEP_MS, timeZone) === dateKey) { + guess -= STEP_MS + steps += 1 + if (steps > MAX_STEPS) throw new Error(`could not resolve earliest instant of ${dateKey} in ${timeZone}`) + } + return guess +} + +/** Half-open [startMs, endMsExclusive) bounds of the calendar month in the zone. */ +export function zonedMonthBounds(monthKey: string, timeZone: string): ZonedMonthBounds { + const { year, month } = parseMonthKey(monthKey) + const startMs = firstInstantOfLocalDate(year, month, 1, timeZone) + const next = nextMonthKey(monthKey) + const endMsExclusive = firstInstantOfLocalDate(Number(next.slice(0, 4)), Number(next.slice(5, 7)), 1, timeZone) + if (endMsExclusive <= startMs) throw new Error(`degenerate month bounds for ${monthKey} in ${timeZone}`) + return { startMs, endMsExclusive } +} + +export function isInstantInMonth(instantMs: number, bounds: ZonedMonthBounds): boolean { + return instantMs >= bounds.startMs && instantMs < bounds.endMsExclusive +} + +/** + * Every local calendar date key of the month, in order, each exactly once. + * Walks in 12h steps (a step can never jump over a local midnight) and + * asserts completeness against the bounds-derived day count, which stays + * correct across 23h/25h DST days via rounding. + */ +export function localDateKeysOfMonth(monthKey: string, timeZone: string): readonly string[] { + const bounds = zonedMonthBounds(monthKey, timeZone) + const keys: string[] = [] + for (let instant = bounds.startMs; instant < bounds.endMsExclusive; instant += 12 * 60 * 60_000) { + const key = localDateKey(instant, timeZone) + if (keys[keys.length - 1] !== key) keys.push(key) + } + const expectedDays = Math.round((bounds.endMsExclusive - bounds.startMs) / (24 * 60 * 60_000)) + if (keys.length !== expectedDays) { + throw new Error(`expected ${expectedDays} calendar days for ${monthKey} in ${timeZone}, enumerated ${keys.length}`) + } + return keys +} + +const dayLabelFormatter = new Intl.DateTimeFormat(LABEL_LOCALE, { + timeZone: "UTC", + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", +}) +const monthLabelFormatter = new Intl.DateTimeFormat(LABEL_LOCALE, { timeZone: "UTC", month: "long", year: "numeric" }) +const timeFormatterCache = new Map() + +/** "Wednesday, September 30, 2026" — pinned en-US, formatted at UTC noon (DST-safe). */ +export function fullDayLabel(dateKey: string): string { + const { year, month, day } = parseDateKey(dateKey) + return dayLabelFormatter.format(Date.UTC(year, month - 1, day, 12)) +} + +/** "September 2026". */ +export function monthLabel(monthKey: string): string { + const { year, month } = parseMonthKey(monthKey) + return monthLabelFormatter.format(Date.UTC(year, month - 1, 1, 12)) +} + +/** "11:50 PM" — household-zone wall-clock time of an instant. */ +export function localTimeLabel(instantMs: number, timeZone: string): string { + const cached = timeFormatterCache.get(timeZone) + if (cached) return cached.format(instantMs) + const formatter = new Intl.DateTimeFormat(LABEL_LOCALE, { + timeZone, + hour: "numeric", + minute: "2-digit", + hour12: true, + }) + timeFormatterCache.set(timeZone, formatter) + return formatter.format(instantMs) +} diff --git a/packages/month-history/test/month-history.test.ts b/packages/month-history/test/month-history.test.ts new file mode 100644 index 0000000..c63007b --- /dev/null +++ b/packages/month-history/test/month-history.test.ts @@ -0,0 +1,213 @@ +/** + * @journal/month-history — package tests (bun). + * + * The deep behavioral coverage lives in the executable journeys + * (src/journeys.ts + rubric.json, run via `bun src/run.ts`). These tests pin + * the same surface for `pnpm test`/CI: every journey check passes, the + * timezone helpers hold their DST/boundary behavior, correction lineage is + * append-only and ordered, the handoff digest is deterministic and + * source-linked, and projections never mutate the dataset. + */ +import { describe, expect, test } from "bun:test" + +import { + CORRECTIONS, + DAD, + ENTRY_IDS, + EVENTS, + EVENT_IDS, + CHILD_ID, + HOUSEHOLD_ID, + HOUSEHOLD_ZONE, + MOM, + NOV1_0130_EDT, + NOV1_0130_EST, + buildAuthorizedView, + buildHandoffDigest, + buildLineage, + buildMonthHistoryView, + daySummary, + entryViewInputFromDocument, + eventViewInputFromDocument, + isInstantInMonth, + latestCorrection, + localDateKey, + monthAccess, + zonedMonthBounds, + type CorrectionRecord, +} from "../src/index.js" +import { ENTRIES, EVENTS as FIXTURE_EVENTS } from "../src/fixtures/monthHistory.js" +import { JOURNEY_CHECKS } from "../src/journeys.js" + +const SCOPE = { childId: CHILD_ID, householdId: HOUSEHOLD_ID } +const MOM_PRINCIPAL = { kind: "caregiver" as const, caregiverId: MOM, householdIds: [HOUSEHOLD_ID] } +const DAD_PRINCIPAL = { kind: "caregiver" as const, caregiverId: DAD, householdIds: [HOUSEHOLD_ID] } + +describe("journey checks", () => { + test("every executable journey check passes", () => { + for (const journey of JOURNEY_CHECKS) { + const outcome = journey.run() + expect(outcome.ok).toBe(true) + } + }) +}) + +describe("household-zone calendar", () => { + test("DST fall-back pairs both land on the local date", () => { + expect(localDateKey(NOV1_0130_EDT, HOUSEHOLD_ZONE)).toBe("2026-11-01") + expect(localDateKey(NOV1_0130_EST, HOUSEHOLD_ZONE)).toBe("2026-11-01") + }) + + test("the November 2026 month in New York spans 721 hours", () => { + const bounds = zonedMonthBounds("2026-11", "America/New_York") + expect((bounds.endMsExclusive - bounds.startMs) / 3_600_000).toBe(721) + }) + + test("month membership follows the household zone, not UTC", () => { + const boundary = EVENTS.find((event) => event._id === EVENT_IDS.sep30Boundary)! + const nySeptember = zonedMonthBounds("2026-09", "America/New_York") + const nyOctober = zonedMonthBounds("2026-10", "America/New_York") + const kolkataOctober = zonedMonthBounds("2026-10", "Asia/Kolkata") + expect(isInstantInMonth(boundary.timestamp, nySeptember)).toBe(true) + expect(isInstantInMonth(boundary.timestamp, nyOctober)).toBe(false) + expect(isInstantInMonth(boundary.timestamp, kolkataOctober)).toBe(true) + }) +}) + +describe("correction lineage", () => { + test("latest correction wins and the chain stays append-only", () => { + const lineage = buildLineage(CORRECTIONS).get(ENTRY_IDS.tower) + expect(lineage).toBeDefined() + expect(latestCorrection(lineage)!.correctedBy).toBe(DAD) + }) + + test("a correction superseding an unknown step is rejected", () => { + const bad: CorrectionRecord = { + correctionId: "co_bad", + originalEntryId: ENTRY_IDS.tower, + correctedBy: MOM, + createdAtMs: 1, + replacementTranscript: "x", + supersedesCorrectionId: "co_never_seen", + } + expect(() => buildLineage([...CORRECTIONS, bad])).toThrow() + }) +}) + +describe("handoff digest", () => { + test("summary formatting is deterministic and category-ordered", () => { + expect(daySummary([{ category: "sleep" }, { category: "potty" }, { category: "potty" }])).toBe("2× potty, 1× sleep") + }) + + test("the digest is stable across identical builds", () => { + const { view } = buildAuthorizedView(MOM_PRINCIPAL, "2026-09", HOUSEHOLD_ZONE) + const options = { preparedByName: "Mom", preparedForName: "Dad", excludedDraftCount: 2 } as const + expect(buildHandoffDigest(view, options)).toEqual(buildHandoffDigest(view, options)) + }) +}) + +describe("projection purity", () => { + test("building views, access, and digests never mutates the dataset", () => { + const before = JSON.stringify({ entries: ENTRIES, events: FIXTURE_EVENTS }) + buildAuthorizedView(MOM_PRINCIPAL, "2026-09", HOUSEHOLD_ZONE) + buildAuthorizedView(DAD_PRINCIPAL, "2026-10", "Asia/Kolkata") + expect(JSON.stringify({ entries: ENTRIES, events: FIXTURE_EVENTS })).toBe(before) + }) +}) + +describe("authorization adapter", () => { + test("drafts stay author-only and non-members are denied at the timeline gate", () => { + const mom = monthAccess(MOM_PRINCIPAL, SCOPE, ENTRIES) + expect(mom.outcome).toBe("allowed") + if (mom.outcome === "allowed") { + const drafts = mom.visible.filter((entry) => entry.visibility === "draft") + expect(drafts.length).toBe(1) + expect(drafts[0]!.authorId).toBe(MOM) + } + + const outsider = monthAccess({ kind: "caregiver", caregiverId: "cg_outsider", householdIds: [] }, SCOPE, ENTRIES) + expect(outsider.outcome).toBe("denied") + }) +}) + +describe("document adapters", () => { + test("field-rename adapters preserve identity", () => { + const doc = ENTRIES[0]! + expect(entryViewInputFromDocument(doc).entryId).toBe(doc._id) + const event = FIXTURE_EVENTS[0]! + expect(eventViewInputFromDocument(event).eventId).toBe(event._id) + }) +}) + +describe("view builder export", () => { + test("an empty authorized month states its emptiness honestly", () => { + const view = buildMonthHistoryView({ + monthKey: "2026-09", + timeZone: HOUSEHOLD_ZONE, + entries: [], + events: [], + corrections: [], + authors: {}, + scopeEntries: [], + }) + expect(view.gap.kind).toBe("empty-month") + expect(view.days.length).toBe(30) + }) +}) + +describe("orphan accounting", () => { + test("events of in-scope-but-invisible entries are excluded without counting as orphans; truly unclaimed events are orphans", () => { + // Dad's perspective: Mom's draft entry exists in the child's scope but is + // invisible to him. Its event must render nowhere AND not inflate the + // orphan count (the event is claimed — by an entry he cannot see). An + // event no scope entry claims IS an orphan. This is the divergence no + // fixture exercises — pinned here per the PR #27 round-1 review. + const sepMs = Date.parse("2026-09-15T10:00:00-04:00") + const category = eventViewInputFromDocument(FIXTURE_EVENTS[0]!).category + const momDraftEntry = { + entryId: "ent_probe_draft", + householdId: HOUSEHOLD_ID, + childId: CHILD_ID, + authorId: MOM, + rawTranscript: "draft probe", + structuredEventIds: ["ev_probe_hidden"], + extractionStatus: "structured" as const, + visibility: "draft" as const, + createdAt: sepMs, + } + const publishedEntry = { + ...momDraftEntry, + entryId: "ent_probe_published", + authorId: DAD, + rawTranscript: "published probe", + structuredEventIds: [], + visibility: "published" as const, + } + const hiddenEvent = { eventId: "ev_probe_hidden", householdId: HOUSEHOLD_ID, childId: CHILD_ID, category, timestamp: sepMs, confidence: 0.9 } + const orphanEvent = { eventId: "ev_probe_orphan", householdId: HOUSEHOLD_ID, childId: CHILD_ID, category, timestamp: sepMs, confidence: 0.9 } + const base = { monthKey: "2026-09", timeZone: HOUSEHOLD_ZONE, authors: { [MOM]: "Mom", [DAD]: "Dad" } } + + const scoped = buildMonthHistoryView({ + ...base, + entries: [publishedEntry], + events: [hiddenEvent, orphanEvent], + scopeEntries: [publishedEntry, momDraftEntry], + }) + expect(scoped.orphanEventCount).toBe(1) + expect(scoped.totalEvents).toBe(0) + for (const day of scoped.days) { + expect(day.events.some((event) => event.eventId === "ev_probe_hidden")).toBe(false) + expect(day.events.some((event) => event.eventId === "ev_probe_orphan")).toBe(false) + } + + // Without scopeEntries the claim universe defaults to the authorized + // entries, so BOTH events count as orphans — the draft claim is unknown. + const unscoped = buildMonthHistoryView({ + ...base, + entries: [publishedEntry], + events: [hiddenEvent, orphanEvent], + }) + expect(unscoped.orphanEventCount).toBe(2) + expect(unscoped.totalEvents).toBe(0) + }) +}) diff --git a/packages/month-history/tsconfig.json b/packages/month-history/tsconfig.json new file mode 100644 index 0000000..e4021e2 --- /dev/null +++ b/packages/month-history/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["bun"] + }, + "include": ["src", "test"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 28d2f47..49cbc64 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: apps/mobile: dependencies: + '@journal/month-history': + specifier: workspace:* + version: link:../../packages/month-history '@journal/ui': specifier: workspace:* version: link:../../packages/ui @@ -107,6 +110,22 @@ importers: specifier: ~6.0.3 version: 6.0.3 + packages/month-history: + dependencies: + '@journal/domain': + specifier: workspace:* + version: link:../domain + effect: + specifier: 4.0.0-rc.115 + version: 4.0.0-rc.115 + devDependencies: + '@types/bun': + specifier: ^1.3.14 + version: 1.4.2 + typescript: + specifier: ~6.0.3 + version: 6.0.3 + packages/retrieval: dependencies: '@journal/domain':