From 2e15388c7439410792215167fa0bcb584ef8c803 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 21:28:02 -0600 Subject: [PATCH 1/7] feat(pm-stack): add C7 Chicago daily period boundaries --- pm-stack/aggregator/src/report-periods.ts | 67 +++++++++++++++++++ .../aggregator/test/report-periods-c7.test.ts | 35 ++++++++++ 2 files changed, 102 insertions(+) create mode 100644 pm-stack/aggregator/src/report-periods.ts create mode 100644 pm-stack/aggregator/test/report-periods-c7.test.ts diff --git a/pm-stack/aggregator/src/report-periods.ts b/pm-stack/aggregator/src/report-periods.ts new file mode 100644 index 0000000000..464772686d --- /dev/null +++ b/pm-stack/aggregator/src/report-periods.ts @@ -0,0 +1,67 @@ +export interface DailyReportPeriod { + id: string; + kind: "daily"; + timezone: "America/Chicago"; + periodStart: string; + periodEnd: string; + softCloseAt: string; +} + +const TIME_ZONE = "America/Chicago" as const; +const localFormatter = new Intl.DateTimeFormat("en-US", { + timeZone: TIME_ZONE, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hourCycle: "h23", +}); + +function localWallTimeToUtc(date: string, hour: number): string { + const [year, month, day] = date.split("-").map(Number) as [number, number, number]; + const wanted = Date.UTC(year, month - 1, day, hour); + let guess = wanted; + + // Solve local wall time = UTC instant + zone offset. Iterating also + // handles offset changes at midnight without assuming a fixed UTC offset. + for (let i = 0; i < 4; i++) { + const parts = Object.fromEntries(localFormatter.formatToParts(new Date(guess)).map((p) => [p.type, p.value])); + const represented = Date.UTC( + Number(parts.year), + Number(parts.month) - 1, + Number(parts.day), + Number(parts.hour), + Number(parts.minute), + Number(parts.second), + ); + const nextGuess = wanted - (represented - guess); + if (nextGuess === guess) break; + guess = nextGuess; + } + return new Date(guess).toISOString(); +} + +function nextCalendarDate(date: string): string { + const [year, month, day] = date.split("-").map(Number) as [number, number, number]; + return new Date(Date.UTC(year, month - 1, day + 1)).toISOString().slice(0, 10); +} + +/** Resolve a daily period from an explicit America/Chicago calendar date. */ +export function dailyReportPeriod(date: string): DailyReportPeriod { + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error("date must be a valid YYYY-MM-DD calendar date"); + const [year, month, day] = date.split("-").map(Number) as [number, number, number]; + const check = new Date(Date.UTC(year, month - 1, day)); + if (check.toISOString().slice(0, 10) !== date) throw new Error("date must be a valid YYYY-MM-DD calendar date"); + + const nextDate = nextCalendarDate(date); + return { + id: `daily:${date}:${TIME_ZONE}`, + kind: "daily", + timezone: TIME_ZONE, + periodStart: localWallTimeToUtc(date, 0), + periodEnd: localWallTimeToUtc(nextDate, 0), + softCloseAt: localWallTimeToUtc(nextDate, 8), + }; +} diff --git a/pm-stack/aggregator/test/report-periods-c7.test.ts b/pm-stack/aggregator/test/report-periods-c7.test.ts new file mode 100644 index 0000000000..cac24206eb --- /dev/null +++ b/pm-stack/aggregator/test/report-periods-c7.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from "bun:test"; +import { dailyReportPeriod } from "../src/report-periods.ts"; + +describe("C7 daily report periods", () => { + test("uses explicit Chicago calendar dates and a stable period identity", () => { + const period = dailyReportPeriod("2026-11-21"); + expect(period).toEqual({ + id: "daily:2026-11-21:America/Chicago", + kind: "daily", + timezone: "America/Chicago", + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }); + expect(dailyReportPeriod("2026-11-21").id).toBe(period.id); + }); + + test("uses calendar boundaries across daylight-saving transitions", () => { + const spring = dailyReportPeriod("2026-03-08"); + expect(spring.periodStart).toBe("2026-03-08T06:00:00.000Z"); + expect(spring.periodEnd).toBe("2026-03-09T05:00:00.000Z"); + expect(spring.softCloseAt).toBe("2026-03-09T13:00:00.000Z"); + + const fall = dailyReportPeriod("2026-11-01"); + expect(fall.periodStart).toBe("2026-11-01T05:00:00.000Z"); + expect(fall.periodEnd).toBe("2026-11-02T06:00:00.000Z"); + expect(fall.softCloseAt).toBe("2026-11-02T14:00:00.000Z"); + }); + + test("rejects invalid calendar dates instead of normalizing them", () => { + expect(() => dailyReportPeriod("2026-02-30")).toThrow(/valid YYYY-MM-DD/); + expect(() => dailyReportPeriod("2026-2-03")).toThrow(/valid YYYY-MM-DD/); + expect(dailyReportPeriod("2024-02-29").periodEnd).toBe("2024-03-01T06:00:00.000Z"); + }); +}); From a4c91e31d432d8c3bd26f369c1f2e929bb92f2bb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 23:48:21 -0600 Subject: [PATCH 2/7] Add canonical C7 report record store --- pm-stack/aggregator/report-records-c7.md | 44 +++ pm-stack/aggregator/src/report-records.ts | 296 ++++++++++++++++++ .../aggregator/test/report-records-c7.test.ts | 178 +++++++++++ 3 files changed, 518 insertions(+) create mode 100644 pm-stack/aggregator/report-records-c7.md create mode 100644 pm-stack/aggregator/src/report-records.ts create mode 100644 pm-stack/aggregator/test/report-records-c7.test.ts diff --git a/pm-stack/aggregator/report-records-c7.md b/pm-stack/aggregator/report-records-c7.md new file mode 100644 index 0000000000..034ab76ef1 --- /dev/null +++ b/pm-stack/aggregator/report-records-c7.md @@ -0,0 +1,44 @@ +# C7 report-record storage seam + +`src/report-records.ts` is the canonical record interface for C7 callers. It +stores versioned report-generation and snapshot events in one append-only +PM-stack JSONL log. The default is +`~/.local/state/pm-aggregator/report-records.jsonl`; set +`PM_AGG_REPORT_RECORDS_FILE` to select another persistent location. This +follows the aggregator's existing append-only event-log pattern rather than +adding a database or writing into the disposable projector. + +## Caller interface + +- `makeReportRecord(input, generatedAt?)` validates timestamps, source + attribution, stable block IDs and the Chicago period, then derives the + stable record ID from `(period.id, templateVersion, sourceCursor)`. +- `appendReportRecord(file, record)` appends a generated event. A rerun with + the same ID and content returns the original record without another write; + changed content at the same ID throws `ReportRecordConflictError`. +- `readReportRecords(file)` reads retained cursor versions; + `readCurrentReportRecords(file)` projects the latest cursor per + `(period, templateVersion)`. +- `appendReportSnapshot(file, record, snapshotAt)` freezes the record once per + period. A changed snapshot conflicts; corrections must be separately linked + records. `readReportSnapshots(file)` reads the immutable snapshots. +- `assertReportUpdateAllowed(period, operation, at)` enforces the daily + 08:00 CT soft-close and its quote/append/banner/event-log/feedback allowlist. + `reportBlockConflict(stored, rendered)` treats whitespace-only differences + as equal and reports substantive changes for callers to skip and surface. + +Events retain `asOf`, source cursor, source IDs/URIs/observation timestamps, +related timestamps, block IDs and links. `dailyReportPeriod` supplies the +period identity and DST-aware boundaries. + +## Storage contract and current scope + +The JSONL file is append-only and local to the PM aggregator's configured +state path. Writes are serialized within one process; the current adapter does +not claim cross-process locking or remote replication. `fleet kv set/put` and +the amendment's indexed KV families are not implemented in this repository, +so this seam does not pretend to expose them. A later adapter may mirror the +same event contract into the fleet's chosen permanent store without changing +the report-record interface. This first slice supports the existing daily +period type; other calendar grains and generation commands remain subsequent +C7 work. diff --git a/pm-stack/aggregator/src/report-records.ts b/pm-stack/aggregator/src/report-records.ts new file mode 100644 index 0000000000..6fa1083d2e --- /dev/null +++ b/pm-stack/aggregator/src/report-records.ts @@ -0,0 +1,296 @@ +// Canonical C7 report records stored in the aggregator's append-only PM-stack +// event log. The log is the durable source; renderers consume the latest +// generation for a period/template and retain the source cursor that produced it. +import { createHash } from "node:crypto"; +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { dailyReportPeriod, type DailyReportPeriod } from "./report-periods.ts"; + +export interface ReportRecordSource { + id: string; + uri: string; + observedAt: string; +} + +export interface ReportRecordBlock { + id: string; + text: string; + relatedAt: string; + links?: string[]; +} + +export interface ReportRecordInput { + period: DailyReportPeriod; + asOf: string; + templateVersion: string; + sourceCursor: string; + sources: ReportRecordSource[]; + blocks: ReportRecordBlock[]; +} + +export interface ReportRecord extends ReportRecordInput { + id: string; + generatedAt: string; +} + +/** Persistent PM-stack location; override for tests and managed deployments. */ +export function defaultReportRecordsFile(env: Record = process.env): string { + const configured = env.PM_AGG_REPORT_RECORDS_FILE?.trim(); + return configured || join(homedir(), ".local", "state", "pm-aggregator", "report-records.jsonl"); +} + +const REPORT_UPDATE_OPERATIONS = ["edit", "replace", "quote", "append", "banner", "event-log", "feedback"] as const; +export type ReportUpdateOperation = (typeof REPORT_UPDATE_OPERATIONS)[number]; + +const ALLOWED_AFTER_SOFT_CLOSE: ReadonlySet = new Set([ + "quote", + "append", + "banner", + "event-log", + "feedback", +]); + +/** Enforce the report's soft-close allowlist; the close instant is exclusive. */ +export function assertReportUpdateAllowed( + period: DailyReportPeriod, + operation: ReportUpdateOperation, + at: string, +): void { + requireIsoDate(at, "update time"); + if (!(REPORT_UPDATE_OPERATIONS as readonly string[]).includes(operation)) throw new Error(`unknown report operation: ${operation}`); + if (Date.parse(at) < Date.parse(period.softCloseAt)) return; + if (!ALLOWED_AFTER_SOFT_CLOSE.has(operation)) { + throw new Error(`report operation ${operation} is not allowed after soft close ${period.softCloseAt}`); + } +} + +export interface ReportSnapshot { + id: string; + reportRecordId: string; + snapshotAt: string; + record: ReportRecord; +} + +type ReportRecordEvent = { + eventId: string; + type: "report.generated" | "report.snapshot"; + record?: ReportRecord; + snapshot?: ReportSnapshot; + ts: string; +}; + +export class ReportRecordConflictError extends Error { + constructor(recordId: string) { + super(`report record ${recordId} already exists with different content`); + this.name = "ReportRecordConflictError"; + } +} + +/** Stable across reruns for the same period, template and source cursor. */ +export function reportRecordId(input: Pick): string { + const key = `${input.period.id}\n${input.templateVersion}\n${input.sourceCursor}`; + return `report:${createHash("sha256").update(key).digest("hex")}`; +} + +/** Build a validated canonical record; generatedAt is injectable for replay. */ +export function makeReportRecord(input: ReportRecordInput, generatedAt = new Date().toISOString()): ReportRecord { + requireIsoDate(input.asOf, "asOf"); + requireIsoDate(generatedAt, "generatedAt"); + if (!input.templateVersion.trim()) throw new Error("templateVersion is required"); + if (!input.sourceCursor.trim()) throw new Error("sourceCursor is required"); + if (input.period.timezone !== "America/Chicago") throw new Error("report period must use America/Chicago"); + const date = /^daily:(\d{4}-\d{2}-\d{2}):America\/Chicago$/.exec(input.period.id)?.[1]; + const canonicalPeriod = date ? dailyReportPeriod(date) : null; + if ( + !canonicalPeriod || + input.period.kind !== canonicalPeriod.kind || + input.period.periodStart !== canonicalPeriod.periodStart || + input.period.periodEnd !== canonicalPeriod.periodEnd || + input.period.softCloseAt !== canonicalPeriod.softCloseAt + ) { + throw new Error("period must be a canonical dailyReportPeriod value"); + } + if (Date.parse(input.asOf) < Date.parse(input.period.periodStart) || Date.parse(input.asOf) >= Date.parse(input.period.periodEnd)) { + throw new Error("asOf must fall within the report period"); + } + if (!Array.isArray(input.sources) || !Array.isArray(input.blocks)) throw new Error("sources and blocks must be arrays"); + for (const source of input.sources) { + if (!source.id.trim() || !source.uri.trim()) throw new Error("each source requires id and uri"); + requireIsoDate(source.observedAt, "source observedAt"); + } + const blockIds = new Set(); + for (const block of input.blocks) { + if (!block.id.trim() || !block.text.trim()) throw new Error("each report block requires id and text"); + if (blockIds.has(block.id)) throw new Error(`duplicate report block id: ${block.id}`); + blockIds.add(block.id); + requireIsoDate(block.relatedAt, "block relatedAt"); + } + return { ...structuredClone(input), id: reportRecordId(input), generatedAt }; +} + +function requireIsoDate(value: string, name: string): void { + if (!Number.isFinite(Date.parse(value)) || new Date(value).toISOString() !== value) { + throw new Error(`${name} must be a canonical ISO-8601 timestamp`); + } +} + +function parseEvent(line: string): ReportRecordEvent | null { + try { + const value: unknown = JSON.parse(line); + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const event = value as Record; + if (typeof event.eventId !== "string" || typeof event.ts !== "string") return null; + if (event.type === "report.generated" && event.record && typeof event.record === "object" && !Array.isArray(event.record)) return value as ReportRecordEvent; + if (event.type === "report.snapshot" && event.snapshot && typeof event.snapshot === "object" && !Array.isArray(event.snapshot)) return value as ReportRecordEvent; + return null; + } catch { + return null; // Ignore a malformed/torn final line, matching decision-events.ts. + } +} + +async function readEvents(file: string): Promise { + let text: string; + try { + text = await readFile(file, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } + return text.split("\n").filter((line) => line.trim()).map(parseEvent).filter((event): event is ReportRecordEvent => event !== null); +} + +// Serialize writes in this process, as decision-events.ts does. A future +// multi-process adapter can replace this seam without changing record callers. +const appendChains = new Map>(); +function serializeAppend(file: string, fn: () => Promise): Promise { + const previous = appendChains.get(file) ?? Promise.resolve(); + const run = previous.then(fn, fn); + appendChains.set(file, run.catch(() => {})); + return run; +} + +export interface AppendReportRecordResult { + inserted: boolean; + record: ReportRecord; +} + +/** + * Append once by stable record ID. A byte-equivalent rerun is a no-op; the + * same id with changed content is a conflict and is never silently replaced. + */ +export async function appendReportRecord(file: string, record: ReportRecord): Promise { + assertCanonicalRecord(record); + return serializeAppend(file, async () => { + const events = await readEvents(file); + const existing = events.find((event) => event.type === "report.generated" && event.record?.id === record.id)?.record; + if (existing) { + if (!sameRecordContent(existing, record)) throw new ReportRecordConflictError(record.id); + return { inserted: false, record: existing }; + } + await mkdir(dirname(file), { recursive: true }); + const event: ReportRecordEvent = { + eventId: record.id, + type: "report.generated", + record, + ts: record.generatedAt, + }; + await appendFile(file, `${JSON.stringify(event)}\n`, "utf8"); + return { inserted: true, record }; + }); +} + +/** Read the latest record per stable ID in append order (currently one per key). */ +export async function readReportRecords(file: string): Promise { + const byId = new Map(); + for (const event of await readEvents(file)) { + if (event.type === "report.generated" && event.record) byId.set(event.record.id, event.record); + } + return [...byId.values()]; +} + +/** Current projection: latest appended source-cursor version per period/template. */ +export async function readCurrentReportRecords(file: string): Promise { + const current = new Map(); + for (const event of await readEvents(file)) { + if (event.type !== "report.generated" || !event.record) continue; + current.set(`${event.record.period.id}\n${event.record.templateVersion}`, event.record); + } + return [...current.values()]; +} + +export interface AppendReportSnapshotResult { + inserted: boolean; + snapshot: ReportSnapshot; +} + +/** Freeze a dated view in the same append-only PM-stack log. Existing snapshot + * IDs are immutable: a repeated identical write is idempotent, changed content + * is a conflict that must become a separately linked correction record. */ +export async function appendReportSnapshot( + file: string, + record: ReportRecord, + snapshotAt: string, +): Promise { + assertCanonicalRecord(record); + requireIsoDate(snapshotAt, "snapshotAt"); + const snapshot: ReportSnapshot = { + id: `snapshot:${record.period.id}`, + reportRecordId: record.id, + snapshotAt, + record: structuredClone(record), + }; + return serializeAppend(file, async () => { + const events = await readEvents(file); + const existing = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshot.id)?.snapshot; + if (existing) { + if (existing.reportRecordId !== snapshot.reportRecordId || !sameRecordContent(existing.record, snapshot.record)) { + throw new ReportRecordConflictError(snapshot.id); + } + return { inserted: false, snapshot: existing }; + } + await mkdir(dirname(file), { recursive: true }); + const event: ReportRecordEvent = { + eventId: snapshot.id, + type: "report.snapshot", + snapshot, + ts: snapshotAt, + }; + await appendFile(file, `${JSON.stringify(event)}\n`, "utf8"); + return { inserted: true, snapshot }; + }); +} + +export async function readReportSnapshots(file: string): Promise { + return (await readEvents(file)) + .filter((event): event is ReportRecordEvent & { snapshot: ReportSnapshot } => event.type === "report.snapshot" && !!event.snapshot) + .map((event) => event.snapshot); +} + +function sameRecordContent(left: ReportRecord, right: ReportRecord): boolean { + const { generatedAt: _leftTime, ...leftContent } = left; + const { generatedAt: _rightTime, ...rightContent } = right; + return canonicalJson(leftContent) === canonicalJson(rightContent); +} + +function assertCanonicalRecord(record: ReportRecord): void { + const canonical = makeReportRecord(record, record.generatedAt); + if (!sameRecordContent(canonical, record)) { + throw new Error("report record does not match its canonical contents and ID"); + } +} + +function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; + if (typeof value === "object" && value !== null) { + const object = value as Record; + return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(",")}}`; + } + return JSON.stringify(value) ?? "null"; +} + +/** Whitespace-only edits are equivalent; any substantive divergence is a conflict. */ +export function reportBlockConflict(storedText: string, renderedText: string): boolean { + const normalize = (text: string) => text.replace(/\s+/g, " ").trim(); + return normalize(storedText) !== normalize(renderedText); +} diff --git a/pm-stack/aggregator/test/report-records-c7.test.ts b/pm-stack/aggregator/test/report-records-c7.test.ts new file mode 100644 index 0000000000..6f723378c3 --- /dev/null +++ b/pm-stack/aggregator/test/report-records-c7.test.ts @@ -0,0 +1,178 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "bun:test"; +import { + appendReportRecord, + appendReportSnapshot, + assertReportUpdateAllowed, + defaultReportRecordsFile, + makeReportRecord, + readCurrentReportRecords, + readReportRecords, + readReportSnapshots, + reportBlockConflict, + ReportRecordConflictError, +} from "../src/report-records.ts"; + +const tempDirs: string[] = []; + +async function storePath(): Promise { + const dir = await mkdtemp(join(tmpdir(), "report-records-c7-")); + tempDirs.push(dir); + return join(dir, "reports.jsonl"); +} + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +describe("C7 canonical report records", () => { + test("persists provenance and cursor and makes a rerun a no-op", async () => { + const file = await storePath(); + const input = { + period: { + id: "daily:2026-11-21:America/Chicago", + kind: "daily" as const, + timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }, + asOf: "2026-11-22T05:45:00.000Z", + templateVersion: "daily-v1", + sourceCursor: "source-event-42", + sources: [{ id: "source-event-42", uri: "gh:developing-today/code/issues/12349", observedAt: "2026-11-22T05:40:00.000Z" }], + blocks: [{ id: "change-12349", text: "Added the period boundary foundation.", relatedAt: "2026-11-22T05:40:00.000Z" }], + }; + + const record = makeReportRecord(input, "2026-11-22T05:45:01.000Z"); + const first = await appendReportRecord(file, record); + const rerun = await appendReportRecord(file, makeReportRecord(input, "2026-11-22T05:46:01.000Z")); + const persisted = await readReportRecords(file); + + expect(first.inserted).toBe(true); + expect(rerun.inserted).toBe(false); + expect(rerun.record).toEqual(record); + expect(persisted).toEqual([record]); + expect(persisted[0]?.sourceCursor).toBe("source-event-42"); + expect(persisted[0]?.sources[0]?.uri).toBe("gh:developing-today/code/issues/12349"); + expect((await readFile(file, "utf8")).trim().split("\n")).toHaveLength(1); + }); + + test("rejects a forged record ID at the persistence boundary", async () => { + const file = await storePath(); + const canonical = makeReportRecord({ + period: { + id: "daily:2026-11-21:America/Chicago", + kind: "daily", + timezone: "America/Chicago", + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }, + asOf: "2026-11-22T05:45:00.000Z", + templateVersion: "daily-v1", + sourceCursor: "source-event-42", + sources: [{ id: "source-event-42", uri: "gh:issue/12349", observedAt: "2026-11-22T05:40:00.000Z" }], + blocks: [{ id: "change-12349", text: "Canonical prose.", relatedAt: "2026-11-22T05:40:00.000Z" }], + }, "2026-11-22T05:45:01.000Z"); + + await expect(appendReportRecord(file, { ...canonical, id: "report:forged" })) + .rejects.toThrow(/canonical contents and ID/); + await expect(appendReportSnapshot(file, { ...canonical, id: "report:forged" }, "2026-11-22T14:00:00.000Z")) + .rejects.toThrow(/canonical contents and ID/); + expect(await readReportRecords(file)).toEqual([]); + expect(await readReportSnapshots(file)).toEqual([]); + }); + + test("rejects changed content for the same cursor and keeps rollover snapshots immutable", async () => { + const file = await storePath(); + const input = { + period: { + id: "daily:2026-11-21:America/Chicago", + kind: "daily" as const, + timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }, + asOf: "2026-11-22T05:45:00.000Z", + templateVersion: "daily-v1", + sourceCursor: "source-event-42", + sources: [{ id: "source-event-42", uri: "gh:developing-today/code/issues/12349", observedAt: "2026-11-22T05:40:00.000Z" }], + blocks: [{ id: "change-12349", text: "Original prose.", relatedAt: "2026-11-22T05:40:00.000Z" }], + }; + const record = makeReportRecord(input, "2026-11-22T05:45:01.000Z"); + await appendReportRecord(file, record); + + const conflictingRecord = makeReportRecord({ + ...input, + blocks: [{ ...input.blocks[0]!, text: "Silently changed prose." }], + }, "2026-11-22T05:46:01.000Z"); + await expect(appendReportRecord(file, conflictingRecord)).rejects.toBeInstanceOf(ReportRecordConflictError); + expect((await readReportRecords(file))[0]?.blocks[0]?.text).toBe("Original prose."); + + const snapshot = await appendReportSnapshot(file, record, "2026-11-22T14:00:00.000Z"); + expect(snapshot.inserted).toBe(true); + const snapshotRerun = await appendReportSnapshot(file, makeReportRecord(input, "2026-11-22T05:46:01.000Z"), "2026-11-22T14:01:00.000Z"); + expect(snapshotRerun.inserted).toBe(false); + expect(snapshotRerun.snapshot.snapshotAt).toBe("2026-11-22T14:00:00.000Z"); + const mutatedSnapshotSource = makeReportRecord({ + ...input, + blocks: [{ ...input.blocks[0]!, text: "Changed after rollover." }], + }, "2026-11-22T05:47:01.000Z"); + await expect(appendReportSnapshot(file, mutatedSnapshotSource, "2026-11-22T14:00:00.000Z")) + .rejects.toBeInstanceOf(ReportRecordConflictError); + expect((await readReportSnapshots(file))[0]?.record.blocks[0]?.text).toBe("Original prose."); + }); + + test("allows ordinary edits only before soft close and the documented append forms after it", () => { + const period = { + id: "daily:2026-11-21:America/Chicago", + kind: "daily" as const, + timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }; + expect(() => assertReportUpdateAllowed(period, "replace", "2026-11-22T13:59:59.000Z")).not.toThrow(); + expect(() => assertReportUpdateAllowed(period, "replace", "2026-11-22T14:00:00.000Z")) + .toThrow(/not allowed after soft close/); + expect(() => assertReportUpdateAllowed(period, "append", "2026-11-22T14:00:00.000Z")).not.toThrow(); + expect(() => assertReportUpdateAllowed(period, "event-log", "2026-11-23T00:00:00.000Z")).not.toThrow(); + }); + + test("keeps prior cursor versions while projecting the latest and flags substantive block conflicts", async () => { + const file = await storePath(); + const base = { + period: { + id: "daily:2026-11-21:America/Chicago", + kind: "daily" as const, + timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }, + asOf: "2026-11-22T05:45:00.000Z", + templateVersion: "daily-v1", + sourceCursor: "cursor-1", + sources: [{ id: "event-1", uri: "gh:issue/1", observedAt: "2026-11-22T05:40:00.000Z" }], + blocks: [{ id: "change-1", text: "Stored paragraph.", relatedAt: "2026-11-22T05:40:00.000Z" }], + }; + const first = makeReportRecord(base, "2026-11-22T05:45:01.000Z"); + const second = makeReportRecord({ ...base, sourceCursor: "cursor-2", asOf: "2026-11-22T05:50:00.000Z" }, "2026-11-22T05:50:01.000Z"); + await appendReportRecord(file, first); + await appendReportRecord(file, second); + + expect((await readReportRecords(file)).map((record) => record.sourceCursor)).toEqual(["cursor-1", "cursor-2"]); + expect((await readCurrentReportRecords(file)).map((record) => record.sourceCursor)).toEqual(["cursor-2"]); + expect(reportBlockConflict("Stored paragraph.\n", "Stored paragraph.")).toBe(false); + expect(reportBlockConflict("Stored paragraph.", "Human changed paragraph.")).toBe(true); + }); + + test("allows a persistent store path override without a second datastore", () => { + expect(defaultReportRecordsFile({ PM_AGG_REPORT_RECORDS_FILE: "/var/lib/pm/report-records.jsonl" })) + .toBe("/var/lib/pm/report-records.jsonl"); + }); +}); From d0b2def6a59d50191b93f21bd8e8ef6b7ca695a4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 00:53:32 -0600 Subject: [PATCH 3/7] fix(pm-stack): harden C7 report appends --- pm-stack/aggregator/src/report-records.ts | 16 ++++++++++ .../aggregator/test/report-periods-c7.test.ts | 32 +++++++++++++++++++ .../aggregator/test/report-records-c7.test.ts | 30 +++++++++++++++++ 3 files changed, 78 insertions(+) diff --git a/pm-stack/aggregator/src/report-records.ts b/pm-stack/aggregator/src/report-records.ts index 6fa1083d2e..5d9fd05d69 100644 --- a/pm-stack/aggregator/src/report-records.ts +++ b/pm-stack/aggregator/src/report-records.ts @@ -160,6 +160,18 @@ async function readEvents(file: string): Promise { return text.split("\n").filter((line) => line.trim()).map(parseEvent).filter((event): event is ReportRecordEvent => event !== null); } +/** Keep a torn final JSONL fragment from swallowing the next acknowledged event. */ +async function terminateTornTail(file: string): Promise { + let text: string; + try { + text = await readFile(file, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + throw error; + } + if (text.length > 0 && !text.endsWith("\n")) await appendFile(file, "\n", "utf8"); +} + // Serialize writes in this process, as decision-events.ts does. A future // multi-process adapter can replace this seam without changing record callers. const appendChains = new Map>(); @@ -189,6 +201,7 @@ export async function appendReportRecord(file: string, record: ReportRecord): Pr return { inserted: false, record: existing }; } await mkdir(dirname(file), { recursive: true }); + await terminateTornTail(file); const event: ReportRecordEvent = { eventId: record.id, type: "report.generated", @@ -242,6 +255,8 @@ export async function appendReportSnapshot( }; return serializeAppend(file, async () => { const events = await readEvents(file); + const generated = events.find((event) => event.type === "report.generated" && event.record?.id === record.id)?.record; + if (generated && !sameRecordContent(generated, record)) throw new ReportRecordConflictError(record.id); const existing = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshot.id)?.snapshot; if (existing) { if (existing.reportRecordId !== snapshot.reportRecordId || !sameRecordContent(existing.record, snapshot.record)) { @@ -250,6 +265,7 @@ export async function appendReportSnapshot( return { inserted: false, snapshot: existing }; } await mkdir(dirname(file), { recursive: true }); + await terminateTornTail(file); const event: ReportRecordEvent = { eventId: snapshot.id, type: "report.snapshot", diff --git a/pm-stack/aggregator/test/report-periods-c7.test.ts b/pm-stack/aggregator/test/report-periods-c7.test.ts index cac24206eb..812fbf517c 100644 --- a/pm-stack/aggregator/test/report-periods-c7.test.ts +++ b/pm-stack/aggregator/test/report-periods-c7.test.ts @@ -27,6 +27,38 @@ describe("C7 daily report periods", () => { expect(fall.softCloseAt).toBe("2026-11-02T14:00:00.000Z"); }); + test("generated dates preserve Chicago-midnight adjacency and next-day soft close", () => { + // Deterministic generated input over 1900–2100; the oracle is Intl's + // America/Chicago wall clock, independent of the conversion under test. + const chicago = new Intl.DateTimeFormat("en-CA", { + timeZone: "America/Chicago", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }); + const parts = (instant: string) => Object.fromEntries( + chicago.formatToParts(new Date(instant)).map(({ type, value }) => [type, value]), + ); + const minDay = Date.UTC(1900, 0, 1); + const dayCount = (Date.UTC(2100, 0, 1) - minDay) / 86_400_000; + let state = 0x7c7c2026; + for (let i = 0; i < 512; i++) { + state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0; + const date = new Date(minDay + (state % dayCount) * 86_400_000).toISOString().slice(0, 10); + const nextDate = new Date(Date.parse(`${date}T00:00:00.000Z`) + 86_400_000).toISOString().slice(0, 10); + const period = dailyReportPeriod(date); + const next = dailyReportPeriod(nextDate); + + expect(parts(period.periodStart)).toMatchObject({ year: date.slice(0, 4), month: date.slice(5, 7), day: date.slice(8, 10), hour: "00", minute: "00" }); + expect(parts(period.periodEnd)).toMatchObject({ year: nextDate.slice(0, 4), month: nextDate.slice(5, 7), day: nextDate.slice(8, 10), hour: "00", minute: "00" }); + expect(period.periodEnd).toBe(next.periodStart); + expect(parts(period.softCloseAt)).toMatchObject({ year: nextDate.slice(0, 4), month: nextDate.slice(5, 7), day: nextDate.slice(8, 10), hour: "08", minute: "00" }); + } + }); + test("rejects invalid calendar dates instead of normalizing them", () => { expect(() => dailyReportPeriod("2026-02-30")).toThrow(/valid YYYY-MM-DD/); expect(() => dailyReportPeriod("2026-2-03")).toThrow(/valid YYYY-MM-DD/); diff --git a/pm-stack/aggregator/test/report-records-c7.test.ts b/pm-stack/aggregator/test/report-records-c7.test.ts index 6f723378c3..354f0b1a3b 100644 --- a/pm-stack/aggregator/test/report-records-c7.test.ts +++ b/pm-stack/aggregator/test/report-records-c7.test.ts @@ -111,6 +111,8 @@ describe("C7 canonical report records", () => { blocks: [{ ...input.blocks[0]!, text: "Silently changed prose." }], }, "2026-11-22T05:46:01.000Z"); await expect(appendReportRecord(file, conflictingRecord)).rejects.toBeInstanceOf(ReportRecordConflictError); + await expect(appendReportSnapshot(file, conflictingRecord, "2026-11-22T14:00:00.000Z")) + .rejects.toBeInstanceOf(ReportRecordConflictError); expect((await readReportRecords(file))[0]?.blocks[0]?.text).toBe("Original prose."); const snapshot = await appendReportSnapshot(file, record, "2026-11-22T14:00:00.000Z"); @@ -127,6 +129,34 @@ describe("C7 canonical report records", () => { expect((await readReportSnapshots(file))[0]?.record.blocks[0]?.text).toBe("Original prose."); }); + test("keeps later appends readable after a torn trailing JSONL fragment", async () => { + const file = await storePath(); + const record = makeReportRecord({ + period: { + id: "daily:2026-11-21:America/Chicago", + kind: "daily", + timezone: "America/Chicago", + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }, + asOf: "2026-11-22T05:45:00.000Z", + templateVersion: "daily-v1", + sourceCursor: "source-event-42", + sources: [{ id: "source-event-42", uri: "gh:issue/12349", observedAt: "2026-11-22T05:40:00.000Z" }], + blocks: [{ id: "change-12349", text: "Recovered append.", relatedAt: "2026-11-22T05:40:00.000Z" }], + }, "2026-11-22T05:45:01.000Z"); + + await Bun.write(file, '{"eventId":"interrupted"'); + expect((await appendReportRecord(file, record)).inserted).toBe(true); + expect(await readReportRecords(file)).toEqual([record]); + + await Bun.write(file, `${await readFile(file, "utf8")}{"eventId":"interrupted-snapshot"`); + expect((await appendReportSnapshot(file, record, "2026-11-22T14:00:00.000Z")).inserted).toBe(true); + expect(await readReportSnapshots(file)).toHaveLength(1); + expect(await readReportRecords(file)).toEqual([record]); + }); + test("allows ordinary edits only before soft close and the documented append forms after it", () => { const period = { id: "daily:2026-11-21:America/Chicago", From 3a1e6d997688d606ff9f4ec7e043a082013d7b4e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 01:33:18 -0600 Subject: [PATCH 4/7] feat(pm-stack): record linked report snapshot corrections --- pm-stack/aggregator/src/report-records.ts | 60 ++++++++++++++++++- .../aggregator/test/report-records-c7.test.ts | 41 +++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) diff --git a/pm-stack/aggregator/src/report-records.ts b/pm-stack/aggregator/src/report-records.ts index 5d9fd05d69..1b6ef8ceff 100644 --- a/pm-stack/aggregator/src/report-records.ts +++ b/pm-stack/aggregator/src/report-records.ts @@ -74,9 +74,10 @@ export interface ReportSnapshot { type ReportRecordEvent = { eventId: string; - type: "report.generated" | "report.snapshot"; + type: "report.generated" | "report.snapshot" | "report.snapshot-correction"; record?: ReportRecord; snapshot?: ReportSnapshot; + correction?: ReportSnapshotCorrection; ts: string; }; @@ -143,6 +144,7 @@ function parseEvent(line: string): ReportRecordEvent | null { if (typeof event.eventId !== "string" || typeof event.ts !== "string") return null; if (event.type === "report.generated" && event.record && typeof event.record === "object" && !Array.isArray(event.record)) return value as ReportRecordEvent; if (event.type === "report.snapshot" && event.snapshot && typeof event.snapshot === "object" && !Array.isArray(event.snapshot)) return value as ReportRecordEvent; + if (event.type === "report.snapshot-correction" && event.correction && typeof event.correction === "object" && !Array.isArray(event.correction)) return value as ReportRecordEvent; return null; } catch { return null; // Ignore a malformed/torn final line, matching decision-events.ts. @@ -237,6 +239,19 @@ export interface AppendReportSnapshotResult { snapshot: ReportSnapshot; } +export interface ReportSnapshotCorrection { + id: string; + snapshotId: string; + originalRecordId: string; + correctedAt: string; + record: ReportRecord; +} + +export interface AppendReportSnapshotCorrectionResult { + inserted: boolean; + correction: ReportSnapshotCorrection; +} + /** Freeze a dated view in the same append-only PM-stack log. Existing snapshot * IDs are immutable: a repeated identical write is idempotent, changed content * is a conflict that must become a separately linked correction record. */ @@ -283,6 +298,49 @@ export async function readReportSnapshots(file: string): Promise event.snapshot); } +/** Append a correction as a new record linked to an immutable snapshot. */ +export async function appendReportSnapshotCorrection( + file: string, + snapshotId: string, + record: ReportRecord, + correctedAt: string, +): Promise { + assertCanonicalRecord(record); + requireIsoDate(correctedAt, "correctedAt"); + const correction: ReportSnapshotCorrection = { + id: `correction:${snapshotId}:${record.id}`, + snapshotId, + originalRecordId: "", + correctedAt, + record: structuredClone(record), + }; + return serializeAppend(file, async () => { + const events = await readEvents(file); + const snapshot = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshotId)?.snapshot; + if (!snapshot) throw new Error(`snapshot does not exist: ${snapshotId}`); + if (snapshot.record.period.id !== record.period.id) throw new Error("correction period must match the snapshot"); + correction.originalRecordId = snapshot.reportRecordId; + const existing = events.find((event) => event.type === "report.snapshot-correction" && event.correction?.id === correction.id)?.correction; + if (existing) { + if (existing.snapshotId !== correction.snapshotId || existing.originalRecordId !== correction.originalRecordId || !sameRecordContent(existing.record, correction.record)) { + throw new ReportRecordConflictError(correction.id); + } + return { inserted: false, correction: existing }; + } + await mkdir(dirname(file), { recursive: true }); + await terminateTornTail(file); + const event: ReportRecordEvent = { eventId: correction.id, type: "report.snapshot-correction", correction, ts: correctedAt }; + await appendFile(file, `${JSON.stringify(event)}\n`, "utf8"); + return { inserted: true, correction }; + }); +} + +export async function readReportSnapshotCorrections(file: string): Promise { + return (await readEvents(file)) + .filter((event): event is ReportRecordEvent & { correction: ReportSnapshotCorrection } => event.type === "report.snapshot-correction" && !!event.correction) + .map((event) => event.correction); +} + function sameRecordContent(left: ReportRecord, right: ReportRecord): boolean { const { generatedAt: _leftTime, ...leftContent } = left; const { generatedAt: _rightTime, ...rightContent } = right; diff --git a/pm-stack/aggregator/test/report-records-c7.test.ts b/pm-stack/aggregator/test/report-records-c7.test.ts index 354f0b1a3b..39e8058681 100644 --- a/pm-stack/aggregator/test/report-records-c7.test.ts +++ b/pm-stack/aggregator/test/report-records-c7.test.ts @@ -5,12 +5,14 @@ import { afterEach, describe, expect, test } from "bun:test"; import { appendReportRecord, appendReportSnapshot, + appendReportSnapshotCorrection, assertReportUpdateAllowed, defaultReportRecordsFile, makeReportRecord, readCurrentReportRecords, readReportRecords, readReportSnapshots, + readReportSnapshotCorrections, reportBlockConflict, ReportRecordConflictError, } from "../src/report-records.ts"; @@ -129,6 +131,45 @@ describe("C7 canonical report records", () => { expect((await readReportSnapshots(file))[0]?.record.blocks[0]?.text).toBe("Original prose."); }); + test("records snapshot corrections as new linked immutable records", async () => { + const file = await storePath(); + const input = { + period: { + id: "daily:2026-11-21:America/Chicago", + kind: "daily" as const, + timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }, + asOf: "2026-11-22T05:45:00.000Z", + templateVersion: "daily-v1", + sourceCursor: "cursor-original", + sources: [{ id: "event-1", uri: "gh:issue/1", observedAt: "2026-11-22T05:40:00.000Z" }], + blocks: [{ id: "change-1", text: "Original snapshot.", relatedAt: "2026-11-22T05:40:00.000Z" }], + }; + const original = makeReportRecord(input, "2026-11-22T05:45:01.000Z"); + await appendReportRecord(file, original); + await appendReportSnapshot(file, original, "2026-11-22T14:00:00.000Z"); + const correction = makeReportRecord({ + ...input, + sourceCursor: "cursor-correction-1", + blocks: [{ ...input.blocks[0]!, text: "Corrected snapshot." }], + }, "2026-11-22T15:00:00.000Z"); + + const first = await appendReportSnapshotCorrection(file, "snapshot:daily:2026-11-21:America/Chicago", correction, "2026-11-22T15:00:00.000Z"); + const rerun = await appendReportSnapshotCorrection(file, "snapshot:daily:2026-11-21:America/Chicago", correction, "2026-11-22T15:05:00.000Z"); + expect(first.inserted).toBe(true); + expect(rerun.inserted).toBe(false); + expect(first.correction.snapshotId).toBe("snapshot:daily:2026-11-21:America/Chicago"); + expect(first.correction.originalRecordId).toBe(original.id); + expect(first.correction.record.id).toBe(correction.id); + expect((await readReportSnapshots(file))[0]?.record.blocks[0]?.text).toBe("Original snapshot."); + expect((await readReportSnapshotCorrections(file)).map((item) => item.record.id)).toEqual([correction.id]); + await expect(appendReportSnapshotCorrection(file, "snapshot:missing", correction, "2026-11-22T15:00:00.000Z")) + .rejects.toThrow(/snapshot does not exist/); + }); + test("keeps later appends readable after a torn trailing JSONL fragment", async () => { const file = await storePath(); const record = makeReportRecord({ From 176c723b9729a63007a5506c54a0d482a14cd9bc Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 01:33:51 -0600 Subject: [PATCH 5/7] docs(pm-stack): describe snapshot correction API --- pm-stack/aggregator/report-records-c7.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pm-stack/aggregator/report-records-c7.md b/pm-stack/aggregator/report-records-c7.md index 034ab76ef1..1342cfc9ff 100644 --- a/pm-stack/aggregator/report-records-c7.md +++ b/pm-stack/aggregator/report-records-c7.md @@ -20,8 +20,11 @@ adding a database or writing into the disposable projector. `readCurrentReportRecords(file)` projects the latest cursor per `(period, templateVersion)`. - `appendReportSnapshot(file, record, snapshotAt)` freezes the record once per - period. A changed snapshot conflicts; corrections must be separately linked - records. `readReportSnapshots(file)` reads the immutable snapshots. + period. A changed snapshot conflicts. `appendReportSnapshotCorrection(file, + snapshotId, record, correctedAt)` creates a separate linked correction event + without mutating the snapshot; correction records must match the snapshot + period. `readReportSnapshots(file)` reads immutable snapshots, and + `readReportSnapshotCorrections(file)` reads their correction history. - `assertReportUpdateAllowed(period, operation, at)` enforces the daily 08:00 CT soft-close and its quote/append/banner/event-log/feedback allowlist. `reportBlockConflict(stored, rendered)` treats whitespace-only differences From 2b79ec3e814f0356cd3a4c3499aaea0b40eac052 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 02:30:49 -0600 Subject: [PATCH 6/7] feat(pm-stack): persist C7 reports in append-only store --- pm-stack/SHARED-SCHEMA-MAP.md | 1 + pm-stack/aggregator/report-records-c7.md | 30 ++- pm-stack/aggregator/src/aa-last-good.ts | 7 + pm-stack/aggregator/src/remote-stores.ts | 25 +- pm-stack/aggregator/src/report-records.ts | 255 ++++++++++++------ .../aggregator/test/report-records-c7.test.ts | 83 ++++++ pm-stack/aggregator/test/turso-stores.test.ts | 6 + pm-stack/shared-schema/README.md | 2 +- 8 files changed, 315 insertions(+), 94 deletions(-) diff --git a/pm-stack/SHARED-SCHEMA-MAP.md b/pm-stack/SHARED-SCHEMA-MAP.md index 321750b442..261ffebf7a 100644 --- a/pm-stack/SHARED-SCHEMA-MAP.md +++ b/pm-stack/SHARED-SCHEMA-MAP.md @@ -61,6 +61,7 @@ backend, and the local JSON is then only a rebuildable cache): | `activity-ingestion.json` | `public.agg_activity_ingestion`, `public.agg_activity_gaps` | `20261116_0001_aggregator_remote_stores` | | `snapshots/usage-YYYY-MM.jsonl` | `public.agg_usage_snapshots` | `20261116_0001_aggregator_remote_stores` | | `aa-last-good.json` | `public.agg_store_documents` (key `aa-last-good`) | `20261116_0001_aggregator_remote_stores` | +| C7 report events | `public.agg_store_documents` (keys `c7-report:v1:*`) | `20261116_0001_aggregator_remote_stores` | The sibling stores (`freshness.json`, `notifications.jsonl`, `needs-drew.json`, `decisions.json`, `decision-events*.jsonl`, diff --git a/pm-stack/aggregator/report-records-c7.md b/pm-stack/aggregator/report-records-c7.md index 1342cfc9ff..b2935d1d74 100644 --- a/pm-stack/aggregator/report-records-c7.md +++ b/pm-stack/aggregator/report-records-c7.md @@ -36,12 +36,24 @@ period identity and DST-aware boundaries. ## Storage contract and current scope -The JSONL file is append-only and local to the PM aggregator's configured -state path. Writes are serialized within one process; the current adapter does -not claim cross-process locking or remote replication. `fleet kv set/put` and -the amendment's indexed KV families are not implemented in this repository, -so this seam does not pretend to expose them. A later adapter may mirror the -same event contract into the fleet's chosen permanent store without changing -the report-record interface. This first slice supports the existing daily -period type; other calendar grains and generation commands remain subsequent -C7 work. +The caller-facing append/read functions accept either a JSONL path or the +append-only document capability returned by `createTursoDocumentRemote`. +The file backend is local to the PM aggregator state path; writes are +serialized within one process and do not claim cross-process locking or remote +replication. It remains useful for development and rollback. + +The durable adapter uses the existing `public.agg_store_documents` table from +#6815; it creates no table or separate report database. Each generated record, +snapshot, and correction is stored as one immutable document under +`c7-report:v1::`. `insertIfAbsent` provides the +atomic idempotency boundary: a duplicate key reads back and compares the +canonical content, returning the original event for an identical rerun and +raising a conflict for changed content. Prefix reads return the event set; projections sort by the canonical event +timestamp and stable event ID. The generic overwrite API is not used for C7 +event keys. + +At the composition root, callers choose the file or Turso store according to +`PM_AGG_STORE_BACKEND` and pass that single backend into the report-record API. +There is no dual write and no silent local fallback when the durable store is +selected. This slice supports daily periods; other calendar grains and report +rendering/source integration remain subsequent C7 work. diff --git a/pm-stack/aggregator/src/aa-last-good.ts b/pm-stack/aggregator/src/aa-last-good.ts index c15e201999..f26effa01e 100644 --- a/pm-stack/aggregator/src/aa-last-good.ts +++ b/pm-stack/aggregator/src/aa-last-good.ts @@ -16,6 +16,13 @@ export interface DocumentRemote { save(store: string, version: number, document: unknown): Promise; } +/** Append-only capabilities over the same durable document table. */ +export interface AppendOnlyDocumentRemote { + load(store: string): Promise<{ version: number; document: unknown } | null>; + insertIfAbsent(store: string, version: number, document: unknown): Promise; + listPrefix(prefix: string): Promise>; +} + export class AaLastGoodStore { constructor( private readonly file: string, diff --git a/pm-stack/aggregator/src/remote-stores.ts b/pm-stack/aggregator/src/remote-stores.ts index a983d5d3cb..9b89192846 100644 --- a/pm-stack/aggregator/src/remote-stores.ts +++ b/pm-stack/aggregator/src/remote-stores.ts @@ -11,7 +11,7 @@ // copy would recreate exactly the laptop-only state #6815 removes. import { ACTION_STATES, type ActionsRemote, type DashAction } from "./actions.ts"; import type { ActivityRemote, ActivitySourceStatus, GapRecord, IngestionFile, SourceCheckpoint } from "./activity.ts"; -import type { DocumentRemote } from "./aa-last-good.ts"; +import type { AppendOnlyDocumentRemote, DocumentRemote } from "./aa-last-good.ts"; import type { SnapshotsRemote } from "./snapshots.ts"; import type { SnapshotRecord } from "./model.ts"; import { snapshotKey } from "./snapshots.ts"; @@ -315,13 +315,13 @@ export function createTursoSnapshotsRemote(getClient: GetClient = getTursoStoreC } // --------------------------------------------------------------------- -// aa-last-good.json -> public.agg_store_documents +// namespaced PM documents -> public.agg_store_documents // --------------------------------------------------------------------- export function createTursoDocumentRemote( getClient: GetClient = getTursoStoreClient, writer: string = storeWriterIdentity(), -): DocumentRemote { +): DocumentRemote & AppendOnlyDocumentRemote { return { async load(store: string): Promise<{ version: number; document: unknown } | null> { const db = await requireClient(getClient); @@ -342,6 +342,25 @@ export function createTursoDocumentRemote( `writer = excluded.writer, updated_at = now()`, ); }, + + async insertIfAbsent(store: string, version: number, document: unknown): Promise { + const db = await requireClient(getClient); + const rows = await db.query>( + `insert into public.agg_store_documents (store, version, document, writer, updated_at) ` + + `values (${sqlStr(store)}, ${version}, ${sqlJson(document)}, ${sqlStr(writer)}, now()) ` + + `on conflict (store) do nothing returning store`, + ); + return rows.length > 0; + }, + + async listPrefix(prefix: string): Promise> { + const db = await requireClient(getClient); + return db.query<{ store: string; version: number; document: unknown }>( + `select store, version, document from public.agg_store_documents ` + + `where substr(store, 1, length(${sqlStr(prefix)})) = ${sqlStr(prefix)} ` + + `order by store asc`, + ); + }, }; } diff --git a/pm-stack/aggregator/src/report-records.ts b/pm-stack/aggregator/src/report-records.ts index 1b6ef8ceff..c0e2b95927 100644 --- a/pm-stack/aggregator/src/report-records.ts +++ b/pm-stack/aggregator/src/report-records.ts @@ -1,10 +1,11 @@ -// Canonical C7 report records stored in the aggregator's append-only PM-stack -// event log. The log is the durable source; renderers consume the latest -// generation for a period/template and retain the source cursor that produced it. +// Canonical C7 report records over PM-stack append-only storage. Local JSONL +// supports development/rollback; the durable adapter appends immutable event +// documents to the existing aggregator document store. import { createHash } from "node:crypto"; import { appendFile, mkdir, readFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; +import type { AppendOnlyDocumentRemote } from "./aa-last-good.ts"; import { dailyReportPeriod, type DailyReportPeriod } from "./report-periods.ts"; export interface ReportRecordSource { @@ -43,20 +44,10 @@ export function defaultReportRecordsFile(env: Record const REPORT_UPDATE_OPERATIONS = ["edit", "replace", "quote", "append", "banner", "event-log", "feedback"] as const; export type ReportUpdateOperation = (typeof REPORT_UPDATE_OPERATIONS)[number]; -const ALLOWED_AFTER_SOFT_CLOSE: ReadonlySet = new Set([ - "quote", - "append", - "banner", - "event-log", - "feedback", -]); +const ALLOWED_AFTER_SOFT_CLOSE: ReadonlySet = new Set(["quote", "append", "banner", "event-log", "feedback"]); /** Enforce the report's soft-close allowlist; the close instant is exclusive. */ -export function assertReportUpdateAllowed( - period: DailyReportPeriod, - operation: ReportUpdateOperation, - at: string, -): void { +export function assertReportUpdateAllowed(period: DailyReportPeriod, operation: ReportUpdateOperation, at: string): void { requireIsoDate(at, "update time"); if (!(REPORT_UPDATE_OPERATIONS as readonly string[]).includes(operation)) throw new Error(`unknown report operation: ${operation}`); if (Date.parse(at) < Date.parse(period.softCloseAt)) return; @@ -72,7 +63,7 @@ export interface ReportSnapshot { record: ReportRecord; } -type ReportRecordEvent = { +export type ReportRecordEvent = { eventId: string; type: "report.generated" | "report.snapshot" | "report.snapshot-correction"; record?: ReportRecord; @@ -103,13 +94,7 @@ export function makeReportRecord(input: ReportRecordInput, generatedAt = new Dat if (input.period.timezone !== "America/Chicago") throw new Error("report period must use America/Chicago"); const date = /^daily:(\d{4}-\d{2}-\d{2}):America\/Chicago$/.exec(input.period.id)?.[1]; const canonicalPeriod = date ? dailyReportPeriod(date) : null; - if ( - !canonicalPeriod || - input.period.kind !== canonicalPeriod.kind || - input.period.periodStart !== canonicalPeriod.periodStart || - input.period.periodEnd !== canonicalPeriod.periodEnd || - input.period.softCloseAt !== canonicalPeriod.softCloseAt - ) { + if (!canonicalPeriod || input.period.kind !== canonicalPeriod.kind || input.period.periodStart !== canonicalPeriod.periodStart || input.period.periodEnd !== canonicalPeriod.periodEnd || input.period.softCloseAt !== canonicalPeriod.softCloseAt) { throw new Error("period must be a canonical dailyReportPeriod value"); } if (Date.parse(input.asOf) < Date.parse(input.period.periodStart) || Date.parse(input.asOf) >= Date.parse(input.period.periodEnd)) { @@ -159,7 +144,67 @@ async function readEvents(file: string): Promise { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; } - return text.split("\n").filter((line) => line.trim()).map(parseEvent).filter((event): event is ReportRecordEvent => event !== null); + return text + .split("\n") + .filter((line) => line.trim()) + .map(parseEvent) + .filter((event): event is ReportRecordEvent => event !== null); +} + +export type ReportRecordLocation = string | AppendOnlyDocumentRemote; +const REPORT_DOCUMENT_PREFIX = "c7-report:v1:"; + +function reportDocumentKey(event: ReportRecordEvent): string { + return `${REPORT_DOCUMENT_PREFIX}${event.type}:${createHash("sha256").update(event.eventId).digest("hex")}`; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function parseDocumentEvent(value: unknown): ReportRecordEvent { + if (!isObject(value) || typeof value.eventId !== "string" || typeof value.ts !== "string") { + throw new Error("invalid C7 report event in permanent document store"); + } + if (value.type === "report.generated" && isObject(value.record)) return value as ReportRecordEvent; + if (value.type === "report.snapshot" && isObject(value.snapshot)) return value as ReportRecordEvent; + if (value.type === "report.snapshot-correction" && isObject(value.correction)) return value as ReportRecordEvent; + throw new Error("unknown C7 report event in permanent document store"); +} + +async function readLocationEvents(location: ReportRecordLocation): Promise { + if (typeof location === "string") return readEvents(location); + const rows = await location.listPrefix(REPORT_DOCUMENT_PREFIX); + const events = rows.map(({ store, document }) => { + if (!store.startsWith(REPORT_DOCUMENT_PREFIX)) throw new Error("permanent report store returned a key outside its namespace"); + return parseDocumentEvent(document); + }); + // The table's stable key ordering is arbitrary; projections need event-time order. + return events.sort((left, right) => left.ts.localeCompare(right.ts) || left.eventId.localeCompare(right.eventId)); +} + +function sameReportEvent(left: ReportRecordEvent, right: ReportRecordEvent): boolean { + if (left.type !== right.type || left.eventId !== right.eventId) return false; + if (left.type === "report.generated" && right.type === "report.generated") { + return !!left.record && !!right.record && sameRecordContent(left.record, right.record); + } + if (left.type === "report.snapshot" && right.type === "report.snapshot") { + return !!left.snapshot && !!right.snapshot && left.snapshot.id === right.snapshot.id && left.snapshot.reportRecordId === right.snapshot.reportRecordId && sameRecordContent(left.snapshot.record, right.snapshot.record); + } + if (left.type === "report.snapshot-correction" && right.type === "report.snapshot-correction") { + return !!left.correction && !!right.correction && left.correction.id === right.correction.id && left.correction.snapshotId === right.correction.snapshotId && left.correction.originalRecordId === right.correction.originalRecordId && sameRecordContent(left.correction.record, right.correction.record); + } + return false; +} + +async function appendDocumentEvent(location: AppendOnlyDocumentRemote, event: ReportRecordEvent): Promise<{ inserted: boolean; event: ReportRecordEvent }> { + const key = reportDocumentKey(event); + if (await location.insertIfAbsent(key, 1, event)) return { inserted: true, event }; + const stored = await location.load(key); + if (!stored) throw new Error(`permanent report event disappeared after duplicate insert: ${event.eventId}`); + const existing = parseDocumentEvent(stored.document); + if (!sameReportEvent(existing, event)) throw new ReportRecordConflictError(event.eventId); + return { inserted: false, event: existing }; } /** Keep a torn final JSONL fragment from swallowing the next acknowledged event. */ @@ -180,7 +225,10 @@ const appendChains = new Map>(); function serializeAppend(file: string, fn: () => Promise): Promise { const previous = appendChains.get(file) ?? Promise.resolve(); const run = previous.then(fn, fn); - appendChains.set(file, run.catch(() => {})); + appendChains.set( + file, + run.catch(() => {}), + ); return run; } @@ -190,44 +238,51 @@ export interface AppendReportRecordResult { } /** - * Append once by stable record ID. A byte-equivalent rerun is a no-op; the + * Append once by stable record ID. A content-equivalent rerun is a no-op; the * same id with changed content is a conflict and is never silently replaced. */ -export async function appendReportRecord(file: string, record: ReportRecord): Promise { +export async function appendReportRecord(location: ReportRecordLocation, record: ReportRecord): Promise { assertCanonicalRecord(record); - return serializeAppend(file, async () => { - const events = await readEvents(file); - const existing = events.find((event) => event.type === "report.generated" && event.record?.id === record.id)?.record; + const event: ReportRecordEvent = { + eventId: record.id, + type: "report.generated", + record, + ts: record.generatedAt, + }; + if (typeof location !== "string") { + assertRecordIdContent(await readLocationEvents(location), record); + const result = await appendDocumentEvent(location, event); + if (result.event.type !== "report.generated" || !result.event.record) throw new Error("permanent report record has an invalid event type"); + return { inserted: result.inserted, record: result.event.record }; + } + return serializeAppend(location, async () => { + const events = await readEvents(location); + assertRecordIdContent(events, record); + const existing = events.find((item) => item.type === "report.generated" && item.record?.id === record.id)?.record; if (existing) { if (!sameRecordContent(existing, record)) throw new ReportRecordConflictError(record.id); return { inserted: false, record: existing }; } - await mkdir(dirname(file), { recursive: true }); - await terminateTornTail(file); - const event: ReportRecordEvent = { - eventId: record.id, - type: "report.generated", - record, - ts: record.generatedAt, - }; - await appendFile(file, `${JSON.stringify(event)}\n`, "utf8"); + await mkdir(dirname(location), { recursive: true }); + await terminateTornTail(location); + await appendFile(location, `${JSON.stringify(event)}\n`, "utf8"); return { inserted: true, record }; }); } /** Read the latest record per stable ID in append order (currently one per key). */ -export async function readReportRecords(file: string): Promise { +export async function readReportRecords(location: ReportRecordLocation): Promise { const byId = new Map(); - for (const event of await readEvents(file)) { + for (const event of await readLocationEvents(location)) { if (event.type === "report.generated" && event.record) byId.set(event.record.id, event.record); } return [...byId.values()]; } /** Current projection: latest appended source-cursor version per period/template. */ -export async function readCurrentReportRecords(file: string): Promise { +export async function readCurrentReportRecords(location: ReportRecordLocation): Promise { const current = new Map(); - for (const event of await readEvents(file)) { + for (const event of await readLocationEvents(location)) { if (event.type !== "report.generated" || !event.record) continue; current.set(`${event.record.period.id}\n${event.record.templateVersion}`, event.record); } @@ -255,11 +310,7 @@ export interface AppendReportSnapshotCorrectionResult { /** Freeze a dated view in the same append-only PM-stack log. Existing snapshot * IDs are immutable: a repeated identical write is idempotent, changed content * is a conflict that must become a separately linked correction record. */ -export async function appendReportSnapshot( - file: string, - record: ReportRecord, - snapshotAt: string, -): Promise { +export async function appendReportSnapshot(location: ReportRecordLocation, record: ReportRecord, snapshotAt: string): Promise { assertCanonicalRecord(record); requireIsoDate(snapshotAt, "snapshotAt"); const snapshot: ReportSnapshot = { @@ -268,10 +319,22 @@ export async function appendReportSnapshot( snapshotAt, record: structuredClone(record), }; - return serializeAppend(file, async () => { - const events = await readEvents(file); - const generated = events.find((event) => event.type === "report.generated" && event.record?.id === record.id)?.record; - if (generated && !sameRecordContent(generated, record)) throw new ReportRecordConflictError(record.id); + const event: ReportRecordEvent = { + eventId: snapshot.id, + type: "report.snapshot", + snapshot, + ts: snapshotAt, + }; + if (typeof location !== "string") { + const events = await readLocationEvents(location); + assertRecordIdContent(events, record); + const result = await appendDocumentEvent(location, event); + if (result.event.type !== "report.snapshot" || !result.event.snapshot) throw new Error("permanent snapshot has an invalid event type"); + return { inserted: result.inserted, snapshot: result.event.snapshot }; + } + return serializeAppend(location, async () => { + const events = await readEvents(location); + assertRecordIdContent(events, record); const existing = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshot.id)?.snapshot; if (existing) { if (existing.reportRecordId !== snapshot.reportRecordId || !sameRecordContent(existing.record, snapshot.record)) { @@ -279,32 +342,19 @@ export async function appendReportSnapshot( } return { inserted: false, snapshot: existing }; } - await mkdir(dirname(file), { recursive: true }); - await terminateTornTail(file); - const event: ReportRecordEvent = { - eventId: snapshot.id, - type: "report.snapshot", - snapshot, - ts: snapshotAt, - }; - await appendFile(file, `${JSON.stringify(event)}\n`, "utf8"); + await mkdir(dirname(location), { recursive: true }); + await terminateTornTail(location); + await appendFile(location, `${JSON.stringify(event)}\n`, "utf8"); return { inserted: true, snapshot }; }); } -export async function readReportSnapshots(file: string): Promise { - return (await readEvents(file)) - .filter((event): event is ReportRecordEvent & { snapshot: ReportSnapshot } => event.type === "report.snapshot" && !!event.snapshot) - .map((event) => event.snapshot); +export async function readReportSnapshots(location: ReportRecordLocation): Promise { + return (await readLocationEvents(location)).filter((event): event is ReportRecordEvent & { snapshot: ReportSnapshot } => event.type === "report.snapshot" && !!event.snapshot).map((event) => event.snapshot); } /** Append a correction as a new record linked to an immutable snapshot. */ -export async function appendReportSnapshotCorrection( - file: string, - snapshotId: string, - record: ReportRecord, - correctedAt: string, -): Promise { +export async function appendReportSnapshotCorrection(location: ReportRecordLocation, snapshotId: string, record: ReportRecord, correctedAt: string): Promise { assertCanonicalRecord(record); requireIsoDate(correctedAt, "correctedAt"); const correction: ReportSnapshotCorrection = { @@ -314,12 +364,32 @@ export async function appendReportSnapshotCorrection( correctedAt, record: structuredClone(record), }; - return serializeAppend(file, async () => { - const events = await readEvents(file); + if (typeof location !== "string") { + const events = await readLocationEvents(location); + const snapshot = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshotId)?.snapshot; + if (!snapshot) throw new Error(`snapshot does not exist: ${snapshotId}`); + if (snapshot.record.period.id !== record.period.id) throw new Error("correction period must match the snapshot"); + correction.originalRecordId = snapshot.reportRecordId; + assertRecordIdContent(events, record); + const event: ReportRecordEvent = { + eventId: correction.id, + type: "report.snapshot-correction", + correction, + ts: correctedAt, + }; + const result = await appendDocumentEvent(location, event); + if (result.event.type !== "report.snapshot-correction" || !result.event.correction) { + throw new Error("permanent snapshot correction has an invalid event type"); + } + return { inserted: result.inserted, correction: result.event.correction }; + } + return serializeAppend(location, async () => { + const events = await readEvents(location); const snapshot = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshotId)?.snapshot; if (!snapshot) throw new Error(`snapshot does not exist: ${snapshotId}`); if (snapshot.record.period.id !== record.period.id) throw new Error("correction period must match the snapshot"); correction.originalRecordId = snapshot.reportRecordId; + assertRecordIdContent(events, record); const existing = events.find((event) => event.type === "report.snapshot-correction" && event.correction?.id === correction.id)?.correction; if (existing) { if (existing.snapshotId !== correction.snapshotId || existing.originalRecordId !== correction.originalRecordId || !sameRecordContent(existing.record, correction.record)) { @@ -327,20 +397,40 @@ export async function appendReportSnapshotCorrection( } return { inserted: false, correction: existing }; } - await mkdir(dirname(file), { recursive: true }); - await terminateTornTail(file); - const event: ReportRecordEvent = { eventId: correction.id, type: "report.snapshot-correction", correction, ts: correctedAt }; - await appendFile(file, `${JSON.stringify(event)}\n`, "utf8"); + await mkdir(dirname(location), { recursive: true }); + await terminateTornTail(location); + const event: ReportRecordEvent = { + eventId: correction.id, + type: "report.snapshot-correction", + correction, + ts: correctedAt, + }; + await appendFile(location, `${JSON.stringify(event)}\n`, "utf8"); return { inserted: true, correction }; }); } -export async function readReportSnapshotCorrections(file: string): Promise { - return (await readEvents(file)) - .filter((event): event is ReportRecordEvent & { correction: ReportSnapshotCorrection } => event.type === "report.snapshot-correction" && !!event.correction) +export async function readReportSnapshotCorrections(location: ReportRecordLocation): Promise { + return (await readLocationEvents(location)) + .filter( + ( + event, + ): event is ReportRecordEvent & { + correction: ReportSnapshotCorrection; + } => event.type === "report.snapshot-correction" && !!event.correction, + ) .map((event) => event.correction); } +function assertRecordIdContent(events: ReportRecordEvent[], candidate: ReportRecord): void { + for (const event of events) { + const persisted = event.type === "report.generated" ? event.record : event.type === "report.snapshot" ? event.snapshot?.record : event.correction?.record; + if (persisted?.id === candidate.id && !sameRecordContent(persisted, candidate)) { + throw new ReportRecordConflictError(candidate.id); + } + } +} + function sameRecordContent(left: ReportRecord, right: ReportRecord): boolean { const { generatedAt: _leftTime, ...leftContent } = left; const { generatedAt: _rightTime, ...rightContent } = right; @@ -358,7 +448,10 @@ function canonicalJson(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; if (typeof value === "object" && value !== null) { const object = value as Record; - return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(",")}}`; + const keys = Object.keys(object) + .filter((key) => object[key] !== undefined) + .sort(); + return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(",")}}`; } return JSON.stringify(value) ?? "null"; } diff --git a/pm-stack/aggregator/test/report-records-c7.test.ts b/pm-stack/aggregator/test/report-records-c7.test.ts index 39e8058681..2bc61a1586 100644 --- a/pm-stack/aggregator/test/report-records-c7.test.ts +++ b/pm-stack/aggregator/test/report-records-c7.test.ts @@ -2,6 +2,7 @@ import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, test } from "bun:test"; +import type { AppendOnlyDocumentRemote } from "../src/aa-last-good.ts"; import { appendReportRecord, appendReportSnapshot, @@ -129,6 +130,11 @@ describe("C7 canonical report records", () => { await expect(appendReportSnapshot(file, mutatedSnapshotSource, "2026-11-22T14:00:00.000Z")) .rejects.toBeInstanceOf(ReportRecordConflictError); expect((await readReportSnapshots(file))[0]?.record.blocks[0]?.text).toBe("Original prose."); + const conflictingGeneration = makeReportRecord({ + ...input, + blocks: [{ ...input.blocks[0]!, text: "Conflicting after standalone snapshot." }], + }, "2026-11-22T05:48:01.000Z"); + await expect(appendReportRecord(file, conflictingGeneration)).rejects.toBeInstanceOf(ReportRecordConflictError); }); test("records snapshot corrections as new linked immutable records", async () => { @@ -166,6 +172,12 @@ describe("C7 canonical report records", () => { expect(first.correction.record.id).toBe(correction.id); expect((await readReportSnapshots(file))[0]?.record.blocks[0]?.text).toBe("Original snapshot."); expect((await readReportSnapshotCorrections(file)).map((item) => item.record.id)).toEqual([correction.id]); + const conflictingOriginal = makeReportRecord({ + ...input, + blocks: [{ ...input.blocks[0]!, text: "Contradictory original record." }], + }, "2026-11-22T15:06:00.000Z"); + await expect(appendReportSnapshotCorrection(file, "snapshot:daily:2026-11-21:America/Chicago", conflictingOriginal, "2026-11-22T15:06:01.000Z")) + .rejects.toBeInstanceOf(ReportRecordConflictError); await expect(appendReportSnapshotCorrection(file, "snapshot:missing", correction, "2026-11-22T15:00:00.000Z")) .rejects.toThrow(/snapshot does not exist/); }); @@ -242,6 +254,77 @@ describe("C7 canonical report records", () => { expect(reportBlockConflict("Stored paragraph.", "Human changed paragraph.")).toBe(true); }); + test("uses append-only permanent document keys for report history and snapshots", async () => { + const documents = new Map(); + const remote: AppendOnlyDocumentRemote = { + async load(store) { + return documents.has(store) ? { version: 1, document: structuredClone(documents.get(store)) } : null; + }, + async insertIfAbsent(store, _version, document) { + if (documents.has(store)) return false; + documents.set(store, structuredClone(document)); + return true; + }, + async listPrefix(prefix) { + return [...documents.entries()].filter(([store]) => store.startsWith(prefix)) + .map(([store, document]) => ({ store, version: 1, document: structuredClone(document) })); + }, + }; + const base = { + period: { id: "daily:2026-11-21:America/Chicago", kind: "daily" as const, timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", periodEnd: "2026-11-22T06:00:00.000Z", softCloseAt: "2026-11-22T14:00:00.000Z" }, + asOf: "2026-11-22T05:45:00.000Z", templateVersion: "daily-v1", sourceCursor: "cursor-1", + sources: [{ id: "event-1", uri: "gh:issue/12349", observedAt: "2026-11-22T05:40:00.000Z" }], + blocks: [{ id: "change-1", text: "Original report.", relatedAt: "2026-11-22T05:40:00.000Z" }], + }; + const record = makeReportRecord(base, "2026-11-22T05:45:01.000Z"); + expect((await appendReportRecord(remote, record)).inserted).toBe(true); + const rerun = await appendReportRecord(remote, makeReportRecord(base, "2026-11-22T05:46:01.000Z")); + expect(rerun.inserted).toBe(false); + expect(rerun.record.generatedAt).toBe(record.generatedAt); + await expect(appendReportRecord(remote, makeReportRecord({ ...base, + blocks: [{ ...base.blocks[0]!, text: "Conflicting content." }], + }, "2026-11-22T05:47:01.000Z"))).rejects.toBeInstanceOf(ReportRecordConflictError); + const snapshot = await appendReportSnapshot(remote, record, "2026-11-22T14:00:00.000Z"); + const snapshotRerun = await appendReportSnapshot(remote, record, "2026-11-22T14:05:00.000Z"); + expect(snapshot.inserted).toBe(true); + expect(snapshotRerun.inserted).toBe(false); + expect(snapshotRerun.snapshot.snapshotAt).toBe("2026-11-22T14:00:00.000Z"); + expect(await readReportRecords(remote)).toEqual([record]); + expect(await readReportSnapshots(remote)).toEqual([snapshot.snapshot]); + expect(documents.size).toBe(2); + }); + + test("canonical JSON retries tolerate omitted optional values", async () => { + const file = await storePath(); + const input = { + period: { + id: "daily:2026-11-21:America/Chicago", + kind: "daily" as const, + timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", + periodEnd: "2026-11-22T06:00:00.000Z", + softCloseAt: "2026-11-22T14:00:00.000Z", + }, + asOf: "2026-11-22T05:45:00.000Z", + templateVersion: "daily-v1", + sourceCursor: "optional-links", + sources: [], + blocks: [ + { + id: "b", + text: "Text", + relatedAt: "2026-11-22T05:40:00.000Z", + links: undefined, + }, + ], + }; + const first = await appendReportRecord(file, makeReportRecord(input, "2026-11-22T05:45:01.000Z")); + const rerun = await appendReportRecord(file, makeReportRecord(input, "2026-11-22T05:45:02.000Z")); + expect(first.inserted).toBe(true); + expect(rerun.inserted).toBe(false); + }); + test("allows a persistent store path override without a second datastore", () => { expect(defaultReportRecordsFile({ PM_AGG_REPORT_RECORDS_FILE: "/var/lib/pm/report-records.jsonl" })) .toBe("/var/lib/pm/report-records.jsonl"); diff --git a/pm-stack/aggregator/test/turso-stores.test.ts b/pm-stack/aggregator/test/turso-stores.test.ts index ad6653db49..02f99df5dc 100644 --- a/pm-stack/aggregator/test/turso-stores.test.ts +++ b/pm-stack/aggregator/test/turso-stores.test.ts @@ -50,6 +50,12 @@ test("activity arrays and document JSON round trip", async () => { expect((await activity.load())!.seen).toEqual(value.seen); await doc.save("test", 1, { quotes: "::jsonb now()", a: [1, true] }); expect(await doc.load("test")).toEqual({ version: 1, document: { quotes: "::jsonb now()", a: [1, true] } }); + const event = { eventId: "report:stable", type: "report.generated", ts: "2026-11-22T00:00:00.000Z" }; + expect(await doc.insertIfAbsent("c7-report:v1:generated:stable", 1, event)).toBe(true); + expect(await doc.insertIfAbsent("c7-report:v1:generated:stable", 1, { ...event, ts: "2026-11-22T00:01:00.000Z" })).toBe(false); + expect(await doc.listPrefix("c7-report:v1:")).toEqual([ + { store: "c7-report:v1:generated:stable", version: 1, document: event }, + ]); db.close(); }); test("alerts partial-index dedupe, JSON preference merge and ack are preserved", async () => { diff --git a/pm-stack/shared-schema/README.md b/pm-stack/shared-schema/README.md index 42e28f0167..bd880717fe 100644 --- a/pm-stack/shared-schema/README.md +++ b/pm-stack/shared-schema/README.md @@ -103,7 +103,7 @@ adds, in dependency order after it: | `public.agg_activity_ingestion` | per-source checkpoints, dedupe seen ids, source status | | `public.agg_activity_gaps` | the activity gap ledger (gaps resolve in place) | | `public.agg_usage_snapshots` | append-only usage observations, dedupe key `service\|metric\|ts\|value` | -| `public.agg_store_documents` | aggregator-owned JSON documents without a typed contract (`aa-last-good`) | +| `public.agg_store_documents` | aggregator-owned JSON documents (`aa-last-good`; namespaced C7 report events use an append-only typed contract) | Each paired `.down.sql` refuses to drop a non-empty table; the #6815 down migration drops its tables in reverse dependency order. The refusal is From a7f33fbb3160872f9b1ec3c43cc5af452cba644c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 02:38:55 -0600 Subject: [PATCH 7/7] fix(pm-stack): claim C7 record identities atomically --- pm-stack/aggregator/report-records-c7.md | 6 ++- pm-stack/aggregator/src/report-records.ts | 15 ++++++- .../aggregator/test/report-records-c7.test.ts | 43 ++++++++++++++++++- 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/pm-stack/aggregator/report-records-c7.md b/pm-stack/aggregator/report-records-c7.md index b2935d1d74..d83ebf1b61 100644 --- a/pm-stack/aggregator/report-records-c7.md +++ b/pm-stack/aggregator/report-records-c7.md @@ -45,8 +45,10 @@ replication. It remains useful for development and rollback. The durable adapter uses the existing `public.agg_store_documents` table from #6815; it creates no table or separate report database. Each generated record, snapshot, and correction is stored as one immutable document under -`c7-report:v1::`. `insertIfAbsent` provides the -atomic idempotency boundary: a duplicate key reads back and compares the +`c7-report:v1::`. A shared atomic content claim +under `c7-report-record:v1:` prevents conflicting payloads +for the same record ID across concurrent event types. `insertIfAbsent` provides +the atomic idempotency boundary: a duplicate key reads back and compares the canonical content, returning the original event for an identical rerun and raising a conflict for changed content. Prefix reads return the event set; projections sort by the canonical event timestamp and stable event ID. The generic overwrite API is not used for C7 diff --git a/pm-stack/aggregator/src/report-records.ts b/pm-stack/aggregator/src/report-records.ts index c0e2b95927..1b86bc9b76 100644 --- a/pm-stack/aggregator/src/report-records.ts +++ b/pm-stack/aggregator/src/report-records.ts @@ -81,7 +81,7 @@ export class ReportRecordConflictError extends Error { /** Stable across reruns for the same period, template and source cursor. */ export function reportRecordId(input: Pick): string { - const key = `${input.period.id}\n${input.templateVersion}\n${input.sourceCursor}`; + const key = JSON.stringify([input.period.id, input.templateVersion, input.sourceCursor]); return `report:${createHash("sha256").update(key).digest("hex")}`; } @@ -153,6 +153,7 @@ async function readEvents(file: string): Promise { export type ReportRecordLocation = string | AppendOnlyDocumentRemote; const REPORT_DOCUMENT_PREFIX = "c7-report:v1:"; +const REPORT_RECORD_CLAIM_PREFIX = "c7-report-record:v1:"; function reportDocumentKey(event: ReportRecordEvent): string { return `${REPORT_DOCUMENT_PREFIX}${event.type}:${createHash("sha256").update(event.eventId).digest("hex")}`; @@ -197,6 +198,16 @@ function sameReportEvent(left: ReportRecordEvent, right: ReportRecordEvent): boo return false; } +async function claimRemoteRecord(location: AppendOnlyDocumentRemote, record: ReportRecord): Promise { + const key = `${REPORT_RECORD_CLAIM_PREFIX}${createHash("sha256").update(record.id).digest("hex")}`; + if (await location.insertIfAbsent(key, 1, record)) return; + const stored = await location.load(key); + if (!stored || !isObject(stored.document) || typeof stored.document.id !== "string") { + throw new Error(`permanent report identity claim disappeared or is malformed: ${record.id}`); + } + if (!sameRecordContent(stored.document as unknown as ReportRecord, record)) throw new ReportRecordConflictError(record.id); +} + async function appendDocumentEvent(location: AppendOnlyDocumentRemote, event: ReportRecordEvent): Promise<{ inserted: boolean; event: ReportRecordEvent }> { const key = reportDocumentKey(event); if (await location.insertIfAbsent(key, 1, event)) return { inserted: true, event }; @@ -251,6 +262,7 @@ export async function appendReportRecord(location: ReportRecordLocation, record: }; if (typeof location !== "string") { assertRecordIdContent(await readLocationEvents(location), record); + await claimRemoteRecord(location, record); const result = await appendDocumentEvent(location, event); if (result.event.type !== "report.generated" || !result.event.record) throw new Error("permanent report record has an invalid event type"); return { inserted: result.inserted, record: result.event.record }; @@ -328,6 +340,7 @@ export async function appendReportSnapshot(location: ReportRecordLocation, recor if (typeof location !== "string") { const events = await readLocationEvents(location); assertRecordIdContent(events, record); + await claimRemoteRecord(location, record); const result = await appendDocumentEvent(location, event); if (result.event.type !== "report.snapshot" || !result.event.snapshot) throw new Error("permanent snapshot has an invalid event type"); return { inserted: result.inserted, snapshot: result.event.snapshot }; diff --git a/pm-stack/aggregator/test/report-records-c7.test.ts b/pm-stack/aggregator/test/report-records-c7.test.ts index 2bc61a1586..7b941c6587 100644 --- a/pm-stack/aggregator/test/report-records-c7.test.ts +++ b/pm-stack/aggregator/test/report-records-c7.test.ts @@ -252,6 +252,9 @@ describe("C7 canonical report records", () => { expect((await readCurrentReportRecords(file)).map((record) => record.sourceCursor)).toEqual(["cursor-2"]); expect(reportBlockConflict("Stored paragraph.\n", "Stored paragraph.")).toBe(false); expect(reportBlockConflict("Stored paragraph.", "Human changed paragraph.")).toBe(true); + const identityFirst = makeReportRecord({ ...base, templateVersion: "daily-v1\nsource", sourceCursor: "cursor" }, "2026-11-22T05:45:01.000Z"); + const identitySecond = makeReportRecord({ ...base, templateVersion: "daily-v1", sourceCursor: "source\ncursor" }, "2026-11-22T05:45:01.000Z"); + expect(identityFirst.id).not.toBe(identitySecond.id); }); test("uses append-only permanent document keys for report history and snapshots", async () => { @@ -292,7 +295,45 @@ describe("C7 canonical report records", () => { expect(snapshotRerun.snapshot.snapshotAt).toBe("2026-11-22T14:00:00.000Z"); expect(await readReportRecords(remote)).toEqual([record]); expect(await readReportSnapshots(remote)).toEqual([snapshot.snapshot]); - expect(documents.size).toBe(2); + expect(documents.size).toBe(3); // generation, snapshot, and atomic record-ID claim + }); + + test("remote generation and snapshot conflict checks are atomic across event types", async () => { + const documents = new Map(); + const remote: AppendOnlyDocumentRemote = { + async load(store) { return documents.has(store) ? { version: 1, document: structuredClone(documents.get(store)) } : null; }, + async insertIfAbsent(store, _version, document) { + if (documents.has(store)) return false; + documents.set(store, structuredClone(document)); + return true; + }, + async listPrefix(prefix) { + return [...documents.entries()].filter(([store]) => store.startsWith(prefix)) + .map(([store, document]) => ({ store, version: 1, document: structuredClone(document) })); + }, + }; + const base = { + period: { id: "daily:2026-11-21:America/Chicago", kind: "daily" as const, timezone: "America/Chicago" as const, + periodStart: "2026-11-21T06:00:00.000Z", periodEnd: "2026-11-22T06:00:00.000Z", softCloseAt: "2026-11-22T14:00:00.000Z" }, + asOf: "2026-11-22T05:45:00.000Z", templateVersion: "daily-v1", sourceCursor: "concurrent-cursor", + sources: [], blocks: [{ id: "block", text: "original", relatedAt: "2026-11-22T05:40:00.000Z" }], + }; + const generated = makeReportRecord(base, "2026-11-22T05:45:01.000Z"); + const conflicting = makeReportRecord({ ...base, blocks: [{ ...base.blocks[0]!, text: "different" }] }, "2026-11-22T05:45:02.000Z"); + const results = await Promise.allSettled([ + appendReportRecord(remote, generated), + appendReportSnapshot(remote, conflicting, "2026-11-22T14:00:00.000Z"), + ]); + expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1); + expect(results.filter((result) => result.status === "rejected")).toHaveLength(1); + const records = await readReportRecords(remote); + const snapshots = await readReportSnapshots(remote); + const stored = records[0] ?? snapshots[0]?.record; + expect(stored).toBeDefined(); + if (stored) { + expect(records.every((item) => item.blocks[0]?.text === stored.blocks[0]?.text)).toBe(true); + expect(snapshots.every((item) => item.record.blocks[0]?.text === stored.blocks[0]?.text)).toBe(true); + } }); test("canonical JSON retries tolerate omitted optional values", async () => {