diff --git a/pm-stack/aggregator/src/actions.ts b/pm-stack/aggregator/src/actions.ts index 3f4ec38097..2afbe82f71 100644 --- a/pm-stack/aggregator/src/actions.ts +++ b/pm-stack/aggregator/src/actions.ts @@ -432,15 +432,44 @@ export class ActionsStore { } private async doLoad(): Promise { + // #1452: a missing file is the only silent empty start ("no store + // yet"). An unparseable or wrongly-shaped file is NOT an empty + // store: it is the append-only audit history, so quarantine the + // original bytes to .corrupt-, start empty, and + // log loudly — the next persist then writes a fresh valid file and + // never touches the quarantined copy. + let raw: string; try { - const parsed: unknown = JSON.parse(await readFile(this.file, "utf8")); - if (typeof parsed === "object" && parsed !== null && Array.isArray((parsed as ActionsFile).actions)) { - this.actions = (parsed as ActionsFile).actions.filter( - (a) => typeof a === "object" && a !== null && typeof (a as DashAction).id === "string", - ); - } + raw = await readFile(this.file, "utf8"); } catch { this.actions = []; // no store yet — the first write creates it + return; + } + try { + const parsed: unknown = JSON.parse(raw); + if (typeof parsed !== "object" || parsed === null || !Array.isArray((parsed as ActionsFile).actions)) { + throw new Error("store file does not have the expected { actions: [...] } shape"); + } + this.actions = (parsed as ActionsFile).actions.filter( + (a) => typeof a === "object" && a !== null && typeof (a as DashAction).id === "string", + ); + } catch (err) { + this.actions = []; + const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`; + try { + await rename(this.file, quarantined); + console.error( + `[actions] WARNING: actions store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); ` + + `quarantined the original bytes to ${quarantined} and started empty. ` + + `The quarantined file holds the prior audit history — do not delete it.`, + ); + } catch (renameErr) { + console.error( + `[actions] WARNING: actions store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}) ` + + `and could not be quarantined (${renameErr instanceof Error ? renameErr.message : String(renameErr)}); starting empty — ` + + `the next persist will overwrite it, so copy it aside now to preserve the audit history.`, + ); + } } } diff --git a/pm-stack/aggregator/src/comments.ts b/pm-stack/aggregator/src/comments.ts index 78c53c33bc..f32f968ed7 100644 --- a/pm-stack/aggregator/src/comments.ts +++ b/pm-stack/aggregator/src/comments.ts @@ -112,15 +112,44 @@ export class CommentsStore { } private async doLoad(): Promise { + // #1452: a missing file is the only silent empty start ("no store + // yet"). An unparseable or wrongly-shaped file is NOT an empty + // store: it is the append-only audit history, so quarantine the + // original bytes to .corrupt-, start empty, and + // log loudly — the next persist then writes a fresh valid file and + // never touches the quarantined copy. + let raw: string; try { - const parsed: unknown = JSON.parse(await readFile(this.file, "utf8")); - if (typeof parsed === "object" && parsed !== null && Array.isArray((parsed as CommentsFile).comments)) { - this.comments = (parsed as CommentsFile).comments.filter( - (c) => typeof c === "object" && c !== null && typeof (c as DashComment).id === "string", - ); - } + raw = await readFile(this.file, "utf8"); } catch { this.comments = []; // no store yet — the first write creates it + return; + } + try { + const parsed: unknown = JSON.parse(raw); + if (typeof parsed !== "object" || parsed === null || !Array.isArray((parsed as CommentsFile).comments)) { + throw new Error("store file does not have the expected { comments: [...] } shape"); + } + this.comments = (parsed as CommentsFile).comments.filter( + (c) => typeof c === "object" && c !== null && typeof (c as DashComment).id === "string", + ); + } catch (err) { + this.comments = []; + const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`; + try { + await rename(this.file, quarantined); + console.error( + `[comments] WARNING: comments store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); ` + + `quarantined the original bytes to ${quarantined} and started empty. ` + + `The quarantined file holds the prior audit history — do not delete it.`, + ); + } catch (renameErr) { + console.error( + `[comments] WARNING: comments store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}) ` + + `and could not be quarantined (${renameErr instanceof Error ? renameErr.message : String(renameErr)}); starting empty — ` + + `the next persist will overwrite it, so copy it aside now to preserve the audit history.`, + ); + } } } diff --git a/pm-stack/aggregator/test/store-corrupt.test.ts b/pm-stack/aggregator/test/store-corrupt.test.ts new file mode 100644 index 0000000000..b83ee911b4 --- /dev/null +++ b/pm-stack/aggregator/test/store-corrupt.test.ts @@ -0,0 +1,126 @@ +// #1452: the dashboard stores are the append-only audit history. A +// missing file is "no store yet" (silent empty start); an unparseable +// or wrongly-shaped file must be quarantined to +// .corrupt- with its original bytes preserved, never +// silently overwritten by the next persist. +import { describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ActionsStore, type NewAction } from "../src/actions.ts"; +import { CommentsStore } from "../src/comments.ts"; + +const drew = { kind: "drew" as const, id: "drew", label: "Drew" }; + +let tokenSeq = 0; +const newAction = (): NewAction => ({ + clientToken: `ct-corrupt-${++tokenSeq}-abcdefgh`, + kind: "triage", + verb: "acknowledge", + objectRef: "orch:item-1", + payload: {}, + author: drew, +}); + +const quarantinedIn = (dir: string, base: string) => + readdirSync(dir).filter((f) => f.startsWith(`${base}.corrupt-`)); + +describe("actions store corruption handling (#1452)", () => { + test("missing file -> empty store, no quarantine", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-actions-missing-")); + const file = join(dir, "actions.json"); + const store = new ActionsStore(file); + expect(await store.all()).toEqual([]); + expect(existsSync(file)).toBe(false); + expect(quarantinedIn(dir, "actions.json")).toEqual([]); + }); + + test("corrupt file -> quarantine with original bytes, empty store, fresh persist is valid and leaves the quarantine untouched", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-actions-corrupt-")); + const file = join(dir, "actions.json"); + const garbage = '{"version":1,"actions":[{"id":"da-1"'; // truncated write + writeFileSync(file, garbage); + const store = new ActionsStore(file); + expect(await store.all()).toEqual([]); + const quarantined = quarantinedIn(dir, "actions.json"); + expect(quarantined.length).toBe(1); + expect(readFileSync(join(dir, quarantined[0]), "utf8")).toBe(garbage); + expect(existsSync(file)).toBe(false); + // The next persist writes a fresh valid version:1 file. + await store.add(newAction()); + const persisted = JSON.parse(readFileSync(file, "utf8")); + expect(persisted.version).toBe(1); + expect(persisted.actions.length).toBe(1); + // The quarantined copy is untouched by the persist. + expect(readFileSync(join(dir, quarantined[0]), "utf8")).toBe(garbage); + expect(quarantinedIn(dir, "actions.json").length).toBe(1); + }); + + test("wrongly-shaped file -> quarantine, empty store", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-actions-shape-")); + const file = join(dir, "actions.json"); + writeFileSync(file, JSON.stringify({ version: 1, nope: [] })); + const store = new ActionsStore(file); + expect(await store.all()).toEqual([]); + expect(quarantinedIn(dir, "actions.json").length).toBe(1); + }); + + test("valid file -> loads unchanged, no quarantine", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-actions-valid-")); + const file = join(dir, "actions.json"); + const first = new ActionsStore(file); + await first.add(newAction()); + const reloaded = new ActionsStore(file); + expect((await reloaded.all()).length).toBe(1); + expect(quarantinedIn(dir, "actions.json")).toEqual([]); + }); +}); + +describe("comments store corruption handling (#1452)", () => { + test("missing file -> empty store, no quarantine", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-comments-missing-")); + const file = join(dir, "comments.json"); + const store = new CommentsStore(file); + expect(await store.all()).toEqual([]); + expect(existsSync(file)).toBe(false); + expect(quarantinedIn(dir, "comments.json")).toEqual([]); + }); + + test("corrupt file -> quarantine with original bytes, empty store, fresh persist is valid and leaves the quarantine untouched", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-comments-corrupt-")); + const file = join(dir, "comments.json"); + const garbage = '{"version":1,"comments":[{"id":"dc-1","body":"audit'; + writeFileSync(file, garbage); + const store = new CommentsStore(file); + expect(await store.all()).toEqual([]); + const quarantined = quarantinedIn(dir, "comments.json"); + expect(quarantined.length).toBe(1); + expect(readFileSync(join(dir, quarantined[0]), "utf8")).toBe(garbage); + expect(existsSync(file)).toBe(false); + await store.add({ objectRef: "gh:developing-today/code#1452", kind: "note", author: drew, body: "fresh start" }); + const persisted = JSON.parse(readFileSync(file, "utf8")); + expect(persisted.version).toBe(1); + expect(persisted.comments.length).toBe(1); + expect(readFileSync(join(dir, quarantined[0]), "utf8")).toBe(garbage); + expect(quarantinedIn(dir, "comments.json").length).toBe(1); + }); + + test("wrongly-shaped file -> quarantine, empty store", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-comments-shape-")); + const file = join(dir, "comments.json"); + writeFileSync(file, JSON.stringify({ version: 1, nope: [] })); + const store = new CommentsStore(file); + expect(await store.all()).toEqual([]); + expect(quarantinedIn(dir, "comments.json").length).toBe(1); + }); + + test("valid file -> loads unchanged, no quarantine", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-comments-valid-")); + const file = join(dir, "comments.json"); + const first = new CommentsStore(file); + await first.add({ objectRef: "gh:developing-today/code#1452", kind: "note", author: drew, body: "kept" }); + const reloaded = new CommentsStore(file); + expect((await reloaded.all()).length).toBe(1); + expect(quarantinedIn(dir, "comments.json")).toEqual([]); + }); +});