Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"ios": "expo start --ios"
},
"dependencies": {
"@journal/domain": "workspace:*",
"@journal/month-history": "workspace:*",
"@journal/ui": "workspace:*",
"convex": "^1.46.0",
Expand Down
125 changes: 125 additions & 0 deletions apps/mobile/src/catchup/CatchUpView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/**
* PROTOTYPE — typecheck-verified only, NOT device-verified.
*
* Since-last-seen catch-up view (contract delta v0.1, art_6qhBut41).
* Presentational: renders a validated domain `CatchUpReport`. The caller owns
* fetching (`getCatchUp`) and watermark advance (`advanceReadState`); this
* component holds no data access, no navigation, no provider wiring, and no
* new dependencies. Disclosure discipline mirrors the domain contract: gaps
* are phrased only as missing recordings — never as "nothing happened" — the
* transcript is shown verbatim (excerpted, never paraphrased), and events
* with confidence below 1 are always marked inferred.
*/
import { ScrollView, StyleSheet, View } from "react-native"

import { gapDisclosure, type CatchUpItem, type CatchUpReport } from "@journal/domain"
import { Text } from "@journal/ui"

const TRANSCRIPT_EXCERPT_MAX = 140

const isoDay = (epochMs: number): string => new Date(epochMs).toISOString().slice(0, 10)

const excerptOf = (transcript: string): string =>
transcript.length <= TRANSCRIPT_EXCERPT_MAX
? transcript
: `${transcript.slice(0, TRANSCRIPT_EXCERPT_MAX)}…`

/** Kind badge; late items name both ends of the delay (happened vs recorded). */
const kindBadgeText = (item: CatchUpItem): string => {
if (item.kind === "late" && item.daysLate !== undefined) {
return `late: happened ${isoDay(item.occurredAt ?? item.entryCreatedAt)}, recorded ${isoDay(item.entryCreatedAt)}`
}
return item.kind
}

/** One canonical event line; confidence below 1 is always disclosed. */
const eventLine = (category: string, payload: Record<string, number> | undefined, confidence: number): string => {
const values =
payload === undefined
? ""
: Object.entries(payload)
.map(([key, value]) => `${key}: ${value}`)
.join(", ")
const summary = values.length > 0 ? `${category} (${values})` : category
return confidence < 1 ? `${summary} — inferred` : summary
}

/** Typecheck-only usage example: proves the props contract, routes nothing. */
export function CatchUpViewUsageExample({ report }: { report: CatchUpReport }) {
return <CatchUpView report={report} />
}

export function CatchUpView({ report }: { report: CatchUpReport }) {
const disclosure = gapDisclosure(report.coverageDays)
const confirmed = report.confirmation.confirmedEvents
const total = confirmed + report.confirmation.inferredEvents
const newItems = report.items.filter((item) => item.kind !== "corrected")
const correctedItems = report.items.filter((item) => item.kind === "corrected")

return (
<ScrollView style={styles.container}>
<View style={styles.header}>
<Text>
Catch-up {isoDay(report.windowStart)} – {isoDay(report.windowEnd)}
</Text>
<Text>
{report.allCaughtUp ? "You're all caught up." : "Here's what was recorded while you were away."}
</Text>
</View>

{newItems.length > 0 && (
<View style={styles.section}>
<Text style={styles.sectionTitle}>New while you were away</Text>
{newItems.map((item) => (
<View key={item.entryId} style={styles.card}>
<Text style={styles.badge}>{kindBadgeText(item)}</Text>
<Text>Recorded by {item.source.authorId}</Text>
<Text>"{excerptOf(item.source.rawTranscript)}"</Text>
{item.events.map((event, index) => (
<Text
key={`${item.entryId}-event-${index}`}
>{`${eventLine(event.category, event.payload, event.confidence)} · ${isoDay(event.timestamp)}`}</Text>
))}
</View>
))}
</View>
)}

{correctedItems.length > 0 && (
<View style={styles.section}>
<Text style={styles.sectionTitle}>Corrected</Text>
{correctedItems.map((item) => (
<View key={item.entryId} style={styles.card}>
{/* The report carries the revised (canonical) value and the
original's citation — never an invented original value. */}
{item.events.map((event, index) => (
<Text
key={`${item.entryId}-revised-${index}`}
>{`Corrected: ${eventLine(event.category, event.payload, event.confidence)} · ${isoDay(event.timestamp)}`}</Text>
))}
<Text>
{`Revised by ${item.correctedBy ?? "unknown"} · original event ${item.originalEventId ?? "unknown"}${item.revisionIds.length > 0 ? ` · ${item.revisionIds.length} revision(s)` : ""}`}
</Text>
<Text>"{excerptOf(item.source.rawTranscript)}"</Text>
</View>
))}
</View>
)}

<View style={styles.footer}>
{disclosure.length > 0 && <Text>{disclosure}</Text>}
<Text>{`${confirmed} of ${total} events caregiver-confirmed`}</Text>
</View>
</ScrollView>
)
}

const styles = StyleSheet.create({
container: { flex: 1 },
header: { padding: 16, gap: 4 },
section: { padding: 16, paddingTop: 0, gap: 8 },
sectionTitle: { fontSize: 18, fontWeight: "600" },
card: { padding: 12, borderWidth: StyleSheet.hairlineWidth, borderRadius: 8, gap: 4 },
badge: { fontWeight: "600" },
footer: { padding: 16, gap: 4 },
})
2 changes: 2 additions & 0 deletions backend/convex/convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* @module
*/

import type * as catchup from "../catchup.js";
import type * as children from "../children.js";
import type * as entries from "../entries.js";
import type * as households from "../households.js";
Expand All @@ -23,6 +24,7 @@ import type {
} from "convex/server";

declare const fullApi: ApiFromModules<{
catchup: typeof catchup;
children: typeof children;
entries: typeof entries;
households: typeof households;
Expand Down
184 changes: 184 additions & 0 deletions backend/convex/convex/catchup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { Schema } from "effect"

import {
AdvanceReadStateInput,
CatchUpQueryInput,
CatchUpReport,
EntryDocument,
EventDocument,
computeCatchUp,
} from "@journal/domain"
import { convexFields } from "@journal/domain/convex"

import { mutation, query } from "./_generated/server"
import { ConvexError } from "convex/values"

import { errorText, stripUndefined } from "./lib"

/**
* Since-last-seen caregiver catch-up (contract delta v0.1, art_6qhBut41).
*
* `getCatchUp` derives the report from the flat model through the
* deterministic domain reducer; `advanceReadState` upserts the monotonic
* per-(caregiver, child) watermark. `now` is part of the decoded contract
* input (the reducer stays pure — no wall clock inside domain code).
*
* Corrected path NOT wired: `eventRevisions` has no table on master — the
* v0.3 fold (slot 10) owns revision persistence and will pass revisions into
* the reducer here. Until then the corrected path stays silent on the
* backend; the reducer's corrected logic is exercised by the domain tests.
*/

// PLACEHOLDER grants pending slot 19 (household members/grants): the flat
// model has no membership table, so the grant is a named allowlist and the
// default is DENY. Replace with the real membership check the moment slot 19
// lands — this list must never graduate to a config surface.
const knownReaders: ReadonlyArray<string> = ["reader_mom", "reader_dad"]

const grantsFor = {
canRead: (readerId: string, _householdId: string): boolean => knownReaders.includes(readerId),
}

/**
* Catch-up report for one (reader, child) pair. Rows are read per-child via
* the canonical indexes; events are joined through each entry's
* structuredEventIds (entries carry no event payloads). Authorization fails
* closed: an unlisted reader is an error, never a partial report.
*/
export const getCatchUp = query({
args: convexFields(CatchUpQueryInput),
handler: async (ctx, rawArgs): Promise<typeof CatchUpReport["Type"]> => {
let args: typeof CatchUpQueryInput["Type"]
try {
args = Schema.decodeUnknownSync(CatchUpQueryInput)(stripUndefined(rawArgs))
} catch (err) {
throw new ConvexError({ code: "INVALID_CATCHUP_INPUT", message: errorText(err) })
}

// Fail-closed referential check (same shape as entries.createEntry).
const childId = ctx.db.normalizeId("children", args.childId)
if (childId === null) {
throw new ConvexError({
code: "CHILD_NOT_FOUND",
message: `child ${args.childId} does not exist`,
})
}
const child = await ctx.db.get(childId)
if (child === null) {
throw new ConvexError({
code: "CHILD_NOT_FOUND",
message: `child ${args.childId} does not exist`,
})
}

// Watermark: absent row = first-time reader (the reducer treats it as 0).
const readState = await ctx.db
.query("caregiverReadState")
.withIndex("by_caregiver_child", (q) =>
q.eq("caregiverId", args.readerId).eq("childId", args.childId),
)
.first()

const [entryRows, eventRows] = await Promise.all([
ctx.db
.query("entries")
.withIndex("by_child", (q) => q.eq("childId", args.childId))
.collect(),
ctx.db
.query("events")
.withIndex("by_child", (q) => q.eq("childId", args.childId))
.collect(),
])

// Rows decode through the *_Document contracts (system fields included —
// the reducer cites entry._id and event._id).
const decodeEntry = Schema.decodeUnknownSync(EntryDocument)
const decodeEvent = Schema.decodeUnknownSync(EventDocument)
// Domain ids are plain strings (convexId is an annotated Schema.String);
// the generated doc type brands them. Key the join by the plain-string view.
const eventsById = new Map(eventRows.map((event) => [event._id as string, event]))

const catchUpEntries = entryRows.map((row) => {
const entry = decodeEntry(row)
return {
entry,
events: entry.structuredEventIds.flatMap((eventId) => {
const found = eventsById.get(eventId)
if (found === undefined) return []
return [decodeEvent(found)]
}),
}
})

// TODO(v0.3 fold / slot 10): load eventRevisions for this child and pass
// them through so in-window corrections surface from the backend.
const result = computeCatchUp(
args,
{
householdId: child.householdId,
readerLastSeenAt: readState?.lastSeenAt,
entries: catchUpEntries,
revisions: [],
},
grantsFor,
)

if ("_tag" in result) {
throw new ConvexError({
code: result._tag === "UnauthorizedReader" ? "UNAUTHORIZED_READER" : "HORIZON_EXCEEDED",
message:
result._tag === "UnauthorizedReader"
? `reader ${args.readerId} is not authorized for this child's household`
: "horizonDays exceeds the 30-day maximum",
})
}
return result
},
})

/**
* Monotonic watermark advance: max(existing, at) — a stale client or a replay
* can never move the reader backwards. Upsert keyed on by_caregiver_child;
* the first write creates the row (undefined -> at).
*/
export const advanceReadState = mutation({
args: convexFields(AdvanceReadStateInput),
handler: async (ctx, rawArgs): Promise<{ lastSeenAt: number }> => {
let args: typeof AdvanceReadStateInput["Type"]
try {
args = Schema.decodeUnknownSync(AdvanceReadStateInput)(stripUndefined(rawArgs))
} catch (err) {
throw new ConvexError({ code: "INVALID_ADVANCE_INPUT", message: errorText(err) })
}

const childId = ctx.db.normalizeId("children", args.childId)
if (childId === null) {
throw new ConvexError({
code: "CHILD_NOT_FOUND",
message: `child ${args.childId} does not exist`,
})
}

const existing = await ctx.db
.query("caregiverReadState")
.withIndex("by_caregiver_child", (q) =>
q.eq("caregiverId", args.caregiverId).eq("childId", args.childId),
)
.first()

if (existing === null) {
await ctx.db.insert("caregiverReadState", {
caregiverId: args.caregiverId,
childId: args.childId,
lastSeenAt: args.at,
})
return { lastSeenAt: args.at }
}
// Same-value advance is a no-op (idempotent by construction).
if (args.at > existing.lastSeenAt) {
await ctx.db.patch(existing._id, { lastSeenAt: args.at })
return { lastSeenAt: args.at }
}
return { lastSeenAt: existing.lastSeenAt }
},
})
15 changes: 14 additions & 1 deletion backend/convex/convex/schema.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { defineSchema, defineTable } from "convex/server"
import { Schema } from "effect"

import { ChildFields, EntryFields, EventFields, HouseholdFields, KnowledgeFields } from "@journal/domain"
import {
CaregiverReadStateFields,
ChildFields,
EntryFields,
EventFields,
HouseholdFields,
KnowledgeFields,
} from "@journal/domain"
import { convexFields } from "@journal/domain/convex"

/**
Expand Down Expand Up @@ -31,4 +38,10 @@ export default defineSchema({
.index("by_household", ["householdId"])
.index("by_child_topic", ["childId", "topic"])
.index("by_supersedes", ["supersedes"]),
// Since-last-seen read state (catch-up contract delta v0.1, art_6qhBut41):
// one monotonic watermark row per (caregiver, child). Additive only.
caregiverReadState: tableFrom(CaregiverReadStateFields).index("by_caregiver_child", [
"caregiverId",
"childId",
]),
})
Loading
Loading