From 12fafe6f1bed981a098f119c1a19a18ad37a3f30 Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 20:24:23 +0000 Subject: [PATCH 1/3] feat(capture): arena-integrated capture slice (D base + C/A/B grafts) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Integrate the ARENA vertical-slice result onto the canonical contract: candidate D's structural base (state machine, stale-result guard, provider layers) with justified grafts per the Arena Cross-Review Receipts (art_KR73IkfH §5) — C's raw-first draft persistence + RetryPersistRaw and Encoded-derived wire codecs and journey probe; A's failure-park modeling and evidence discipline; the example-adapter extraction conventions for the all-candidate-unsolved relative-time/quantity problem. B's event model is deliberately not grafted (cannot express the canonical wire). packages/domain stays untouched (rule-2 discipline): the capture package composes canonical Effect schemas and adapts to the canonical entry model via wire codecs. evaluation/ gains the integrated-adapter wrapper that runs the PR #6 corpus harness against it (6/6 fixtures). Evidence: ARENA-INTEGRATION.md (graft ledger, rejected ideas, ND-claim disposition, verification results on the tested head). Co-authored-by: Gilbert Polanco --- ARENA-INTEGRATION.md | 96 ++++++++ evaluation/src/integrated-adapter.ts | 16 ++ packages/capture/README.md | 56 +++++ packages/capture/package.json | 26 ++ packages/capture/src/commands.ts | 50 ++++ packages/capture/src/evaluation-adapter.ts | 106 ++++++++ packages/capture/src/event.ts | 59 +++++ packages/capture/src/index.ts | 35 +++ packages/capture/src/journey/run.ts | 175 +++++++++++++ packages/capture/src/loop.test.ts | 196 +++++++++++++++ packages/capture/src/runtime.ts | 107 ++++++++ packages/capture/src/services/entries.ts | 171 +++++++++++++ packages/capture/src/services/extraction.ts | 128 ++++++++++ packages/capture/src/services/relativeTime.ts | 127 ++++++++++ packages/capture/src/state.ts | 173 +++++++++++++ packages/capture/src/update.ts | 230 ++++++++++++++++++ packages/capture/src/wire.ts | 68 ++++++ packages/capture/tsconfig.json | 8 + 18 files changed, 1827 insertions(+) create mode 100644 ARENA-INTEGRATION.md create mode 100644 evaluation/src/integrated-adapter.ts create mode 100644 packages/capture/README.md create mode 100644 packages/capture/package.json create mode 100644 packages/capture/src/commands.ts create mode 100644 packages/capture/src/evaluation-adapter.ts create mode 100644 packages/capture/src/event.ts create mode 100644 packages/capture/src/index.ts create mode 100644 packages/capture/src/journey/run.ts create mode 100644 packages/capture/src/loop.test.ts create mode 100644 packages/capture/src/runtime.ts create mode 100644 packages/capture/src/services/entries.ts create mode 100644 packages/capture/src/services/extraction.ts create mode 100644 packages/capture/src/services/relativeTime.ts create mode 100644 packages/capture/src/state.ts create mode 100644 packages/capture/src/update.ts create mode 100644 packages/capture/src/wire.ts create mode 100644 packages/capture/tsconfig.json diff --git a/ARENA-INTEGRATION.md b/ARENA-INTEGRATION.md new file mode 100644 index 0000000..7b816bc --- /dev/null +++ b/ARENA-INTEGRATION.md @@ -0,0 +1,96 @@ +# ARENA Integration — Base Pick, Graft Ledger, Verification Evidence + +Branch: `task/arena-integration-pick-base-graft-justif-qKuZn1nq` (non-candidate, +from master `fd7a6ab` — post PR #28 + #31). Authoritative inputs: Arena +Cross-Review Receipts v1 (`art_KR73IkfH`); PR #26 verification gate; PR #6 +corpus harness. + +## Base pick (receipts §4, unchanged) + +**Candidate D** (`8514d1b`) — the only candidate both structurally compliant on +the PR #6 harness and fully green untouched in a clean worktree (typecheck 4/4, +48/48 tests, build incl. Expo export). Canonical stack preserved: Expo 57 / +RN 0.86 / pnpm 10.34.5, `_generated` committed. + +## Graft ledger (receipts §5) + +| # | Source | Graft | Where it landed | Justification | +| --- | --- | --- | --- | --- | +| 1 | C `6230ecc` | Raw-first draft persistence at `TextCaptured` + `RetryPersistRaw` on failure | `packages/capture/src/update.ts`, `state.ts`, `runtime.ts`; backend `entries.ts` (raw-capture row on create) | A caregiver's words must be durable before any derived processing; the corpus `raw-fidelity` fixture checks byte-for-byte survival across retry | +| 2 | C `6230ecc` | Wire codecs derived from `Encoded` types | `packages/capture/src/wire.ts` | Candidate-native wire vocabulary must round-trip through the canonical `EventSchema` without restating it | +| 3 | C `6230ecc` | 17-test fail-closed security suite | **Not duplicated** — see "Rejected ideas" | master's `security/` (29 cases, 13 negative + 4 positive + knowledge cases) already supersedes C's 17-case suite; grafting would fork the suite | +| 4 | C `6230ecc` | Journey CLI contract probe | `packages/capture/src/journey/run.ts` (15 checks) | Executable behavioral probe of the full capture loop incl. failure parking and replay | +| 5 | A `ea5c736` | Server-side Effect re-decode of publish/append payloads | `backend/convex/convex/entriesInput.ts` `decodeAppendEvents` + the `appendEvents` mutation | The backend must reject out-of-bounds confidence (1.5) regardless of client validation — proven executable in `test/entries.test.ts` | +| 6 | A `ea5c736` | Failure-park state modeling | `packages/capture/src/state.ts` (`RawPersistFailed`) + `update.ts` arms | Storage failures park with raw retained instead of dropping the caregiver's words | +| 7 | A `ea5c736` | EVIDENCE.md claim discipline | this document + `packages/capture/README.md` | Every claim names where it was executed | +| 8 | B `15fe84f9` | Append-only raw-captures table + server-enforced raw-before-events | `backend/convex/convex/schema.ts` (`rawCaptures`, backend-local `RawCaptureFields` composition), `entriesInput.ts` (`requireRawCaptureBeforeEvents`, `buildRawCaptureRow`), `entries.ts` (`appendEvents`) | Entries are mutable (extraction status, structured links, the v0.4 retraction fold); the immutable raw text needs its own append-only storage, and events must fail closed without it | + +**B's event model was NOT grafted** (per the receipts): the per-category union, +one-event entries, and explicit-null shapes cannot express the canonical wire. +Canonical events (`EventFields`: bounded confidence, payload record, lineage) +win wherever the two conflict. + +## Settled decisions honored (not re-opened) + +1. **Corpus status reading** — draft-with-events at creation. D's + draft-at-publish behavior was deliberately fixed: `AttachEvents` keeps the + entry a draft (canonical `visibility`), and the corpus `reload-persistence` + + `retry-double-submit` fixtures pin the semantics. +2. **Relative time + quantity** — unsolved in all four candidates. The + deterministic double grafts the example adapter's conventions + (`packages/extraction` + corpus worked example): spelled-out `ounces of`, + first-match-per-sentence rules in example-adapter order (multi-event + narratives are separate sentences), DST-safe zone resolution. Documented as + an extracted-service seam for the future model-backed extractor. + +## Rejected ideas / dropouts (with reasons) + +- **Duplicating C's 17-test security suite** — master's security suite is a + verified superset (29/0 this session, includes the fail-closed access cases + C's 17 cover plus the later knowledge cases). A second suite would fork the + failure surface. The superset relationship was verified, not assumed. +- **B's event model** (per-category union, one-event entries, explicit null) — + cannot express the canonical wire; canonical contracts win (rule 2). +- **Grafting into `packages/domain`** — rule-2 discipline: canonical Effect + schemas are the contract source of truth; every graft composes or adapts + around them. `git diff` over `packages/domain` is empty on this branch. +- **Deferring the backend enforcement entirely** — the receipts marked B's + server-enforced raw-before-events as ND (backend blocker). Rather than drop + the claim, it is implemented and evidenced at the validator level this + session (below); runtime-harness evidence remains the standing N1 limitation. + +## ND-claim disposition (receipts) + +| Claim | Receipts status | Disposition on this branch | +| --- | --- | --- | +| B: server-enforced raw-before-events | ND (backend blocker) | **Implemented** — `requireRawCaptureBeforeEvents` + `appendEvents`; 4 dedicated validator tests; handler wiring proven by strict typecheck against the generated API (`rawCaptures` table resolves in `dataModel`) | +| A: server-side re-decode rejects confidence 1.5 | proven on A | **Re-run here** — `decodeAppendEvents` + test rejects 1.5 through the canonical `EventFields` decoder | +| Convex runtime behavior of the capture path | ND | **Still ND** — no local Convex runtime harness (N1); documented, not claimed | + +## Verification evidence (this session, this branch) + +Executed in `/home/user/work/arena-int` (worktree of +`task/arena-integration-pick-base-graft-justif-qKuZn1nq`, base `fd7a6ab`): + +- `pnpm turbo run typecheck test build --force` — **20/20 tasks, 0 cached** + (baseline clean-master was 18/18; +2 = the new capture package). +- `bun test ./security` — **29 pass, 0 fail** (unchanged by this branch). +- `bun test` in `backend/convex` — **31 pass, 0 fail** (17 knowledge + 14 new + entries-graft tests). +- `bun src/run.ts --adapter=./src/integrated-adapter.ts` (PR #6 harness) — + **6/6 fixtures** on the integrated adapter; negative control + (`broken-adapter.ts --expect-failure`) fails as required (1/6). +- `pnpm --filter @journal/capture journeys` — **15/15 checks**. +- `packages/domain` diff vs `fd7a6ab` — **empty** (rule-2 discipline held). + +## Known limitations (stated, not hidden) + +- **N1** — no local Convex runtime harness; the append path's handler wiring is + proven by generated-API typecheck + validator-level tests, not live Convex. +- **Codegen side effect** — regenerating `_generated` ran `npx convex codegen` + with the deploy key; its log included an "Uploading functions to Convex…" + step (the command's own help says it does not modify the deployment; this + was not separately verified). The dev deployment should be re-synced from + master after merge. +- **Model-backed extraction** remains out of scope — the deterministic double + is the demo-path stand-in by settled decision. diff --git a/evaluation/src/integrated-adapter.ts b/evaluation/src/integrated-adapter.ts new file mode 100644 index 0000000..e777309 --- /dev/null +++ b/evaluation/src/integrated-adapter.ts @@ -0,0 +1,16 @@ +/** + * Integrated-arena adapter wrapper — the harness entry point for the + * integrated capture pipeline living in packages/capture. + * + * Thin on purpose: it exists only to type-check the integrated adapter + * against the corpus CandidateAdapter interface (packages/capture stays + * corpus-agnostic and imports nothing from evaluation/). + */ +import type { CandidateAdapter } from './adapter.ts' + +// Plain relative import (bun resolves it; evaluation/ is not a pnpm +// workspace member, so no package boundary is crossed). The capture package +// itself stays corpus-agnostic — it imports nothing from evaluation/. +import { createIntegratedAdapter } from '../../packages/capture/src/evaluation-adapter.ts' + +export const createAdapter = (): CandidateAdapter => createIntegratedAdapter() diff --git a/packages/capture/README.md b/packages/capture/README.md new file mode 100644 index 0000000..cb940e3 --- /dev/null +++ b/packages/capture/README.md @@ -0,0 +1,56 @@ +# @journal/capture — arena-integrated capture slice + +Deterministic capture pipeline integrating the ARENA vertical-slice result: +candidate D (`8514d1b`) as the structural base, with justified grafts from C +(`6230ecc`), A (`ea5c736`), and B (`15fe84f9`) per the Arena Cross-Review +Receipts (art_KR73IkfH §5). + +## Shape + +``` +src/ + event.ts capture-surface event/entry schemas (canonical-composed) + state.ts capture machine states incl. RawPersistFailed park + commands.ts PersistRawDraft / ExtractEvents / AttachEvents / PublishEntry + update.ts pure reducer (stale-result guard, failure parking, retry) + runtime.ts sequential command execution loop (side effects live here) + wire.ts wire codecs derived from Encoded return types + services/ extraction (deterministic, corpus-tuned) + relative time + journey/run.ts 15-check CLI contract probe + loop.test.ts 13 unit/integration tests +``` + +## Pipeline (raw-first, per candidate C) + +1. `CompletedTranscription` → emits `PersistRawDraft` **only** — the durable + draft exists before any extraction work. +2. `SubmittedForExtraction` → `ExtractEvents` (a separate step, so extraction + can never overtake raw persistence). +3. Extraction success → draft-with-events at creation (corpus status reading, + settled decision 1); failure → back to `Transcribed` (raw already durable, + same captureId re-runs extraction). +4. Storage failures (persist from `Transcribed` or attach/publish from + `Review`) → **park** in `RawPersistFailed` with the raw transcript retained; + `RetryPersistRaw` re-issues the idempotent persist. + +Relative time + quantity extraction is the unsolved-in-all-candidates problem: +the deterministic double here follows the example adapter's conventions +(`packages/extraction` + the evaluation corpus worked example) — spelled-out +`ounces of` quantities, first-match-per-sentence category rules in the +example-adapter order, DST-safe IANA-zone resolution. + +## Verification + +```bash +pnpm --filter @journal/capture typecheck +pnpm --filter @journal/capture test # 13 tests +pnpm --filter @journal/capture journeys # 15/15 checks +cd ../../evaluation && bun src/run.ts --adapter=./src/integrated-adapter.ts + # 6/6 corpus fixtures +``` + +`packages/domain` is untouched: the capture package composes the canonical +Effect schemas (`EventFields`, `CaptureId`, `EventSchema`) and adapts to the +canonical entry model (`visibility`, `extractionStatus`, `structuredEventIds`) +via the codecs in `wire.ts`. The backend mirror of the raw-first invariants +lives in `backend/convex` (`entriesInput.ts` + the `rawCaptures` table). diff --git a/packages/capture/package.json b/packages/capture/package.json new file mode 100644 index 0000000..f30881e --- /dev/null +++ b/packages/capture/package.json @@ -0,0 +1,26 @@ +{ + "name": "@journal/capture", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Integrated voice-capture pipeline (Arena integration slice): pure capture state machine with raw-first durable persistence and retry, deterministic extraction double, append-only raw-before-events entry store, wire codecs derived from canonical Encoded types, corpus adapter, and a journey CLI contract probe.", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "scripts": { + "test": "bun test", + "typecheck": "tsc -p tsconfig.json --noEmit", + "journeys": "bun src/journey/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/capture/src/commands.ts b/packages/capture/src/commands.ts new file mode 100644 index 0000000..693ca8d --- /dev/null +++ b/packages/capture/src/commands.ts @@ -0,0 +1,50 @@ +/** + * Named effectful commands (Foldkit R4): pure data descriptions of the side + * effects the capture state machine may need. The update function never runs + * them — `runtime.executeCommand` maps each to a service effect and feeds the + * resulting result-message back into the same update loop. + * + * Command set (base: candidate D; grafts: candidate C): + * - PersistRawDraft — raw-first durable draft at TextCaptured (C). + * - AttachEvents — extracted events attach to the existing DRAFT entry + * (corpus status-model decision: fresh entries are drafts with events). + * - ExtractEvents / PublishEntry — candidate D's original commands, with + * PublishEntry narrowed to a status flip (the entry already exists). + */ +import type { CapturedEvent } from "./event.js" + +import type { CaptureId } from "@journal/domain" + +export interface ExtractEvents { + readonly _tag: "ExtractEvents" + readonly captureId: CaptureId + readonly childId: string + readonly authorId: string + readonly transcript: string + readonly capturedAt: number + readonly timezone: string +} + +export interface PersistRawDraft { + readonly _tag: "PersistRawDraft" + readonly captureId: CaptureId + readonly childId: string + readonly authorId: string + readonly rawTranscript: string + readonly createdAt: number +} + +export interface AttachEvents { + readonly _tag: "AttachEvents" + readonly captureId: CaptureId + readonly events: ReadonlyArray +} + +export interface PublishEntry { + readonly _tag: "PublishEntry" + readonly captureId: CaptureId +} + +export type CaptureCommand = ExtractEvents | PersistRawDraft | AttachEvents | PublishEntry + +export type CommandName = CaptureCommand["_tag"] diff --git a/packages/capture/src/evaluation-adapter.ts b/packages/capture/src/evaluation-adapter.ts new file mode 100644 index 0000000..daf1e3f --- /dev/null +++ b/packages/capture/src/evaluation-adapter.ts @@ -0,0 +1,106 @@ +/** + * Integrated corpus adapter (graft: the harness "runs identically against + * every candidate"). Drives the integrated capture pipeline — D's loop and + * reducer, C's raw-first persistence and retry, A's failure-park modeling — + * over the in-memory entry store, and exposes ONLY the CandidateAdapter + * surface (structural, no corpus import): the corpus must not import + * candidate code, so this file must not import corpus internals either. + */ +import { Effect } from "effect" + +import { makeCaptureLoop } from "./runtime.js" +import { makeInMemoryEntryStore } from "./services/entries.js" +import { makeDeterministicExtractor } from "./services/extraction.js" + +import type { CaptureServices } from "./runtime.js" +import type { CapturedEntry } from "./services/entries.js" + +/** Corpus-scoped child: one child's timeline, per evaluation/README.md. */ +export const CORPUS_CHILD_ID = "child-corpus" + +export const createIntegratedAdapter = () => { + const entries = makeInMemoryEntryStore() + const services: CaptureServices = { + extraction: makeDeterministicExtractor(), + entries, + } + + const toWire = (entry: CapturedEntry) => ({ + _tag: "Entry" as const, + captureId: entry.captureId, + transcript: entry.rawTranscript, + authorId: entry.authorId, + createdAt: entry.createdAt, + status: entry.status, + events: entry.events, + }) + + const runPipeline = async (input: { + readonly captureId: string + readonly transcript: string + readonly authorId: string + readonly capturedAt: number + readonly timezone: string + }): Promise => { + // One machine per capture; the store is the shared durable layer. + const loop = makeCaptureLoop(services) + const dispatch = (message: unknown) => Effect.runPromise(loop.dispatch(message as never)) + await dispatch({ + _tag: "CaptureStarted", + captureId: input.captureId, + childId: CORPUS_CHILD_ID, + authorId: input.authorId, + }) + await dispatch({ + _tag: "CompletedTranscription", + captureId: input.captureId, + transcript: input.transcript, + at: input.capturedAt, + timezone: input.timezone, + }) + await dispatch({ _tag: "SubmittedForExtraction", captureId: input.captureId }) + } + + return { + name: "integrated-arena", + createEntry: async (input: { + readonly captureId: string + readonly transcript: string + readonly authorId: string + readonly capturedAt: number + readonly timezone: string + }) => { + // Raw-input policy refusal (corpus contract): empty transcript is + // rejected before the machine runs — never for extraction failure. + if (input.transcript.length === 0) { + return { _tag: "Rejected" as const, reason: "transcript is empty" } + } + const existing = await Effect.runPromise(entries.timeline(CORPUS_CHILD_ID)) + const prior = existing.find((entry) => entry.captureId === input.captureId) + if (prior !== undefined) { + // Idempotency key: same captureId is a replay — return the existing + // entry, persist nothing new. Conflicting raw text is refused. + if (prior.rawTranscript === input.transcript) { + return { _tag: "IdempotentReplay" as const, entry: toWire(prior) } + } + return { _tag: "Rejected" as const, reason: `capture ${input.captureId} already exists with different raw text` } + } + await runPipeline(input) + const after = await Effect.runPromise(entries.timeline(CORPUS_CHILD_ID)) + const created = after.find((entry) => entry.captureId === input.captureId) + if (created === undefined) { + // The machine parked (store failure) — surface as refusal while the + // raw text stays preserved in the machine's failure state. + return { _tag: "Rejected" as const, reason: "capture pipeline failed to persist raw draft" } + } + return { _tag: "Created" as const, entry: toWire(created) } + }, + readTimeline: async () => { + const all = await Effect.runPromise(entries.timeline(CORPUS_CHILD_ID)) + return all.map(toWire) + }, + reload: async () => { + await Effect.runPromise(entries.reloadFromLog()) + }, + } +} diff --git a/packages/capture/src/event.ts b/packages/capture/src/event.ts new file mode 100644 index 0000000..feced27 --- /dev/null +++ b/packages/capture/src/event.ts @@ -0,0 +1,59 @@ +/** + * Capture-surface event and entry schemas (arena integration of candidate D's + * base onto the canonical master contract). + * + * These are PIPELINE types for the capture slice: they speak the corpus wire + * vocabulary (art_I2TCG08V — `_tag` literals, `occurredAt` millis, structured + * `quantity`) because the acceptance corpus and the capture UX hold the + * pipeline to that shape. Domain authority is preserved by composition, not + * restatement: the category taxonomy and the confidence range come straight + * from the canonical `EventFields` in @journal/domain, so a change to the + * canonical contract fails to compile here instead of drifting silently. + * + * The mapping to the canonical storage shape (timestamp / payload) lives in + * `./wire.ts` and is the only place the two vocabularies meet. + */ +import { Schema } from "effect" + +import { CaptureId, EventFields } from "@journal/domain" + +export const CapturedEventSchema = Schema.Struct({ + _tag: Schema.Literals(["Event"]), + category: EventFields.category, + /** Absolute instant, Unix ms — relative expressions are resolved before this point. */ + occurredAt: Schema.Number, + quantity: Schema.optionalKey( + Schema.Struct({ + value: Schema.Number, + unit: Schema.optionalKey(Schema.NonEmptyString), + }), + ), + confidence: EventFields.confidence, + authorId: Schema.String, + /** Optional free text; the source sentence for deterministic extraction. */ + note: Schema.optionalKey(Schema.NonEmptyString), +}) +export type CapturedEvent = Schema.Schema.Type + +export const EntryStatus = Schema.Literals(["draft", "published"]) +export type EntryStatus = Schema.Schema.Type + +/** + * The capture pipeline's entry: created as a DRAFT at raw capture (raw-first) + * with empty events; extracted events attach to the draft; the caregiver + * confirm flips the status. `createdAt` is the capture instant in millis — + * never process time. + */ +export const CapturedEntrySchema = Schema.Struct({ + _tag: Schema.Literals(["Entry"]), + captureId: CaptureId, + childId: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, + /** Verbatim dictated text — never trimmed, normalized, or re-encoded. */ + rawTranscript: Schema.NonEmptyString, + createdAt: Schema.Number, + status: EntryStatus, + /** May be empty — extraction failure never blocks capture. */ + events: Schema.Array(CapturedEventSchema), +}) +export type CapturedEntry = Schema.Schema.Type diff --git a/packages/capture/src/index.ts b/packages/capture/src/index.ts new file mode 100644 index 0000000..6956c0e --- /dev/null +++ b/packages/capture/src/index.ts @@ -0,0 +1,35 @@ +// Capture pipeline — public surface. Decision points are the pure reducer; +// services are plain interfaces (DI by object), runtime is the only side-effectful glue. +export { + CaptureStarted, + CompletedTranscription, + SubmittedForExtraction, + SucceededExtraction, + FailedExtraction, + RawDraftPersisted, + RawDraftPersistFailed, + RetryPersistRaw, + EventsAttached, + ConfirmedReview, + PublishedEntry, + FailedPublish, + CancelledCapture, + CaptureMessage, + CaptureState, +} from "./state.js" +export type { Idle, Recording, Transcribed, Extracting, Review, Published, RawPersistFailed } from "./state.js" +export type { CaptureCommand, CommandName } from "./commands.js" +export { update, type UpdateResult } from "./update.js" +export { executeCommand, makeCaptureLoop, type CaptureServices, type CaptureLoop } from "./runtime.js" +export { CapturedEventSchema, CapturedEntrySchema, EntryStatus } from "./event.js" +export type { CapturedEvent, CapturedEntry } from "./event.js" +export { zoneOffsetMs, wallToUtc, captureWallDate, to24h, resolveOccurredAt, type RelativeTimeInput } from "./services/relativeTime.js" +export { + makeDeterministicExtractor, + type ExtractionServiceShape, + type ExtractionInput, + type ExtractionError, +} from "./services/extraction.js" +export { makeInMemoryEntryStore, type EntryStoreShape, type StoreError, type DraftInput } from "./services/entries.js" +export { toCanonicalEvent, fromCanonicalEvent, type EncodedCaptureEvent, type EncodedCanonicalEvent } from "./wire.js" +export { createIntegratedAdapter, CORPUS_CHILD_ID } from "./evaluation-adapter.js" diff --git a/packages/capture/src/journey/run.ts b/packages/capture/src/journey/run.ts new file mode 100644 index 0000000..6d2ec12 --- /dev/null +++ b/packages/capture/src/journey/run.ts @@ -0,0 +1,175 @@ +/** + * Journey CLI contract probe (grafted from candidate C): walks the complete + * capture journey over the integrated pipeline and machine-checks the + * contracts that matter across candidates — raw-before-events durability, + * failure park + retry, idempotent replay, publish visibility flip, + * cold-start reload stability, and the stale-result guard. + * + * Usage: bun src/journey/run.ts (exit 0 = all checks pass) + */ +import { Effect, Schema } from "effect" +import { CaptureId } from "@journal/domain" + +import { makeCaptureLoop } from "../runtime.js" +import { makeInMemoryEntryStore } from "../services/entries.js" +import { makeDeterministicExtractor } from "../services/extraction.js" + +import type { CaptureServices } from "../runtime.js" +import type { InMemoryEntryStore } from "../services/entries.js" + +const BASE = 1_760_000_000_000 // fixed "now" — probe is deterministic +const CHILD = "child-journey" +const AUTHOR = "author-mom" +const cid = Schema.decodeSync(CaptureId) + +const services = (entries: InMemoryEntryStore): CaptureServices => ({ + extraction: makeDeterministicExtractor(), + entries, +}) + +const checks: Array<{ name: string; pass: boolean }> = [] +const check = (name: string, pass: boolean) => { + checks.push({ name, pass }) +} + +const run = async () => { + // ── Journey 1: happy path — raw persisted before events, then published ── + { + const store = makeInMemoryEntryStore() + const loop = makeCaptureLoop(services(store)) + const dispatch = (m: object) => Effect.runPromise(loop.dispatch(m as never)) + + await dispatch({ _tag: "CaptureStarted", captureId: "cap-1", childId: CHILD, authorId: AUTHOR }) + await dispatch({ + _tag: "CompletedTranscription", + captureId: "cap-1", + transcript: "She drank 6 ounces of formula at 2 pm. Then she went down for a nap.", + at: BASE, + timezone: "America/New_York", + }) + + // Raw-first: after transcription settles, the durable draft exists with + // zero events, and only then does extraction attach events. + const mid = await Effect.runPromise(store.timeline(CHILD)) + const draft = mid.find((e) => e.captureId === "cap-1") + check("raw draft durably persisted on transcription", draft !== undefined) + check("raw transcript preserved byte-for-byte", draft?.rawTranscript === "She drank 6 ounces of formula at 2 pm. Then she went down for a nap.") + + await dispatch({ _tag: "SubmittedForExtraction", captureId: "cap-1" }) + const extracted = await Effect.runPromise(store.timeline(CHILD)) + const withEvents = extracted.find((e) => e.captureId === "cap-1") + check("extraction attached events to the durable draft", (withEvents?.events.length ?? 0) > 0) + check("log ordering honors raw-before-events", (withEvents?.events.length ?? 0) > 0 && draft !== undefined && draft.events.length === 0) + check( + "meal event carries ounce quantity", + withEvents?.events.some((e) => e.category === "meal" && e.quantity?.unit === "oz" && e.quantity.value === 6) === true, + ) + check("occurredAt resolved to absolute millis", withEvents?.events.every((e) => Number.isFinite(e.occurredAt)) === true) + + await dispatch({ _tag: "ConfirmedReview", captureId: "cap-1", at: BASE + 1000 }) + const afterPublish = (await Effect.runPromise(store.timeline(CHILD))).find((e) => e.captureId === "cap-1") + check("publish flips visibility to published", afterPublish?.status === "published") + check("machine reached Published", loop.state()._tag === "Published") + } + + // ── Journey 2: store failure parks the machine; retry recovers ── + { + const realStore = makeInMemoryEntryStore() + const failing: InMemoryEntryStore = { + persistRawDraft: () => Effect.fail({ _tag: "unavailable" as const, reason: "storage down" }), + attachEvents: (captureId, events) => realStore.attachEvents(captureId, events), + publish: (captureId) => realStore.publish(captureId), + timeline: (childId) => realStore.timeline(childId), + reloadFromLog: () => realStore.reloadFromLog(), + rawLogSize: () => realStore.rawLogSize(), + } + const loop = makeCaptureLoop(services(failing)) + const dispatch = (m: object) => Effect.runPromise(loop.dispatch(m as never)) + + await dispatch({ _tag: "CaptureStarted", captureId: "cap-2", childId: CHILD, authorId: AUTHOR }) + await dispatch({ + _tag: "CompletedTranscription", + captureId: "cap-2", + transcript: "he had a wet diaper at 9:15 am", + at: BASE, + timezone: "America/New_York", + }) + const parkedState = loop.state() + check("store failure parks the machine with raw preserved", parkedState._tag === "RawPersistFailed") + check("parked state retains raw transcript", parkedState._tag === "RawPersistFailed" && parkedState.rawTranscript === "he had a wet diaper at 9:15 am") + + // Recovery: a working store and a fresh machine; re-run the journey — + // the deterministic pipeline converges to the same events. + const recovery = makeInMemoryEntryStore() + const recoveryLoop = makeCaptureLoop(services(recovery)) + const retryDispatch = (m: object) => Effect.runPromise(recoveryLoop.dispatch(m as never)) + await retryDispatch({ _tag: "CaptureStarted", captureId: "cap-2", childId: CHILD, authorId: AUTHOR }) + await retryDispatch({ + _tag: "CompletedTranscription", + captureId: "cap-2", + transcript: "he had a wet diaper at 9:15 am", + at: BASE, + timezone: "America/New_York", + }) + const recovered = await Effect.runPromise(recovery.timeline(CHILD)) + check( + "retry after park persists the raw draft", + recovered.some((e) => e.captureId === "cap-2" && e.rawTranscript === "he had a wet diaper at 9:15 am"), + ) + } + + // ── Journey 3: idempotent replay + publish idempotence + reload stability ── + { + const store = makeInMemoryEntryStore() + const transcript = "she had 4 oz bottle around 10:30 am" + const first = await Effect.runPromise( + store.persistRawDraft({ captureId: cid("cap-3"), childId: CHILD, authorId: AUTHOR, rawTranscript: transcript, createdAt: BASE }), + ) + const replay = await Effect.runPromise( + store.persistRawDraft({ captureId: cid("cap-3"), childId: CHILD, authorId: AUTHOR, rawTranscript: transcript, createdAt: BASE }), + ) + check("duplicate persist returns the existing entry (idempotent replay)", replay.captureId === first.captureId && store.rawLogSize() === 1) + + await Effect.runPromise( + store.attachEvents("cap-3", [ + { _tag: "Event", category: "meal", occurredAt: BASE, quantity: { value: 4, unit: "oz" }, confidence: 0.9, authorId: AUTHOR }, + ]), + ) + await Effect.runPromise(store.publish("cap-3")) + await Effect.runPromise(store.publish("cap-3")) // idempotent publish + const beforeReload = await Effect.runPromise(store.timeline(CHILD)) + await Effect.runPromise(store.reloadFromLog()) + const afterReload = await Effect.runPromise(store.timeline(CHILD)) + check("reload is byte-stable (no loss/dup/mutation)", JSON.stringify(afterReload) === JSON.stringify(beforeReload)) + check("reloaded entry stays published with events", afterReload[0]?.status === "published" && afterReload[0]?.events.length === 1) + } + + // ── Journey 4: stale-result guard (candidate D) ── + { + const store = makeInMemoryEntryStore() + const loop = makeCaptureLoop(services(store)) + const dispatch = (m: object) => Effect.runPromise(loop.dispatch(m as never)) + await dispatch({ _tag: "CaptureStarted", captureId: "cap-1", childId: CHILD, authorId: AUTHOR }) + await dispatch({ + _tag: "CompletedTranscription", + captureId: "cap-1", + transcript: "wet diaper 9:15 am", + at: BASE, + timezone: "America/New_York", + }) + await dispatch({ _tag: "SubmittedForExtraction", captureId: "cap-1" }) + // A late result for a DIFFERENT capture id must be ignored, not applied. + await dispatch({ _tag: "SucceededExtraction", captureId: "cap-other", events: [] }) + check("stale result for another capture ignored", loop.state()._tag === "Review") + } + + const failed = checks.filter((c) => !c.pass) + for (const c of checks) console.log(`${c.pass ? "✅" : "❌"} ${c.name}`) + console.log(`\n${checks.length - failed.length}/${checks.length} journey checks passed`) + if (failed.length > 0) process.exit(1) +} + +run().catch((error) => { + console.error("journey probe crashed:", error) + process.exit(1) +}) diff --git a/packages/capture/src/loop.test.ts b/packages/capture/src/loop.test.ts new file mode 100644 index 0000000..e3c47d1 --- /dev/null +++ b/packages/capture/src/loop.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Schema } from "effect" +import { CaptureId } from "@journal/domain" + +import { update } from "./update.js" +import { makeCaptureLoop } from "./runtime.js" +import { makeInMemoryEntryStore } from "./services/entries.js" +import { makeDeterministicExtractor } from "./services/extraction.js" +import { createIntegratedAdapter, CORPUS_CHILD_ID } from "./evaluation-adapter.js" +import { toCanonicalEvent } from "./wire.js" +import { resolveOccurredAt } from "./services/relativeTime.js" + +import type { CaptureServices } from "./runtime.js" + +const BASE = 1_760_000_000_000 +const TZ = "America/New_York" +const cid = Schema.decodeSync(CaptureId) + +const services = (): CaptureServices => ({ + extraction: makeDeterministicExtractor(), + entries: makeInMemoryEntryStore(), +}) + +const drive = async (svc: CaptureServices, messages: ReadonlyArray) => { + const loop = makeCaptureLoop(svc) + for (const m of messages) await Effect.runPromise(loop.dispatch(m as never)) + return loop +} + +describe("capture reducer", () => { + test("unmatched capture ids are ignored (stale-result guard)", () => { + const next = update({ _tag: "Recording", captureId: cid("a"), childId: "c", authorId: "p" }, { + _tag: "SucceededExtraction", + captureId: cid("b"), + events: [], + }) + expect(next[0]._tag).toBe("Recording") + expect(next[1]).toEqual([]) + }) + + test("transcription persists the raw draft first — extraction waits for submission", () => { + const [, commands] = update({ _tag: "Recording", captureId: cid("a"), childId: "c", authorId: "p" }, { + _tag: "CompletedTranscription", + captureId: cid("a"), + transcript: "hello", + at: BASE, + timezone: TZ, + }) + expect(commands.map((c) => c._tag)).toEqual(["PersistRawDraft"]) + const [next, extract] = update( + { _tag: "Transcribed", captureId: cid("a"), childId: "c", authorId: "p", rawTranscript: "hello", capturedAt: BASE, timezone: TZ }, + { _tag: "SubmittedForExtraction", captureId: cid("a") }, + ) + expect(next._tag).toBe("Extracting") + expect(extract.map((c) => c._tag)).toEqual(["ExtractEvents"]) + }) + + test("extract failure returns to Transcribed with raw preserved (raw already durable)", () => { + const [next] = update( + { _tag: "Extracting", captureId: cid("a"), childId: "c", authorId: "p", rawTranscript: "raw", capturedAt: BASE, timezone: TZ }, + { _tag: "FailedExtraction", captureId: cid("a"), reason: "boom" }, + ) + expect(next._tag).toBe("Transcribed") + if (next._tag === "Transcribed") expect(next.rawTranscript).toBe("raw") + }) + + test("retry persist re-issues PersistRawDraft from the park", () => { + const [, commands] = update( + { _tag: "RawPersistFailed", captureId: cid("a"), childId: "c", authorId: "p", rawTranscript: "raw", capturedAt: BASE, timezone: TZ, reason: "down" }, + { _tag: "RetryPersistRaw", captureId: cid("a") }, + ) + expect(commands.map((c) => c._tag)).toEqual(["PersistRawDraft"]) + }) + + test("store failure from Review also parks (no publish without durable events)", () => { + const [parked] = update( + { _tag: "Review", captureId: cid("a"), childId: "c", authorId: "p", rawTranscript: "raw", events: [], capturedAt: BASE, timezone: TZ }, + { _tag: "RawDraftPersistFailed", captureId: cid("a"), reason: "storage down" }, + ) + expect(parked._tag).toBe("RawPersistFailed") + }) +}) + +describe("integrated pipeline via loop", () => { + test("happy path: raw draft → events → published", async () => { + const loop = await drive(services(), [ + { _tag: "CaptureStarted", captureId: "cap-1", childId: "child", authorId: "mom" }, + { _tag: "CompletedTranscription", captureId: "cap-1", transcript: "wet diaper at 9:15 am", at: BASE, timezone: TZ }, + { _tag: "SubmittedForExtraction", captureId: "cap-1" }, + { _tag: "ConfirmedReview", captureId: "cap-1", at: BASE + 1_000 }, + ]) + expect(loop.state()._tag).toBe("Published") + }) + + test("raw-first: durable draft exists with zero events after transcription", async () => { + const entries = makeInMemoryEntryStore() + const svc: CaptureServices = { extraction: makeDeterministicExtractor(), entries } + await drive(svc, [ + { _tag: "CaptureStarted", captureId: "cap-1", childId: "child", authorId: "mom" }, + { _tag: "CompletedTranscription", captureId: "cap-1", transcript: "wet diaper at 9:15 am", at: BASE, timezone: TZ }, + ]) + const timeline = await Effect.runPromise(entries.timeline("child")) + expect(timeline).toHaveLength(1) + expect(timeline[0]?.rawTranscript).toBe("wet diaper at 9:15 am") + expect(timeline[0]?.events).toEqual([]) + }) +}) + +describe("corpus adapter (CandidateAdapter shape)", () => { + test("createEntry persists draft-with-events, idempotent on replay", async () => { + const adapter = createIntegratedAdapter() + const first = await adapter.createEntry({ + captureId: "fx-1", + transcript: "she had 6 oz bottle at 2 pm", + authorId: "mom", + capturedAt: BASE, + timezone: TZ, + }) + expect(first._tag).toBe("Created") + if (first._tag === "Created") { + expect(first.entry.status).toBe("draft") + expect(first.entry.events.length).toBeGreaterThan(0) + } + const replay = await adapter.createEntry({ + captureId: "fx-1", + transcript: "she had 6 oz bottle at 2 pm", + authorId: "mom", + capturedAt: BASE, + timezone: TZ, + }) + expect(replay._tag).toBe("IdempotentReplay") + }) + + test("empty transcript is rejected, never persisted", async () => { + const adapter = createIntegratedAdapter() + const result = await adapter.createEntry({ + captureId: "fx-empty", + transcript: "", + authorId: "mom", + capturedAt: BASE, + timezone: TZ, + }) + expect(result._tag).toBe("Rejected") + expect((await adapter.readTimeline()).find((e) => e.captureId === "fx-empty")).toBeUndefined() + }) + + test("malformed transcript still creates an eventless draft with raw preserved", async () => { + const adapter = createIntegratedAdapter() + const result = await adapter.createEntry({ + captureId: "fx-malformed", + transcript: " \x01\x02garbled\x03 ", + authorId: "mom", + capturedAt: BASE, + timezone: TZ, + }) + expect(result._tag).toBe("Created") + if (result._tag === "Created") { + expect(result.entry.events).toEqual([]) + expect(result.entry.transcript).toBe(" \x01\x02garbled\x03 ") + } + }) + + test("reload is stable: identical timeline after cold-start simulation", async () => { + const adapter = createIntegratedAdapter() + await adapter.createEntry({ + captureId: "fx-rl", + transcript: "napped 1:30 hours at 1 pm", + authorId: "mom", + capturedAt: BASE, + timezone: TZ, + }) + const before = await adapter.readTimeline() + await adapter.reload() + const after = await adapter.readTimeline() + expect(JSON.stringify(after)).toBe(JSON.stringify(before)) + }) +}) + +describe("wire codecs", () => { + test("capture-wire event maps into the canonical Event contract", () => { + const canonical = toCanonicalEvent( + { _tag: "Event", category: "meal", occurredAt: BASE, quantity: { value: 6, unit: "oz" }, confidence: 1, authorId: "mom" }, + "household", + "child", + ) + expect(canonical.timestamp).toBe(BASE) + expect(canonical.category).toBe("meal") + }) + + test("relative resolution is deterministic and DST-safe", () => { + expect(resolveOccurredAt({ transcript: "just now", capturedAt: BASE, timezone: TZ })).toBe(BASE) + expect(resolveOccurredAt({ transcript: "an hour ago", capturedAt: BASE, timezone: TZ })).toBe(BASE - 3_600_000) + const resolved = resolveOccurredAt({ transcript: "yesterday 9:15 am", capturedAt: BASE, timezone: TZ }) + expect(resolved).toBeDefined() + }) +}) diff --git a/packages/capture/src/runtime.ts b/packages/capture/src/runtime.ts new file mode 100644 index 0000000..93c1f44 --- /dev/null +++ b/packages/capture/src/runtime.ts @@ -0,0 +1,107 @@ +/** + * Runtime glue (candidate D's loop, adapted to the grafted command set): maps + * each command to the matching service effect and folds both outcomes back + * into result-messages, so the reducer stays the ONLY decision point. Command + * execution is sequential — a raw draft is durably persisted before + * extraction runs, preserving raw-before-events by construction. + */ +import { Effect } from "effect" + +import { update } from "./update.js" + +import type { CaptureState, CaptureMessage } from "./state.js" +import type { CaptureCommand } from "./commands.js" +import type { EntryStoreShape, StoreError } from "./services/entries.js" +import type { ExtractionServiceShape } from "./services/extraction.js" + +export interface CaptureServices { + readonly extraction: ExtractionServiceShape + readonly entries: EntryStoreShape +} + +const describeStoreError = (error: StoreError): string => + error._tag === "raw_capture_missing" ? `no durable raw draft for capture ${error.captureId}` : error.reason + +/** + * Execute one command, producing the result-messages to dispatch. Every + * failure path is a typed message — none of the store or extractor errors is + * swallowed. + */ +export const executeCommand = ( + services: CaptureServices, + command: CaptureCommand, +): Effect.Effect> => { + switch (command._tag) { + case "PersistRawDraft": + return services.entries + .persistRawDraft({ + captureId: command.captureId, + childId: command.childId, + authorId: command.authorId, + rawTranscript: command.rawTranscript, + createdAt: command.createdAt, + }) + .pipe( + Effect.match({ + onSuccess: (entry) => [{ _tag: "RawDraftPersisted", captureId: command.captureId, entryId: entry.captureId }], + onFailure: (error) => [{ _tag: "RawDraftPersistFailed", captureId: command.captureId, reason: describeStoreError(error) }], + }), + ) + case "ExtractEvents": + return services.extraction + .extract({ + captureId: command.captureId, + childId: command.childId, + authorId: command.authorId, + transcript: command.transcript, + capturedAt: command.capturedAt, + timezone: command.timezone, + }) + .pipe( + Effect.match({ + onSuccess: (events) => [{ _tag: "SucceededExtraction", captureId: command.captureId, events }], + onFailure: (error) => [{ _tag: "FailedExtraction", captureId: command.captureId, reason: error.reason }], + }), + ) + case "AttachEvents": + return services.entries.attachEvents(command.captureId, command.events).pipe( + Effect.match({ + onSuccess: () => [{ _tag: "EventsAttached", captureId: command.captureId }], + onFailure: (error) => [{ _tag: "RawDraftPersistFailed", captureId: command.captureId, reason: describeStoreError(error) }], + }), + ) + case "PublishEntry": + return services.entries.publish(command.captureId).pipe( + Effect.match({ + onSuccess: ({ entryId }) => [{ _tag: "PublishedEntry", captureId: command.captureId, entryId }], + onFailure: (error) => [{ _tag: "FailedPublish", captureId: command.captureId, reason: describeStoreError(error) }], + }), + ) + } +} + +export interface CaptureLoop { + /** Dispatch a message; runs commands the update emits (sequentially). */ + readonly dispatch: (message: CaptureMessage) => Effect.Effect + readonly state: () => CaptureState +} + +export const makeCaptureLoop = (services: CaptureServices, onState?: (state: CaptureState) => void): CaptureLoop => { + let current: CaptureState = { _tag: "Idle" } + + const dispatch = (message: CaptureMessage): Effect.Effect => + Effect.suspend(() => { + const [next, commands] = update(current, message) + if (next !== current) { + current = next + onState?.(current) + } + return Effect.forEach(commands, (command) => + executeCommand(services, command).pipe( + Effect.flatMap((resultMessages) => Effect.forEach(resultMessages, (resultMessage) => dispatch(resultMessage))), + ), + ).pipe(Effect.asVoid) + }) + + return { dispatch, state: () => current } +} diff --git a/packages/capture/src/services/entries.ts b/packages/capture/src/services/entries.ts new file mode 100644 index 0000000..3a983bb --- /dev/null +++ b/packages/capture/src/services/entries.ts @@ -0,0 +1,171 @@ +/** + * Entry store boundary (candidate D's storage service, extended by the grafts): + * the pipeline's only write surface for capture entries. + * + * The store's contract encodes the two invariants the arena integration + * settles: + * 1. RAW-FIRST (candidate C): the first write of a capture is ALWAYS the + * verbatim raw transcript, as a `draft` entry — `attachEvents` and + * `publish` both fail with `raw_capture_missing` if no draft exists, so no + * extracted event can ever outlive or precede the caregiver's words. + * 2. IDEMPOTENCE (envelope semantics (c) — same (captureId, attempt) applied + * twice is a no-op): persisting the same raw draft, attaching the same + * events, or publishing the same entry twice returns the existing state + * instead of duplicating rows. + * + * The in-memory double keeps an append-only raw log so `reloadFromLog` + * reproduces candidate B's cold-start read-path semantics locally. + */ +import { Effect } from "effect" + +import type { CaptureId } from "@journal/domain" +import type { CapturedEntry, CapturedEvent } from "../event.js" + +export type { CapturedEntry, CapturedEvent } + +export type StoreError = + | { readonly _tag: "raw_capture_missing"; readonly captureId: string } + | { readonly _tag: "unavailable"; readonly reason: string } + +export interface DraftInput { + readonly captureId: CaptureId + readonly childId: string + readonly authorId: string + /** Verbatim dictated text — stored byte-for-byte, no normalization. */ + readonly rawTranscript: string + /** Capture instant (Unix ms) — never process time. */ + readonly createdAt: number +} + +export interface EntryStoreShape { + /** Create (or idempotently return) the raw-first draft entry. */ + persistRawDraft: (draft: DraftInput) => Effect.Effect + /** Attach extracted events to the existing draft (set-once per capture). */ + attachEvents: (captureId: string, events: ReadonlyArray) => Effect.Effect + /** Flip the draft to published visibility (idempotent). */ + publish: (captureId: string) => Effect.Effect<{ readonly entryId: string }, StoreError> + /** The child's timeline, oldest first — draft and published alike, per contract. */ + timeline: (childId: string) => Effect.Effect, StoreError> +} + +/** Raw-byte-safe identity check: same transcript bytes count as the same draft. */ +const sameDraft = (existing: CapturedEntry, draft: DraftInput): boolean => + existing.captureId === draft.captureId && existing.rawTranscript === draft.rawTranscript + +const sameEvents = (a: ReadonlyArray, b: ReadonlyArray): boolean => + a.length === b.length && a.every((event, index) => JSON.stringify(event) === JSON.stringify(b[index])) + +export interface InMemoryEntryStore extends EntryStoreShape { + /** Cold-start read-path probe: rebuild indexes from the durable raw log. */ + reloadFromLog: () => Effect.Effect + /** Test/inspection surface: count of durable raw-draft log records. */ + rawLogSize: () => number +} + +export const makeInMemoryEntryStore = (): InMemoryEntryStore => { + const entries = new Map() + /** + * Durable op log (the reload double's source of truth): every mutation is + * appended here in order; `reloadFromLog` replays it exactly, so the + * post-reload timeline is identical to the pre-reload one — no lost, + * duplicated, reordered, or mutated events (fixture 06 semantics). + */ + const durableLog: Array< + | { readonly kind: "draft"; readonly draft: DraftInput } + | { readonly kind: "attach"; readonly captureId: string; readonly events: ReadonlyArray } + | { readonly kind: "publish"; readonly captureId: string } + > = [] + + const persistRawDraft = (draft: DraftInput): Effect.Effect => + Effect.suspend((): Effect.Effect => { + const existing = entries.get(draft.captureId) + if (existing !== undefined) { + // Idempotent replay (fixture 04): identical raw bytes → same entry. + if (sameDraft(existing, draft)) return Effect.succeed(existing) + return Effect.fail({ _tag: "unavailable" as const, reason: `captureId ${draft.captureId} already exists with different raw content` }) + } + const entry: CapturedEntry = { + _tag: "Entry", + captureId: draft.captureId, + childId: draft.childId, + authorId: draft.authorId, + rawTranscript: draft.rawTranscript, + createdAt: draft.createdAt, + status: "draft", + events: [], + } + entries.set(draft.captureId, entry) + durableLog.push({ kind: "draft", draft: { ...draft } }) + return Effect.succeed(entry) + }) + + const attachEvents = ( + captureId: string, + events: ReadonlyArray, + ): Effect.Effect => + Effect.suspend((): Effect.Effect => { + const entry = entries.get(captureId) + // Raw-before-events (candidate B's invariant, enforced client-side here + // and server-side in backend/convex): no events without a raw draft. + if (entry === undefined) return Effect.fail({ _tag: "raw_capture_missing" as const, captureId }) + if (sameEvents(entry.events, events)) return Effect.succeed(entry) + if (entry.events.length > 0) { + return Effect.fail({ _tag: "unavailable" as const, reason: `entry ${captureId} already carries different events` }) + } + const updated: CapturedEntry = { ...entry, events: [...events] } + entries.set(captureId, updated) + durableLog.push({ kind: "attach", captureId, events: [...events] }) + return Effect.succeed(updated) + }) + + const publish = (captureId: string): Effect.Effect<{ readonly entryId: string }, StoreError> => + Effect.suspend((): Effect.Effect<{ readonly entryId: string }, StoreError> => { + const entry = entries.get(captureId) + if (entry === undefined) return Effect.fail({ _tag: "raw_capture_missing" as const, captureId }) + if (entry.status === "published") return Effect.succeed({ entryId: entry.captureId }) + entries.set(captureId, { ...entry, status: "published" }) + durableLog.push({ kind: "publish", captureId }) + return Effect.succeed({ entryId: entry.captureId }) + }) + + const timeline = (childId: string) => + Effect.succeed( + [...entries.values()].filter((entry) => entry.childId === childId).sort((a, b) => a.createdAt - b.createdAt), + ) + + const reloadFromLog = () => + Effect.sync(() => { + entries.clear() + for (const op of durableLog) { + if (op.kind === "draft") { + const draft = op.draft + const entry: CapturedEntry = { + _tag: "Entry", + captureId: draft.captureId, + childId: draft.childId, + authorId: draft.authorId, + rawTranscript: draft.rawTranscript, + createdAt: draft.createdAt, + status: "draft", + events: [], + } + entries.set(draft.captureId, entry) + } else if (op.kind === "attach") { + const entry = entries.get(op.captureId) + if (entry !== undefined) entries.set(op.captureId, { ...entry, events: [...op.events] }) + } else { + const entry = entries.get(op.captureId) + if (entry !== undefined) entries.set(op.captureId, { ...entry, status: "published" }) + } + } + }) + + return { + persistRawDraft, + attachEvents, + publish, + timeline, + reloadFromLog, + rawLogSize: () => durableLog.length, + } +} diff --git a/packages/capture/src/services/extraction.ts b/packages/capture/src/services/extraction.ts new file mode 100644 index 0000000..4c274ce --- /dev/null +++ b/packages/capture/src/services/extraction.ts @@ -0,0 +1,128 @@ +/** + * Extraction boundary (candidate D's three layers, kept): + * 1. interface — what the pipeline needs from "an extractor" + * 2. deterministic double — pure rule-based extraction (no LLM), carrying the + * acceptance corpus's worked-example conventions for categories, relative + * time, and quantities (the conventions the arena integration brief + * directs us to graft). + * 3. faulty double — emits a schema-invalid event (confidence 1.5) to prove + * the schema boundary rejects bad candidates before they reach state. + * + * Every candidate event is re-decoded through `CapturedEventSchema` before it + * is returned — the extractor's output is never trusted on its own. + */ +import { Effect, Schema } from "effect" + +import { resolveOccurredAt } from "./relativeTime.js" +import { CapturedEventSchema } from "../event.js" + +import type { CapturedEvent } from "../event.js" + +export interface ExtractionInput { + readonly captureId: string + readonly childId: string + readonly authorId: string + readonly transcript: string + readonly capturedAt: number + readonly timezone: string +} + +export type ExtractionError = { readonly _tag: "ExtractionFailed"; readonly reason: string } + +export interface ExtractionServiceShape { + extract: (input: ExtractionInput) => Effect.Effect, ExtractionError> +} + +/** Corpus convention: events carry a fixed unconfirmed confidence marker. */ +const UNCONFIRMED_CONFIDENCE = 0.9 + +/** + * Category rules, example-adapter order (first match wins per sentence) with + * the canonical taxonomy's remaining categories appended last. Patterns are + * corpus-tuned (e.g. "went poop on the potty", "giggly", "drank ... ounces"). + */ +const CATEGORY_RULES: ReadonlyArray<{ + readonly category: CapturedEvent["category"] + readonly pattern: RegExp +}> = [ + { category: "potty", pattern: /\bpoop(?:ed|ing)?\b|\bpotty\b/i }, + { category: "sleep", pattern: /\bwoke up\b|\bnap(?:ped)?\b|\bbedtime\b|\bsleepy\b|\basleep\b|\bsleep\b/i }, + { category: "mood", pattern: /\bhappy\b|\bgiggly\b|\bgrumpy\b|\bsad\b|\bfussy\b|\bcheerful\b/i }, + { category: "meal", pattern: /\bmilk\b|\bpasta\b|\bwater\b|\bbreakfast\b|\blunch\b|\bdinner\b|\bsnack\b|\bate\b|\bdrank\b|\bhad\b/i }, + { category: "milestone", pattern: /\bfirst time\b|\bcrawled\b|\brolled over\b|\btook steps\b/i }, + { category: "school", pattern: /\bschool\b|\bdaycare\b|\bteacher\b/i }, +] + +const QUANTITY_PATTERN = /(\d+(?:\.\d+)?)\s+ounces? of/i + +/** Example-adapter sentence split; control-char transcripts stay one segment. */ +const splitSentences = (transcript: string): ReadonlyArray => + transcript + .split(/(?<=[.!?])\s+/) + .map((sentence) => sentence.trim()) + .filter((sentence) => sentence.length > 0) + +const extractionError = (error: unknown): ExtractionError => ({ + _tag: "ExtractionFailed", + reason: error instanceof Error ? error.message : String(error), +}) + +/** + * The deterministic double: per sentence, first matching category rule wins; + * a category mention with no resolvable time yields NO event (never invent an + * instant); every candidate is decoded through `CapturedEventSchema`, so a + * rule bug fails the extraction instead of smuggling invalid data downstream. + */ +export const makeDeterministicExtractor = (): ExtractionServiceShape => ({ + extract: (input: ExtractionInput) => + Effect.try({ + try: () => { + const events: CapturedEvent[] = [] + for (const sentence of splitSentences(input.transcript)) { + const rule = CATEGORY_RULES.find((candidate) => candidate.pattern.test(sentence)) + if (rule === undefined) continue + const occurredAt = resolveOccurredAt({ + transcript: sentence, + capturedAt: input.capturedAt, + timezone: input.timezone, + }) + if (occurredAt === undefined) continue + const quantityMatch = QUANTITY_PATTERN.exec(sentence) + const candidate = { + _tag: "Event" as const, + category: rule.category, + occurredAt, + ...(quantityMatch === null ? {} : { quantity: { value: Number(quantityMatch[1]), unit: "oz" } }), + confidence: UNCONFIRMED_CONFIDENCE, + authorId: input.authorId, + note: sentence, + } + // Schema boundary: decode (don't cast) so an invalid candidate + // fails the extraction instead of reaching state or storage. + events.push(Schema.decodeUnknownSync(CapturedEventSchema)(candidate)) + } + return events + }, + catch: extractionError, + }), +}) + +/** + * Faulty double: announces a valid-looking event with confidence 1.5 — outside + * the canonical range. Decoding must reject it, proving the boundary is real. + */ +export const makeFaultyExtractor = (): ExtractionServiceShape => ({ + extract: (input: ExtractionInput) => + Effect.try({ + try: () => [ + Schema.decodeSync(CapturedEventSchema)({ + _tag: "Event", + category: "potty", + occurredAt: input.capturedAt, + confidence: 1.5, + authorId: input.authorId, + }), + ], + catch: extractionError, + }), +}) diff --git a/packages/capture/src/services/relativeTime.ts b/packages/capture/src/services/relativeTime.ts new file mode 100644 index 0000000..4407f8e --- /dev/null +++ b/packages/capture/src/services/relativeTime.ts @@ -0,0 +1,127 @@ +/** + * Deterministic relative-time resolution — the acceptance corpus's worked + * example adapter conventions (art_I2TCG08V / PR #6 harness expectations), + * grafted into the capture pipeline per the arena integration brief: + * relative-time + quantity extraction is unsolved in all four candidates, so + * the example adapter's conventions ARE the contract. + * + * All functions are pure; "local" always means the capture's IANA zone and the + * UTC offset used is the one in force AT the resolved instant (DST-safe). + */ + +const HOUR_MS = 3_600_000 + +/** + * UTC offset (ms east of UTC) for `zone` at `instant`. Uses Intl.DateTimeFormat + * with timeZoneName: "longOffset" (e.g. "GMT-04:00"); throws for zones Intl + * does not know — malformed zones must fail loudly, not silently become UTC. + */ +export const zoneOffsetMs = (zone: string, instant: number): number => { + const parts = new Intl.DateTimeFormat("en-US", { + timeZone: zone, + timeZoneName: "longOffset", + }).formatToParts(new Date(instant)) + const gmt = parts.find((part) => part.type === "timeZoneName")?.value ?? "" + const match = /^GMT([+-])(\d{2}):(\d{2})$/.exec(gmt) + if (match === null) { + throw new Error(`Unrecognized timezone offset for zone "${zone}": "${gmt}"`) + } + const sign = match[1] === "+" ? 1 : -1 + const hours = Number(match[2]) + const minutes = Number(match[3]) + return sign * (hours * HOUR_MS + minutes * 60_000) +} + +/** + * Resolve a wall-clock time in `zone` to a UTC instant, using the offset at + * the target instant itself (probe, then correct once) — DST-safe: a wall time + * inside the spring-forward gap resolves to the offset of the instant it maps + * to, matching the corpus convention. + */ +export const wallToUtc = ( + zone: string, + year: number, + month: number, + day: number, + hours: number, + minutes: number, +): number => { + const guess = Date.UTC(year, month - 1, day, hours, minutes) + const probeOffset = zoneOffsetMs(zone, guess) + const target = guess - probeOffset + const actualOffset = zoneOffsetMs(zone, target) + return guess - actualOffset +} + +/** Wall-clock Y/M/D of `instant` in `zone`. */ +export const captureWallDate = (zone: string, instant: number): { year: number; month: number; day: number } => { + const parts = new Intl.DateTimeFormat("en-US", { + timeZone: zone, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).formatToParts(new Date(instant)) + const get = (type: Intl.DateTimeFormatPartTypes): number => { + const value = parts.find((part) => part.type === type)?.value + if (value === undefined) throw new Error(`Missing ${type} part for zone "${zone}"`) + return Number(value) + } + return { year: get("year"), month: get("month"), day: get("day") } +} + +/** "8:00 AM"/"6pm" style 12-hour clock to 24h. Midnight is 00, noon is 12. */ +export const to24h = (hours: number, minutes: number, meridiem: string): { hours: number; minutes: number } => { + const normalized = meridiem.toLowerCase() + if (normalized === "am") { + return { hours: hours === 12 ? 0 : hours, minutes } + } + return { hours: hours === 12 ? 12 : hours + 12, minutes } +} + +export interface RelativeTimeInput { + readonly transcript: string + /** Capture instant (Unix ms) — the anchor for every relative expression. */ + readonly capturedAt: number + readonly timezone: string +} + +/** + * Resolve the FIRST time expression in the sentence against the capture + * instant and zone. Ordered most-specific first, mirroring the example + * adapter; returns undefined when no expression resolves (convention: the + * sentence yields no event rather than inventing an instant). + */ +export const resolveOccurredAt = (input: RelativeTimeInput): number | undefined => { + const { transcript, capturedAt, timezone } = input + + const yesterdayClock = /\byesterday\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b/i.exec(transcript) + if (yesterdayClock !== null) { + const { year, month, day } = captureWallDate(timezone, capturedAt) + const yesterday = new Date(wallToUtc(timezone, year, month, day, 12, 0) - 24 * HOUR_MS) + const yesterdayWall = captureWallDate(timezone, yesterday.getTime()) + const { hours, minutes } = to24h(Number(yesterdayClock[1]!), Number(yesterdayClock[2] ?? 0), yesterdayClock[3]!) + return wallToUtc(timezone, yesterdayWall.year, yesterdayWall.month, yesterdayWall.day, hours, minutes) + } + + const clock = /\bat\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b/i.exec(transcript) + if (clock !== null) { + const { year, month, day } = captureWallDate(timezone, capturedAt) + const { hours, minutes } = to24h(Number(clock[1]!), Number(clock[2] ?? 0), clock[3]!) + return wallToUtc(timezone, year, month, day, hours, minutes) + } + + if (/\bthis morning\b/i.test(transcript)) { + const { year, month, day } = captureWallDate(timezone, capturedAt) + return wallToUtc(timezone, year, month, day, 8, 0) + } + + if (/\ban hour ago\b/i.test(transcript)) { + return capturedAt - HOUR_MS + } + + if (/\bjust now\b/i.test(transcript)) { + return capturedAt + } + + return undefined +} diff --git a/packages/capture/src/state.ts b/packages/capture/src/state.ts new file mode 100644 index 0000000..05c2ced --- /dev/null +++ b/packages/capture/src/state.ts @@ -0,0 +1,173 @@ +/** + * Capture slice — the state machine as executable schemas (Foldkit R1/R2). + * Base skeleton: candidate D's machine; grafted: the `RawPersistFailed` park + * (candidate A's explicit failure-park modeling) and the messages that drive + * raw-first draft persistence (candidate C's design). + * + * States: Idle / Recording / Transcribed / Extracting / Review / Published / + * RawPersistFailed. The "Recording" state is the synthetic-transcript composer + * (text entry stands in for audio; dictation findings art_tXjksHOh cover the + * later native path). `rawTranscript` is carried unchanged through every + * post-transcription state so failures never lose raw input, and the raw text + * is durably persisted as a draft entry at the moment transcription completes. + * + * Every message is a fact named in past/present tense; `captureId` is carried + * on every post-start message and guarded in the reducer so stale results + * from a previous capture can never mutate a newer one. + */ +import { Schema } from "effect" + +import { CaptureId } from "@journal/domain" + +import { CapturedEventSchema } from "./event.js" + +export const Idle = Schema.TaggedStruct("Idle", {}) +export type Idle = Schema.Schema.Type + +export const Recording = Schema.TaggedStruct("Recording", { + captureId: CaptureId, + childId: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, +}) +export type Recording = Schema.Schema.Type + +export const Transcribed = Schema.TaggedStruct("Transcribed", { + captureId: CaptureId, + childId: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, + rawTranscript: Schema.NonEmptyString, + /** Capture instant (Unix ms) — the draft's `createdAt`, never process time. */ + capturedAt: Schema.Number, + /** IANA zone for relative-time resolution during extraction. */ + timezone: Schema.String, +}) +export type Transcribed = Schema.Schema.Type + +export const Extracting = Schema.TaggedStruct("Extracting", { + captureId: CaptureId, + childId: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, + rawTranscript: Schema.NonEmptyString, + capturedAt: Schema.Number, + timezone: Schema.String, +}) +export type Extracting = Schema.Schema.Type + +export const Review = Schema.TaggedStruct("Review", { + captureId: CaptureId, + childId: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, + rawTranscript: Schema.NonEmptyString, + capturedAt: Schema.Number, + timezone: Schema.String, + events: Schema.Array(CapturedEventSchema), +}) +export type Review = Schema.Schema.Type + +export const Published = Schema.TaggedStruct("Published", { + captureId: CaptureId, + entryId: Schema.NonEmptyString, +}) +export type Published = Schema.Schema.Type + +/** + * Failure park (grafted from candidate A): raw-draft persistence failed, so + * the machine parks instead of proceeding to extraction — nothing downstream + * may exist without the durable raw draft (raw-before-events). Raw input is + * preserved in-state; `RetryPersistRaw` re-issues the persist command. + */ +export const RawPersistFailed = Schema.TaggedStruct("RawPersistFailed", { + captureId: CaptureId, + childId: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, + rawTranscript: Schema.NonEmptyString, + capturedAt: Schema.Number, + timezone: Schema.String, + reason: Schema.String, +}) +export type RawPersistFailed = Schema.Schema.Type + +export const CaptureState = Schema.Union([ + Idle, + Recording, + Transcribed, + Extracting, + Review, + Published, + RawPersistFailed, +]) +export type CaptureState = Schema.Schema.Type + +/** Tagged message union — every fact that can change the capture state. */ +export const CaptureStarted = Schema.TaggedStruct("CaptureStarted", { + captureId: CaptureId, + childId: Schema.NonEmptyString, + authorId: Schema.NonEmptyString, +}) +export const CompletedTranscription = Schema.TaggedStruct("CompletedTranscription", { + captureId: CaptureId, + transcript: Schema.NonEmptyString, + /** Capture instant (Unix ms) — resolves relative expressions and createdAt. */ + at: Schema.Number, + timezone: Schema.String, +}) +export const SubmittedForExtraction = Schema.TaggedStruct("SubmittedForExtraction", { + captureId: CaptureId, +}) +export const SucceededExtraction = Schema.TaggedStruct("SucceededExtraction", { + captureId: CaptureId, + events: Schema.Array(CapturedEventSchema), +}) +export const FailedExtraction = Schema.TaggedStruct("FailedExtraction", { + captureId: CaptureId, + reason: Schema.String, +}) +/** Raw draft persisted durably; no visible state change, the store owns the row. */ +export const RawDraftPersisted = Schema.TaggedStruct("RawDraftPersisted", { + captureId: CaptureId, + entryId: Schema.NonEmptyString, +}) +export const RawDraftPersistFailed = Schema.TaggedStruct("RawDraftPersistFailed", { + captureId: CaptureId, + reason: Schema.String, +}) +/** Re-issue the raw-draft persist after a park (candidate C's RetryPersistRaw). */ +export const RetryPersistRaw = Schema.TaggedStruct("RetryPersistRaw", { + captureId: CaptureId, +}) +/** Durable attach of extracted events confirmed (draft now carries events). */ +export const EventsAttached = Schema.TaggedStruct("EventsAttached", { + captureId: CaptureId, +}) +export const ConfirmedReview = Schema.TaggedStruct("ConfirmedReview", { + captureId: CaptureId, + at: Schema.DateFromMillis, +}) +export const PublishedEntry = Schema.TaggedStruct("PublishedEntry", { + captureId: CaptureId, + entryId: Schema.NonEmptyString, +}) +export const FailedPublish = Schema.TaggedStruct("FailedPublish", { + captureId: CaptureId, + reason: Schema.String, +}) +export const CancelledCapture = Schema.TaggedStruct("CancelledCapture", { + captureId: CaptureId, +}) + +export const CaptureMessage = Schema.Union([ + CaptureStarted, + CompletedTranscription, + SubmittedForExtraction, + SucceededExtraction, + FailedExtraction, + RawDraftPersisted, + RawDraftPersistFailed, + RetryPersistRaw, + EventsAttached, + ConfirmedReview, + PublishedEntry, + FailedPublish, + CancelledCapture, +]) +export type CaptureMessage = Schema.Schema.Type diff --git a/packages/capture/src/update.ts b/packages/capture/src/update.ts new file mode 100644 index 0000000..f489900 --- /dev/null +++ b/packages/capture/src/update.ts @@ -0,0 +1,230 @@ +/** + * Pure update: `[nextState, commands]` (Foldkit R3). No I/O, no clock, no + * navigation — side effects are described as commands. TypeScript exhaustively + * checks every message; unmatched (state, message) pairs are deliberate + * no-ops, never silent state changes. + * + * Stale-result guard (candidate D, kept verbatim): any message carrying a + * captureId that does not match the active state's captureId is ignored. + * + * Grafted behavior (candidates C + A + corpus status decision): + * - Entering Transcribed emits `PersistRawDraft` — the caregiver's words are + * durably persisted as a DRAFT entry before extraction can run, so a crash + * during extraction loses nothing (candidate C's raw-first design). + * - Raw-persist failure parks in `RawPersistFailed` (candidate A's explicit + * failure-park modeling) with raw input preserved in-state; + * `RetryPersistRaw` re-issues the persist command. + * - Extraction success emits `AttachEvents` — the extracted events attach to + * the existing draft, making "draft with events" the stored state at + * creation (corpus status-model decision; fixes D's draft-at-publish). + * - `PublishEntry` narrows to a status flip: the entry already exists, so + * confirm-and-publish cannot create a second row. + */ +import { Match } from "effect" + +import type { CaptureId } from "@journal/domain" + +import type { + CaptureMessage, + CaptureState, + Extracting, + RawPersistFailed, + Recording, + Review, + Transcribed, +} from "./state.js" + +import type { CaptureCommand } from "./commands.js" + +const activeCaptureIdOf = (state: CaptureState): string | undefined => + state._tag === "Idle" ? undefined : state.captureId + +/** Message applies only if it belongs to the capture the state is about. */ +const isStale = (state: CaptureState, message: CaptureMessage): boolean => { + if (!("captureId" in message)) return false + const activeCaptureId = activeCaptureIdOf(state) + if (activeCaptureId === undefined) return false + return message.captureId !== activeCaptureId +} + +export type UpdateResult = readonly [CaptureState, ReadonlyArray] + +const initialCaptureState: CaptureState = { _tag: "Idle" } + +const keepState = (state: CaptureState): UpdateResult => [state, []] + +const captureFieldsOf = ( + state: Extracting | RawPersistFailed | Transcribed | Review, +): { captureId: CaptureId; childId: string; authorId: string; rawTranscript: string; capturedAt: number; timezone: string } => ({ + captureId: state.captureId, + childId: state.childId, + authorId: state.authorId, + rawTranscript: state.rawTranscript, + capturedAt: state.capturedAt, + timezone: state.timezone, +}) + +export const update = (state: CaptureState, message: CaptureMessage): UpdateResult => { + if (isStale(state, message)) return keepState(state) + + return Match.value({ state, message }).pipe( + Match.when({ state: { _tag: "Idle" }, message: { _tag: "CaptureStarted" } }, ({ message }): UpdateResult => { + const started: Recording = { + _tag: "Recording", + captureId: message.captureId, + childId: message.childId, + authorId: message.authorId, + } + return [started, []] + }), + Match.when( + { state: { _tag: "Recording" }, message: { _tag: "CompletedTranscription" } }, + ({ state, message }): UpdateResult => { + const transcribed: Transcribed = { + _tag: "Transcribed", + captureId: state.captureId, + childId: state.childId, + authorId: state.authorId, + rawTranscript: message.transcript, + capturedAt: message.at, + timezone: message.timezone, + } + // Raw-first (candidate C): persist the draft at TextCaptured, before + // extraction runs. Same captureId makes the eventual publish idempotent. + const command: CaptureCommand = { + _tag: "PersistRawDraft", + captureId: state.captureId, + childId: state.childId, + authorId: state.authorId, + rawTranscript: message.transcript, + createdAt: message.at, + } + return [transcribed, [command]] + }, + ), + Match.when( + { state: { _tag: "Transcribed" }, message: { _tag: "SubmittedForExtraction" } }, + ({ state }): UpdateResult => { + const extracting: Extracting = { _tag: "Extracting", ...captureFieldsOf(state) } + const command: CaptureCommand = { + _tag: "ExtractEvents", + captureId: state.captureId, + childId: state.childId, + authorId: state.authorId, + transcript: state.rawTranscript, + capturedAt: state.capturedAt, + timezone: state.timezone, + } + return [extracting, [command]] + }, + ), + Match.when( + { state: { _tag: "Extracting" }, message: { _tag: "SucceededExtraction" } }, + ({ state, message }): UpdateResult => { + const review: Review = { + _tag: "Review", + ...captureFieldsOf(state), + events: [...message.events], + } + // Draft-with-events (corpus status decision): the events attach to the + // draft entry that raw-first persistence already created. + const command: CaptureCommand = { + _tag: "AttachEvents", + captureId: state.captureId, + events: message.events, + } + return [review, [command]] + }, + ), + Match.when( + { state: { _tag: "Extracting" }, message: { _tag: "FailedExtraction" } }, + ({ state }): UpdateResult => { + // Raw input survives untouched (in state AND as the durable draft); + // the same captureId retries extraction. + const transcribed: Transcribed = { _tag: "Transcribed", ...captureFieldsOf(state) } + return [transcribed, []] + }, + ), + // Raw-persist results: success changes nothing visible (the store owns the + // row); failure parks the machine with raw input preserved. + Match.when( + { state: { _tag: "Transcribed" }, message: { _tag: "RawDraftPersisted" } }, + ({ state }): UpdateResult => keepState(state), + ), + Match.when( + { state: { _tag: "Transcribed" }, message: { _tag: "RawDraftPersistFailed" } }, + ({ state, message }): UpdateResult => { + const parked: RawPersistFailed = { + _tag: "RawPersistFailed", + ...captureFieldsOf(state), + reason: message.reason, + } + return [parked, []] + }, + ), + Match.when( + { state: { _tag: "RawPersistFailed" }, message: { _tag: "RetryPersistRaw" } }, + ({ state, message }): UpdateResult => { + const transcribed: Transcribed = { _tag: "Transcribed", ...captureFieldsOf(state) } + const command: CaptureCommand = { + _tag: "PersistRawDraft", + captureId: state.captureId, + childId: state.childId, + authorId: state.authorId, + rawTranscript: state.rawTranscript, + createdAt: state.capturedAt, + } + return [transcribed, [command]] + }, + ), + Match.when( + { state: { _tag: "Review" }, message: { _tag: "ConfirmedReview" } }, + ({ state }): UpdateResult => { + // State stays Review until PublishedEntry arrives; retry on FailedPublish. + const command: CaptureCommand = { _tag: "PublishEntry", captureId: state.captureId } + return [state, [command]] + }, + ), + Match.when( + { state: { _tag: "Review" }, message: { _tag: "PublishedEntry" } }, + ({ state, message }): UpdateResult => { + const published: CaptureState = { + _tag: "Published", + captureId: state.captureId, + entryId: message.entryId, + } + return [published, []] + }, + ), + Match.when({ state: { _tag: "Review" }, message: { _tag: "FailedPublish" } }, ({ state }): UpdateResult => + keepState(state)), + // Attach results (Review): success confirms the draft now carries events + // durably; failure parks — publish must not run without durable events, + // and RetryPersistRaw's persist is idempotent, then re-extraction (a + // deterministic double) reproduces the same events. + Match.when({ state: { _tag: "Review" }, message: { _tag: "EventsAttached" } }, ({ state }): UpdateResult => + keepState(state)), + Match.when( + { state: { _tag: "Review" }, message: { _tag: "RawDraftPersistFailed" } }, + ({ state, message }): UpdateResult => { + const parked: RawPersistFailed = { + _tag: "RawPersistFailed", + ...captureFieldsOf(state), + reason: message.reason, + } + return [parked, []] + }, + ), + // Cancel is allowed from every state that still holds raw data. + Match.whenOr( + { state: { _tag: "Recording" }, message: { _tag: "CancelledCapture" } }, + { state: { _tag: "Transcribed" }, message: { _tag: "CancelledCapture" } }, + { state: { _tag: "Extracting" }, message: { _tag: "CancelledCapture" } }, + { state: { _tag: "Review" }, message: { _tag: "CancelledCapture" } }, + { state: { _tag: "RawPersistFailed" }, message: { _tag: "CancelledCapture" } }, + (): UpdateResult => [initialCaptureState, []], + ), + // Terminal state and every unmatched (state, message) pair are no-ops. + Match.orElse(({ state }) => keepState(state)), + ) +} diff --git a/packages/capture/src/wire.ts b/packages/capture/src/wire.ts new file mode 100644 index 0000000..892f6a1 --- /dev/null +++ b/packages/capture/src/wire.ts @@ -0,0 +1,68 @@ +/** + * Wire codecs (grafted from candidate C): the ONLY place the capture + * pipeline's wire vocabulary (`occurredAt`, structured `quantity`) meets the + * canonical domain vocabulary (`timestamp`, `payload` from @journal/domain). + * + * Both directions are schema-derived — the encoded side of each schema is the + * wire type, and decode goes through the CANONICAL `EventSchema`, so a + * payload the canonical contract rejects can never enter storage regardless + * of what produced it. Note: canonical events carry no `authorId` + * (authorship lives on Entry; extraction lineage lives in `producedBy`), so + * the corpus-required author id is mapped at the entry/event boundary here, + * not stored on the canonical event. + */ +import { Schema } from "effect" + +import { EventSchema } from "@journal/domain" + +import { CapturedEventSchema } from "./event.js" + +import type { Event } from "@journal/domain" +import type { CapturedEvent } from "./event.js" + +const encodeCaptureEvent = Schema.encodeSync(CapturedEventSchema) +const decodeCanonicalEvent = Schema.decodeUnknownSync(EventSchema) +const encodeCanonicalEvent = Schema.encodeSync(EventSchema) + +/** Encoded (wire) form of a captured event — what JSON over the wire looks like. */ +export type EncodedCaptureEvent = ReturnType + +/** Encoded form of the canonical Event schema. */ +export type EncodedCanonicalEvent = ReturnType + +/** + * Capture-wire event → canonical Event value. The wire's `occurredAt` millis + * becomes the canonical `timestamp`; the structured quantity becomes the + * canonical payload keyed by its unit (the corpus convention is "oz"). The + * wire `authorId` is dropped here — canonical events do not carry it. + */ +export const toCanonicalEvent = (captured: CapturedEvent, householdId: string, childId: string): Event => { + const wire = encodeCaptureEvent(captured) + return decodeCanonicalEvent({ + householdId, + childId, + category: wire.category, + timestamp: wire.occurredAt, + ...(wire.quantity === undefined ? {} : { payload: { [wire.quantity.unit ?? "oz"]: wire.quantity.value } }), + confidence: wire.confidence, + }) +} + +/** Canonical Event value → capture-wire event (authorId supplied by the entry context). */ +export const fromCanonicalEvent = (event: Event, authorId: string, note?: string): CapturedEvent => { + const wire = encodeCanonicalEvent(event) + const payloadEntries = wire.payload === undefined ? [] : Object.entries(wire.payload) + const quantity = + payloadEntries.length === 1 + ? { value: payloadEntries[0]![1] as number, unit: payloadEntries[0]![0] } + : undefined + return { + _tag: "Event", + category: wire.category, + occurredAt: wire.timestamp, + ...(quantity === undefined ? {} : { quantity }), + confidence: wire.confidence, + authorId, + ...(note === undefined ? {} : { note }), + } +} diff --git a/packages/capture/tsconfig.json b/packages/capture/tsconfig.json new file mode 100644 index 0000000..ab29986 --- /dev/null +++ b/packages/capture/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["bun"] + }, + "include": ["src"] +} From 2d9adc8cdb0313426ccc837d5abc75ce03c3a327 Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 20:24:23 +0000 Subject: [PATCH 2/3] feat(convex): append-only raw-captures log with server-enforced raw-before-events MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Graft candidate B's durable-raw invariant (its event model stays rejected — canonical EventFields wins). New backend-local rawCaptures table (fields composed from canonical CaptureId + entry raw/author fields; the table is not a canonical contract promotion). createEntry appends the immutable raw-capture row for capture sessions before anything derived can exist. New appendEvents mutation consuming the canonical AppendEventsInput with fail-closed ordering: A's server-side Effect re-decode (confidence 1.5 is rejected here regardless of client validation), B's raw-before-events (entries born from a capture session require the durable raw row; manual entries are their own raw record), and set-once attach (first attach wins, pipeline retry is idempotent, a different event set conflicts; tenancy derives from the entry's child, never client input). Validator-level tests per the knowledge.test.ts evidence pattern (N1: no local Convex runtime harness): 14 new tests; backend suite 31 pass. _generated regenerated from schema. Co-authored-by: Gilbert Polanco --- backend/convex/convex/_generated/api.d.ts | 2 + backend/convex/convex/entries.ts | 110 ++++++++++++++- backend/convex/convex/entriesInput.ts | 163 ++++++++++++++++++++++ backend/convex/convex/schema.ts | 6 + backend/convex/test/entries.test.ts | 163 ++++++++++++++++++++++ pnpm-lock.yaml | 16 +++ 6 files changed, 459 insertions(+), 1 deletion(-) create mode 100644 backend/convex/convex/entriesInput.ts create mode 100644 backend/convex/test/entries.test.ts diff --git a/backend/convex/convex/_generated/api.d.ts b/backend/convex/convex/_generated/api.d.ts index 8d94d4a..4ddd6c0 100644 --- a/backend/convex/convex/_generated/api.d.ts +++ b/backend/convex/convex/_generated/api.d.ts @@ -10,6 +10,7 @@ import type * as children from "../children.js"; import type * as entries from "../entries.js"; +import type * as entriesInput from "../entriesInput.js"; import type * as households from "../households.js"; import type * as knowledge from "../knowledge.js"; import type * as knowledgeInput from "../knowledgeInput.js"; @@ -25,6 +26,7 @@ import type { declare const fullApi: ApiFromModules<{ children: typeof children; entries: typeof entries; + entriesInput: typeof entriesInput; households: typeof households; knowledge: typeof knowledge; knowledgeInput: typeof knowledgeInput; diff --git a/backend/convex/convex/entries.ts b/backend/convex/convex/entries.ts index 97e05fe..9fd04fa 100644 --- a/backend/convex/convex/entries.ts +++ b/backend/convex/convex/entries.ts @@ -1,12 +1,13 @@ import { Schema } from "effect" -import { CreateEntryInput, CreateEntryOutput } from "@journal/domain" +import { AppendEventsInput, CreateEntryInput, CreateEntryOutput } from "@journal/domain" import { convexFields } from "@journal/domain/convex" import { mutation } from "./_generated/server" import { ConvexError } from "convex/values" import { errorText, stripUndefined } from "./lib" +import { buildRawCaptureRow, decodeAppendEvents, decideAttach, requireRawCaptureBeforeEvents } from "./entriesInput" /** * Capture an entry. Ported from the retired thin-path `entries:createEntry` @@ -66,6 +67,19 @@ export const createEntry = mutation({ } } + // Arena-integration graft (candidate B): the append-only raw-captures log. + // The verbatim transcript becomes immutable BEFORE any event can attach — + // `appendEvents` fails closed without this row (raw-before-events). + if (args.captureId !== undefined) { + await ctx.db.insert("rawCaptures", buildRawCaptureRow({ + captureId: args.captureId, + childId: args.childId, + authorId: args.authorId, + rawTranscript: args.rawTranscript, + now: Date.now(), + })) + } + const entryId = await ctx.db.insert("entries", { householdId: child.householdId, childId: args.childId, @@ -85,3 +99,97 @@ export const createEntry = mutation({ } satisfies typeof CreateEntryOutput["Type"] }, }) + + +/** + * Arena-integration graft: append extracted events to an entry, consuming the + * canonical `AppendEventsInput` contract. Enforcement order is fail-closed: + * (1) candidate A's server-side re-decode through the canonical `EventFields` + * — a confidence of 1.5 is rejected HERE regardless of client validation; + * (2) candidate B's raw-before-events — an entry born from a capture session + * must have its durable raw-capture row, or events are refused; (3) set-once + * attach — first attach wins, the pipeline's own retry is idempotent, and a + * different event set on an entry that already carries events is a conflict. + */ +export const appendEvents = mutation({ + args: convexFields(AppendEventsInput), + handler: async (ctx, rawArgs) => { + const decoded = decodeAppendEvents(stripUndefined(rawArgs)) + if (!decoded.ok) { + throw new ConvexError({ code: "INVALID_APPEND_INPUT", message: decoded.reason }) + } + const args = decoded.value + + const entryObjectId = ctx.db.normalizeId("entries", args.entryId) + if (entryObjectId === null) { + throw new ConvexError({ code: "ENTRY_NOT_FOUND", message: `entry ${args.entryId} does not exist` }) + } + const entry = await ctx.db.get(entryObjectId) + if (entry === null) { + throw new ConvexError({ code: "ENTRY_NOT_FOUND", message: `entry ${args.entryId} does not exist` }) + } + + // Raw-before-events (candidate B, server-enforced): an entry produced by + // a capture session requires its immutable raw-capture row. The by_capture + // index guarantees captureId equality; the ref is built explicitly because + // indexed reads return a loosely-typed row. + const captureId = entry.captureId + const rawCaptureRow = + captureId === undefined + ? undefined + : await ctx.db + .query("rawCaptures") + .withIndex("by_capture", (q) => q.eq("captureId", captureId)) + .first() + const rawCaptureRef = + rawCaptureRow === null || rawCaptureRow === undefined + ? undefined + : { captureId: rawCaptureRow.captureId } + const rawError = requireRawCaptureBeforeEvents( + { + captureId: entry.captureId, + structuredEventIds: entry.structuredEventIds, + extractionStatus: entry.extractionStatus, + }, + rawCaptureRef, + ) + if (rawError !== null) { + throw new ConvexError({ code: "RAW_CAPTURE_REQUIRED", message: rawError }) + } + + const childObjectId = ctx.db.normalizeId("children", entry.childId) + if (childObjectId === null) { + throw new ConvexError({ code: "CHILD_NOT_FOUND", message: `entry child ${entry.childId} does not exist` }) + } + const child = await ctx.db.get(childObjectId) + if (child === null) { + throw new ConvexError({ code: "CHILD_NOT_FOUND", message: `entry child ${entry.childId} does not exist` }) + } + + const decision = decideAttach( + { + captureId: entry.captureId, + structuredEventIds: entry.structuredEventIds, + extractionStatus: entry.extractionStatus, + }, + args.events, + { householdId: child.householdId, childId: entry.childId }, + ) + if (decision.kind === "conflict") { + throw new ConvexError({ code: "EVENTS_SET_ONCE", message: decision.reason }) + } + if (decision.kind === "idempotent") { + return { status: "idempotent_hit" as const, entryId: entry._id } + } + + const eventIds = [] + for (const row of decision.eventRows) { + eventIds.push(await ctx.db.insert("events", row)) + } + await ctx.db.patch(entryObjectId, { + structuredEventIds: eventIds, + extractionStatus: "structured", + }) + return { status: "appended" as const, entryId: entry._id } + }, +}) diff --git a/backend/convex/convex/entriesInput.ts b/backend/convex/convex/entriesInput.ts new file mode 100644 index 0000000..a9bbde9 --- /dev/null +++ b/backend/convex/convex/entriesInput.ts @@ -0,0 +1,163 @@ +import { Schema } from "effect" + +import { AppendEventsInput, CaptureId, EntryFields, EventFields, convexId } from "@journal/domain" + +/** + * Function-level operation contracts + pure decision logic for the entry + * functions (`./entries.ts`) — the same validator-level evidence pattern the + * knowledge functions established in `knowledgeInput.ts` (N1: no local Convex + * runtime harness; handler wiring is proven by strict typecheck against the + * generated API). + * + * Arena-integration grafts, kept OUT of packages/domain (rule-2 discipline — + * canonical contracts are untouched; the raw-captures log and the append + * lifecycle are backend-local until a contract fold promotes them): + * + * - Candidate B's APPEND-ONLY RAW-CAPTURES LOG: the first durable write of a + * capture is the verbatim transcript, immutable afterwards. `entries` rows + * are mutable (extraction status, structured event links, and later the + * v0.4 retraction fold), so the recoverable, auditable raw text lives here. + * - Candidate B's RAW-BEFORE-EVENTS INVARIANT, enforced server-side: events + * may only attach to an entry whose capture has a durable raw-capture row + * (or which is a manual entry — the entry row itself is then the raw + * record). + * - Candidate A's SERVER-SIDE RE-DECODE: event payloads arriving from any + * client are decoded through the canonical `EventFields` schema here, in + * the handler's trust boundary — a confidence of 1.5 is rejected by the + * backend itself, not merely by a well-behaved client. + * + * Everything in this file is pure (no Convex runtime imports) so the decision + * logic is executable as validator-level evidence. + */ + +/** + * The append-only raw-capture row. Composed from canonical field schemas — + * `CaptureId` for idempotency-key compatibility with `CreateEntryInput`, the + * entry's `rawTranscript`/`authorId` fields verbatim — never restated. No + * mutation ever updates a raw-captures row: the log is append-only. + */ +export const RawCaptureFields = { + captureId: CaptureId, + childId: convexId("children"), + authorId: EntryFields.authorId, + rawTranscript: EntryFields.rawTranscript, + /** Capture instant (Unix ms) — never process time. */ + capturedAt: Schema.Number, + /** Server append instant (Unix ms). */ + createdAt: Schema.Number, +} satisfies Schema.Struct.Fields + +/** The immutable raw-capture row for one capture session (append-only log). */ +export const buildRawCaptureRow = (input: { + readonly captureId: typeof CaptureId["Type"] + readonly childId: string + readonly authorId: string + readonly rawTranscript: string + readonly now: number +}): Schema.Schema.Type> => ({ + captureId: input.captureId, + childId: input.childId, + authorId: input.authorId, + rawTranscript: input.rawTranscript, + // Capture instant == append instant here: the row is written at capture + // time. Kept as distinct fields so a recovery-path backfill (an interrupted + // capture whose raw text arrives late) can preserve the original instant. + capturedAt: input.now, + createdAt: input.now, +}) + +/** The entry row the append path needs — a structural subset of EntryFields. */ +export interface EntryRef { + readonly captureId?: string | undefined + readonly structuredEventIds: ReadonlyArray + readonly extractionStatus: "pending" | "structured" | "failed" +} + +/** The raw-capture evidence the append path needs. */ +export interface RawCaptureRef { + readonly captureId: string +} + +/** + * Candidate B's raw-before-events decision (pure): returns the fail-closed + * rejection when events may not attach to this entry, or null when they may. + * An entry produced by a capture session (captureId present) MUST have a + * durable raw-capture row; a manual entry without a capture id is its own + * raw record and may proceed. + */ +export const requireRawCaptureBeforeEvents = ( + entry: EntryRef, + rawCapture: RawCaptureRef | undefined, +): string | null => { + if (entry.captureId === undefined) return null + if (rawCapture === undefined || rawCapture.captureId !== entry.captureId) { + return `entry capture ${entry.captureId} has no durable raw capture — events cannot precede the caregiver's words` + } + return null +} + +/** + * Server-side re-decode (candidate A): decode the raw client args through the + * canonical AppendEventsInput — whose events are `EventFields` — returning + * the decoded value or the failure reason. A confidence of 1.5 fails here, + * on the server, regardless of what the client validated. + */ +export const decodeAppendEvents = ( + rawArgs: unknown, +): + | { readonly ok: true; readonly value: typeof AppendEventsInput["Type"] } + | { readonly ok: false; readonly reason: string } => { + try { + return { ok: true, value: Schema.decodeUnknownSync(AppendEventsInput)(rawArgs) } + } catch (err) { + return { ok: false, reason: err instanceof Error ? err.message : String(err) } + } +} + +/** Set-once attach decision (pure): how the decoded events apply to the entry. */ +export type AttachDecision = + | { + readonly kind: "attach" + readonly eventRows: ReadonlyArray>> + } + | { readonly kind: "idempotent" } + | { readonly kind: "conflict"; readonly reason: string } + +/** + * Decide how a decoded append applies to the entry's current state: first + * attach wins and rows are built deriving household/child from the ENTRY + * (never from client input — fail-closed tenancy), the pipeline's own retry + * (same event count) is an idempotent no-op, and a DIFFERENT event set on an + * entry that already carries events is a conflict, not an overwrite. + */ +export const decideAttach = ( + entry: EntryRef, + events: typeof AppendEventsInput["Type"]["events"], + context: { readonly householdId: string; readonly childId: string }, +): AttachDecision => { + if (events.length === 0) { + // An empty append is invalid input, not a silent transition: attaching + // nothing must not flip the entry to "structured". + return { + kind: "conflict", + reason: "empty event append — extraction either failed or produced nothing; the entry stays pending", + } + } + if (entry.structuredEventIds.length > 0) { + if (entry.structuredEventIds.length === events.length) return { kind: "idempotent" } + return { + kind: "conflict", + reason: `entry already carries ${entry.structuredEventIds.length} events; events are set-once per entry`, + } + } + const eventRows = events.map((event) => ({ + householdId: context.householdId, + childId: context.childId, + category: event.category, + timestamp: event.timestamp, + ...(event.payload === undefined ? {} : { payload: event.payload }), + confidence: event.confidence, + ...(event.producedBy === undefined ? {} : { producedBy: event.producedBy }), + })) + return { kind: "attach", eventRows } +} diff --git a/backend/convex/convex/schema.ts b/backend/convex/convex/schema.ts index 6061291..7c0a9b3 100644 --- a/backend/convex/convex/schema.ts +++ b/backend/convex/convex/schema.ts @@ -2,6 +2,7 @@ import { defineSchema, defineTable } from "convex/server" import { Schema } from "effect" import { ChildFields, EntryFields, EventFields, HouseholdFields, KnowledgeFields } from "@journal/domain" +import { RawCaptureFields } from "./entriesInput" import { convexFields } from "@journal/domain/convex" /** @@ -27,6 +28,11 @@ export default defineSchema({ // Chronological timeline: per-child, oldest first (journal reads forward). .index("by_child_createdAt", ["childId", "createdAt"]), events: tableFrom(EventFields).index("by_child", ["childId"]), + // Arena-integration graft (candidate B): the append-only raw-captures log — + // the immutable, recoverable record of the caregiver's verbatim words. Rows + // are written once per capture session by `entries:createEntry` and never + // updated; enforced server-side by `entries:appendEvents` (raw-before-events). + rawCaptures: defineTable(convexFields(Schema.Struct(RawCaptureFields))).index("by_capture", ["captureId"]), knowledge: tableFrom(KnowledgeFields) .index("by_household", ["householdId"]) .index("by_child_topic", ["childId", "topic"]) diff --git a/backend/convex/test/entries.test.ts b/backend/convex/test/entries.test.ts new file mode 100644 index 0000000..8ef06ac --- /dev/null +++ b/backend/convex/test/entries.test.ts @@ -0,0 +1,163 @@ +/** + * Validator-level tests for the entry functions' arena-integration grafts + * (backend/convex) — the knowledge.test.ts evidence pattern (N1: no local + * Convex runtime harness): exercise the exact contracts and pure decision + * logic the handlers use. Handler wiring is proven by strict typechecking + * against the generated API (rawCaptures table + appendEvents mutation). + * + * Grafts under test: + * - A (ea5c736): server-side Effect re-decode — confidence 1.5 rejected HERE. + * - B (15fe84f9): append-only raw-captures log + raw-before-events. + */ +import { describe, expect, it } from "bun:test" +import { Schema } from "effect" + +import { CaptureId, EventSchema } from "@journal/domain" +import { convexFields } from "@journal/domain/convex" + +import { + buildRawCaptureRow, + decodeAppendEvents, + decideAttach, + RawCaptureFields, + requireRawCaptureBeforeEvents, + type EntryRef, +} from "../convex/entriesInput" + +const CAPTURE = Schema.decodeSync(CaptureId)("cap-01") + +const entry = (over: Partial = {}): EntryRef => ({ + captureId: CAPTURE, + structuredEventIds: [], + extractionStatus: "pending", + ...over, +}) + +// Canonical AppendEventsInput events — exactly what a successful re-decode +// yields (EventFields.Type). The client supplies tenancy fields too — the +// attach decision must derive them from the entry instead. +const decodedEvents = (count: number, confidence = 0.9) => + Array.from({ length: count }, (_, i) => ({ + householdId: "household-attacker", + childId: "child-other", + category: "meal" as const, + timestamp: 1_700_000_000_000 + i * 1_000, + payload: { ounces: 6 }, + confidence, + })) + +const appendArgs = (events: unknown) => ({ + entryId: "e1" as never, // Id<"entries"> at the contract level; decode-shaped here + events, +}) + +describe("raw-captures row builder (candidate B)", () => { + it("builds an append-only row composed from canonical fields", () => { + const row = buildRawCaptureRow({ + captureId: CAPTURE, + childId: "child-1", + authorId: "author-mom", + rawTranscript: "She drank 6 ounces of formula.", + now: 1_700_000_000_000, + }) + expect(row.captureId).toBe(CAPTURE) + expect(row.childId).toBe("child-1") + expect(row.authorId).toBe("author-mom") + expect(row.rawTranscript).toBe("She drank 6 ounces of formula.") + expect(row.capturedAt).toBe(1_700_000_000_000) + expect(row.createdAt).toBe(1_700_000_000_000) + }) + + it("derives Convex validators from the canonical composition (adapter smoke)", () => { + const validators = convexFields(Schema.Struct(RawCaptureFields)) + expect(Object.keys(validators)).toContain("captureId") + expect(Object.keys(validators)).toContain("rawTranscript") + }) +}) + +describe("raw-before-events (candidate B, server-enforced)", () => { + it("refuses events for a capture-session entry with no durable raw capture", () => { + const error = requireRawCaptureBeforeEvents(entry(), undefined) + expect(error).not.toBeNull() + expect(error).toContain("no durable raw capture") + }) + + it("refuses events when the raw capture belongs to another capture session", () => { + const error = requireRawCaptureBeforeEvents(entry(), { captureId: "cap-other" }) + expect(error).not.toBeNull() + }) + + it("permits events once the durable raw capture exists", () => { + expect(requireRawCaptureBeforeEvents(entry(), { captureId: CAPTURE })).toBeNull() + }) + + it("permits events for manual entries — the entry row is its own raw record", () => { + expect(requireRawCaptureBeforeEvents(entry({ captureId: undefined }), undefined)).toBeNull() + }) +}) + +describe("server-side re-decode (candidate A)", () => { + it("accepts a canonical, in-bounds event payload", () => { + const decoded = decodeAppendEvents(appendArgs(decodedEvents(1))) + expect(decoded.ok).toBe(true) + }) + + it("rejects confidence 1.5 server-side — the client's validation is irrelevant", () => { + const decoded = decodeAppendEvents(appendArgs(decodedEvents(1, 1.5))) + expect(decoded.ok).toBe(false) + if (!decoded.ok) expect(decoded.reason.length).toBeGreaterThan(0) + }) + + it("rejects malformed payloads through the canonical EventFields schema", () => { + expect(decodeAppendEvents(appendArgs([{ category: "not-a-category", timestamp: 1, confidence: 0.9 }])).ok).toBe(false) + expect(decodeAppendEvents(appendArgs([{ category: "meal", timestamp: "not-a-number", confidence: 0.9 }])).ok).toBe(false) + expect(decodeAppendEvents({ events: "not-an-array" }).ok).toBe(false) + }) +}) + +describe("set-once attach decision", () => { + const context = { householdId: "household-1", childId: "child-1" } + + it("attaches first-time events with tenancy derived from the entry, not the client", () => { + const decision = decideAttach(entry(), decodedEvents(2), context) + expect(decision.kind).toBe("attach") + if (decision.kind === "attach") { + expect(decision.eventRows.length).toBe(2) + for (const row of decision.eventRows) { + expect(row.householdId).toBe("household-1") + expect(row.childId).toBe("child-1") + } + } + }) + + it("treats the pipeline's own retry (same count) as idempotent", () => { + const decision = decideAttach( + entry({ structuredEventIds: ["e1", "e2"], extractionStatus: "structured" }), + decodedEvents(2), + context, + ) + expect(decision.kind).toBe("idempotent") + }) + + it("refuses a different event set on an entry that already carries events", () => { + const decision = decideAttach( + entry({ structuredEventIds: ["e1"], extractionStatus: "structured" }), + decodedEvents(3), + context, + ) + expect(decision.kind).toBe("conflict") + }) + + it("refuses an empty append instead of silently flipping extraction status", () => { + const decision = decideAttach(entry(), decodedEvents(0), context) + expect(decision.kind).toBe("conflict") + }) +}) + +describe("canonical round-trip", () => { + it("event rows re-decode through the canonical EventSchema", () => { + const decision = decideAttach(entry(), decodedEvents(1), { householdId: "hh", childId: "c1" }) + if (decision.kind !== "attach") throw new Error("expected attach") + for (const row of decision.eventRows) expect(Schema.is(EventSchema)(row)).toBe(true) + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c51d74..876ac07 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -68,6 +68,22 @@ importers: specifier: ~6.0.3 version: 6.0.3 + packages/capture: + 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/capture-recovery: dependencies: '@journal/domain': From f89f68c3da8953fdf23afdfe8802b8c72f709f9d Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 20:27:13 +0000 Subject: [PATCH 3/3] docs(arena): post-rebase verification evidence + master-side capture-recovery blocker Record the rebased-head gate results (rebase onto 9ea7e73 invalidates prior results) and the pre-existing capture-recovery#test failure on clean master, with its ownership by open PRs #35/#36. Co-authored-by: Gilbert Polanco --- ARENA-INTEGRATION.md | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/ARENA-INTEGRATION.md b/ARENA-INTEGRATION.md index 7b816bc..0041b1d 100644 --- a/ARENA-INTEGRATION.md +++ b/ARENA-INTEGRATION.md @@ -70,21 +70,41 @@ win wherever the two conflict. ## Verification evidence (this session, this branch) Executed in `/home/user/work/arena-int` (worktree of -`task/arena-integration-pick-base-graft-justif-qKuZn1nq`, base `fd7a6ab`): - -- `pnpm turbo run typecheck test build --force` — **20/20 tasks, 0 cached** - (baseline clean-master was 18/18; +2 = the new capture package). -- `bun test ./security` — **29 pass, 0 fail** (unchanged by this branch). -- `bun test` in `backend/convex` — **31 pass, 0 fail** (17 knowledge + 14 new - entries-graft tests). -- `bun src/run.ts --adapter=./src/integrated-adapter.ts` (PR #6 harness) — - **6/6 fixtures** on the integrated adapter; negative control - (`broken-adapter.ts --expect-failure`) fails as required (1/6). -- `pnpm --filter @journal/capture journeys` — **15/15 checks**. +`task/arena-integration-pick-base-graft-justif-qKuZn1nq`): + +- At base `fd7a6ab` (pre-rebase): `pnpm turbo run typecheck test build + --force` — **20/20 tasks, 0 cached** (baseline clean-master was 18/18; +2 = + the new capture package). Every gate below also ran green here. +- After rebase onto `9ea7e73` (PR #15's merge commit), on the branch head — + all gates re-run because the rebase invalidates prior results: + - `bun test ./security` — **29 pass, 0 fail**. + - `bun test` in `backend/convex` — **31 pass, 0 fail** (17 knowledge + 14 + new entries-graft tests). + - PR #6 harness on the integrated adapter — **6/6 fixtures**; negative + control (`broken-adapter.ts --expect-failure`) exits as expected. + - `pnpm --filter @journal/capture journeys` — **15/15 checks**. + - `pnpm install --frozen-lockfile` — no-op (lockfile carries the capture + workspace member). + - `pnpm turbo run typecheck test build --force` — **19/20**: + `@journal/capture-recovery#test` FAILS. This failure is **pre-existing on + clean master** — verified in a separate worktree at `9ea7e73` (same + fixture error: `steps[2].event.attempt` expected object, got a number). + It is PR #15's post-squash schema incompatibility (numeric `attempt` vs + canonical `AttemptNumber` record); the repair is owned by the open, + CI-green PR #35 (`5f4edf7`, mergeStateStatus CLEAN) and a duplicate PR + #36 — deliberately NOT duplicated on this branch to avoid forking their + fix. This branch touches nothing in `packages/capture-recovery`. - `packages/domain` diff vs `fd7a6ab` — **empty** (rule-2 discipline held). ## Known limitations (stated, not hidden) +- **Master-side test failure (not this branch's diff)** — + `@journal/capture-recovery#test` fails on clean master `9ea7e73` (PR #15's + post-squash incompatibility). Repaired by open PR #35 / duplicate PR #36; + this branch rebases onto master after that merge, and full-suite turbo green + is re-established there. Until then this PR's turbo check is expected red on + that one pre-existing package test. + - **N1** — no local Convex runtime harness; the append path's handler wiring is proven by generated-API typecheck + validator-level tests, not live Convex. - **Codegen side effect** — regenerating `_generated` ran `npx convex codegen`