From 30b03b37b4b04d4fc8a37f7c1eafc6c37ffccd62 Mon Sep 17 00:00:00 2001 From: Obvious Date: Thu, 17 Sep 2026 19:15:50 +0000 Subject: [PATCH] feat(backend): family-knowledge Convex functions with fail-closed access cases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Write path (create + atomic append-only supersede) and bounded read path (listCurrent/listHistory) over the knowledge table, composed from the PR #16 canonical contract in packages/domain — no domain changes. Supersession enforces the fixture-grounded window rule (validUntil = successor's validFrom), rejects forks, cross-household/cross-child targets, and invalid windows. Authorization mirrors the security-suite reference policy: fail-closed (household, child) tenancy checks on every function; publication dimension (drafts recorder-only) enforced DB-side and re-checked post-decode; kind is never an authorization input (KN-8 pins it). Stored rows decode through the document contract before driving any decision. Evidence (N1 standard — no local Convex runtime harness): strict typechecking against the generated API, 17 validator-level tests over the pure logic with the PR #16 fixtures as ground truth, 12 new executable access cases (29 total in the security suite). Co-authored-by: Gilbert Polanco --- backend/convex/convex/_generated/api.d.ts | 4 + backend/convex/convex/knowledge.ts | 262 +++++++++++++++++++ backend/convex/convex/knowledgeInput.ts | 231 +++++++++++++++++ backend/convex/package.json | 4 +- backend/convex/test/knowledge.test.ts | 293 ++++++++++++++++++++++ backend/convex/tsconfig.test.json | 8 + pnpm-lock.yaml | 3 + security/access/knowledge.test.ts | 173 +++++++++++++ security/access/policy.ts | 14 +- security/access/schema-mock.ts | 29 +++ security/access/types.ts | 10 +- 11 files changed, 1028 insertions(+), 3 deletions(-) create mode 100644 backend/convex/convex/knowledge.ts create mode 100644 backend/convex/convex/knowledgeInput.ts create mode 100644 backend/convex/test/knowledge.test.ts create mode 100644 backend/convex/tsconfig.test.json create mode 100644 security/access/knowledge.test.ts diff --git a/backend/convex/convex/_generated/api.d.ts b/backend/convex/convex/_generated/api.d.ts index b314d85..8d94d4a 100644 --- a/backend/convex/convex/_generated/api.d.ts +++ b/backend/convex/convex/_generated/api.d.ts @@ -11,6 +11,8 @@ import type * as children from "../children.js"; import type * as entries from "../entries.js"; import type * as households from "../households.js"; +import type * as knowledge from "../knowledge.js"; +import type * as knowledgeInput from "../knowledgeInput.js"; import type * as lib from "../lib.js"; import type * as timeline from "../timeline.js"; @@ -24,6 +26,8 @@ declare const fullApi: ApiFromModules<{ children: typeof children; entries: typeof entries; households: typeof households; + knowledge: typeof knowledge; + knowledgeInput: typeof knowledgeInput; lib: typeof lib; timeline: typeof timeline; }>; diff --git a/backend/convex/convex/knowledge.ts b/backend/convex/convex/knowledge.ts new file mode 100644 index 0000000..51d4c46 --- /dev/null +++ b/backend/convex/convex/knowledge.ts @@ -0,0 +1,262 @@ +import { Schema } from "effect" + +import { KnowledgeDocument, assertKnowledgeInvariants } from "@journal/domain" +import { convexFields } from "@journal/domain/convex" + +import { + CreateKnowledgeItemInput, + CreateKnowledgeItemOutput, + ListKnowledgeInput, + ListKnowledgeOutput, + SupersedeKnowledgeItemInput, + SupersedeKnowledgeItemOutput, + buildKnowledgeItemRow, + checkSupersession, + isCurrentKnowledgeItem, + isVisibleKnowledgeItem, +} from "./knowledgeInput" + +import { mutation, query } from "./_generated/server" +import type { DatabaseReader } from "./_generated/server" +import type { DataModel } from "./_generated/dataModel" +import type { FilterBuilder } from "convex/server" +import { ConvexError } from "convex/values" + +import { errorText, stripUndefined } from "./lib" + +/** + * Family-knowledge functions over the `knowledge` table (contract: PR #16's + * `KnowledgeFields` in @journal/domain; input contracts composed in + * `./knowledgeInput.ts` from the same canonical fields — packages/domain is + * untouched). + * + * Authorization wiring (see security/access for the reference policy this + * mirrors): every function resolves the (householdId, childId) pair against + * the stored child row and FAILS CLOSED on a mismatch — cross-household reads + * and writes are rejected, never silently rewritten to the child's real + * household. Reads additionally enforce the publication dimension: drafts are + * visible only to their recorder; with no viewer identity drafts are + * invisible. `kind` is NEVER an authorization input — it is a + * retrieval/rendering discriminant only (guardrail adopted with the PR #16 + * contract decisions; negative case in security/access/knowledge.test.ts). + * + * Attribution: `statedBy`/`recordedBy` are the schema's attribution fields and + * arrive from the client — server-authenticated identity is not wired in this + * backend yet (the same documented platform gap as `authorId` on the entry + * write path, PR #13). The supersession rules below are enforced + * server-side regardless of identity. + * + * Evidence note (N1): there is no local Convex runtime harness, so these + * handlers are exercised by strict typechecking against the generated API + * plus validator-level bun tests over the pure logic in ./knowledgeInput.ts; + * runtime/deployment evidence is deferred to the future harness. + */ + +/** + * Fail-closed tenancy check shared by every function: the child must exist, + * and the requested household must be the child's ACTUAL owning household. + * A (household, child) pair that crosses tenancies is an authorization + * signal — rejected, not rewritten. + */ +const requireChildInHousehold = async ( + db: DatabaseReader, + householdId: string, + childId: string, +): Promise => { + const normalizedChildId = db.normalizeId("children", childId) + if (normalizedChildId === null) { + throw new ConvexError({ code: "CHILD_NOT_FOUND", message: `child ${childId} does not exist` }) + } + const child = await db.get(normalizedChildId) + if (child === null) { + throw new ConvexError({ code: "CHILD_NOT_FOUND", message: `child ${childId} does not exist` }) + } + if (child.householdId !== householdId) { + throw new ConvexError({ + code: "CHILD_HOUSEHOLD_MISMATCH", + message: `child ${childId} belongs to household ${child.householdId}, not ${householdId} — cross-household access is rejected`, + }) + } +} + +/** + * Write path (1/2): append a new knowledge item. Household-scoped via the + * fail-closed pair check, attributed per the schema's attribution fields, + * entering the draft→published lifecycle at `visibility: "draft"`. + */ +export const create = mutation({ + args: convexFields(CreateKnowledgeItemInput), + handler: async (ctx, rawArgs): Promise => { + let args: typeof CreateKnowledgeItemInput["Type"] + let row: ReturnType + try { + args = Schema.decodeUnknownSync(CreateKnowledgeItemInput)(stripUndefined(rawArgs)) + row = buildKnowledgeItemRow(args, Date.now()) + } catch (err) { + throw new ConvexError({ code: "INVALID_KNOWLEDGE_INPUT", message: errorText(err) }) + } + + await requireChildInHousehold(ctx.db, args.householdId, args.childId) + + const knowledgeItemId = await ctx.db.insert("knowledge", row) + return { status: "created" as const, knowledgeItemId } satisfies typeof CreateKnowledgeItemOutput["Type"] + }, +}) + +/** + * Write path (2/2): append-only supersession, atomic. Appends the successor + * (forward `supersedes` edge) and marks the target `superseded` with + * `validUntil` = the successor's `validFrom` — matching the PR #16 fixture + * chains. The target must be a CURRENT item in the same household and for + * the same child (checkSupersession); the full history stays readable via + * the history query. + */ +export const supersede = mutation({ + args: convexFields(SupersedeKnowledgeItemInput), + handler: async (ctx, rawArgs): Promise => { + let args: typeof SupersedeKnowledgeItemInput["Type"] + let successor: ReturnType + try { + args = Schema.decodeUnknownSync(SupersedeKnowledgeItemInput)(stripUndefined(rawArgs)) + successor = buildKnowledgeItemRow(args, Date.now()) + } catch (err) { + throw new ConvexError({ code: "INVALID_KNOWLEDGE_INPUT", message: errorText(err) }) + } + + await requireChildInHousehold(ctx.db, args.householdId, args.childId) + + const targetId = ctx.db.normalizeId("knowledge", args.supersedes) + if (targetId === null) { + throw new ConvexError({ + code: "KNOWLEDGE_ITEM_NOT_FOUND", + message: `knowledge item ${args.supersedes} does not exist`, + }) + } + const target = await ctx.db.get(targetId) + if (target === null) { + throw new ConvexError({ + code: "KNOWLEDGE_ITEM_NOT_FOUND", + message: `knowledge item ${args.supersedes} does not exist`, + }) + } + // The stored target is decoded through the document contract before it + // drives any decision — a corrupted or cross-contract row fails loudly. + const targetDoc = decodeKnowledgeRow(target) + + const validFrom = successor.validFrom + const check = checkSupersession(targetDoc, { householdId: args.householdId, childId: args.childId, validFrom }) + if (check.outcome === "rejected") { + throw new ConvexError({ code: check.code, message: check.detail }) + } + + // Defense in depth: the closed target must still satisfy the full + // family-knowledge contract (window, lifecycle) before anything is + // written. A violation here is a server-state bug — surfaces loudly. + assertKnowledgeInvariants({ ...targetDoc, status: "superseded", validUntil: validFrom }) + + const knowledgeItemId = await ctx.db.insert("knowledge", { + ...successor, + supersedes: targetId, + }) + await ctx.db.patch(targetId, { status: "superseded", validUntil: validFrom }) + + return { + status: "superseded" as const, + knowledgeItemId, + supersededId: targetId, + } satisfies typeof SupersedeKnowledgeItemOutput["Type"] + }, +}) + +/** + * Fail-closed read projection shared by every function that touches a stored + * knowledge row: decode it (Convex hands back loosely-typed documents) + * through the canonical document contract and re-run the cross-field + * invariants. A stored row that violates the contract fails loudly instead + * of serving invalid knowledge or driving a supersession decision. + */ +const decodeKnowledgeRow = (row: unknown): KnowledgeDocument => { + const decoded = Schema.decodeUnknownSync(KnowledgeDocument)(row) + assertKnowledgeInvariants(decoded) + return decoded +} + +/** + * The publication-dimension filter as a database-side expression, mirroring + * isVisibleKnowledgeItem: with no viewer identity only published items are + * readable; with a viewer, their own drafts are also readable. + */ +const audienceExpression = (q: FilterBuilder, viewerId: string | undefined) => + viewerId === undefined + ? q.eq(q.field("visibility"), "published") + : q.or(q.eq(q.field("visibility"), "published"), q.eq(q.field("recordedBy"), viewerId)) + +/** + * Bounded read (1/2): CURRENT items for the household/child(/topic) — + * superseded items are excluded by default. Explicit `limit` (1..200). The + * tested predicates re-check every decoded row in the serving path, so the + * database-level filters can never widen the audience. + */ +export const listCurrent = query({ + args: convexFields(ListKnowledgeInput), + handler: async (ctx, rawArgs): Promise => { + let args: typeof ListKnowledgeInput["Type"] + try { + args = Schema.decodeUnknownSync(ListKnowledgeInput)(stripUndefined(rawArgs)) + } catch (err) { + throw new ConvexError({ code: "INVALID_KNOWLEDGE_QUERY", message: errorText(err) }) + } + + await requireChildInHousehold(ctx.db, args.householdId, args.childId) + + // The composite (childId, topic) index serves both forms: binding the + // childId prefix alone scans the child's items across topics. Filters + // apply within the index scan; take() bounds the page. + const base = + args.topic === undefined + ? ctx.db.query("knowledge").withIndex("by_child_topic", (q) => q.eq("childId", args.childId)) + : ctx.db + .query("knowledge") + .withIndex("by_child_topic", (q) => q.eq("childId", args.childId).eq("topic", args.topic)) + + const rows = await base + .filter((q) => q.eq(q.field("status"), "current")) + .filter((q) => audienceExpression(q, args.viewerId)) + .take(args.limit) + + return rows + .map((row) => decodeKnowledgeRow(row)) + .filter((doc) => isCurrentKnowledgeItem(doc) && isVisibleKnowledgeItem(doc, args.viewerId)) + }, +}) + +/** + * Bounded read (2/2): the explicit HISTORY capability — includes superseded + * items (the full append-only chain), same household scoping, publication + * dimension, and page bound as listCurrent. Within a topic, rows return in + * append order (supersession chains are appended chronologically). + */ +export const listHistory = query({ + args: convexFields(ListKnowledgeInput), + handler: async (ctx, rawArgs): Promise => { + let args: typeof ListKnowledgeInput["Type"] + try { + args = Schema.decodeUnknownSync(ListKnowledgeInput)(stripUndefined(rawArgs)) + } catch (err) { + throw new ConvexError({ code: "INVALID_KNOWLEDGE_QUERY", message: errorText(err) }) + } + + await requireChildInHousehold(ctx.db, args.householdId, args.childId) + + const base = + args.topic === undefined + ? ctx.db.query("knowledge").withIndex("by_child_topic", (q) => q.eq("childId", args.childId)) + : ctx.db + .query("knowledge") + .withIndex("by_child_topic", (q) => q.eq("childId", args.childId).eq("topic", args.topic)) + + const rows = await base.filter((q) => audienceExpression(q, args.viewerId)).take(args.limit) + + return rows.map((row) => decodeKnowledgeRow(row)).filter((doc) => isVisibleKnowledgeItem(doc, args.viewerId)) + }, +}) diff --git a/backend/convex/convex/knowledgeInput.ts b/backend/convex/convex/knowledgeInput.ts new file mode 100644 index 0000000..818567a --- /dev/null +++ b/backend/convex/convex/knowledgeInput.ts @@ -0,0 +1,231 @@ +import { Schema } from "effect" + +import { + KnowledgeDocument, + KnowledgeFields, + KnowledgeSchema, + assertKnowledgeInvariants, + convexId, +} from "@journal/domain" + +/** + * Function-level operation contracts + pure decision logic for the knowledge + * functions (`./knowledge.ts`). + * + * The operation inputs are COMPOSED here from the canonical `KnowledgeFields` + * — the same exported field schemas the `knowledge` table is registered with — + * never restated, so a value rejected by these inputs is rejected identically + * by the table validators. packages/domain is deliberately untouched: the + * knowledge operation shapes are not yet promoted into + * `packages/domain/contracts.ts`, and promoting them is a contract-thread + * decision (v0.4 fold). When that fold lands, these compositions derive + * identical Convex validators because they reference the same field schemas. + * + * Everything in this file is pure (no Convex runtime imports) so the decision + * logic is executable as validator-level evidence — the N1 observation (no + * local Convex runtime harness) stands; runtime/deployment evidence is + * deferred to the future harness. + */ + +/** Hard page cap for the bounded read path — an explicit limit is required. */ +export const MAX_KNOWLEDGE_PAGE = 200 + +/** + * Create input: the item content + attribution. Lifecycle fields are + * server-set and deliberately absent — items always enter as + * `status: "current"`, `visibility: "draft"` (the draft→published entry + * point), and there is no client-chosen `supersedes` on create: corrections + * go through the atomic `supersede` mutation, which both appends the + * successor and closes the target in one transaction. + */ +export const CreateKnowledgeItemInput = Schema.Struct({ + householdId: KnowledgeFields.householdId, + childId: KnowledgeFields.childId, + kind: KnowledgeFields.kind, + topic: KnowledgeFields.topic, + statement: KnowledgeFields.statement, + quoteText: KnowledgeFields.quoteText, + spokenBy: KnowledgeFields.spokenBy, + steps: KnowledgeFields.steps, + statedBy: KnowledgeFields.statedBy, + recordedBy: KnowledgeFields.recordedBy, + provenanceKind: KnowledgeFields.provenanceKind, + confidence: KnowledgeFields.confidence, + sourceType: KnowledgeFields.sourceType, + sourceEntryId: KnowledgeFields.sourceEntryId, + sourceRef: KnowledgeFields.sourceRef, + sourceSpan: KnowledgeFields.sourceSpan, + sourceQuote: KnowledgeFields.sourceQuote, + /** When the statement became valid/known; defaults to the write time. */ + validFrom: Schema.optional(KnowledgeFields.validFrom), +}) +export type CreateKnowledgeItemInput = typeof CreateKnowledgeItemInput["Type"] + +export const CreateKnowledgeItemOutput = Schema.Struct({ + status: Schema.Literals(["created"]), + knowledgeItemId: convexId("knowledge"), +}) +export type CreateKnowledgeItemOutput = typeof CreateKnowledgeItemOutput["Type"] + +/** + * Supersede input: the replacement content PLUS the target. The mutation + * appends the successor (`supersedes` = target id, forward edge) and marks + * the target `superseded` with `validUntil` = the successor's `validFrom` + * (chain continuity, matching the PR #16 fixtures) in one transaction. + */ +export const SupersedeKnowledgeItemInput = Schema.Struct({ + householdId: KnowledgeFields.householdId, + childId: KnowledgeFields.childId, + supersedes: convexId("knowledge"), + kind: KnowledgeFields.kind, + topic: KnowledgeFields.topic, + statement: KnowledgeFields.statement, + quoteText: KnowledgeFields.quoteText, + spokenBy: KnowledgeFields.spokenBy, + steps: KnowledgeFields.steps, + statedBy: KnowledgeFields.statedBy, + recordedBy: KnowledgeFields.recordedBy, + provenanceKind: KnowledgeFields.provenanceKind, + confidence: KnowledgeFields.confidence, + sourceType: KnowledgeFields.sourceType, + sourceEntryId: KnowledgeFields.sourceEntryId, + sourceRef: KnowledgeFields.sourceRef, + sourceSpan: KnowledgeFields.sourceSpan, + sourceQuote: KnowledgeFields.sourceQuote, + validFrom: Schema.optional(KnowledgeFields.validFrom), +}) +export type SupersedeKnowledgeItemInput = typeof SupersedeKnowledgeItemInput["Type"] + +export const SupersedeKnowledgeItemOutput = Schema.Struct({ + status: Schema.Literals(["superseded"]), + knowledgeItemId: convexId("knowledge"), + supersededId: convexId("knowledge"), +}) +export type SupersedeKnowledgeItemOutput = typeof SupersedeKnowledgeItemOutput["Type"] + +/** + * Bounded read input, shared by the current and history queries (the + * difference is behavioral, not shape). `limit` is REQUIRED and capped — + * an unbounded read path has no caller. `viewerId` is the caller-asserted + * caregiver identity (client-asserted until the auth lane wires server + * identity — the same documented platform gap as `authorId` on the entry + * write path): drafts are visible ONLY to their recorder, and with no + * viewerId at all drafts are invisible (fail-closed). + */ +export const ListKnowledgeInput = Schema.Struct({ + householdId: KnowledgeFields.householdId, + childId: KnowledgeFields.childId, + topic: Schema.optional(KnowledgeFields.topic), + limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: MAX_KNOWLEDGE_PAGE })), + viewerId: Schema.optional(Schema.String), +}) +export type ListKnowledgeInput = typeof ListKnowledgeInput["Type"] + +/** Rows decode through the canonical document contract — ids included (supersede targets, citations). */ +export const ListKnowledgeOutput = Schema.Array(KnowledgeDocument) +export type ListKnowledgeOutput = typeof ListKnowledgeOutput["Type"] + +/** + * Compose the storage row for a new item and assert the family-knowledge + * contract on it. Throws `KnowledgeShapeError` on a contract violation + * (kind-conditional structure, provenance partition, source attribution) — + * the input schema validates shape, this validates the cross-field rules. + */ +export const buildKnowledgeItemRow = ( + args: typeof CreateKnowledgeItemInput["Type"], + now: number, +): typeof KnowledgeSchema["Type"] => { + const row: typeof KnowledgeSchema["Type"] = { + householdId: args.householdId, + childId: args.childId, + kind: args.kind, + topic: args.topic, + statement: args.statement, + ...(args.quoteText === undefined ? {} : { quoteText: args.quoteText }), + ...(args.spokenBy === undefined ? {} : { spokenBy: args.spokenBy }), + ...(args.steps === undefined ? {} : { steps: args.steps }), + status: "current", + statedBy: args.statedBy, + recordedBy: args.recordedBy, + provenanceKind: args.provenanceKind, + confidence: args.confidence, + sourceType: args.sourceType, + ...(args.sourceEntryId === undefined ? {} : { sourceEntryId: args.sourceEntryId }), + ...(args.sourceRef === undefined ? {} : { sourceRef: args.sourceRef }), + ...(args.sourceSpan === undefined ? {} : { sourceSpan: args.sourceSpan }), + ...(args.sourceQuote === undefined ? {} : { sourceQuote: args.sourceQuote }), + visibility: "draft", + validFrom: args.validFrom ?? now, + createdAt: now, + } + assertKnowledgeInvariants(row) + return row +} + +/** + * Supersession eligibility — a pure decision (values, not exceptions, per + * the security-suite pattern). Rejects: + * - a target that is not `current` (superseding a superseded item forks the + * append-only chain), + * - cross-household and cross-child supersession (tenancy + scope + * integrity — the edge may never jump households or children), + * - a replacement `validFrom` before the target's `validFrom` (the target's + * closing `validUntil` would precede its own `validFrom` — a domain + * invariant violation). + */ +export type SupersessionRejection = + | "SUPERSESSION_TARGET_NOT_CURRENT" + | "SUPERSESSION_HOUSEHOLD_MISMATCH" + | "SUPERSESSION_CHILD_MISMATCH" + | "SUPERSESSION_WINDOW_INVALID" + +export const checkSupersession = ( + target: KnowledgeDocument, + replacement: { householdId: string; childId: string; validFrom: number }, +): { outcome: "eligible" } | { outcome: "rejected"; code: SupersessionRejection; detail: string } => { + if (target.status !== "current") { + return { + outcome: "rejected", + code: "SUPERSESSION_TARGET_NOT_CURRENT", + detail: `knowledge item ${target._id} is ${target.status}; only current items can be superseded (append-only chains — no forks)`, + } + } + if (target.householdId !== replacement.householdId) { + return { + outcome: "rejected", + code: "SUPERSESSION_HOUSEHOLD_MISMATCH", + detail: `knowledge item ${target._id} belongs to household ${target.householdId}; cross-household supersession is rejected`, + } + } + if (target.childId !== replacement.childId) { + return { + outcome: "rejected", + code: "SUPERSESSION_CHILD_MISMATCH", + detail: `knowledge item ${target._id} belongs to child ${target.childId}; cross-child supersession is rejected`, + } + } + if (replacement.validFrom < target.validFrom) { + return { + outcome: "rejected", + code: "SUPERSESSION_WINDOW_INVALID", + detail: `replacement validFrom ${replacement.validFrom} precedes the target's validFrom ${target.validFrom}; the target's validUntil would precede its validFrom`, + } + } + return { outcome: "eligible" } +} + +/** + * Publication-dimension visibility for a knowledge row (wires the reference + * policy's draft rule): published items are household-audience; drafts are + * recorder-only; with no viewer identity drafts are invisible. `kind` is + * NEVER consulted — it is a retrieval/rendering discriminant only, never an + * authorization input (guardrail, tested in security/access/knowledge.test.ts). + */ +export const isVisibleKnowledgeItem = ( + item: Pick, + viewerId: string | undefined, +): boolean => item.visibility === "published" || (viewerId !== undefined && item.recordedBy === viewerId) + +/** The read model's current-items predicate: superseded rows are excluded by default. */ +export const isCurrentKnowledgeItem = (item: Pick): boolean => + item.status === "current" diff --git a/backend/convex/package.json b/backend/convex/package.json index b6ff0b5..737266b 100644 --- a/backend/convex/package.json +++ b/backend/convex/package.json @@ -5,7 +5,8 @@ "type": "module", "description": "Convex backend: schema derived from the Effect domain contracts via the tested adapter", "scripts": { - "typecheck": "tsc -p tsconfig.json --noEmit" + "typecheck": "tsc -p tsconfig.test.json --noEmit", + "test": "bun test test" }, "dependencies": { "@journal/domain": "workspace:*", @@ -13,6 +14,7 @@ "effect": "4.0.0-rc.115" }, "devDependencies": { + "@types/bun": "^1.3.14", "typescript": "~6.0.3" } } diff --git a/backend/convex/test/knowledge.test.ts b/backend/convex/test/knowledge.test.ts new file mode 100644 index 0000000..5d76c4c --- /dev/null +++ b/backend/convex/test/knowledge.test.ts @@ -0,0 +1,293 @@ +/** + * Validator-level tests for the knowledge functions (backend/convex). + * + * There is no local Convex runtime harness (N1 observation, still open), so + * the evidence standard is the PR #24 precedent: exercise the exact + * contracts and pure decision logic the handlers use — input decoding, row + * composition, supersession eligibility, publication-dimension visibility — + * plus the PR #16 synthetic fixtures as semantic ground truth. Handler + * wiring is proven by strict typechecking against the generated API. + * + * Fixtures are treated as ground truth, not re-derived: the PR #16 fixtures + * in packages/domain/test/fixtures/knowledge/ must decode and pass the + * domain invariants unchanged, and fixture 06's negative cases must fail at + * their stated stage (decode vs invariants) through the function pipeline. + */ +import { describe, expect, it } from "bun:test" +import { Schema } from "effect" + +import { KnowledgeDocument, KnowledgeSchema, assertKnowledgeInvariants, KnowledgeShapeError } from "@journal/domain" + +import { + CreateKnowledgeItemInput, + ListKnowledgeInput, + MAX_KNOWLEDGE_PAGE, + SupersedeKnowledgeItemInput, + buildKnowledgeItemRow, + checkSupersession, + isCurrentKnowledgeItem, + isVisibleKnowledgeItem, +} from "../convex/knowledgeInput" + +import settlingFixture from "../../../packages/domain/test/fixtures/knowledge/01-settling-preferences.json" +import changingFixture from "../../../packages/domain/test/fixtures/knowledge/04-changing-preferences.json" +import invalidFixture from "../../../packages/domain/test/fixtures/knowledge/06-invalid-items.json" + +// --- World: fixture-derived ground truth --------------------------------------------------- + +const decodeKnowledge = Schema.decodeUnknownSync(KnowledgeSchema) +const decodeKnowledgeDoc = Schema.decodeUnknownSync(KnowledgeDocument) + +const NOW = 1789700000000 + +/** Content fields lifted from the fixture world (conflicting bedtime reports, fixture 05). */ +const baseCreate = { + householdId: "synthetic-household-0001", + childId: "synthetic-child-0001", + kind: "settling", + topic: "bedtime", + statement: "Bedtime is 7:30 pm on school nights and she is asleep within minutes.", + statedBy: "caregiver-mom", + recordedBy: "caregiver-mom", + provenanceKind: "caregiver-stated", + confidence: 0.8, + sourceType: "entry", + sourceEntryId: "synthetic-entry-0005", + sourceSpan: { start: 0, end: 66 }, + sourceQuote: "7:30 sharp on school nights and she's out within minutes.", +} + +/** A current fixture item promoted to a stored document (system fields added). */ +const storedCurrentDoc = (item: unknown, id: string): typeof KnowledgeDocument["Type"] => + decodeKnowledgeDoc({ ...(item as object), _id: id, _creationTime: 0 }) + +// --- Ground truth: the PR #16 fixtures stay valid ------------------------------------------- + +describe("Fixture ground truth (PR #16 corpus)", () => { + it("settling-preferences and changing-preferences items decode and pass the domain invariants", () => { + for (const fixture of [settlingFixture, changingFixture]) { + const items = (fixture as { items: unknown[] }).items + expect(items.length).toBeGreaterThan(0) + for (const item of items) { + const decoded = decodeKnowledge(item) + assertKnowledgeInvariants(decoded) + } + } + }) + + it("fixture 06's negative cases fail at their stated stage", () => { + for (const negative of invalidFixture.cases) { + if (negative.rejectAt === "decode") { + expect(() => decodeKnowledge(negative.item)).toThrow() + } else { + // Shape-valid but contract-invalid: decode passes, invariants throw. + // Document-shaped cases (e.g. self-supersession) must decode through + // the document contract so system fields like `_id` are present for + // the invariants; the base schema strips them. + const decoded = "_id" in negative.item ? decodeKnowledgeDoc(negative.item) : decodeKnowledge(negative.item) + expect(() => assertKnowledgeInvariants(decoded)).toThrow(KnowledgeShapeError) + } + } + }) +}) + +// --- Create pipeline: decode -> row composition ---------------------------------------------- + +describe("CreateKnowledgeItemInput decode", () => { + it("accepts content for every kind (settling, routine, quote, preference)", () => { + const payloads = [ + baseCreate, + { ...baseCreate, kind: "routine", topic: "bedtime-routine", statement: "Fixed order, every night.", steps: ["warm bath", "pajamas", "books", "lights out"] }, + { ...baseCreate, kind: "quote", topic: "sayings", statement: "Something funny at breakfast.", quoteText: "Where does the sun sleep?", spokenBy: "child" }, + { ...baseCreate, kind: "preference", topic: "milk-cup", statement: "Drinks from the open cup at meals now." }, + ] + for (const payload of payloads) { + const args = Schema.decodeUnknownSync(CreateKnowledgeItemInput)(payload) + // Composition must satisfy the full family-knowledge contract. + const row = buildKnowledgeItemRow(args, NOW) + assertKnowledgeInvariants(row) + } + }) + + it("rejects shape violations at decode (medical kind, confidence out of range, empty statement)", () => { + expect(() => + Schema.decodeUnknownSync(CreateKnowledgeItemInput)({ ...baseCreate, kind: "medical" }), + ).toThrow() + expect(() => + Schema.decodeUnknownSync(CreateKnowledgeItemInput)({ ...baseCreate, confidence: 1.5 }), + ).toThrow() + expect(() => + Schema.decodeUnknownSync(CreateKnowledgeItemInput)({ ...baseCreate, statement: "" }), + ).toThrow() + }) + + it("rejects contract violations at row composition (topic slug, quote structure, provenance, source)", () => { + // Decode passes (shape-valid); the cross-field invariants must reject. + const cases = [ + { ...baseCreate, topic: "Bedtime!!" }, // not a lowercase kebab-case slug + { ...baseCreate, kind: "quote", topic: "sayings", quoteText: undefined }, // quote without quoteText + { ...baseCreate, recordedBy: "extraction-model", provenanceKind: "caregiver-confirmed", confidence: 1 }, // model claims confirmed certainty + { ...baseCreate, sourceEntryId: undefined }, // entry source without sourceEntryId + { ...baseCreate, steps: ["books"] }, // steps only valid for kind "routine" + ] + for (const payload of cases) { + const args = Schema.decodeUnknownSync(CreateKnowledgeItemInput)(payload) + expect(() => buildKnowledgeItemRow(args, NOW)).toThrow(KnowledgeShapeError) + } + }) + + it("sets lifecycle server-side: status current, visibility draft, validFrom defaulting to now", () => { + const row = buildKnowledgeItemRow(Schema.decodeUnknownSync(CreateKnowledgeItemInput)(baseCreate), NOW) + expect(row.status).toBe("current") + expect(row.visibility).toBe("draft") + expect(row.validFrom).toBe(NOW) + expect(row.createdAt).toBe(NOW) + + const backdated = buildKnowledgeItemRow( + Schema.decodeUnknownSync(CreateKnowledgeItemInput)({ ...baseCreate, validFrom: 123 }), + NOW, + ) + expect(backdated.validFrom).toBe(123) + }) +}) + +// --- Supersede pipeline: eligibility decisions ----------------------------------------------- + +describe("checkSupersession", () => { + const currentTarget = storedCurrentDoc( + (changingFixture as { items: unknown[] }).items[1], + "synthetic-knowledge-0402", + ) + const supersededTarget = storedCurrentDoc( + (changingFixture as { items: unknown[] }).items[0], + "synthetic-knowledge-0401", + ) + + it("eligibility for a current target with a valid window", () => { + expect( + checkSupersession(currentTarget, { + householdId: currentTarget.householdId, + childId: currentTarget.childId, + validFrom: currentTarget.validFrom + 1000, + }), + ).toEqual({ outcome: "eligible" }) + }) + + it("rejects a superseded target (append-only chains — no forks)", () => { + expect( + checkSupersession(supersededTarget, { + householdId: supersededTarget.householdId, + childId: supersededTarget.childId, + validFrom: NOW, + }), + ).toMatchObject({ outcome: "rejected", code: "SUPERSESSION_TARGET_NOT_CURRENT" }) + }) + + it("rejects cross-household and cross-child supersession", () => { + expect( + checkSupersession(currentTarget, { + householdId: "synthetic-household-9999", + childId: currentTarget.childId, + validFrom: NOW, + }), + ).toMatchObject({ outcome: "rejected", code: "SUPERSESSION_HOUSEHOLD_MISMATCH" }) + expect( + checkSupersession(currentTarget, { + householdId: currentTarget.householdId, + childId: "synthetic-child-9999", + validFrom: NOW, + }), + ).toMatchObject({ outcome: "rejected", code: "SUPERSESSION_CHILD_MISMATCH" }) + }) + + it("rejects a replacement validFrom before the target's validFrom (validUntil would precede validFrom)", () => { + expect( + checkSupersession(currentTarget, { + householdId: currentTarget.householdId, + childId: currentTarget.childId, + validFrom: currentTarget.validFrom - 1, + }), + ).toMatchObject({ outcome: "rejected", code: "SUPERSESSION_WINDOW_INVALID" }) + }) + + it("the closing patch the handler performs satisfies the domain invariants (chain continuity)", () => { + const validFrom = currentTarget.validFrom + 1000 + const closed = { ...currentTarget, status: "superseded" as const, validUntil: validFrom } + assertKnowledgeInvariants(closed) + expect(closed.validUntil).toBe(validFrom) + // And the same patch with an invalid window is caught by the domain — + // the handler's defense-in-depth assertion fires before any write. + expect(() => + assertKnowledgeInvariants({ ...currentTarget, status: "superseded", validUntil: currentTarget.validFrom - 1 }), + ).toThrow(KnowledgeShapeError) + }) +}) + +// --- Supersede input: the forward edge is required -------------------------------------------- + +describe("SupersedeKnowledgeItemInput decode", () => { + it("requires the supersedes target", () => { + expect(() => Schema.decodeUnknownSync(SupersedeKnowledgeItemInput)(baseCreate)).toThrow() + expect(() => + Schema.decodeUnknownSync(SupersedeKnowledgeItemInput)({ ...baseCreate, supersedes: "synthetic-knowledge-0402" }), + ).not.toThrow() + }) +}) + +// --- Bounded read input: explicit, capped limit ------------------------------------------------ + +describe("ListKnowledgeInput bounds", () => { + const listArgs = { householdId: "synthetic-household-0001", childId: "synthetic-child-0001" } + + it("requires the limit — an unbounded read has no caller", () => { + expect(() => Schema.decodeUnknownSync(ListKnowledgeInput)(listArgs)).toThrow() + }) + + it("accepts limit 1..MAX and rejects 0, MAX+1, and non-integers", () => { + expect(() => Schema.decodeUnknownSync(ListKnowledgeInput)({ ...listArgs, limit: 1 })).not.toThrow() + expect(() => Schema.decodeUnknownSync(ListKnowledgeInput)({ ...listArgs, limit: MAX_KNOWLEDGE_PAGE })).not.toThrow() + expect(() => Schema.decodeUnknownSync(ListKnowledgeInput)({ ...listArgs, limit: 0 })).toThrow() + expect(() => Schema.decodeUnknownSync(ListKnowledgeInput)({ ...listArgs, limit: MAX_KNOWLEDGE_PAGE + 1 })).toThrow() + expect(() => Schema.decodeUnknownSync(ListKnowledgeInput)({ ...listArgs, limit: 1.5 })).toThrow() + }) +}) + +// --- Read-model predicates ---------------------------------------------------------------------- + +describe("Read-model predicates", () => { + // Stored rows in production are buildKnowledgeItemRow outputs with system + // fields attached — build the mock the same way so every lifecycle field + // is present and valid before overrides are applied. + const storedRow = (overrides: Record) => { + const row = buildKnowledgeItemRow(Schema.decodeUnknownSync(CreateKnowledgeItemInput)(baseCreate), NOW) + return decodeKnowledgeDoc({ ...row, ...overrides, _id: "synthetic-knowledge-x", _creationTime: 0 }) + } + + it("current-items predicate: superseded rows are excluded from current by default", () => { + expect(isCurrentKnowledgeItem(storedRow({}))).toBe(true) + expect(isCurrentKnowledgeItem(storedRow({ status: "superseded", validUntil: NOW }))).toBe(false) + }) + + it("publication dimension: published is household-audience; drafts are recorder-only; no viewer sees no drafts", () => { + const published = storedRow({ visibility: "published" }) + const draft = storedRow({ visibility: "draft" }) + + expect(isVisibleKnowledgeItem(published, undefined)).toBe(true) + expect(isVisibleKnowledgeItem(published, "caregiver-dad")).toBe(true) + expect(isVisibleKnowledgeItem(draft, undefined)).toBe(false) + // baseCreate records as caregiver-mom: the recorder sees their draft, another member does not. + expect(isVisibleKnowledgeItem(draft, "caregiver-mom")).toBe(true) + expect(isVisibleKnowledgeItem(draft, "caregiver-dad")).toBe(false) + }) + + it("a composed row round-trips through the document contract; a corrupted row fails the read loudly", () => { + // Read path: rows decode through KnowledgeDocument and re-run invariants. + const decoded = storedRow({}) + assertKnowledgeInvariants(decoded) + + // A stored row that violates the contract (current + validUntil) must + // fail the read instead of serving invalid knowledge. + const corrupted = storedRow({ validUntil: NOW }) + expect(() => assertKnowledgeInvariants(corrupted)).toThrow(KnowledgeShapeError) + }) +}) diff --git a/backend/convex/tsconfig.test.json b/backend/convex/tsconfig.test.json new file mode 100644 index 0000000..c50da35 --- /dev/null +++ b/backend/convex/tsconfig.test.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["bun"] + }, + "include": ["convex", "test"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 28d2f47..11bb448 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -58,6 +58,9 @@ importers: 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 diff --git a/security/access/knowledge.test.ts b/security/access/knowledge.test.ts new file mode 100644 index 0000000..c1dd6b6 --- /dev/null +++ b/security/access/knowledge.test.ts @@ -0,0 +1,173 @@ +/** + * Executable access cases for family-knowledge items (the Convex knowledge + * functions' reference policy — backend/convex/convex/knowledge.ts mirrors + * these rules). + * + * Every test names its case (KP-* positive control, KN-* negative) and pins + * the EXACT assertion that decides access — outcome plus deny reason code — + * so a policy that denies for the wrong reason also fails. + * + * Guardrail (contract decision adopted 2026-09-17 with the PR #16 knowledge + * contract): a knowledge item's `kind` is a retrieval/rendering discriminant + * ONLY and never an authorization input — audience is governed by + * publication/audience state. KN-8 proves the policy is kind-blind. + */ +import { describe, expect, it } from 'bun:test' +import { evaluateAccess } from './policy' +import { KNOWLEDGE_KINDS, makeKnowledgeItem } from './schema-mock' +import type { Decision, KnowledgeItem, Principal, Resource } from './types' + +// --- World: two households, one child each (same world as policy.test.ts) ------------------- + +const H1 = 'household-1' +const H2 = 'household-2' +const CHILD_H1 = 'child-in-household-1' +const CHILD_H2 = 'child-in-household-2' + +const scopeH1 = { childId: CHILD_H1, householdId: H1 } +const scopeH2 = { childId: CHILD_H2, householdId: H2 } + +const caregiverA: Principal = { kind: 'caregiver', caregiverId: 'caregiver-a', householdIds: [H1] } +const caregiverB: Principal = { kind: 'caregiver', caregiverId: 'caregiver-b', householdIds: [H1] } +const caregiverOfH2: Principal = { kind: 'caregiver', caregiverId: 'caregiver-of-h2', householdIds: [H2] } +const anonymous: Principal = { kind: 'anonymous' } + +const read = { type: 'read' } as const +const writeAsA = { type: 'write', asAuthorId: 'caregiver-a' } as const + +const publishedByA = makeKnowledgeItem({ + kind: 'preference', + topic: 'bedtime', + status: 'current', + visibility: 'published', + recordedBy: 'caregiver-a', +}) + +const draftByA = makeKnowledgeItem({ + kind: 'settling', + topic: 'bedtime', + status: 'current', + visibility: 'draft', + recordedBy: 'caregiver-a', +}) + +const supersededPublishedByA = makeKnowledgeItem({ + kind: 'preference', + topic: 'vegetables-broccoli', + status: 'superseded', + visibility: 'published', + recordedBy: 'caregiver-a', +}) + +const knowledgeResource = (scope: typeof scopeH1 | typeof scopeH2, item: KnowledgeItem): Resource => ({ + kind: 'knowledgeItem', + scope, + item, +}) + +// --- Positive controls ----------------------------------------------------------------------- + +describe('Knowledge positive controls (ALLOW paths)', () => { + it('KP-1: caregiver B reads caregiver A’s PUBLISHED knowledge item in the same household', () => { + // Exact assertion: outcome === 'ALLOW' — published knowledge is household-audience. + expect(evaluateAccess(caregiverB, read, knowledgeResource(scopeH1, publishedByA))).toEqual({ outcome: 'ALLOW' }) + }) + + it('KP-2: the recorder reads their own draft knowledge item', () => { + // Exact assertion: outcome === 'ALLOW'. + expect(evaluateAccess(caregiverA, read, knowledgeResource(scopeH1, draftByA))).toEqual({ outcome: 'ALLOW' }) + }) + + it('KP-3: caregiver A creates/supersedes knowledge for a child in their own household', () => { + // Exact assertion: outcome === 'ALLOW' (both write-path functions evaluate this resource). + expect(evaluateAccess(caregiverA, writeAsA, knowledgeResource(scopeH1, draftByA))).toEqual({ outcome: 'ALLOW' }) + }) + + it('KP-4: the history capability reads a SUPERSEDED published item under the same audience rules', () => { + // Exact assertion: outcome === 'ALLOW' — supersession filters read models + // (current vs history); it never changes authorization. + expect(evaluateAccess(caregiverB, read, knowledgeResource(scopeH1, supersededPublishedByA))).toEqual({ + outcome: 'ALLOW', + }) + }) +}) + +// --- Required negative cases ----------------------------------------------------------------- + +describe('Knowledge household-membership boundary (Dimension 2: audience)', () => { + it('KN-1: caregiver of household 1 reading household 2’s knowledge item → DENIED', () => { + // Deny assertion: outcome === 'DENY' && code === 'DENY_NO_HOUSEHOLD_PATH'. + const decision: Decision = evaluateAccess(caregiverA, read, knowledgeResource(scopeH2, publishedByA)) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_NO_HOUSEHOLD_PATH' }) + }) + + it('KN-2: cross-household CREATE (write) of a knowledge item → DENIED', () => { + // Deny assertion: outcome === 'DENY' && code === 'DENY_NO_HOUSEHOLD_PATH' + // (write target child is owned by household-2; author’s membership is household-1). + const decision: Decision = evaluateAccess(caregiverA, writeAsA, knowledgeResource(scopeH2, draftByA)) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_NO_HOUSEHOLD_PATH' }) + }) + + it('KN-3: cross-household SUPERSEDE — write against a target item in another household → DENIED', () => { + // Deny assertion: outcome === 'DENY' && code === 'DENY_NO_HOUSEHOLD_PATH' + // (supersede is a write whose resource is the target item; no household path exists). + const decision: Decision = evaluateAccess(caregiverA, writeAsA, knowledgeResource(scopeH2, publishedByA)) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_NO_HOUSEHOLD_PATH' }) + }) + + it('KN-4: anonymous principal reading a published knowledge item → DENIED', () => { + // Deny assertion: outcome === 'DENY' && code === 'DENY_ANONYMOUS'. + const decision: Decision = evaluateAccess(anonymous, read, knowledgeResource(scopeH1, publishedByA)) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_ANONYMOUS' }) + }) +}) + +describe('Knowledge publication-state boundary (Dimension 1: authoring lifecycle)', () => { + it('KN-5: household member reading ANOTHER member’s draft knowledge item → DENIED', () => { + // Deny assertion: outcome === 'DENY' && code === 'DENY_DRAFT_AUTHOR_ONLY' + // (membership does not pierce drafts; recordedBy is the author-analog). + const decision: Decision = evaluateAccess(caregiverB, read, knowledgeResource(scopeH1, draftByA)) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_DRAFT_AUTHOR_ONLY' }) + }) +}) + +describe('Knowledge attribution integrity and scope integrity', () => { + it('KN-6: a knowledge write attributed to another caregiver → DENIED', () => { + // Deny assertion: outcome === 'DENY' && code === 'DENY_ATTRIBUTION_MISMATCH' + // (attribution is bound to the authenticated principal, never client-chosen). + const decision = evaluateAccess(caregiverA, { type: 'write', asAuthorId: 'caregiver-b' }, knowledgeResource(scopeH1, draftByA)) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_ATTRIBUTION_MISMATCH' }) + }) + + it('KN-7: a knowledge resource with an incomplete child scope → DENIED (fail-closed)', () => { + // Deny assertion: outcome === 'DENY' && code === 'DENY_UNKNOWN_CHILD_SCOPE' + // (missing/malformed scoping data denies — never falls through). + const decision: Decision = evaluateAccess(caregiverA, read, knowledgeResource({ childId: '', householdId: H1 }, publishedByA)) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_UNKNOWN_CHILD_SCOPE' }) + }) +}) + +describe('Guardrail: kind is never an authorization input', () => { + it('KN-8: access outcomes are IDENTICAL across all four kinds for the same audience state', () => { + // Exact assertion: for every kind, with principal/scope/action/publication + // state held fixed, the decisions are pairwise equal AND pin the expected + // outcome — published items ALLOW for household members, other members’ + // drafts DENY_DRAFT_AUTHOR_ONLY. A policy that branched on kind (e.g. + // treating "quote" or "settling" as more sensitive) fails here. + const publishedDecisions = KNOWLEDGE_KINDS.map((kind) => + evaluateAccess(caregiverB, read, knowledgeResource(scopeH1, { ...publishedByA, kind })), + ) + for (const decision of publishedDecisions) { + expect(decision).toEqual(publishedDecisions[0]) + expect(decision).toEqual({ outcome: 'ALLOW' }) + } + + const draftDecisions = KNOWLEDGE_KINDS.map((kind) => + evaluateAccess(caregiverB, read, knowledgeResource(scopeH1, { ...draftByA, kind })), + ) + for (const decision of draftDecisions) { + expect(decision).toEqual(draftDecisions[0]) + expect(decision).toMatchObject({ outcome: 'DENY', code: 'DENY_DRAFT_AUTHOR_ONLY' }) + } + }) +}) diff --git a/security/access/policy.ts b/security/access/policy.ts index 2b5dc59..88eb80b 100644 --- a/security/access/policy.ts +++ b/security/access/policy.ts @@ -53,7 +53,11 @@ export function evaluateAccess(principal: Principal, action: Action, resource: R } // 4. Publication-state boundary — Dimension 1. Applies to an entry and to its - // derived events (events inherit the entry's visibility). + // derived events (events inherit the entry's visibility), and to knowledge + // items (drafts recorder-only — recordedBy is the author-analog). The + // knowledge item's `kind` is NEVER consulted here: it is a + // retrieval/rendering discriminant only, not an authorization input + // (guardrail; KN-8 pins it). if ((resource.kind === 'entry' || resource.kind === 'entryEvents') && resource.entry.status === 'draft') { if (resource.entry.authorId !== principal.caregiverId) { return deny( @@ -62,6 +66,14 @@ export function evaluateAccess(principal: Principal, action: Action, resource: R ) } } + if (resource.kind === 'knowledgeItem' && resource.item.visibility === 'draft') { + if (resource.item.recordedBy !== principal.caregiverId) { + return deny( + 'DENY_DRAFT_AUTHOR_ONLY', + `knowledge item on topic ${resource.item.topic} is draft and recorded by ${resource.item.recordedBy}; caregiver ${principal.caregiverId} is a household member but not the recorder`, + ) + } + } // 5. Attribution integrity — authorId is server-bound to the authenticated principal. if (action.type === 'write' && action.asAuthorId !== principal.caregiverId) { diff --git a/security/access/schema-mock.ts b/security/access/schema-mock.ts index 99423d6..8d2cad6 100644 --- a/security/access/schema-mock.ts +++ b/security/access/schema-mock.ts @@ -81,3 +81,32 @@ export function makeEvent(event: Omit): Event { export function makeEntry(entry: Omit): Entry { return assertEntryInvariants({ _tag: 'Entry', ...entry }) } + +// --- Knowledge items (family-knowledge slice) ------------------------------------------------ +// +// Minimal projection of the canonical family-knowledge contract +// (packages/domain/src/knowledge.ts, PR #16 — KnowledgeFields), transcribed +// not invented: only the fields the access policy consumes. `kind` is carried +// ONLY so the kind-is-never-an-authorization-input negative case can prove +// the policy ignores it (KN-8); it is a retrieval/rendering discriminant, +// never an authorization input (contract decision adopted 2026-09-17). + +export const KNOWLEDGE_KINDS = ['settling', 'routine', 'quote', 'preference'] as const +export type KnowledgeKind = (typeof KNOWLEDGE_KINDS)[number] + +export const KNOWLEDGE_ITEM_STATUSES = ['current', 'superseded'] as const +export type KnowledgeItemStatus = (typeof KNOWLEDGE_ITEM_STATUSES)[number] + +export interface KnowledgeItem { + readonly kind: KnowledgeKind + readonly topic: string + readonly status: KnowledgeItemStatus + /** Per-item publication state ONLY (contract v0.2) — mirrors Entry.status. */ + readonly visibility: PublicationState + /** External identity of whoever captured the item — the author-analog for the draft rule. */ + readonly recordedBy: string +} + +export function makeKnowledgeItem(item: KnowledgeItem): KnowledgeItem { + return item +} diff --git a/security/access/types.ts b/security/access/types.ts index 489c0fd..520aac1 100644 --- a/security/access/types.ts +++ b/security/access/types.ts @@ -8,7 +8,7 @@ * (documented in THREAT-MODEL.md §Contract gaps), not claims about the * existing schema. */ -import type { Entry } from './schema-mock' +import type { Entry, KnowledgeItem } from './schema-mock' /** An authenticated caregiver and the households they are EXPLICITLY a member of. */ export interface CaregiverPrincipal { @@ -44,6 +44,14 @@ export type Resource = * prove extraction events INHERIT the entry's publication-state visibility. */ | { readonly kind: 'entryEvents'; readonly scope: ChildScope; readonly entry: Entry } + /** + * A family-knowledge item (packages/domain knowledge table, PR #16). + * Household scoping is identical to every other resource; the publication + * dimension mirrors entries (drafts author-only, via recordedBy). The + * item's `kind` is deliberately part of the resource but MUST never affect + * the decision — KN-8 proves that. + */ + | { readonly kind: 'knowledgeItem'; readonly scope: ChildScope; readonly item: KnowledgeItem } export type Action = | { readonly type: 'read' }