diff --git a/packages/retrieval/README.md b/packages/retrieval/README.md new file mode 100644 index 0000000..8f9cfc6 --- /dev/null +++ b/packages/retrieval/README.md @@ -0,0 +1,65 @@ +# @journal/retrieval — remember & retrieve (read-only, synthetic data) + +Bounded read-only query path for scoped natural-language history questions: +plans compiled from a fixed phrase inventory, executed against a deterministic +synthetic corpus, answered with citations, coverage, and disclosed gaps. + +**This package is the executable form of a rule-2 proposal.** The query +contracts in `src/queryContracts.ts` (`HistoryQueryInput`, `HistoryQueryPlan`, +`HistoryQueryAnswer` and their parts) are PROPOSALS for the canonical contract +— promotion into `packages/domain` is owned by the contract v0.3 fold thread +and is deliberately not self-landed here. Boundaries that keep the canonical +contract authoritative: + +- Entry/Event decoding goes through `@journal/domain`; nothing here redefines + those shapes. The corpus fail-fasts at generation time if it ever drifts. +- `category` fields reuse the canonical `EventFields.category` — the + six-literal taxonomy is never restated. +- Id fields reuse `convexId()` annotations so a later promotion derives + identical Convex validators. + +## Invariants + +- **Read-only.** No write path of any kind; queries do not mutate the corpus + (tested). +- **Synthetic data only.** The 30-day corpus (`src/corpus.ts`) is pure + constants — no clock reads, no randomness; two runs are byte-identical + (tested). +- **Never serve superseded events.** Append-only corrections exclude the + superseded event from answers and disclose the correction as a notice + (tested). +- **Disclose, don't pretend.** Answers carry `AnswerCoverage` (confirmed / + inferred / total, per contract v0.2 T2), correction notices, conflicting- + author notices, and missing-log gap notices instead of an inferred story. +- **Clarify, don't guess.** Unknown activities, unresolved persons, and + missing time windows return structured `clarify` answers; multi-child + questions without a pinned child return `ambiguous` with per-child + candidates. +- **Honest not-found.** An empty match set is `not-found` — never answered + from another child's data, even when the question used a pronoun under a + pinned scope (tested: `hq-14`). + +## Layout + +- `src/queryContracts.ts` — the rule-2 proposal schemas (input, plan, answer). +- `src/corpus.ts` — deterministic 30-day synthetic corpus (timeline documented + inline: gaps Aug 22–23, correction Aug 20, conflicting pasta Aug 17, + shared dinner Aug 30, confirmed school Sep 5). +- `src/resolve.ts` — bounded NL question → `HistoryQueryPlan` compiler with + zone-aware window parsing (`today`/`yesterday`/`this week`/`last week`/ + `on `/`between and `/`since `). +- `src/engine.ts` — plan executor: matching, supersession filtering, notices, + citations, coverage, statements; `resolveEntrySource` navigates a citation's + `entryId` back to the verbatim record. + +## Verify + +```sh +pnpm test # bun: 14 hand-derived fixtures + determinism + navigation +pnpm typecheck # strict TS over src and test +pnpm build # tsc emit +``` + +The fixtures in `test/expectedAnswers.ts` are hand-derived from the corpus +timeline, NOT generated by running the implementation — a failing fixture +test is either an implementation bug or a fixture arithmetic bug; both matter. diff --git a/packages/retrieval/package.json b/packages/retrieval/package.json new file mode 100644 index 0000000..1c8828d --- /dev/null +++ b/packages/retrieval/package.json @@ -0,0 +1,26 @@ +{ + "name": "@journal/retrieval", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Read-only remember-and-retrieve query path over the deterministic synthetic history corpus (slots 15/17 groundwork; query contracts are rule-2 proposals, not self-landed)", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p tsconfig.test.json --noEmit", + "test": "bun test" + }, + "dependencies": { + "@journal/domain": "workspace:*", + "effect": "4.0.0-rc.115" + }, + "devDependencies": { + "@types/bun": "^1.3.14", + "typescript": "~6.0.3" + } +} diff --git a/packages/retrieval/src/corpus.ts b/packages/retrieval/src/corpus.ts new file mode 100644 index 0000000..d377753 --- /dev/null +++ b/packages/retrieval/src/corpus.ts @@ -0,0 +1,374 @@ +import { Schema } from "effect" + +import { EntrySchema, EventSchema, type Entry, type Event } from "@journal/domain" + +/** + * Deterministic 30-day synthetic family-history corpus. + * + * Slot 03 (30-day fixture generator, branch feat/family-history-fixtures) + * had not merged when this was written — no such branch existed on the + * remote — so per the expansion brief this is the DETERMINISTIC FALLBACK: + * pure constants, no clock reads, no randomness. Two runs produce + * byte-identical data, and every entry/event decodes through the canonical + * `@journal/domain` schemas at generation time (fail-fast). + * + * The corpus is synthetic data only — one demo household, two children, + * three authors — engineered so each retrieval behavior in scope has a + * hand-checkable scenario pinned below. + */ + +/** Append-only correction: one event supersedes another (slot 10 territory; modeled in data here). */ +export interface CorrectionRecord { + readonly id: string + readonly supersedesEventId: string + readonly replacementEventId: string + readonly reason: string + readonly correctedBy: string + readonly correctedAt: number +} + +/** An entry plus its extracted events, paired with the entry's stable id. */ +export interface CorpusRecord { + readonly entryId: string + readonly entry: Entry + /** Aligned with `entry.structuredEventIds` by index. */ + readonly events: readonly Event[] +} + +export interface JournalCorpus { + readonly householdId: string + readonly householdTimezone: string + readonly children: readonly { readonly childId: string; readonly name: string }[] + readonly records: readonly CorpusRecord[] + readonly corrections: readonly CorrectionRecord[] + /** Coverage span: `dayCount` local days starting at `firstDayUtcMs`. */ + readonly coverage: { readonly firstDayUtcMs: number; readonly dayCount: number } +} + +/** + * Timeline: 30 days, Aug 14 2026 – Sep 12 2026, household in + * America/New_York (EDT, UTC-4 the whole window — no DST transition). + * Local midnight is 04:00Z, so a local hour `h` is `4 + h` UTC. + */ +const DAY_COUNT = 30 +const dayUtc = (dayIndex: number, hourUtc = 4): number => Date.UTC(2026, 7, 14 + dayIndex, hourUtc) + +/** Local (EDT) clock hours for recurring captures. */ +const BREAKFAST_HOUR_UTC = 12 // 08:00 EDT +const NAP_HOUR_UTC = 17 // 13:00 EDT +const DINNER_HOUR_UTC = 22 // 18:00 EDT + +/** Days with zero entries — the missing-log window (Aug 22–23). */ +const GAP_DAYS: readonly number[] = [8, 9] + +/** Day the younger child has no nap on the timeline (entries still exist). */ +const NO_NAP_DAYS: readonly number[] = [1] + +/** Nap durations by day index — explicit table, fully auditable. */ +const NAP_MINUTES: Readonly> = { + 0: 45, 2: 40, 3: 50, 4: 40, 5: 45, 6: 40, 7: 35, 10: 45, 11: 40, 12: 30, + 13: 45, 14: 50, 15: 40, 16: 45, 17: 35, 18: 45, 19: 40, 20: 50, 21: 45, + 22: 40, 23: 45, 24: 35, 25: 50, 26: 40, 27: 45, 28: 40, 29: 45, +} + +const CONFLICT_DAY = 3 // Aug 17 — mom and dad log different pasta servings +const CORRECTION_DAY = 6 // Aug 20 — dad corrects the Aug 19 nap duration +const TOOTH_DAY = 12 // Aug 26 — grandma (visiting, Pacific/Auckland) logs a milestone +const BOTH_DINNER_DAY = 16 // Aug 30 — both children eat dinner (ambiguity source) +const SCHOOL_DAY = 22 // Sep 5 — caregiver-confirmed school event + +const pad2 = (n: number): string => String(n).padStart(2, "0") + +/** Breakfast author alternates by day parity so attribution stays hand-checkable. */ +const breakfastAuthor = (dayIndex: number): string => (dayIndex % 2 === 0 ? "mom" : "dad") + +const breakfastTranscript = (child: string, author: string): string => + author === "mom" + ? `${child} ate one serving of oatmeal for breakfast this morning.` + : `${child} had one serving of oatmeal at breakfast.` + +const napTranscript = (minutes: number): string => `Ada napped ${minutes} minutes after lunch.` + +/** + * Build the corpus. Throws (fail-fast) if any generated record fails to + * decode through the canonical schemas — synthetic data must stay + * contract-valid by construction. + */ +export const generateCorpus = (): JournalCorpus => { + const householdId = "household_demo" + const records: CorpusRecord[] = [] + + const addRecord = (record: CorpusRecord): void => { + // Decode through the canonical schemas — the contract is the authority. + Schema.decodeUnknownSync(EntrySchema)(record.entry) + for (const event of record.events) Schema.decodeUnknownSync(EventSchema)(event) + records.push(record) + } + + for (let dayIndex = 0; dayIndex < DAY_COUNT; dayIndex++) { + if (GAP_DAYS.includes(dayIndex)) continue + + const dd = pad2(dayIndex) + + // Mechanical filler: both children have breakfast every non-gap day. + for (const child of ["Ada", "Milo"] as const) { + const childId = `child_${child.toLowerCase()}` + const author = breakfastAuthor(dayIndex) + const eventId = `ev-${childId}-breakfast-d${dd}` + addRecord({ + entryId: `en-bf-d${dd}-${childId}`, + entry: { + householdId, + childId, + authorId: author, + rawTranscript: breakfastTranscript(child, author), + structuredEventIds: [eventId], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(dayIndex, BREAKFAST_HOUR_UTC) + 30 * 60_000, + }, + events: [ + { + householdId, + childId, + category: "meal", + timestamp: dayUtc(dayIndex, BREAKFAST_HOUR_UTC), + payload: { servings: 1 }, + confidence: 0.9, + }, + ], + }) + } + + // Ada naps most days (day 1: no nap logged — entries still exist). + if (!NO_NAP_DAYS.includes(dayIndex)) { + const minutes = NAP_MINUTES[dayIndex] + if (minutes === undefined) throw new Error(`corpus: missing nap minutes for day ${dayIndex}`) + addRecord({ + entryId: `en-nap-d${dd}`, + entry: { + householdId, + childId: "child_ada", + authorId: "mom", + rawTranscript: napTranscript(minutes), + structuredEventIds: [`ev-ada-nap-d${dd}`], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(dayIndex, NAP_HOUR_UTC) + 30 * 60_000, + }, + events: [ + { + householdId, + childId: "child_ada", + category: "sleep", + timestamp: dayUtc(dayIndex, NAP_HOUR_UTC), + payload: { minutes }, + confidence: 0.88, + }, + ], + }) + } + } + + // Scenario: conflicting authors (Aug 17) — same child, same category, same + // local day, two authors, differing payload on the shared key. + addRecord({ + entryId: `en-dinner-d${pad2(CONFLICT_DAY)}-mom`, + entry: { + householdId, + childId: "child_ada", + authorId: "mom", + rawTranscript: "Ada ate two servings of pasta at dinner tonight.", + structuredEventIds: [`ev-ada-dinner-d${pad2(CONFLICT_DAY)}-mom`], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(CONFLICT_DAY, DINNER_HOUR_UTC) + 30 * 60_000, + }, + events: [ + { + householdId, + childId: "child_ada", + category: "meal", + timestamp: dayUtc(CONFLICT_DAY, DINNER_HOUR_UTC), + payload: { servings: 2 }, + confidence: 0.91, + }, + ], + }) + addRecord({ + entryId: `en-dinner-d${pad2(CONFLICT_DAY)}-dad`, + entry: { + householdId, + childId: "child_ada", + authorId: "dad", + rawTranscript: "Dinner was a struggle tonight — Ada only ate one serving of pasta.", + structuredEventIds: [`ev-ada-dinner-d${pad2(CONFLICT_DAY)}-dad`], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(CONFLICT_DAY, DINNER_HOUR_UTC) + 45 * 60_000, + }, + events: [ + { + householdId, + childId: "child_ada", + category: "meal", + timestamp: dayUtc(CONFLICT_DAY, DINNER_HOUR_UTC), + payload: { servings: 1 }, + confidence: 0.9, + }, + ], + }) + + // Scenario: append-only correction (Aug 20) — dad corrects the Aug 19 nap + // duration. The replacement event keeps the ORIGINAL nap instant. + const supersededNapEventId = `ev-ada-nap-d${pad2(5)}` + const correctedNapEventId = "ev-ada-nap-d05-corrected" + const correctionEntryId = `en-correction-d${pad2(CORRECTION_DAY)}` + addRecord({ + entryId: correctionEntryId, + entry: { + householdId, + childId: "child_ada", + authorId: "dad", + rawTranscript: "Correction to yesterday's entry: Ada's nap was actually 75 minutes, not 45.", + structuredEventIds: [correctedNapEventId], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(CORRECTION_DAY, 24) + 10 * 60_000, // 20:10 EDT Aug 20 + }, + events: [ + { + householdId, + childId: "child_ada", + category: "sleep", + timestamp: dayUtc(5, NAP_HOUR_UTC), + payload: { minutes: 75 }, + confidence: 1, // caregiver-corrected — confirmed + }, + ], + }) + + // Scenario: invited caregiver logs a milestone from Auckland (NZST, +12). + // The event instant is absolute; her timezone is recorded on the author + // roster (kept in the README, not on the wire — the contract has no + // per-event timezone field; the asker's zone formats statements). + addRecord({ + entryId: `en-milestone-d${pad2(TOOTH_DAY)}-grandma`, + entry: { + householdId, + childId: "child_ada", + authorId: "grandma", + rawTranscript: "Ada lost her first tooth today! It had been wobbly for weeks.", + structuredEventIds: [`ev-ada-tooth-d${pad2(TOOTH_DAY)}`], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(TOOTH_DAY, 7), // 19:00 NZST = 07:00Z + }, + events: [ + { + householdId, + childId: "child_ada", + category: "milestone", + timestamp: dayUtc(TOOTH_DAY, 3), // 15:00 NZST = 03:00Z + confidence: 0.98, + }, + ], + }) + + // Scenario: both children eat dinner the same evening (Aug 30) — equal + // payloads, so no conflict, but an unpinned "last dinner" question is + // ambiguous across children. + addRecord({ + entryId: `en-dinner-d${pad2(BOTH_DINNER_DAY)}-mom`, + entry: { + householdId, + childId: "child_ada", + authorId: "mom", + rawTranscript: "Ada ate one serving of pasta at dinner.", + structuredEventIds: [`ev-ada-dinner-d${pad2(BOTH_DINNER_DAY)}`], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(BOTH_DINNER_DAY, DINNER_HOUR_UTC) + 30 * 60_000, + }, + events: [ + { + householdId, + childId: "child_ada", + category: "meal", + timestamp: dayUtc(BOTH_DINNER_DAY, DINNER_HOUR_UTC), + payload: { servings: 1 }, + confidence: 0.9, + }, + ], + }) + addRecord({ + entryId: `en-dinner-d${pad2(BOTH_DINNER_DAY)}-dad`, + entry: { + householdId, + childId: "child_milo", + authorId: "dad", + rawTranscript: "Milo ate one serving of pasta at dinner.", + structuredEventIds: [`ev-milo-dinner-d${pad2(BOTH_DINNER_DAY)}`], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(BOTH_DINNER_DAY, DINNER_HOUR_UTC) + 30 * 60_000, + }, + events: [ + { + householdId, + childId: "child_milo", + category: "meal", + timestamp: dayUtc(BOTH_DINNER_DAY, DINNER_HOUR_UTC), + payload: { servings: 1 }, + confidence: 0.9, + }, + ], + }) + + // Scenario: caregiver-confirmed school event (confidence 1) on Sep 5. + addRecord({ + entryId: `en-school-d${pad2(SCHOOL_DAY)}-mom`, + entry: { + householdId, + childId: "child_ada", + authorId: "mom", + rawTranscript: "Ada's first day of kindergarten today — she was so proud of her new backpack.", + structuredEventIds: [`ev-ada-school-d${pad2(SCHOOL_DAY)}`], + extractionStatus: "structured", + visibility: "published", + createdAt: dayUtc(SCHOOL_DAY, 13) + 30 * 60_000, // 09:00 EDT + }, + events: [ + { + householdId, + childId: "child_ada", + category: "school", + timestamp: dayUtc(SCHOOL_DAY, 13), + confidence: 1, // caregiver-confirmed — confirmed + }, + ], + }) + + const corrections: CorrectionRecord[] = [ + { + id: "cor-d06-nap-duration", + supersedesEventId: supersededNapEventId, + replacementEventId: correctedNapEventId, + reason: "nap duration was misreported", + correctedBy: "dad", + correctedAt: dayUtc(CORRECTION_DAY, 24), // 20:00 EDT Aug 20 + }, + ] + + return { + householdId, + householdTimezone: "America/New_York", + children: [ + { childId: "child_ada", name: "Ada" }, + { childId: "child_milo", name: "Milo" }, + ], + records, + corrections, + coverage: { firstDayUtcMs: dayUtc(0), dayCount: DAY_COUNT }, + } +} diff --git a/packages/retrieval/src/engine.ts b/packages/retrieval/src/engine.ts new file mode 100644 index 0000000..5442565 --- /dev/null +++ b/packages/retrieval/src/engine.ts @@ -0,0 +1,439 @@ +import { Schema } from "effect" + +import type { Entry, Event } from "@journal/domain" + +import type { JournalCorpus } from "./corpus.js" +import { + HistoryQueryAnswer, + HistoryQueryInput, + type AmbiguityCandidate, + type AnswerCoverage, + type AnswerCitation, + type AnswerNotice, + type ConflictClaim, + type HistoryQueryInput as Input, + type HistoryQueryPlan as Plan, + type QueryWindow as Window, +} from "./queryContracts.js" +import { compilePlan, localDayStartUtcMs, addLocalDays } from "./resolve.js" + +/** + * Read-only query executor: plan in, contract-shaped answer out — over the + * synthetic corpus only, with no write path of any kind. Answers cite their + * sources and disclose corrections, author conflicts, and coverage gaps + * rather than presenting an inferred story as complete. + */ + +const DAY_MS = 86_400_000 +const EXCERPT_LIMIT = 160 +const MAX_GAP_SCAN_DAYS = 60 + +interface Match { + readonly eventId: string + readonly event: Event + readonly record: CorpusRecordRef +} + +interface CorpusRecordRef { + readonly entryId: string + readonly entry: Entry + readonly events: readonly Event[] +} + +interface CorpusIndex { + /** eventId -> the record (entry + aligned events) containing it. */ + readonly byEventId: ReadonlyMap +} + +const buildIndex = (corpus: JournalCorpus): CorpusIndex => { + const byEventId = new Map() + for (const record of corpus.records) { + const ref: CorpusRecordRef = record + const ids = record.entry.structuredEventIds + if (ids.length !== record.events.length) { + throw new Error(`engine: entry ${record.entryId} has ${ids.length} ids for ${record.events.length} events`) + } + for (let i = 0; i < ids.length; i++) { + const eventId = ids[i] + const event = record.events[i] + if (eventId === undefined || event === undefined) { + throw new Error(`engine: entry ${record.entryId} has misaligned events`) + } + byEventId.set(eventId, { eventId, event, record: ref }) + } + } + return { byEventId } +} + +// --------------------------------------------------------------------------- +// Filtering helpers +// --------------------------------------------------------------------------- + +const inWindow = (event: Event, window: Window | undefined): boolean => + window === undefined || (event.timestamp >= window.from && event.timestamp < window.to) + +const subjectOk = (event: Event, subjectChildId: string | undefined): boolean => + subjectChildId === undefined || event.childId === subjectChildId + +const keywordOk = (match: Match, keyword: string | undefined): boolean => + keyword === undefined || match.record.entry.rawTranscript.toLowerCase().includes(keyword.toLowerCase()) + +/** Events the plan asks about, superseded events excluded, deterministic order. */ +const matchingEvents = ( + plan: Plan, + corpus: JournalCorpus, + index: CorpusIndex, +): readonly Match[] => { + const superseded = new Set(corpus.corrections.map((c) => c.supersedesEventId)) + const window = plan._tag === "last-event" ? undefined : plan.window + const category = plan._tag === "day-summary" ? undefined : plan.category + const keyword = plan._tag === "day-summary" ? undefined : plan.keyword + + const matches: Match[] = [] + for (const [eventId, match] of index.byEventId) { + if (superseded.has(eventId)) continue + if (!inWindow(match.event, window)) continue + if (!subjectOk(match.event, plan.subjectChildId)) continue + if (category !== undefined && match.event.category !== category) continue + if (!keywordOk(match, keyword)) continue + matches.push(match) + } + matches.sort((a, b) => { + if (a.event.timestamp !== b.event.timestamp) return a.event.timestamp - b.event.timestamp + return a.eventId.localeCompare(b.eventId) + }) + return matches +} + +// --------------------------------------------------------------------------- +// Notices: gaps, corrections, conflicts +// --------------------------------------------------------------------------- + +/** Local-day starts (asker's zone) that have at least one entry. */ +const coveredDays = (corpus: JournalCorpus, timezone: string): ReadonlySet => { + const days = new Set() + for (const record of corpus.records) { + days.add(localDayStartUtcMs(record.entry.createdAt, timezone)) + } + return days +} + +/** + * Consecutive entry-less local days inside the window, merged into notices. + * These are the "missing logs disclosed as gaps" — the answer states what + * the journal does NOT cover instead of answering as if it were complete. + */ +const gapNotices = (window: Window | undefined, corpus: JournalCorpus, timezone: string): readonly AnswerNotice[] => { + if (window === undefined) return [] + const covered = coveredDays(corpus, timezone) + const notices: AnswerNotice[] = [] + let day = localDayStartUtcMs(window.from, timezone) + let open: { from: number; days: number } | undefined + let scanned = 0 + while (day < window.to && scanned < MAX_GAP_SCAN_DAYS) { + if (covered.has(day)) { + if (open !== undefined) { + notices.push({ _tag: "gap", from: open.from, to: day, days: open.days }) + open = undefined + } + } else { + open = open === undefined ? { from: day, days: 1 } : { from: open.from, days: open.days + 1 } + } + day = addLocalDays(day, 1, timezone) + scanned += 1 + } + if (open !== undefined) { + notices.push({ _tag: "gap", from: open.from, to: day, days: open.days }) + } + return notices +} + +const eventTimestamp = (corpus: JournalCorpus, eventId: string): number | undefined => { + for (const record of corpus.records) { + const i = record.entry.structuredEventIds.indexOf(eventId) + if (i >= 0) return record.events[i]?.timestamp + } + return undefined +} + +/** Corrections whose superseded event falls inside the window affected this answer. */ +const correctionNotices = ( + window: Window | undefined, + matches: readonly Match[], + corpus: JournalCorpus, +): readonly AnswerNotice[] => { + if (window === undefined) return [] + const matchIds = new Set(matches.map((m) => m.eventId)) + const notices: AnswerNotice[] = [] + for (const correction of corpus.corrections) { + const ts = eventTimestamp(corpus, correction.supersedesEventId) + if (ts === undefined || ts < window.from || ts >= window.to) continue + const replacementEventId = matchIds.has(correction.replacementEventId) ? correction.replacementEventId : undefined + notices.push({ + _tag: "correction", + supersedesEventId: correction.supersedesEventId, + ...(replacementEventId !== undefined ? { replacementEventId } : {}), + correctedBy: correction.correctedBy, + reason: correction.reason, + }) + } + return notices +} + +/** + * Conflicting authors: matched events for the same child/category/local day + * from different authors with a shared payload key holding different values. + * Detected among the MATCHED events only (the slice the answer is about) — + * global conflict modeling belongs to the append-only corrections proposal. + */ +const conflictNotices = (matches: readonly Match[], corpus: JournalCorpus): readonly AnswerNotice[] => { + const groups = new Map() + for (const match of matches) { + const day = localDayStartUtcMs(match.event.timestamp, corpus.householdTimezone) + const key = `${match.event.childId}|${match.event.category}|${day}` + const group = groups.get(key) + groups.set(key, group === undefined ? [match] : [...group, match]) + } + + const notices: AnswerNotice[] = [] + for (const group of groups.values()) { + const first = group[0] + if (first === undefined) continue + const authors = new Set(group.map((m) => m.record.entry.authorId)) + if (authors.size < 2) continue + const payloadKeys = new Set() + for (const match of group) { + for (const k of Object.keys(match.event.payload ?? {})) payloadKeys.add(k) + } + const dayStart = localDayStartUtcMs(first.event.timestamp, corpus.householdTimezone) + const localDay: Window = { from: dayStart, to: dayStart + DAY_MS } + for (const payloadKey of payloadKeys) { + const claims: ConflictClaim[] = group + .filter((m) => m.event.payload?.[payloadKey] !== undefined) + .map((m) => ({ + authorId: m.record.entry.authorId, + eventIds: [m.eventId], + payloadKey, + payloadValue: m.event.payload?.[payloadKey] ?? 0, + })) + .sort((a, b) => a.authorId.localeCompare(b.authorId) || a.payloadValue - b.payloadValue) + const values = new Set(claims.map((c) => c.payloadValue)) + if (claims.length < 2 || values.size < 2) continue + notices.push({ _tag: "conflict", category: first.event.category, localDay, claims }) + } + } + return notices +} + +// --------------------------------------------------------------------------- +// Citations, coverage, statements +// --------------------------------------------------------------------------- + +const excerptOf = (transcript: string): string => + transcript.length <= EXCERPT_LIMIT ? transcript : `${transcript.slice(0, EXCERPT_LIMIT - 1)}…` + +const citationFor = (match: Match): AnswerCitation => ({ + entryId: match.record.entryId, + eventIds: [match.eventId], + childId: match.event.childId, + authorId: match.record.entry.authorId, + excerpt: excerptOf(match.record.entry.rawTranscript), + occurredAt: match.event.timestamp, +}) + +/** T2 (Gap 3/A7): confirmation breakdown over the events an answer rests on. */ +const coverageOf = (matches: readonly Match[]): AnswerCoverage => { + const confirmed = matches.filter((m) => m.event.confidence === 1).length + return { confirmed, inferred: matches.length - confirmed, total: matches.length } +} + +const fmtDate = (ms: number, timezone: string): string => + new Intl.DateTimeFormat("en-US", { timeZone: timezone, month: "long", day: "numeric", year: "numeric" }).format(ms) + +const fmtShort = (ms: number, timezone: string): string => + new Intl.DateTimeFormat("en-US", { timeZone: timezone, month: "short", day: "numeric" }).format(ms) + +const fmtTime = (ms: number, timezone: string): string => + new Intl.DateTimeFormat("en-US", { timeZone: timezone, hour: "numeric", minute: "2-digit", hour12: true }).format(ms) + +/** "on September 5" for a one-local-day window, "between Sep 6 and Sep 8" otherwise. */ +const windowPhrase = (window: Window | undefined, timezone: string): string => { + if (window === undefined) return "in the recorded history" + const singleDay = localDayStartUtcMs(window.from, timezone) === localDayStartUtcMs(window.to - 1, timezone) + return singleDay + ? `on ${fmtDate(window.from, timezone)}` + : `between ${fmtShort(window.from, timezone)} and ${fmtShort(window.to - 1_000, timezone)}` +} + +const payloadPhrase = (event: Event): string => { + const payload = event.payload ?? {} + if (payload["minutes"] !== undefined) { + return event.category === "sleep" ? `napped ${payload["minutes"]} minutes` : `${payload["minutes"]} minutes` + } + if (payload["servings"] !== undefined) { + const n = payload["servings"] + return `ate ${n} serving${n === 1 ? "" : "s"}` + } + if (payload["count"] !== undefined) return `${payload["count"]} recorded` + return event.category +} + +const claimPhrase = (claim: ConflictClaim): string => { + const unit = claim.payloadKey === "servings" ? `serving${claim.payloadValue === 1 ? "" : "s"}` : claim.payloadKey + return `${claim.authorId} logged ${claim.payloadValue} ${unit}` +} + +const childName = (corpus: JournalCorpus, childId: string | undefined): string => + corpus.children.find((c) => c.childId === childId)?.name ?? "The child" + +const nounFor = (plan: Plan): string => { + switch (plan._tag) { + case "last-event": + return plan.keyword === "dinner" ? "dinner" + : plan.keyword === "breakfast" ? "breakfast" + : plan.keyword === "lunch" ? "lunch" + : plan.category === "sleep" ? "nap" + : plan.category + case "count-events": + case "probe-events": + return plan.keyword === "breakfast" ? "breakfast" + : plan.keyword === "dinner" ? "dinner" + : plan.keyword === "lunch" ? "lunch" + : plan.category === "sleep" ? "nap" + : plan.category + case "day-summary": + return "event" + } +} + +const pluralFor = (plan: Plan): string => { + const singular = nounFor(plan) + return singular === "meal" ? "meals" : singular === "event" ? "events" : `${singular}s` +} + +// --------------------------------------------------------------------------- +// Executor +// --------------------------------------------------------------------------- + +const executePlan = (plan: Plan, input: Input, corpus: JournalCorpus): typeof HistoryQueryAnswer["Type"] => { + const index = buildIndex(corpus) + const window = plan._tag === "last-event" ? undefined : plan.window + const matches = matchingEvents(plan, corpus, index) + + // Unpinned subject: one child with matches resolves implicitly; more than + // one is ambiguous — the answer offers candidates instead of guessing. + if (plan._tag !== "day-summary" && plan.subjectChildId === undefined) { + const childIds = new Set(matches.map((m) => m.event.childId)) + if (childIds.size > 1) { + const latestByChild = new Map() + for (const match of matches) latestByChild.set(match.event.childId, match) // matches are time-sorted + const candidates: AmbiguityCandidate[] = [...latestByChild.values()] + .sort((a, b) => a.event.childId.localeCompare(b.event.childId)) + .map((match) => ({ + childId: match.event.childId, + entryId: match.record.entryId, + eventIds: [match.eventId], + occurredAt: match.event.timestamp, + })) + return { _tag: "ambiguous", reason: "multiple-children-matched", candidates } + } + } + + const notices: AnswerNotice[] = [ + ...correctionNotices(window, matches, corpus), + ...conflictNotices(matches, corpus), + ...gapNotices(window, corpus, input.timezone), + ] + + if (matches.length === 0) { + return { + _tag: "not-found", + statement: `No matching ${nounFor(plan)} records were found ${windowPhrase(window, input.timezone)}.`, + ...(window !== undefined ? { window } : {}), // optionalKey rejects explicit undefined + notices, + } + } + + if (plan._tag === "last-event") { + const latest = matches[matches.length - 1] + if (latest === undefined) { + return { _tag: "not-found", statement: "No matching records were found.", notices } + } + const name = childName(corpus, latest.event.childId) + const payloadPart = latest.event.payload === undefined ? "" : ` — ${payloadPhrase(latest.event)}` + return { + _tag: "found", + statement: `${name}'s last recorded ${nounFor(plan)} was on ${fmtDate(latest.event.timestamp, input.timezone)} at ${fmtTime(latest.event.timestamp, input.timezone)}${payloadPart}.`, + citations: [citationFor(latest)], + coverage: coverageOf(matches), + notices, + } + } + + if (plan._tag === "count-events") { + const name = childName(corpus, plan.subjectChildId ?? matches[0]?.event.childId) + const coverage = coverageOf(matches) + return { + _tag: "found", + statement: `${name} had ${matches.length} ${pluralFor(plan)} ${windowPhrase(window, input.timezone)} — ${coverage.confirmed} of ${coverage.total} caregiver-confirmed.`, + citations: matches.map(citationFor), + coverage, + notices, + } + } + + if (plan._tag === "day-summary") { + const name = childName(corpus, plan.subjectChildId ?? matches[0]?.event.childId) + const categories = matches.map((m) => m.event.category).join(", ") + const coverage = coverageOf(matches) + return { + _tag: "found", + statement: `${name} had ${matches.length} recorded ${pluralFor(plan)} ${windowPhrase(window, input.timezone)}: ${categories} — ${coverage.confirmed} of ${coverage.total} caregiver-confirmed.`, + citations: matches.map(citationFor), + coverage, + notices, + } + } + + // probe-events + const name = childName(corpus, plan.subjectChildId ?? matches[0]?.event.childId) + const conflict = notices.find((n): n is Extract => n._tag === "conflict") + if (conflict !== undefined) { + return { + _tag: "found", + statement: `Conflicting records for ${name}'s ${nounFor(plan)} ${windowPhrase(window, input.timezone)}: ${conflict.claims.map(claimPhrase).join(", ")}.`, + citations: matches.map(citationFor), + coverage: coverageOf(matches), + notices, + } + } + return { + _tag: "found", + statement: `Yes — ${name}: ${matches.map((m) => payloadPhrase(m.event)).join("; ")}.`, + citations: matches.map(citationFor), + coverage: coverageOf(matches), + notices, + } +} + +/** + * Answer a history question. `input` is decoded through the input contract; + * the returned answer satisfies `HistoryQueryAnswer` (tests re-decode it). + */ +export const answerQuery = (rawInput: Input, corpus: JournalCorpus): typeof HistoryQueryAnswer["Type"] => { + const input = Schema.decodeUnknownSync(HistoryQueryInput)(rawInput) + const compiled = compilePlan(input, corpus) + if (compiled._tag === "clarify") { + return { _tag: "clarify", reason: compiled.reason, message: compiled.message } + } + return executePlan(compiled.plan, input, corpus) +} + +/** Source navigation: a citation's entryId back to the verbatim record. */ +export const resolveEntrySource = ( + corpus: JournalCorpus, + entryId: string, +): { readonly entryId: string; readonly entry: Entry; readonly events: readonly Event[] } | undefined => { + const record = corpus.records.find((r) => r.entryId === entryId) + return record === undefined ? undefined : { entryId: record.entryId, entry: record.entry, events: record.events } +} diff --git a/packages/retrieval/src/index.ts b/packages/retrieval/src/index.ts new file mode 100644 index 0000000..7b862b2 --- /dev/null +++ b/packages/retrieval/src/index.ts @@ -0,0 +1,23 @@ +export { generateCorpus, type JournalCorpus, type CorpusRecord, type CorrectionRecord } from "./corpus.js" +export { answerQuery, resolveEntrySource } from "./engine.js" +export { compilePlan, parseWindow, type CompiledQuery, type ClarifyReason, type ActivityRef, type ParsedWindow } from "./resolve.js" +export { + HistoryQueryInput, + HistoryQueryPlan, + HistoryQueryAnswer, + QueryWindow as QueryWindowSchema, + AnswerCoverage as AnswerCoverageSchema, + AnswerNotice as AnswerNoticeSchema, + AnswerCitation as AnswerCitationSchema, + AmbiguityCandidate as AmbiguityCandidateSchema, + ConflictClaim as ConflictClaimSchema, + type HistoryQueryInput as Input, + type HistoryQueryPlan as Plan, + type HistoryQueryAnswer as Answer, + type QueryWindow as Window, + type AnswerCoverage, + type AnswerCitation, + type AnswerNotice, + type AmbiguityCandidate, + type ConflictClaim, +} from "./queryContracts.js" diff --git a/packages/retrieval/src/queryContracts.ts b/packages/retrieval/src/queryContracts.ts new file mode 100644 index 0000000..4c6722b --- /dev/null +++ b/packages/retrieval/src/queryContracts.ts @@ -0,0 +1,181 @@ +import { Schema } from "effect" + +import { EventFields, convexId } from "@journal/domain" + +/** + * Query-surface contracts for the remember-and-retrieve read-only path. + * + * This module is the EXECUTABLE FORM of a contract rule-2 proposal (rule 2: + * "Adding fields: propose in this thread first; the schema is the single + * source of truth"). Canonical promotion — moving these operation schemas + * into packages/domain — is owned by the contract v0.3 fold thread + * (th_IL2xKJpO) and is deliberately NOT self-landed here. + * + * Boundaries that keep the canonical contract authoritative: + * - Entry/Event decoding still goes through `@journal/domain`; nothing here + * redefines those shapes. + * - `category` fields reuse the canonical `EventFields.category` schema — + * the six-literal taxonomy is never restated. + * - Household/child id fields reuse `convexId()` annotations so a later + * promotion derives identical Convex validators. + */ + +/** Half-open window `[from, to)` in unix ms — `to` is exclusive. */ +export const QueryWindow = Schema.Struct({ + from: Schema.Number, + to: Schema.Number, +}) +export type QueryWindow = typeof QueryWindow["Type"] + +/** One citation: a source entry plus the events in it backing the claim. */ +export const AnswerCitation = Schema.Struct({ + entryId: Schema.String, + eventIds: Schema.Array(Schema.String), + childId: Schema.String, + authorId: Schema.String, + /** Bounded verbatim excerpt of the cited entry's raw transcript. */ + excerpt: Schema.String, + /** Timestamp of the first cited event, unix ms. */ + occurredAt: Schema.Number, +}) +export type AnswerCitation = typeof AnswerCitation["Type"] + +/** + * Confirmation breakdown over the events an answer rests on (T2, Gap 3/A7). + * `confidence === 1` is caregiver-confirmed per contract v0.2; anything + * lower is an inferred (raw extractor) event. `confirmed + inferred` is the + * denominator of aggregate claims such as "potty success rate 80%". + */ +export const AnswerCoverage = Schema.Struct({ + confirmed: Schema.Number, + inferred: Schema.Number, + total: Schema.Number, +}) +export type AnswerCoverage = typeof AnswerCoverage["Type"] + +/** One side of a conflicting-authors claim. */ +export const ConflictClaim = Schema.Struct({ + authorId: Schema.String, + eventIds: Schema.Array(Schema.String), + payloadKey: Schema.String, + payloadValue: Schema.Number, +}) +export type ConflictClaim = typeof ConflictClaim["Type"] + +/** + * Out-of-band facts the answer must disclose alongside the claim itself: + * corrections that superseded data the answer used, conflicting authors for + * the same subject/category/day, and missing-log gaps inside the window. + */ +export const AnswerNotice = Schema.Union([ + Schema.Struct({ + _tag: Schema.Literal("correction"), + supersedesEventId: Schema.String, + replacementEventId: Schema.optionalKey(Schema.String), + correctedBy: Schema.String, + reason: Schema.String, + }), + Schema.Struct({ + _tag: Schema.Literal("conflict"), + category: EventFields.category, + localDay: QueryWindow, + claims: Schema.Array(ConflictClaim), + }), + Schema.Struct({ + _tag: Schema.Literal("gap"), + from: Schema.Number, + to: Schema.Number, + days: Schema.Number, + }), +]) +export type AnswerNotice = typeof AnswerNotice["Type"] + +/** One candidate in an ambiguous-subject answer (latest match per child). */ +export const AmbiguityCandidate = Schema.Struct({ + childId: Schema.String, + entryId: Schema.String, + eventIds: Schema.Array(Schema.String), + occurredAt: Schema.Number, +}) +export type AmbiguityCandidate = typeof AmbiguityCandidate["Type"] + +/** + * The answer union. Every variant is a tagged struct so consumers decode + * through one schema and switch on `_tag`. + */ +export const HistoryQueryAnswer = Schema.Union([ + Schema.Struct({ + _tag: Schema.Literal("found"), + statement: Schema.NonEmptyString, + citations: Schema.Array(AnswerCitation), + coverage: AnswerCoverage, + notices: Schema.Array(AnswerNotice), + }), + Schema.Struct({ + _tag: Schema.Literal("ambiguous"), + reason: Schema.Literal("multiple-children-matched"), + candidates: Schema.Array(AmbiguityCandidate), + }), + Schema.Struct({ + _tag: Schema.Literal("clarify"), + reason: Schema.Literals(["unknown-activity", "unresolved-person", "missing-time-window"]), + message: Schema.NonEmptyString, + }), + Schema.Struct({ + _tag: Schema.Literal("not-found"), + statement: Schema.NonEmptyString, + window: Schema.optionalKey(QueryWindow), + notices: Schema.Array(AnswerNotice), + }), +]) +export type HistoryQueryAnswer = typeof HistoryQueryAnswer["Type"] + +/** + * The structured plan a question compiles to. The bounded resolver in + * `./resolve.js` produces plans; richer NL layers (slot 15/17) target the + * same schema. `window` is half-open; absent on `last-event` = whole + * corpus span. + */ +export const HistoryQueryPlan = Schema.Union([ + Schema.Struct({ + _tag: Schema.Literal("last-event"), + category: EventFields.category, + keyword: Schema.optionalKey(Schema.NonEmptyString), + subjectChildId: Schema.optionalKey(Schema.String), + window: Schema.optionalKey(QueryWindow), + }), + Schema.Struct({ + _tag: Schema.Literal("count-events"), + category: EventFields.category, + keyword: Schema.optionalKey(Schema.NonEmptyString), + subjectChildId: Schema.optionalKey(Schema.String), + window: QueryWindow, + }), + Schema.Struct({ + _tag: Schema.Literal("probe-events"), + category: EventFields.category, + keyword: Schema.optionalKey(Schema.NonEmptyString), + subjectChildId: Schema.optionalKey(Schema.String), + window: QueryWindow, + }), + Schema.Struct({ + _tag: Schema.Literal("day-summary"), + subjectChildId: Schema.optionalKey(Schema.String), + window: QueryWindow, + }), +]) +export type HistoryQueryPlan = typeof HistoryQueryPlan["Type"] + +/** Input contract for a history question (read-only; no writes anywhere). */ +export const HistoryQueryInput = Schema.Struct({ + householdId: convexId("households"), + /** Pinned subject child; absent = derived from the question or ambiguous. */ + childId: Schema.optionalKey(convexId("children")), + askedBy: Schema.NonEmptyString, + /** "Now" for relative-time resolution, unix ms. */ + askedAt: Schema.Number, + /** IANA zone of the asker — day boundaries and statement clocks. */ + timezone: Schema.NonEmptyString, + question: Schema.NonEmptyString, +}) +export type HistoryQueryInput = typeof HistoryQueryInput["Type"] diff --git a/packages/retrieval/src/resolve.ts b/packages/retrieval/src/resolve.ts new file mode 100644 index 0000000..8011961 --- /dev/null +++ b/packages/retrieval/src/resolve.ts @@ -0,0 +1,403 @@ +import type { EventCategory } from "@journal/domain" + +import type { JournalCorpus } from "./corpus.js" +import type { HistoryQueryInput, HistoryQueryPlan, QueryWindow } from "./queryContracts.js" + +/** + * Bounded natural-language question -> structured query plan. + * + * This is deliberately NOT an NLP layer: a fixed phrase inventory (four + * question forms, a small activity lexicon, a handful of window phrases) + * compiles deterministically to a `HistoryQueryPlan`. Anything outside the + * inventory returns `clarify` instead of guessing — the slots 15/17 NL + * layers would replace this compiler, not the plan schema it targets. + */ + +/** Reason an answer asks the user to clarify instead of guessing. */ +export type ClarifyReason = "unknown-activity" | "unresolved-person" | "missing-time-window" + +export type CompiledQuery = + | { readonly _tag: "plan"; readonly plan: HistoryQueryPlan } + | { readonly _tag: "clarify"; readonly reason: ClarifyReason; readonly message: string } + +/** Subject lookup result — tagged so call sites narrow on `_tag`, not `in`. */ +export type SubjectResolution = + | { readonly _tag: "resolved"; readonly childId: string | undefined } + | { readonly _tag: "clarify"; readonly reason: ClarifyReason; readonly message: string } + +// --------------------------------------------------------------------------- +// Zone-aware calendar math (asker's IANA timezone; two-pass offset +// convergence, DST-safe by construction). +// --------------------------------------------------------------------------- + +interface ZonedParts { + readonly year: number + readonly month: number // 1-based + readonly day: number + readonly hour: number + readonly minute: number + readonly second: number +} + +const zonedParts = (ms: number, timezone: string): ZonedParts => { + const dtf = new Intl.DateTimeFormat("en-US", { + timeZone: timezone, + hour12: false, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + const parts: Record = {} + for (const part of dtf.formatToParts(ms)) { + if (part.type !== "literal") parts[part.type] = part.value + } + const hour = parts["hour"] + return { + year: Number(parts["year"]), + month: Number(parts["month"]), + day: Number(parts["day"]), + hour: hour === "24" ? 0 : Number(hour), + minute: Number(parts["minute"]), + second: Number(parts["second"]), + } +} + +const zoneOffsetMs = (ms: number, timezone: string): number => { + const p = zonedParts(ms, timezone) + return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - ms +} + +/** UTC instant of 00:00 local time on the day containing `ms`. */ +export const localDayStartUtcMs = (ms: number, timezone: string): number => { + const p = zonedParts(ms, timezone) + const guess = Date.UTC(p.year, p.month - 1, p.day) + const first = guess - zoneOffsetMs(guess, timezone) + return guess - zoneOffsetMs(first, timezone) +} + +const DAY_MS = 86_400_000 + +/** Local day start `days` days from the day containing `ms` (+/-). */ +export const addLocalDays = (ms: number, days: number, timezone: string): number => + localDayStartUtcMs(ms + days * DAY_MS, timezone) + +/** 0 = Monday … 6 = Sunday, in the asker's zone. */ +const weekdayIndex = (ms: number, timezone: string): number => { + const wd = new Intl.DateTimeFormat("en-US", { timeZone: timezone, weekday: "short" }).format(ms) + const index = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(wd) + return index < 0 ? 0 : index +} + +/** Local midnight of the Monday of the week containing `ms`. */ +const mondayStartUtcMs = (ms: number, timezone: string): number => + localDayStartUtcMs(ms, timezone) - weekdayIndex(ms, timezone) * DAY_MS + +const MONTHS: Readonly> = { + january: 0, february: 1, march: 2, april: 3, may: 4, june: 5, + july: 6, august: 7, september: 8, october: 9, november: 10, december: 11, +} + +interface MonthDay { + readonly month: number // 0-based + readonly day: number +} + +const parseMonthDay = (phrase: string): MonthDay | undefined => { + const match = /^([a-z]+) (\d{1,2})$/.exec(phrase.trim()) + const name = match?.[1] + const dayNum = match?.[2] + if (name === undefined || dayNum === undefined) return undefined + const month = MONTHS[name] + if (month === undefined) return undefined + const day = Number(dayNum) + if (!Number.isInteger(day) || day < 1 || day > 31) return undefined + return { month, day } +} + +/** Local midnight of a month/day in the asker's year (no year rollover in the inventory). */ +const localDayStartFor = (md: MonthDay, askedAt: number, timezone: string): number => { + const p = zonedParts(askedAt, timezone) + const guess = Date.UTC(p.year, md.month, md.day) + const first = guess - zoneOffsetMs(guess, timezone) + return guess - zoneOffsetMs(first, timezone) +} + +export interface ParsedWindow { + readonly window: QueryWindow + readonly phrase: string +} + +/** Parse a supported window phrase against the asker's clock. `undefined` = unsupported. */ +export const parseWindow = (phrase: string, askedAt: number, timezone: string): ParsedWindow | undefined => { + const p = phrase.trim().toLowerCase() + const dayStart = localDayStartUtcMs(askedAt, timezone) + if (p === "today") return { window: { from: dayStart, to: addLocalDays(askedAt, 1, timezone) }, phrase: p } + if (p === "yesterday") return { window: { from: addLocalDays(askedAt, -1, timezone), to: dayStart }, phrase: p } + if (p === "this week") { + const monday = mondayStartUtcMs(askedAt, timezone) + return { window: { from: monday, to: monday + 7 * DAY_MS }, phrase: p } + } + if (p === "last week") { + const monday = mondayStartUtcMs(askedAt, timezone) + return { window: { from: monday - 7 * DAY_MS, to: monday }, phrase: p } + } + const on = /^on (.+)$/.exec(p) + if (on !== null) { + const md = parseMonthDay(on[1] ?? "") + if (md === undefined) return undefined + const from = localDayStartFor(md, askedAt, timezone) + return { window: { from, to: from + DAY_MS }, phrase: p } + } + const between = /^between (.+) and (.+)$/.exec(p) + if (between !== null) { + const a = parseMonthDay(between[1] ?? "") + const b = parseMonthDay(between[2] ?? "") + if (a === undefined || b === undefined) return undefined + const from = localDayStartFor(a, askedAt, timezone) + const to = localDayStartFor(b, askedAt, timezone) + DAY_MS + return { window: { from, to }, phrase: p } + } + const since = /^since (.+)$/.exec(p) + if (since !== null) { + const md = parseMonthDay(since[1] ?? "") + if (md === undefined) return undefined + return { window: { from: localDayStartFor(md, askedAt, timezone), to: askedAt }, phrase: p } + } + return undefined +} + +// --------------------------------------------------------------------------- +// Activity lexicon +// --------------------------------------------------------------------------- + +export interface ActivityRef { + readonly category: EventCategory + /** Case-insensitive transcript keyword narrowing a category (e.g. dinner vs meal). */ + readonly keyword?: string + readonly noun: string + readonly plural: string +} + +const activityFor = (word: string): ActivityRef | undefined => { + switch (word) { + case "nap": + case "napped": + case "napping": + case "sleep": + return { category: "sleep", noun: "nap", plural: "naps" } + case "breakfast": + case "breakfasts": + return { category: "meal", keyword: "breakfast", noun: "breakfast", plural: "breakfasts" } + case "dinner": + case "dinners": + return { category: "meal", keyword: "dinner", noun: "dinner", plural: "dinners" } + case "lunch": + case "lunches": + return { category: "meal", keyword: "lunch", noun: "lunch", plural: "lunches" } + case "meal": + case "meals": + case "ate": + case "eat": + case "eating": + return { category: "meal", noun: "meal", plural: "meals" } + case "potty": + case "poop": + case "pooped": + case "pee": + case "peed": + return { category: "potty", noun: "potty event", plural: "potty events" } + case "mood": + case "tantrum": + case "meltdown": + case "fussy": + case "happy": + return { category: "mood", noun: "mood note", plural: "mood notes" } + case "tooth": + return { category: "milestone", keyword: "tooth", noun: "milestone", plural: "milestones" } + case "milestone": + case "milestones": + return { category: "milestone", noun: "milestone", plural: "milestones" } + case "school": + case "kindergarten": + return { category: "school", noun: "school note", plural: "school notes" } + default: + return undefined + } +} + +const PRONOUNS: ReadonlySet = new Set(["he", "she", "they"]) + +/** Plural-tolerant lookup: "tantrums"/"naps" fall back to their singular form. */ +const activityForWord = (word: string): ActivityRef | undefined => + activityFor(word) ?? (word.endsWith("s") ? activityFor(word.slice(0, -1)) : undefined) + +/** Flat clarify member — structurally assignable to both tagged unions above. */ +const clarify = ( + reason: ClarifyReason, + message: string, +): { readonly _tag: "clarify"; readonly reason: ClarifyReason; readonly message: string } => ({ + _tag: "clarify", + reason, + message, +}) + +/** Resolve a subject word to a childId — undefined = intentionally unpinned. */ +const resolveSubject = ( + word: string | undefined, + input: HistoryQueryInput, + corpus: JournalCorpus, +): SubjectResolution => { + if (word === undefined) return { _tag: "resolved", childId: undefined } + if (PRONOUNS.has(word)) { + if (input.childId !== undefined) return { _tag: "resolved", childId: input.childId } + return clarify( + "unresolved-person", + `I can't tell who "${word}" refers to — ask with a child's name (or ask from a view scoped to one child).`, + ) + } + const child = corpus.children.find((c) => c.name.toLowerCase() === word) + return child === undefined + ? clarify("unresolved-person", `I don't know "${word}" in this household — known children: ${corpus.children.map((c) => c.name.toLowerCase()).join(", ")}.`) + : { _tag: "resolved", childId: child.childId } +} + +/** Omit optional keys when absent (optionalKey rejects explicit undefined). */ +const planWith = (base: T, subjectChildId: string | undefined): T => + subjectChildId === undefined ? base : { ...base, subjectChildId } + +const withKeyword = (base: T, activity: ActivityRef): T => + activity.keyword === undefined ? base : { ...base, keyword: activity.keyword } + +// --------------------------------------------------------------------------- +// Question grammar (bounded) +// --------------------------------------------------------------------------- + +export const compilePlan = (input: HistoryQueryInput, corpus: JournalCorpus): CompiledQuery => { + const question = input.question.trim().toLowerCase().replace(/[?.!]+$/, "") + const { askedAt, timezone } = input + const windowHelp = "I couldn't tell which time window you mean — try 'on August 19', 'yesterday', 'last week', or 'between September 1 and September 5'." + const categoryHelp = (word: string): string => + `I couldn't map "${word}" to a recorded care event (potty, meal, sleep, mood, milestone, school).` + + // "when did ada last nap?" / "when did she last nap?" + let match = /^when did ([a-z]+) last ([a-z]+)$/.exec(question) + if (match !== null) { + const subject = resolveSubject(match[1], input, corpus) + if (subject._tag === "clarify") return clarify(subject.reason, subject.message) + const activity = activityForWord(match[2] ?? "") + if (activity === undefined) return clarify("unknown-activity", categoryHelp(match[2] ?? "")) + return { + _tag: "plan", + plan: planWith( + withKeyword({ _tag: "last-event", category: activity.category } as HistoryQueryPlan & { _tag: "last-event" }, activity), + subject.childId, + ), + } + } + + // "when was the last dinner?" + match = /^when was the last ([a-z]+)$/.exec(question) + if (match !== null) { + const activity = activityForWord(match[1] ?? "") + if (activity === undefined) return clarify("unknown-activity", categoryHelp(match[1] ?? "")) + return { + _tag: "plan", + plan: withKeyword({ _tag: "last-event", category: activity.category } as HistoryQueryPlan & { _tag: "last-event" }, activity), + } + } + + // "how many breakfasts did milo have last week?" / "how many tantrums did ada have" + match = /^how many ([a-z]+) did ([a-z]+) have(?: (.+))?$/.exec(question) + if (match !== null) { + const activity = activityForWord(match[1] ?? "") + if (activity === undefined) return clarify("unknown-activity", categoryHelp(match[1] ?? "")) + const subject = resolveSubject(match[2], input, corpus) + if (subject._tag === "clarify") return clarify(subject.reason, subject.message) + const tail = match[3] + if (tail === undefined) return clarify("missing-time-window", "I can count over a time window — try '…last week', '…yesterday', or '…between September 1 and September 5'.") + const parsed = parseWindow(tail, askedAt, timezone) + if (parsed === undefined) return clarify("missing-time-window", windowHelp) + return { + _tag: "plan", + plan: planWith( + withKeyword({ _tag: "count-events", category: activity.category, window: parsed.window } as HistoryQueryPlan & { _tag: "count-events" }, activity), + subject.childId, + ), + } + } + + // "how much pasta did ada eat on august 17?" + match = /^how much ([a-z]+) did ([a-z]+) eat (.+)$/.exec(question) + if (match !== null) { + const subject = resolveSubject(match[2], input, corpus) + if (subject._tag === "clarify") return clarify(subject.reason, subject.message) + const parsed = parseWindow(match[3] ?? "", askedAt, timezone) + if (parsed === undefined) return clarify("missing-time-window", windowHelp) + return { + _tag: "plan", + plan: planWith( + { + _tag: "probe-events", + category: "meal", + keyword: match[1] ?? "", + window: parsed.window, + } as HistoryQueryPlan & { _tag: "probe-events" }, + subject.childId, + ), + } + } + + // "did ada nap on august 19?" / "did ada nap between august 21 and august 25?" / "did she nap yesterday?" + match = /^did ([a-z]+) (.+)$/.exec(question) + if (match !== null) { + const subject = resolveSubject(match[1], input, corpus) + if (subject._tag === "clarify") return clarify(subject.reason, subject.message) + const rest = match[2] ?? "" + // Longest window tail first: "between A and B", then "on ", then bare words. + const between = /^(.*?) between ([a-z]+ \d+) and ([a-z]+ \d+)$/.exec(rest) + const on = /^(.*?) on ([a-z]+ \d+)$/.exec(rest) + const bare = /^(.*?) (today|yesterday|this week|last week)$/.exec(rest) + let activityPhrase: string + let parsed: ParsedWindow | undefined + if (between !== null) { + activityPhrase = between[1] ?? "" + parsed = parseWindow(`between ${between[2]} and ${between[3] ?? ""}`, askedAt, timezone) + } else if (on !== null) { + activityPhrase = on[1] ?? "" + parsed = parseWindow(`on ${on[2] ?? ""}`, askedAt, timezone) + } else if (bare !== null) { + activityPhrase = bare[1] ?? "" + parsed = parseWindow(bare[2] ?? "", askedAt, timezone) + } else { + activityPhrase = rest + } + const activity = activityPhrase.trim() === "" ? undefined : activityForWord(activityPhrase.trim()) + if (activity === undefined) return clarify("unknown-activity", categoryHelp(rest)) + if (parsed === undefined) return clarify("missing-time-window", windowHelp) + return { + _tag: "plan", + plan: planWith( + withKeyword({ _tag: "probe-events", category: activity.category, window: parsed.window } as HistoryQueryPlan & { _tag: "probe-events" }, activity), + subject.childId, + ), + } + } + + // "what happened with ada on september 5?" + match = /^what happened (?:with|for) ([a-z]+) (.+)$/.exec(question) + if (match !== null) { + const subject = resolveSubject(match[1], input, corpus) + if (subject._tag === "clarify") return clarify(subject.reason, subject.message) + const parsed = parseWindow(match[2] ?? "", askedAt, timezone) + if (parsed === undefined) return clarify("missing-time-window", windowHelp) + return { _tag: "plan", plan: planWith({ _tag: "day-summary", window: parsed.window } as HistoryQueryPlan & { _tag: "day-summary" }, subject.childId) } + } + + return clarify( + "unknown-activity", + "I can answer questions about recorded care events — try 'when did ada last nap?', 'how many breakfasts did milo have last week?', or 'what happened with ada on september 5?'.", + ) +} diff --git a/packages/retrieval/test/expectedAnswers.ts b/packages/retrieval/test/expectedAnswers.ts new file mode 100644 index 0000000..b0267a1 --- /dev/null +++ b/packages/retrieval/test/expectedAnswers.ts @@ -0,0 +1,321 @@ +import type { HistoryQueryAnswer as Answer, HistoryQueryInput as Input } from "../src/queryContracts.js" + +/** + * Independent expected-answer fixtures over the deterministic 30-day corpus. + * + * Every expectation here is hand-derived from the corpus timeline documented + * in `src/corpus.ts` — NOT produced by running the implementation. When a + * test fails here, the diff is either an implementation bug or a fixture + * arithmetic bug; both matter. The fixture numbers: + * + * - askedAt = Sep 12 2026 7:30 PM EDT (1788339000000): evening catch-up; + * late enough that the day's 1:00 PM nap is in the past. + * - "last week" asked then = local Mon Aug 31 – Sun Sep 6 = corpus days + * 17..23 — all covered days (the Aug 22–23 gap is outside this window). + * - Milo's breakfasts last week: 7 (one per day, one event each). + * - Ada's sleep universe: 30 days − day 1 (no nap) − days 8–9 (gap) = 27 + * nap events, with day 5's nap superseded and its caregiver-corrected + * replacement (75 min, confidence 1) included. + * - Naps between Aug 21–25 = days 7, 10, 11 → 35, 45, 40 min (days 8–9 gap). + * - Milo has NO naps in the corpus, so a Milo-scoped nap question is an + * honest not-found — it must never be answered from Ada's records. + */ + +/** Corpus timeline helper — mirrors the documented constants in src/corpus.ts. */ +const dayUtc = (dayIndex: number, hourUtc = 4): number => Date.UTC(2026, 7, 14 + dayIndex, hourUtc) + +export const ASKED_AT = Date.UTC(2026, 8, 12, 23, 30) // Sep 12 2026 7:30 PM EDT +const NY = "America/New_York" +const HOUSEHOLD = "household_demo" + +/** Contract-shaped input: childId is set only when a fixture pins the subject. */ +const input = (overrides: { question: string; askedAt?: number; childId?: string }): Input => ({ + householdId: HOUSEHOLD, + askedBy: "mom", + askedAt: overrides.askedAt ?? ASKED_AT, + timezone: NY, + question: overrides.question, + ...(overrides.childId !== undefined ? { childId: overrides.childId } : {}), +}) + +export interface ExpectedFixture { + readonly id: string + readonly input: Input + /** Hand-derived expected answer; tests deep-compare against `answerQuery`. */ + readonly expected: Answer +} + +export const fixtures: readonly ExpectedFixture[] = [ + { + id: "hq-01-last-nap", + input: input({ question: "When did Ada last nap?" }), + expected: { + _tag: "found", + statement: "Ada's last recorded nap was on September 12, 2026 at 1:00 PM — napped 45 minutes.", + citations: [ + { + entryId: "en-nap-d29", + eventIds: ["ev-ada-nap-d29"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada napped 45 minutes after lunch.", + occurredAt: dayUtc(29, 17), + }, + ], + coverage: { confirmed: 1, inferred: 26, total: 27 }, + notices: [], + }, + }, + { + id: "hq-02-count-last-week", + input: input({ question: "How many breakfasts did Milo have last week?" }), + expected: { + _tag: "found", + statement: "Milo had 7 breakfasts between Aug 31 and Sep 6 — 0 of 7 caregiver-confirmed.", + citations: Array.from({ length: 7 }, (_, i) => { + const day = 17 + i + const dd = String(day).padStart(2, "0") + const author = day % 2 === 0 ? "mom" : "dad" + return { + entryId: `en-bf-d${dd}-child_milo`, + eventIds: [`ev-child_milo-breakfast-d${dd}`], + childId: "child_milo", + authorId: author, + excerpt: + author === "mom" + ? "Milo ate one serving of oatmeal for breakfast this morning." + : "Milo had one serving of oatmeal at breakfast.", + occurredAt: dayUtc(day, 12), + } + }), + coverage: { confirmed: 0, inferred: 7, total: 7 }, + notices: [], + }, + }, + { + id: "hq-03-range-with-gap", + input: input({ question: "How many naps did Ada have between August 21 and August 25?" }), + expected: { + _tag: "found", + statement: "Ada had 3 naps between Aug 21 and Aug 25 — 0 of 3 caregiver-confirmed.", + citations: [ + { + entryId: "en-nap-d07", + eventIds: ["ev-ada-nap-d07"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada napped 35 minutes after lunch.", + occurredAt: dayUtc(7, 17), + }, + { + entryId: "en-nap-d10", + eventIds: ["ev-ada-nap-d10"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada napped 45 minutes after lunch.", + occurredAt: dayUtc(10, 17), + }, + { + entryId: "en-nap-d11", + eventIds: ["ev-ada-nap-d11"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada napped 40 minutes after lunch.", + occurredAt: dayUtc(11, 17), + }, + ], + coverage: { confirmed: 0, inferred: 3, total: 3 }, + notices: [{ _tag: "gap", from: dayUtc(8), to: dayUtc(10), days: 2 }], + }, + }, + { + id: "hq-04-author-conflict", + input: input({ question: "How much pasta did Ada eat on August 17?" }), + expected: { + _tag: "found", + statement: "Conflicting records for Ada's meal on August 17, 2026: dad logged 1 serving, mom logged 2 servings.", + citations: [ + { + entryId: "en-dinner-d03-dad", + eventIds: ["ev-ada-dinner-d03-dad"], + childId: "child_ada", + authorId: "dad", + excerpt: "Dinner was a struggle tonight — Ada only ate one serving of pasta.", + occurredAt: dayUtc(3, 22), + }, + { + entryId: "en-dinner-d03-mom", + eventIds: ["ev-ada-dinner-d03-mom"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada ate two servings of pasta at dinner tonight.", + occurredAt: dayUtc(3, 22), + }, + ], + coverage: { confirmed: 0, inferred: 2, total: 2 }, + notices: [ + { + _tag: "conflict", + category: "meal", + localDay: { from: dayUtc(3), to: dayUtc(4) }, + claims: [ + { authorId: "dad", eventIds: ["ev-ada-dinner-d03-dad"], payloadKey: "servings", payloadValue: 1 }, + { authorId: "mom", eventIds: ["ev-ada-dinner-d03-mom"], payloadKey: "servings", payloadValue: 2 }, + ], + }, + ], + }, + }, + { + id: "hq-05-notfound-with-gap", + input: input({ question: "How much pasta did Ada eat between August 21 and August 25?" }), + expected: { + _tag: "not-found", + statement: "No matching meal records were found between Aug 21 and Aug 25.", + window: { from: dayUtc(7), to: dayUtc(12) }, + notices: [{ _tag: "gap", from: dayUtc(8), to: dayUtc(10), days: 2 }], + }, + }, + { + id: "hq-06-correction-applied", + input: input({ question: "Did Ada nap on August 19?" }), + expected: { + _tag: "found", + statement: "Yes — Ada: napped 75 minutes.", + citations: [ + { + entryId: "en-correction-d06", + eventIds: ["ev-ada-nap-d05-corrected"], + childId: "child_ada", + authorId: "dad", + excerpt: "Correction to yesterday's entry: Ada's nap was actually 75 minutes, not 45.", + occurredAt: dayUtc(5, 17), + }, + ], + coverage: { confirmed: 1, inferred: 0, total: 1 }, + notices: [ + { + _tag: "correction", + supersedesEventId: "ev-ada-nap-d05", + replacementEventId: "ev-ada-nap-d05-corrected", + correctedBy: "dad", + reason: "nap duration was misreported", + }, + ], + }, + }, + { + id: "hq-07-day-summary", + input: input({ question: "What happened with Ada on September 5?" }), + expected: { + _tag: "found", + statement: "Ada had 3 recorded events on September 5, 2026: meal, school, sleep — 1 of 3 caregiver-confirmed.", + citations: [ + { + entryId: "en-bf-d22-child_ada", + eventIds: ["ev-child_ada-breakfast-d22"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada ate one serving of oatmeal for breakfast this morning.", + occurredAt: dayUtc(22, 12), + }, + { + entryId: "en-school-d22-mom", + eventIds: ["ev-ada-school-d22"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada's first day of kindergarten today — she was so proud of her new backpack.", + occurredAt: dayUtc(22, 13), + }, + { + entryId: "en-nap-d22", + eventIds: ["ev-ada-nap-d22"], + childId: "child_ada", + authorId: "mom", + excerpt: "Ada napped 40 minutes after lunch.", + occurredAt: dayUtc(22, 17), + }, + ], + coverage: { confirmed: 1, inferred: 2, total: 3 }, + notices: [], + }, + }, + { + id: "hq-08-gap-day-notfound", + input: input({ question: "Did Ada nap on August 22?" }), + expected: { + _tag: "not-found", + statement: "No matching nap records were found on August 22, 2026.", + window: { from: dayUtc(8), to: dayUtc(9) }, + notices: [{ _tag: "gap", from: dayUtc(8), to: dayUtc(9), days: 1 }], + }, + }, + { + id: "hq-09-ambiguous-unpinned", + input: input({ question: "When was the last dinner?" }), + expected: { + _tag: "ambiguous", + reason: "multiple-children-matched", + candidates: [ + { + childId: "child_ada", + entryId: "en-dinner-d16-mom", + eventIds: ["ev-ada-dinner-d16"], + occurredAt: dayUtc(16, 22), + }, + { + childId: "child_milo", + entryId: "en-dinner-d16-dad", + eventIds: ["ev-milo-dinner-d16"], + occurredAt: dayUtc(16, 22), + }, + ], + }, + }, + { + id: "hq-10-count-empty-category", + input: input({ question: "How many tantrums did Ada have last week?" }), + expected: { + _tag: "not-found", + statement: "No matching mood records were found between Aug 31 and Sep 6.", + window: { from: dayUtc(17), to: dayUtc(24) }, + notices: [], + }, + }, + { + id: "hq-11-clarify-activity", + input: input({ question: "What's your favorite color?" }), + expected: { + _tag: "clarify", + reason: "unknown-activity", + message: "I can answer questions about recorded care events — try 'when did ada last nap?', 'how many breakfasts did milo have last week?', or 'what happened with ada on september 5?'.", + }, + }, + { + id: "hq-12-clarify-person", + input: input({ question: "When did she last nap?" }), + expected: { + _tag: "clarify", + reason: "unresolved-person", + message: "I can't tell who \"she\" refers to — ask with a child's name (or ask from a view scoped to one child).", + }, + }, + { + id: "hq-13-clarify-window", + input: input({ question: "How many tantrums did Ada have" }), + expected: { + _tag: "clarify", + reason: "missing-time-window", + message: "I can count over a time window — try '…last week', '…yesterday', or '…between September 1 and September 5'.", + }, + }, + { + id: "hq-14-scoped-empty-not-cross-child", + input: input({ question: "When did she last nap?", childId: "child_milo" }), + expected: { + _tag: "not-found", + statement: "No matching nap records were found in the recorded history.", + notices: [], + }, + }, +] diff --git a/packages/retrieval/test/query.test.ts b/packages/retrieval/test/query.test.ts new file mode 100644 index 0000000..40bd6ac --- /dev/null +++ b/packages/retrieval/test/query.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" + +import { EntrySchema, EventSchema } from "@journal/domain" + +import { generateCorpus } from "../src/corpus.js" +import { answerQuery, resolveEntrySource } from "../src/engine.js" +import { HistoryQueryAnswer } from "../src/queryContracts.js" +import { fixtures } from "./expectedAnswers.js" + +const corpus = generateCorpus() + +describe("corpus validity", () => { + test("every record decodes through the canonical domain schemas", () => { + expect(corpus.records.length).toBeGreaterThan(50) + for (const record of corpus.records) { + expect(Schema.is(EntrySchema)(record.entry)).toBe(true) + for (const event of record.events) { + expect(Schema.is(EventSchema)(event)).toBe(true) + expect(event.householdId).toBe(corpus.householdId) + } + } + }) + + test("coverage is exactly 30 days with the two pinned gap days empty", () => { + expect(corpus.coverage.dayCount).toBe(30) + for (const record of corpus.records) { + const day = Math.floor((record.entry.createdAt - corpus.coverage.firstDayUtcMs) / 86_400_000) + expect(day === 8 || day === 9).toBe(false) + } + }) +}) + +describe("expected-answer fixtures (hand-derived)", () => { + for (const fixture of fixtures) { + test(fixture.id, () => { + const actual = answerQuery(fixture.input, corpus) + // The answer must satisfy the answer contract... + expect(Schema.is(HistoryQueryAnswer)(actual)).toBe(true) + // ...and deep-equal the hand-derived expectation (decoded for key normalization). + expect(actual).toEqual(Schema.decodeUnknownSync(HistoryQueryAnswer)(fixture.expected)) + }) + } + + test("superseded events are never served as citation sources", () => { + for (const fixture of fixtures) { + if (fixture.expected._tag !== "found") continue + for (const citation of fixture.expected.citations) { + for (const eventId of citation.eventIds) { + for (const correction of corpus.corrections) { + expect(eventId).not.toBe(correction.supersedesEventId) + } + } + } + } + }) +}) + +describe("determinism", () => { + test("two runs produce byte-identical corpora and answers", () => { + const first = generateCorpus() + const second = generateCorpus() + expect(JSON.stringify(first)).toBe(JSON.stringify(second)) + for (const fixture of fixtures) { + const a = answerQuery(fixture.input, first) + const b = answerQuery(fixture.input, second) + expect(JSON.stringify(a)).toBe(JSON.stringify(b)) + } + }) + + test("querying does not mutate the corpus", () => { + const frozen = generateCorpus() + const before = JSON.stringify(frozen) + for (const fixture of fixtures) answerQuery(fixture.input, frozen) + expect(JSON.stringify(frozen)).toBe(before) + }) +}) + +describe("source navigation", () => { + test("a citation's entryId resolves to the verbatim record", () => { + const source = resolveEntrySource(corpus, "en-nap-d29") + expect(source).toBeDefined() + expect(source?.entry.rawTranscript).toBe("Ada napped 45 minutes after lunch.") + expect(source?.events.length).toBe(1) + }) + + test("an unknown entryId resolves to undefined instead of guessing", () => { + expect(resolveEntrySource(corpus, "en-nope")).toBeUndefined() + }) + + test("every fixture citation entryId resolves", () => { + for (const fixture of fixtures) { + if (fixture.expected._tag !== "found") continue + for (const citation of fixture.expected.citations) { + expect(resolveEntrySource(corpus, citation.entryId)).toBeDefined() + } + } + }) +}) diff --git a/packages/retrieval/tsconfig.json b/packages/retrieval/tsconfig.json new file mode 100644 index 0000000..5a24989 --- /dev/null +++ b/packages/retrieval/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/packages/retrieval/tsconfig.test.json b/packages/retrieval/tsconfig.test.json new file mode 100644 index 0000000..e4021e2 --- /dev/null +++ b/packages/retrieval/tsconfig.test.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["bun"] + }, + "include": ["src", "test"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cfb5c9d..28d2f47 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -107,6 +107,22 @@ importers: specifier: ~6.0.3 version: 6.0.3 + packages/retrieval: + 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/ui: devDependencies: '@types/react':