From 9c4a86a16e09aa251a4763fe64a485cb20bbc10a Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:50:24 -0600 Subject: [PATCH 1/3] =?UTF-8?q?feat(aggregator):=20audit=20event=20v2=20?= =?UTF-8?q?=E2=80=94=20stable=20ids,=20attribution,=20hash-linked=20integr?= =?UTF-8?q?ity,=20durable=20retry=20outbox=20(#3322=20slice=20A)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/aggregator/src/events.ts | 431 ++++++++++++++++++++++-- pm-stack/aggregator/src/server.ts | 5 +- pm-stack/aggregator/test/events.test.ts | 123 +++++++ 3 files changed, 531 insertions(+), 28 deletions(-) diff --git a/pm-stack/aggregator/src/events.ts b/pm-stack/aggregator/src/events.ts index 80dfbb9e85..d171647cd3 100644 --- a/pm-stack/aggregator/src/events.ts +++ b/pm-stack/aggregator/src/events.ts @@ -1,9 +1,33 @@ -// The cross-stack event log (#1739). One append-only chronological -// stream of what happened across the pm-stack: dashboard action -// outcomes, orchestration publishes / tier changes, and session -// registry outcomes — the facts the actions store, the orchestration -// section, and the session registry each held separately, with no -// single stream a human (or /today) could read. +// The cross-stack event log (#1739), audit v2 since #3322 slice A. +// One append-only chronological stream of what happened across the +// pm-stack: dashboard action outcomes, orchestration publishes / tier +// changes, and session registry outcomes — the facts the actions +// store, the orchestration section, and the session registry each +// held separately, with no single stream a human (or /today) could +// read. +// +// Audit v2 (#3322 slice A, follow-on to the #1739 stream): every +// stored record is a versioned AuditEvent carrying a stable id, +// separate event (`at`) and ingest (`ingestedAt`) timestamps, actor +// attribution with an explicit confidence (pre-SSO / unknown actors +// are marked as such and never asserted as authenticated), a source +// identity (+ optional link), and a hash link (`prevHash` / `hash`) +// over its predecessor so silent edits or deletions of stored +// records are detectable (`verifyEventChain`, `EventsStore.health`). +// Corrections are separate append-only `correction` records naming +// the record they correct (`corrects`) — a stored record is never +// edited in place. Retention pruning (below) is the one sanctioned +// removal: the first retained record's `prevHash` stays as the +// anchor naming the pruned predecessor, so a pruned chain still +// verifies link-by-link from its anchor. +// +// Failed appends are no longer lost (#3322 slice A): when a persist +// fails, the record is written to a durable retry outbox +// (`.outbox.jsonl`) before the error is rethrown, and the +// outbox is flushed — merged by stable id, then cleared — on load +// and on every subsequent append. `EventsStore.health()` exposes the +// pending-retry count and the integrity verdict as a readable +// surface; failures are also logged loudly at the point of failure. // // Storage follows the views/comments store discipline (#906, #1276): // one JSON file in the aggregator's data directory @@ -11,15 +35,21 @@ // and serialized through a per-store promise chain; a missing file is // the only silent empty start — an unparseable or wrongly-shaped file // is quarantined to .corrupt- with a loud log, never -// silently overwritten. +// silently overwritten. v1 files ({version: 1}) remain readable: +// their rows are migrated in memory to v2 records with deterministic +// stable ids (see migrateV1Event) and the file is rewritten as v2 on +// the next persist. // // Retention is bounded (#1739 acceptance): records older than 30 days // or beyond the newest 5000 are dropped on append and on load, // whichever bound hits first. // // Writers are fire-and-forget (see emitEvent): an event write failure -// never blocks or fails the underlying action, publish, or merge. -import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +// never blocks or fails the underlying action, publish, or merge — +// and since slice A the failed record waits in the retry outbox +// instead of being lost. +import { createHash, randomUUID } from "node:crypto"; +import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; export interface StreamEvent { @@ -36,9 +66,66 @@ export interface StreamEvent { summary: string; } +/** How sure the stream is that `actor` is who it claims to be. + * `authenticated` may only be recorded with `asserted: true`; + * pre-SSO and unknown actors are explicitly marked, never silently + * upgraded. */ +export interface EventAttribution { + confidence: "authenticated" | "pre-sso" | "unknown"; + asserted: boolean; +} + +/** Where a record came from: the writing component's identity and, + * when there is one, a link to the source artifact. */ +export interface EventSource { + identity: string; + link?: string; +} + +/** The v2 audit record (#3322 slice A): a StreamEvent plus the audit + * fields. `action` in the #3322 wording is `kind`; `object` is + * `ref` — the v1 field names are kept so every existing reader and + * writer keeps working unchanged. */ +export interface AuditEvent extends StreamEvent { + /** Record format version, per record. */ + version: 2; + /** Stable unique id, assigned at first append and never changed. */ + id: string; + /** ISO timestamp of when the store ingested the record; `at` is + * when the event itself happened. */ + ingestedAt: string; + attribution: EventAttribution; + source: EventSource; + /** For `kind: "correction"` records: the id of the record this + * correction annotates. The corrected record is never modified. */ + corrects?: string; + /** Set on records migrated in memory from a v1 store file. */ + migratedFromVersion?: 1; + /** Hash of the previous record in the stored chain (the genesis + * constant for the first record ever; after retention pruning, + * the hash of the last pruned record — the chain anchor). */ + prevHash: string; + /** sha256 over `prevHash` + this record's canonical fields. */ + hash: string; +} + export type NewStreamEvent = Omit & { at?: string }; +/** A new audit record: everything a writer may supply. The store + * fills `id` (when omitted), `ingestedAt`, and the hash link. */ +export type NewAuditEvent = NewStreamEvent & { + id?: string; + attribution?: EventAttribution; + source?: EventSource; + corrects?: string; +}; + export interface EventsFile { + version: 2; + events: AuditEvent[]; +} + +interface EventsFileV1 { version: 1; events: StreamEvent[]; } @@ -46,6 +133,9 @@ export interface EventsFile { export const EVENT_RETENTION_DAYS = 30; export const EVENT_RETENTION_MAX = 5000; +/** prevHash of the first record in an unpruned chain. */ +export const EVENT_CHAIN_GENESIS = "0".repeat(64); + const FIELD = /^[\w ./#:@-]+$/; export function validateStreamEvent(e: unknown): { ok: true; value: StreamEvent } | { ok: false; error: string } { @@ -89,10 +179,135 @@ function isStreamEvent(value: unknown): value is StreamEvent { return validateStreamEvent(value).ok; } +/** Validate the v2-only fields a writer may supply. Attribution that + * claims `authenticated` without asserting it is rejected outright: + * an unauthenticated actor must be recorded as pre-sso / unknown. */ +function validateAuditExtras(input: NewAuditEvent): { ok: true } | { ok: false; error: string } { + if (input.id !== undefined && (typeof input.id !== "string" || input.id.trim() === "" || input.id.length > 200)) { + return { ok: false, error: "event.id must be a non-empty string of at most 200 chars" }; + } + if (input.attribution !== undefined) { + const a = input.attribution; + if ( + typeof a !== "object" || a === null || + !["authenticated", "pre-sso", "unknown"].includes(a.confidence) || + typeof a.asserted !== "boolean" + ) { + return { ok: false, error: "event.attribution must be {confidence: authenticated|pre-sso|unknown, asserted: boolean}" }; + } + if (a.confidence === "authenticated" && !a.asserted) { + return { ok: false, error: "event.attribution: confidence 'authenticated' requires asserted: true" }; + } + } + if (input.source !== undefined) { + const s = input.source; + if (typeof s !== "object" || s === null || typeof s.identity !== "string" || s.identity.trim() === "" || s.identity.length > 200) { + return { ok: false, error: "event.source.identity must be a non-empty string of at most 200 chars" }; + } + if (s.link !== undefined && (typeof s.link !== "string" || s.link.length > 500)) { + return { ok: false, error: "event.source.link must be a string of at most 500 chars" }; + } + } + if (input.corrects !== undefined && (typeof input.corrects !== "string" || input.corrects.trim() === "")) { + return { ok: false, error: "event.corrects must be the non-empty id of the record being corrected" }; + } + return { ok: true }; +} + +function canonicalFields(e: AuditEvent): string { + return JSON.stringify({ + version: e.version, + id: e.id, + at: e.at, + ingestedAt: e.ingestedAt, + actor: e.actor, + attribution: e.attribution, + kind: e.kind, + ref: e.ref, + summary: e.summary, + source: e.source, + corrects: e.corrects ?? null, + migratedFromVersion: e.migratedFromVersion ?? null, + }); +} + +/** The hash a record must carry given its predecessor's hash. */ +export function eventHash(prevHash: string, e: AuditEvent): string { + return createHash("sha256").update(`${prevHash}\n${canonicalFields(e)}`).digest("hex"); +} + +/** Recompute the chain in stored order and re-stamp prevHash/hash. + * Used at persist time so backfilled (out-of-order `at`) appends + * still produce one consistent chain in stored order. */ +function rechain(events: AuditEvent[]): AuditEvent[] { + let prev = EVENT_CHAIN_GENESIS; + return events.map((e) => { + const stamped = { ...e, prevHash: prev }; + stamped.hash = eventHash(prev, stamped); + prev = stamped.hash; + return stamped; + }); +} + +/** Verify a stored chain: every record's hash must recompute from + * its fields and its recorded prevHash, and every record after the + * first must link to its predecessor's hash. The first record's + * prevHash is the retention anchor (genesis, or the last pruned + * record's hash) and is covered by its own hash, so pruning does + * not break verification — but a silently edited field, a re-stamped + * hash, or a deleted middle record all fail here. */ +export function verifyEventChain(events: readonly AuditEvent[]): { ok: true } | { ok: false; error: string; index: number } { + for (let i = 0; i < events.length; i++) { + const e = events[i]!; + if (eventHash(e.prevHash, e) !== e.hash) { + return { ok: false, error: `record ${e.id} (index ${i}): hash does not match its fields — stored record was altered`, index: i }; + } + if (i > 0 && e.prevHash !== events[i - 1]!.hash) { + return { ok: false, error: `record ${e.id} (index ${i}): prevHash does not match its predecessor — a record was deleted or reordered`, index: i }; + } + } + return { ok: true }; +} + +/** Migrate one v1 row to a v2 record. The stable id is deterministic + * (a hash of the row's fields + position) so the same v1 file + * migrates to the same ids on every load until it is persisted as + * v2. Ingest time is unknown for migrated rows; `ingestedAt` falls + * back to the event time and `migratedFromVersion` records why — + * attribution is `unknown`, never asserted. */ +export function migrateV1Event(row: StreamEvent, index: number): AuditEvent { + const digest = createHash("sha256") + .update(JSON.stringify([index, row.at, row.actor, row.kind, row.ref, row.summary])) + .digest("hex") + .slice(0, 24); + return { + ...row, + version: 2, + id: `evt_v1_${digest}`, + ingestedAt: row.at, + attribution: { confidence: "unknown", asserted: false }, + source: { identity: "unknown (migrated from v1 events file)" }, + migratedFromVersion: 1, + prevHash: EVENT_CHAIN_GENESIS, + hash: "", + }; +} + +function isAuditEvent(value: unknown): value is AuditEvent { + if (!isStreamEvent(value)) return false; + const v = value as unknown as Record; + return ( + v.version === 2 && + typeof v.id === "string" && v.id !== "" && + typeof v.ingestedAt === "string" && Number.isFinite(Date.parse(v.ingestedAt)) && + typeof v.prevHash === "string" && typeof v.hash === "string" + ); +} + /** Drop records past the retention bounds (#1739): older than * EVENT_RETENTION_DAYS, or beyond the newest EVENT_RETENTION_MAX. * Input and output are chronological (oldest first). */ -export function pruneEvents(events: readonly StreamEvent[], now = new Date()): StreamEvent[] { +export function pruneEvents(events: readonly T[], now = new Date()): T[] { const cutoff = now.getTime() - EVENT_RETENTION_DAYS * 24 * 60 * 60 * 1000; const fresh = events .map((event, index) => ({ event, index })) @@ -110,7 +325,7 @@ export interface EventFilter { /** The read surface: newest first, exact-match filters on * kind / ref / actor (case-insensitive, like the views matcher). */ -export function filterEvents(events: readonly StreamEvent[], filter: EventFilter = {}): StreamEvent[] { +export function filterEvents(events: readonly T[], filter: EventFilter = {}): T[] { const eq = (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); // Newest first by PARSED time (#4489 Codex re-review): accepted // timestamps may carry offsets or omit fractional seconds, where a @@ -132,11 +347,14 @@ export function filterEvents(events: readonly StreamEvent[], filter: EventFilter * The fire-and-forget writer every emission point uses (#1739 * acceptance: writing an event never blocks the underlying action). * Never throws: a failed append is logged and reported as `false`; - * the caller's action / publish / merge proceeds regardless. + * the caller's action / publish / merge proceeds regardless. Since + * #3322 slice A a failed append to the real store is also persisted + * to the durable retry outbox, so "lost" below means "not yet in the + * main file" — it is retried on the next load / append. */ export async function emitEvent( - store: { record: (event: NewStreamEvent) => Promise }, - event: NewStreamEvent, + store: { record: (event: NewAuditEvent) => Promise }, + event: NewAuditEvent, ): Promise { try { await store.record(event); @@ -144,22 +362,37 @@ export async function emitEvent( } catch (err) { console.error( `[events] WARNING: event append failed (${err instanceof Error ? err.message : String(err)}); ` + - `the underlying action proceeds — event lost: ${event.kind} ${event.ref}`, + `the underlying action proceeds — event queued for retry if the store has an outbox, otherwise lost: ${event.kind} ${event.ref}`, ); return false; } } +export interface EventsHealth { + version: 2; + events: number; + /** Records waiting in the durable retry outbox. */ + pendingRetries: number; + integrity: { ok: boolean; detail: string }; +} + // -- the store ------------------------------------------------------------ export class EventsStore { - private events: StreamEvent[] = []; + private events: AuditEvent[] = []; private loadPromise: Promise | null = null; private writeChain: Promise = Promise.resolve(); private writeSeq = 0; + private integrityViolation: string | null = null; constructor(private readonly file: string) {} + /** The durable retry outbox: one JSON audit record per line, + * written when a persist fails, flushed on load / next append. */ + get outboxFile(): string { + return `${this.file}.outbox.jsonl`; + } + async load(): Promise { if (!this.loadPromise) this.loadPromise = this.doLoad(); return this.loadPromise; @@ -172,6 +405,7 @@ export class EventsStore { } catch (err) { if ((err as { code?: unknown })?.code === "ENOENT") { this.events = []; + await this.flushOutbox(); return; } this.events = []; @@ -184,15 +418,41 @@ export class EventsStore { throw new Error("store file does not have the expected { events: [...] } shape"); } const rows = (parsed as { events: unknown[] }).events; - const malformedIndex = rows.findIndex((event) => !isStreamEvent(event)); - if (malformedIndex !== -1) { - throw new Error(`event row ${malformedIndex} does not have the expected StreamEvent shape`); + const normalized: AuditEvent[] = []; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (isAuditEvent(row)) { + normalized.push({ + ...row, + attribution: row.attribution ?? { confidence: "unknown", asserted: false }, + source: row.source ?? { identity: "unknown" }, + }); + } else if (isStreamEvent(row)) { + normalized.push(migrateV1Event(row, i)); + } else { + throw new Error(`event row ${i} does not have the expected StreamEvent/AuditEvent shape`); + } + } + this.events = pruneEvents(normalized); + // Integrity is checked against the STORED hashes before any + // persist can re-stamp them: a mismatch means the file was + // altered outside the store. The records still load (the + // stream stays readable) but the violation is loud and is + // reported by health() until a human looks. + const verdict = verifyEventChain(this.events.filter((e) => e.hash !== "")); + if (!verdict.ok) { + this.integrityViolation = verdict.error; + console.error( + `[events] WARNING: events store ${this.file} failed its integrity check: ${verdict.error}. ` + + `Stored audit records must not be edited or deleted outside retention pruning — investigate before trusting this stream.`, + ); } - this.events = pruneEvents(rows.filter(isStreamEvent)); } catch (err) { this.events = []; await this.quarantine(`is unparseable (${err instanceof Error ? err.message : String(err)})`); + return; } + await this.flushOutbox(); } private async quarantine(why: string): Promise { @@ -214,7 +474,8 @@ export class EventsStore { private persist(): Promise { const run = this.writeChain.then(async () => { - const data: EventsFile = { version: 1, events: this.events }; + this.events = rechain(this.events); + const data: EventsFile = { version: 2, events: this.events }; await mkdir(dirname(this.file), { recursive: true }); const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`; await writeFile(tmp, JSON.stringify(data, null, 2)); @@ -224,8 +485,91 @@ export class EventsStore { return run; } + /** Persist one record to the retry outbox after a failed append. + * Best-effort on top of a failure (the disk may be the problem), + * but a failed outbox write is logged as the true loss it is. */ + private async queueForRetry(event: AuditEvent, cause: unknown): Promise { + try { + await mkdir(dirname(this.file), { recursive: true }); + await appendFile(this.outboxFile, `${JSON.stringify(event)}\n`); + console.error( + `[events] WARNING: event ${event.id} (${event.kind} ${event.ref}) could not be appended ` + + `(${cause instanceof Error ? cause.message : String(cause)}); persisted to the retry outbox ${this.outboxFile} — ` + + `it will be merged on the next load/append. Pending retries are visible via the events health surface.`, + ); + } catch (outboxErr) { + console.error( + `[events] WARNING: event ${event.id} (${event.kind} ${event.ref}) could not be appended and the retry outbox write also failed ` + + `(${outboxErr instanceof Error ? outboxErr.message : String(outboxErr)}); this event is lost.`, + ); + } + } + + /** Merge any outbox records not already in the stream (by stable + * id), persist, and clear the outbox. Runs on load and at the + * start of every append; a still-failing persist leaves the + * outbox in place for the next attempt. */ + private async flushOutbox(): Promise { + let raw: string; + try { + raw = await readFile(this.outboxFile, "utf8"); + } catch { + return; // no outbox — the common case + } + const pending: AuditEvent[] = []; + for (const line of raw.split("\n")) { + if (line.trim() === "") continue; + try { + const parsed: unknown = JSON.parse(line); + if (isAuditEvent(parsed)) pending.push(parsed); + else console.error(`[events] WARNING: dropping an unparseable retry-outbox line in ${this.outboxFile}: ${line.slice(0, 200)}`); + } catch { + console.error(`[events] WARNING: dropping an unparseable retry-outbox line in ${this.outboxFile}: ${line.slice(0, 200)}`); + } + } + const known = new Set(this.events.map((e) => e.id)); + const fresh = pending.filter((e) => !known.has(e.id)); + if (fresh.length > 0) { + this.events = pruneEvents([...this.events, ...fresh]); + try { + await this.persist(); + } catch { + return; // still failing — leave the outbox for the next attempt + } + } + await rm(this.outboxFile, { force: true }); + } + + private async pendingRetryCount(): Promise { + try { + const raw = await readFile(this.outboxFile, "utf8"); + return raw.split("\n").filter((line) => line.trim() !== "").length; + } catch { + return 0; + } + } + + /** The readable failure/integrity surface (#3322 slice A): how + * many records wait in the retry outbox, and whether the stored + * hash chain still verifies. */ + async health(): Promise { + await this.load(); + const verdict = this.integrityViolation + ? { ok: false, detail: this.integrityViolation } + : (() => { + const v = verifyEventChain(this.events.filter((e) => e.hash !== "")); + return v.ok ? { ok: true, detail: "hash chain verifies" } : { ok: false, detail: v.error }; + })(); + return { + version: 2, + events: this.events.length, + pendingRetries: await this.pendingRetryCount(), + integrity: verdict, + }; + } + /** All retained events, newest first, with optional filters. */ - async list(filter: EventFilter = {}): Promise { + async list(filter: EventFilter = {}): Promise { await this.load(); return filterEvents(this.events, filter); } @@ -237,13 +581,46 @@ export class EventsStore { return this.events.some((event) => event.kind === kind && event.ref === ref); } - /** Append one event (retention enforced on append). */ - async record(input: NewStreamEvent): Promise { + /** Append one event (retention enforced on append). On a persist + * failure the record is queued in the durable retry outbox and + * the error is rethrown, so fire-and-forget callers still see the + * failure exactly as before — the record is retried, not lost. */ + async record(input: NewAuditEvent): Promise { await this.load(); + await this.flushOutbox(); const parsed = validateStreamEvent({ ...input, at: input.at ?? new Date().toISOString() }); if (!parsed.ok) throw new Error(parsed.error); - this.events = pruneEvents([...this.events, parsed.value]); - await this.persist(); - return parsed.value; + const extras = validateAuditExtras(input); + if (!extras.ok) throw new Error(extras.error); + const event: AuditEvent = { + ...parsed.value, + version: 2, + id: input.id ?? randomUUID(), + ingestedAt: new Date().toISOString(), + attribution: input.attribution ?? { confidence: "unknown", asserted: false }, + source: input.source ?? { identity: "pm-stack/aggregator" }, + ...(input.corrects !== undefined ? { corrects: input.corrects } : {}), + prevHash: EVENT_CHAIN_GENESIS, + hash: "", + }; + this.events = pruneEvents([...this.events, event]); + try { + await this.persist(); + } catch (err) { + await this.queueForRetry(event, err); + throw err; + } + // persist() rechains in place-order; return the stamped record. + return this.events.find((e) => e.id === event.id) ?? event; + } + + /** Append a correction to an existing record (#3322 slice A): + * corrections are separate, attributable, append-only records — + * the corrected record is never edited. */ + async recordCorrection(targetId: string, input: Omit & { kind?: string; ref?: string }): Promise { + await this.load(); + const target = this.events.find((e) => e.id === targetId); + if (!target) throw new Error(`cannot correct event ${targetId}: no such record in the stream`); + return this.record({ ...input, kind: "correction", ref: input.ref ?? target.ref, corrects: targetId }); } } diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 5f8c651610..5198267507 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -1029,7 +1029,10 @@ async function handler(req: Request): Promise { ref: url.searchParams.get("ref") ?? undefined, actor: url.searchParams.get("actor") ?? undefined, }); - return json({ events }); + // #3322 slice A: the audit health surface rides along — pending + // retry-outbox count + hash-chain integrity verdict. + const health = await eventsStore.health(); + return json({ events, health }); } if (path === "/events") { // #1739: the human page over the same stream /api/events.json diff --git a/pm-stack/aggregator/test/events.test.ts b/pm-stack/aggregator/test/events.test.ts index 2646585cc3..44c6ced28e 100644 --- a/pm-stack/aggregator/test/events.test.ts +++ b/pm-stack/aggregator/test/events.test.ts @@ -187,3 +187,126 @@ describe("events store (#1739)", () => { expect((await store.list()).length).toBe(1); }); }); + +// #3322 slice A: audit v2 — versioned records with stable ids, +// attribution confidence, separate event/ingest timestamps, source +// identity, hash-linked integrity, append-only corrections, v1 +// dual-read, and the durable retry outbox. +import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from "node:fs"; +import { verifyEventChain } from "../src/events.ts"; + +describe("events audit v2 (#3322 slice A)", () => { + test("record stamps v2 audit fields: stable id, ingest time, attribution, source, hash link", async () => { + const { store } = tmpStore(); + const at = new Date(Date.now() - 60_000).toISOString(); + const e = await store.record({ ...base, at }); + expect(e.version).toBe(2); + expect(typeof e.id).toBe("string"); + expect(e.id.length).toBeGreaterThan(0); + // Event time is the supplied `at`; ingest time is stamped by the + // store and is not the event time. + expect(e.at).toBe(at); + expect(Number.isFinite(Date.parse(e.ingestedAt))).toBe(true); + expect(e.ingestedAt).not.toBe(at); + // Unknown actors are marked unknown and never asserted. + expect(e.attribution).toEqual({ confidence: "unknown", asserted: false }); + expect(e.source.identity.length).toBeGreaterThan(0); + expect(e.hash.length).toBe(64); + const second = await store.record({ ...base, summary: "second" }); + expect(second.prevHash).toBe(e.hash); + expect(verifyEventChain(await store.list().then((l) => [...l].reverse())).ok).toBe(true); + const health = await store.health(); + expect(health.integrity.ok).toBe(true); + expect(health.pendingRetries).toBe(0); + expect(health.events).toBe(2); + }); + + test("authenticated attribution must be asserted; unasserted claims are rejected", async () => { + const { store } = tmpStore(); + const ok = await store.record({ + ...base, + attribution: { confidence: "authenticated", asserted: true }, + source: { identity: "dashboard", link: "https://example.test/x" }, + }); + expect(ok.attribution.confidence).toBe("authenticated"); + expect(ok.source.link).toBe("https://example.test/x"); + await expect( + store.record({ ...base, attribution: { confidence: "authenticated", asserted: false } }), + ).rejects.toThrow("asserted"); + }); + + test("v1 store files remain readable and migrate with deterministic ids", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-events-v1-")); + const file = join(dir, "events.json"); + const at = new Date(Date.now() - 60_000).toISOString(); + writeFileSync(file, JSON.stringify({ version: 1, events: [{ ...base, at }] }, null, 2)); + const first = await new EventsStore(file).list(); + expect(first.length).toBe(1); + expect(first[0]?.version).toBe(2); + expect(first[0]?.migratedFromVersion).toBe(1); + expect(first[0]?.attribution.confidence).toBe("unknown"); + const second = await new EventsStore(file).list(); + expect(second[0]?.id).toBe(first[0]?.id); // deterministic migration id + // The next append persists the file as v2. + const store = new EventsStore(file); + await store.record({ ...base, summary: "after migration" }); + const onDisk = JSON.parse(readFileSync(file, "utf8")) as { version: number }; + expect(onDisk.version).toBe(2); + }); + + test("a silently edited stored record fails the integrity check", async () => { + const { file, store } = tmpStore(); + await store.record({ ...base }); + await store.record({ ...base, summary: "second" }); + const onDisk = JSON.parse(readFileSync(file, "utf8")) as { events: { summary: string }[] }; + onDisk.events[0]!.summary = "tampered"; + writeFileSync(file, JSON.stringify(onDisk, null, 2)); + const reloaded = new EventsStore(file); + const health = await reloaded.health(); + expect(health.integrity.ok).toBe(false); + // The stream itself stays readable; the violation is surfaced, + // not hidden. + expect((await reloaded.list()).length).toBe(2); + }); + + test("corrections are separate append-only records naming their target", async () => { + const { store } = tmpStore(); + const original = await store.record({ ...base, summary: "original claim" }); + const correction = await store.recordCorrection(original.id, { + actor: "keeper", + summary: "correction: the claim above was about code#2", + }); + expect(correction.kind).toBe("correction"); + expect(correction.corrects).toBe(original.id); + const list = await store.list(); + expect(list.length).toBe(2); + expect(list.find((e) => e.id === original.id)?.summary).toBe("original claim"); // untouched + await expect(store.recordCorrection("no-such-id", { actor: "keeper", summary: "x" })).rejects.toThrow( + "no such record", + ); + }); + + test("a failed append is persisted to the retry outbox and merged on the next append", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-events-retry-")); + const file = join(dir, "events.json"); + const store = new EventsStore(file); + await store.record({ ...base, summary: "landed" }); + // Make persist fail: the events path becomes a non-empty + // directory, so the atomic rename over it fails — while the + // sibling outbox file stays writable. + rmSync(file); + mkdirSync(file); + writeFileSync(join(file, "occupant"), "x"); + await expect(store.record({ ...base, summary: "queued for retry" })).rejects.toThrow(); + expect(existsSync(store.outboxFile)).toBe(true); + expect(await store.health().then((h) => h.pendingRetries)).toBe(1); + // Recover and append again: the outbox flushes first. + rmSync(file, { recursive: true }); + await store.record({ ...base, summary: "after recovery" }); + const summaries = (await new EventsStore(file).list()).map((e) => e.summary); + expect(summaries).toContain("queued for retry"); + expect(summaries).toContain("after recovery"); + expect(summaries).toContain("landed"); + expect(existsSync(store.outboxFile)).toBe(false); + }); +}); From 621f790d8b1c9a005a04eba60d58750d1af5af7f Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:26:03 -0600 Subject: [PATCH 2/3] =?UTF-8?q?fix(aggregator):=20address=20Codex=20re-rev?= =?UTF-8?q?iew=20on=20audit=20v2=20=E2=80=94=20persist=20before=20outbox?= =?UTF-8?q?=20clear,=20never=20re-stamp=20a=20failed=20chain,=20gate=20v1?= =?UTF-8?q?=20migration=20on=20file=20version=20(#3322)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/aggregator/src/events.ts | 40 +++++++++++++- pm-stack/aggregator/test/events.test.ts | 69 ++++++++++++++++++++++++- 2 files changed, 107 insertions(+), 2 deletions(-) diff --git a/pm-stack/aggregator/src/events.ts b/pm-stack/aggregator/src/events.ts index d171647cd3..a4123be2f6 100644 --- a/pm-stack/aggregator/src/events.ts +++ b/pm-stack/aggregator/src/events.ts @@ -417,6 +417,7 @@ export class EventsStore { if (typeof parsed !== "object" || parsed === null || !Array.isArray((parsed as EventsFile).events)) { throw new Error("store file does not have the expected { events: [...] } shape"); } + const fileVersion = (parsed as { version?: unknown }).version; const rows = (parsed as { events: unknown[] }).events; const normalized: AuditEvent[] = []; for (let i = 0; i < rows.length; i++) { @@ -427,7 +428,14 @@ export class EventsStore { attribution: row.attribution ?? { confidence: "unknown", asserted: false }, source: row.source ?? { identity: "unknown" }, }); - } else if (isStreamEvent(row)) { + } else if (fileVersion === 1 && isStreamEvent(row)) { + // Legacy migration is gated on the FILE version (#3322 + // Codex re-review, PR #5137): in a v2 file, a row that + // fails the v2 shape is a damaged audit record, not a v1 + // row — migrating it would give it an empty hash, exclude + // it from verification, and hide a possible silent edit. + // It falls through to the shape error below instead, and + // the file is quarantined with its bytes preserved. normalized.push(migrateV1Event(row, i)); } else { throw new Error(`event row ${i} does not have the expected StreamEvent/AuditEvent shape`); @@ -474,6 +482,27 @@ export class EventsStore { private persist(): Promise { const run = this.writeChain.then(async () => { + // Never re-stamp a chain that failed verification (#3322 + // Codex re-review, PR #5137): rechain() recomputes every + // hash, so an ordinary append after a tamper would launder + // the altered history into a valid chain and health() would + // report success after a restart, with nobody having + // investigated. Refuse instead — the caller's record is + // queued in the retry outbox, the on-disk evidence stays + // byte-identical, and the violation stays visible until a + // human investigates and repairs the store deliberately. + if (this.integrityViolation) { + throw new Error( + `events store integrity violation: ${this.integrityViolation} — refusing to persist over a chain that failed verification`, + ); + } + const verdict = verifyEventChain(this.events.filter((e) => e.hash !== "")); + if (!verdict.ok) { + this.integrityViolation = verdict.error; + throw new Error( + `events store integrity violation: ${verdict.error} — refusing to persist over a chain that failed verification`, + ); + } this.events = rechain(this.events); const data: EventsFile = { version: 2, events: this.events }; await mkdir(dirname(this.file), { recursive: true }); @@ -531,6 +560,15 @@ export class EventsStore { const fresh = pending.filter((e) => !known.has(e.id)); if (fresh.length > 0) { this.events = pruneEvents([...this.events, ...fresh]); + } + // Clear the outbox only after a successful persist of everything + // it held (#3322 Codex re-review, PR #5137): a pending record can + // already be in memory — record() keeps the event in this.events + // when its persist fails — so "already known" does not mean + // durable. Clearing on presence alone dropped the earlier record + // when the next append also failed and the process restarted: + // only the newer failure was re-queued. + if (fresh.length > 0 || pending.length > 0) { try { await this.persist(); } catch { diff --git a/pm-stack/aggregator/test/events.test.ts b/pm-stack/aggregator/test/events.test.ts index 44c6ced28e..487bb8f404 100644 --- a/pm-stack/aggregator/test/events.test.ts +++ b/pm-stack/aggregator/test/events.test.ts @@ -192,7 +192,7 @@ describe("events store (#1739)", () => { // attribution confidence, separate event/ingest timestamps, source // identity, hash-linked integrity, append-only corrections, v1 // dual-read, and the durable retry outbox. -import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, readdirSync } from "node:fs"; import { verifyEventChain } from "../src/events.ts"; describe("events audit v2 (#3322 slice A)", () => { @@ -309,4 +309,71 @@ describe("events audit v2 (#3322 slice A)", () => { expect(summaries).toContain("landed"); expect(existsSync(store.outboxFile)).toBe(false); }); + + test("outbox records already in memory are not cleared until a persist succeeds", async () => { + // Codex re-review on PR #5137 (P1): record() keeps a failed event + // in memory, so the next append's flush saw it as "known", skipped + // the persist, and cleared the outbox — a second failure then + // re-queued only the newer event and a restart lost the first. + const dir = mkdtempSync(join(tmpdir(), "agg-events-outbox-persist-")); + const file = join(dir, "events.json"); + const store = new EventsStore(file); + await store.record({ ...base, summary: "landed" }); + rmSync(file); + mkdirSync(file); + writeFileSync(join(file, "occupant"), "x"); + await expect(store.record({ ...base, summary: "first failure" })).rejects.toThrow(); + await expect(store.record({ ...base, summary: "second failure" })).rejects.toThrow(); + // Both failures must still be queued: the first was never made + // durable, so its outbox entry may not be cleared. + expect(await store.health().then((h) => h.pendingRetries)).toBe(2); + rmSync(file, { recursive: true }); + await store.record({ ...base, summary: "after recovery" }); + const summaries = (await new EventsStore(file).list()).map((e) => e.summary); + expect(summaries).toContain("first failure"); + expect(summaries).toContain("second failure"); + expect(summaries).toContain("after recovery"); + expect(summaries).toContain("landed"); + expect(existsSync(store.outboxFile)).toBe(false); + }); + + test("a chain that failed verification is not re-stamped by a later append", async () => { + // Codex re-review on PR #5137 (P2): persist() re-stamped every + // hash, so one ordinary append after a tamper laundered the + // altered history into a valid chain and the violation vanished + // on restart. Persists must refuse until a human investigates. + const { file, store } = tmpStore(); + await store.record({ ...base }); + await store.record({ ...base, summary: "second" }); + const onDisk = JSON.parse(readFileSync(file, "utf8")) as { events: { summary: string }[] }; + onDisk.events[0]!.summary = "tampered"; + writeFileSync(file, JSON.stringify(onDisk, null, 2)); + const reloaded = new EventsStore(file); + expect((await reloaded.health()).integrity.ok).toBe(false); + await expect(reloaded.record({ ...base, summary: "routine append" })).rejects.toThrow("integrity violation"); + // The on-disk evidence is untouched and a fresh process still + // sees the violation; the refused append waits in the outbox. + expect(readFileSync(file, "utf8")).toContain("tampered"); + const fresh = new EventsStore(file); + expect((await fresh.health()).integrity.ok).toBe(false); + expect(existsSync(reloaded.outboxFile)).toBe(true); + }); + + test("a damaged record in a v2 file is quarantined, not migrated as v1", async () => { + // Codex re-review on PR #5137 (P2): deleting a v2 record's hash + // made it fail the v2 shape but pass the v1 shape, so it was + // silently "migrated" with an empty hash and excluded from + // verification. Migration is gated on the file version now. + const dir = mkdtempSync(join(tmpdir(), "agg-events-damaged-v2-")); + const file = join(dir, "events.json"); + const store = new EventsStore(file); + await store.record({ ...base }); + const onDisk = JSON.parse(readFileSync(file, "utf8")) as { version: number; events: Record[] }; + expect(onDisk.version).toBe(2); + delete onDisk.events[0]!.hash; + writeFileSync(file, JSON.stringify(onDisk, null, 2)); + const reloaded = new EventsStore(file); + expect(await reloaded.list()).toEqual([]); + expect(readdirSync(dir).some((name) => name.includes(".corrupt-"))).toBe(true); + }); }); From 378ec8f211809de4ee6302fb4846072bb2cc13e6 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:00:27 -0600 Subject: [PATCH 3/3] fix(aggregator): disposition Codex round-2 findings on audit event v2 (#3322) - Verify the full stored chain before retention pruning in doLoad, so a backdated tamper cannot escape verification. - Reject v2 main-file records with an empty hash as damaged (quarantine); unhashed records stay legitimate only for v1 migration rows and retry-outbox lines. - Serialize the whole record() lifecycle (flush/append/retry) on recordChain so an outbox unlink cannot erase a concurrently queued retry. - Caller-supplied event ids replay idempotently: record() returns the existing record instead of appending a twin. Tests: events+orchestration 62 pass; full aggregator suite 1424 pass on re-run (one unidentified flaky failure in the first full run did not reproduce in two subsequent full runs). --- pm-stack/aggregator/src/events.ts | 67 ++++++++++++++++++++--- pm-stack/aggregator/test/events.test.ts | 72 +++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 7 deletions(-) diff --git a/pm-stack/aggregator/src/events.ts b/pm-stack/aggregator/src/events.ts index a4123be2f6..fb3b58db55 100644 --- a/pm-stack/aggregator/src/events.ts +++ b/pm-stack/aggregator/src/events.ts @@ -382,6 +382,7 @@ export class EventsStore { private events: AuditEvent[] = []; private loadPromise: Promise | null = null; private writeChain: Promise = Promise.resolve(); + private recordChain: Promise = Promise.resolve(); private writeSeq = 0; private integrityViolation: string | null = null; @@ -422,6 +423,18 @@ export class EventsStore { const normalized: AuditEvent[] = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; + if (isAuditEvent(row) && fileVersion === 2 && row.hash === "") { + // A v2 main-file record with an empty hash is damaged, not + // unhashed-by-design (#3322 Codex re-review, PR #5137): + // persist() rechains before every write, so a record the + // store wrote always carries a hash. Accepting an empty + // one would exclude it from verification (both checks + // filter hash !== "") and let a silent edit pass as + // healthy. Unhashed records remain legitimate ONLY as v1 + // migration rows (fileVersion 1, handled below) and as + // retry-outbox lines (parsed in flushOutbox, never here). + throw new Error(`event row ${i} is a v2 audit record with an empty hash`); + } if (isAuditEvent(row)) { normalized.push({ ...row, @@ -441,13 +454,20 @@ export class EventsStore { throw new Error(`event row ${i} does not have the expected StreamEvent/AuditEvent shape`); } } - this.events = pruneEvents(normalized); // Integrity is checked against the STORED hashes before any - // persist can re-stamp them: a mismatch means the file was - // altered outside the store. The records still load (the - // stream stays readable) but the violation is loud and is - // reported by health() until a human looks. - const verdict = verifyEventChain(this.events.filter((e) => e.hash !== "")); + // persist can re-stamp them — and before retention pruning + // drops any record (#3322 Codex re-review, PR #5137): pruning + // first would let an edit hide by also backdating the altered + // record past the retention cutoff (it would be dropped + // unverified, and the remaining chain's first record is a + // trusted retention anchor), so the full normalized chain + // verifies first and pruning applies only afterwards. A + // mismatch means the file was altered outside the store. The + // records still load (the stream stays readable) but the + // violation is loud and is reported by health() until a + // human looks. + const verdict = verifyEventChain(normalized.filter((e) => e.hash !== "")); + this.events = pruneEvents(normalized); if (!verdict.ok) { this.integrityViolation = verdict.error; console.error( @@ -622,14 +642,47 @@ export class EventsStore { /** Append one event (retention enforced on append). On a persist * failure the record is queued in the durable retry outbox and * the error is rethrown, so fire-and-forget callers still see the - * failure exactly as before — the record is retried, not lost. */ + * failure exactly as before — the record is retried, not lost. + * Whole calls are serialized on recordChain (#3322 Codex + * re-review, PR #5137): flushOutbox's outbox removal and a failed + * append's queueForRetry are both file operations on the outbox, + * and interleaved they lose retries — a flush that read the + * outbox before a concurrent failure queued its record could + * unlink the file after the queue, deleting a record no + * successful persist had ever held. Serializing the complete + * flush/append/retry lifecycle makes the removal always cover + * exactly the snapshot that was persisted. */ async record(input: NewAuditEvent): Promise { + let result!: AuditEvent; + const run = this.recordChain.then(async () => { + result = await this.recordSerialized(input); + }); + this.recordChain = run.then( + () => {}, + () => {}, + ); + await run; + return result; + } + + private async recordSerialized(input: NewAuditEvent): Promise { await this.load(); await this.flushOutbox(); const parsed = validateStreamEvent({ ...input, at: input.at ?? new Date().toISOString() }); if (!parsed.ok) throw new Error(parsed.error); const extras = validateAuditExtras(input); if (!extras.ok) throw new Error(extras.error); + // A caller-supplied id is a stable identity (#3322 Codex + // re-review, PR #5137): replaying it returns the existing record + // instead of appending a twin that the id can no longer + // unambiguously name (record() and recordCorrection() both + // resolve ids with find()). flushOutbox above has already + // merged any pending retry with this id into the stream, so a + // retry of a queued-but-unlanded append replays correctly too. + if (input.id !== undefined) { + const existing = this.events.find((e) => e.id === input.id); + if (existing) return existing; + } const event: AuditEvent = { ...parsed.value, version: 2, diff --git a/pm-stack/aggregator/test/events.test.ts b/pm-stack/aggregator/test/events.test.ts index 487bb8f404..50a220495a 100644 --- a/pm-stack/aggregator/test/events.test.ts +++ b/pm-stack/aggregator/test/events.test.ts @@ -376,4 +376,76 @@ describe("events audit v2 (#3322 slice A)", () => { expect(await reloaded.list()).toEqual([]); expect(readdirSync(dir).some((name) => name.includes(".corrupt-"))).toBe(true); }); + + test("a stored record backdated past retention is still integrity-checked (PR #5137 codex)", async () => { + // Pruning ran before verification, so altering a record AND + // backdating it past the 30-day cutoff removed it before its + // hash was ever checked and health reported a healthy stream. + const { file, store } = tmpStore(); + await store.record({ ...base }); + const onDisk = JSON.parse(readFileSync(file, "utf8")) as { events: { at: string }[] }; + onDisk.events[0]!.at = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(); + writeFileSync(file, JSON.stringify(onDisk, null, 2)); + const reloaded = new EventsStore(file); + expect((await reloaded.health()).integrity.ok).toBe(false); + }); + + test("a v2 record with an empty hash is quarantined as damaged (PR #5137 codex)", async () => { + // An empty hash passed the shape check and was then excluded + // from verification by the hash !== "" filters, so a tampered + // summary with hash:"" reported healthy integrity. + const dir = mkdtempSync(join(tmpdir(), "agg-events-empty-hash-")); + const file = join(dir, "events.json"); + const store = new EventsStore(file); + await store.record({ ...base }); + const onDisk = JSON.parse(readFileSync(file, "utf8")) as { version: number; events: Record[] }; + expect(onDisk.version).toBe(2); + onDisk.events[0]!.hash = ""; + onDisk.events[0]!.summary = "tampered"; + writeFileSync(file, JSON.stringify(onDisk, null, 2)); + const reloaded = new EventsStore(file); + expect(await reloaded.list()).toEqual([]); + expect(readdirSync(dir).some((name) => name.includes(".corrupt-"))).toBe(true); + }); + + test("a caller-supplied id replays idempotently instead of appending a twin (PR #5137 codex)", async () => { + const { store } = tmpStore(); + const first = await store.record({ ...base, id: "evt-caller-1", summary: "first version" }); + const replay = await store.record({ ...base, id: "evt-caller-1", summary: "second version" }); + expect(replay.id).toBe(first.id); + expect(replay.summary).toBe("first version"); + const list = await store.list(); + expect(list.filter((e) => e.id === "evt-caller-1")).toHaveLength(1); + // The id resolves unambiguously for corrections. + const correction = await store.recordCorrection("evt-caller-1", { actor: "keeper", summary: "correction" }); + expect(correction.corrects).toBe("evt-caller-1"); + }); + + test("concurrent failed appends both reach the retry outbox; neither flush erases the other (PR #5137 codex)", async () => { + // flushOutbox's unlink raced queueForRetry: a flush could delete + // a record queued after its snapshot was persisted. The record + // lifecycle is serialized now, so concurrent failures queue + // independently and both land on recovery. + const dir = mkdtempSync(join(tmpdir(), "agg-events-concurrent-retry-")); + const file = join(dir, "events.json"); + const store = new EventsStore(file); + await store.record({ ...base, summary: "landed" }); + rmSync(file); + mkdirSync(file); + writeFileSync(join(file, "occupant"), "x"); + const results = await Promise.allSettled([ + store.record({ ...base, summary: "concurrent failure A" }), + store.record({ ...base, summary: "concurrent failure B" }), + ]); + expect(results.map((r) => r.status)).toEqual(["rejected", "rejected"]); + expect(await store.health().then((h) => h.pendingRetries)).toBe(2); + rmSync(file, { recursive: true }); + await store.record({ ...base, summary: "after recovery" }); + const summaries = (await new EventsStore(file).list()).map((e) => e.summary); + expect(summaries).toContain("concurrent failure A"); + expect(summaries).toContain("concurrent failure B"); + expect(summaries).toContain("after recovery"); + expect(summaries).toContain("landed"); + expect(existsSync(store.outboxFile)).toBe(false); + }); });