diff --git a/pm-stack/aggregator/src/actions.ts b/pm-stack/aggregator/src/actions.ts index 53e3239f7e..eb28d6dadc 100644 --- a/pm-stack/aggregator/src/actions.ts +++ b/pm-stack/aggregator/src/actions.ts @@ -64,7 +64,8 @@ import { isObjectRef, validateAuthor } from "./comments.ts"; import type { ViewFilters } from "./views.ts"; import { validateViewFilters, validateViewName } from "./views.ts"; import type { DashAuthor, RefKey, SessionSource } from "./model.ts"; -import { isRecord } from "./validate.ts"; +import { isNonEmptyString, isRecord, parseIsoDate } from "./validate.ts"; +import { archiveStoreBytes, quarantineUnreadableStore, quarantineWholeStore, type InvalidStoreRecord, type StoreArchive } from "./store-recovery.ts"; export type DashActionKind = "triage" | "status-request" | "session" | "preference"; @@ -121,6 +122,36 @@ export const VERBS_BY_KIND: Record = preference: ["set-delegation-default", "set-needs-order", "save-view", "rename-view", "delete-view", "set-default-view"], }; +const ACTION_KINDS = new Set(["triage", "status-request", "session", "preference"]); +const ACTION_STATES = new Set(["new", "applied", "rejected", "superseded"]); + +function actionRecordProblem(value: unknown): string | null { + if (!isRecord(value)) return "record must be an object"; + if (!isNonEmptyString(value.id)) return "id must be a non-empty string"; + if (!isObjectRef(value.objectRef)) return "objectRef must be a non-empty ref string"; + if (typeof value.kind !== "string" || !ACTION_KINDS.has(value.kind as DashActionKind)) { + return "kind must be triage, status-request, session, or preference"; + } + const kind = value.kind as DashActionKind; + if (typeof value.verb !== "string" || !VERBS_BY_KIND[kind].includes(value.verb as DashActionVerb)) { + return "verb must be supported for the action kind"; + } + if (parseIsoDate(value.createdAt) === null) return "createdAt must be a valid ISO date/time string"; + if (!isRecord(value.payload)) return "payload must be an object"; + if (!validateAuthor(value.author)) return "author must have a supported kind, id, and label"; + if (typeof value.state !== "string" || !ACTION_STATES.has(value.state)) { + return "state must be new, applied, rejected, or superseded"; + } + // Pre-token audit rows remain readable; when a token exists it must be + // a string so dedupe comparisons have their intended semantics. + if (value.clientToken !== undefined && !isNonEmptyString(value.clientToken)) { + return "clientToken must be a non-empty string when present"; + } + // Historical payloads are intentionally only required to be records; + // individual verbs tolerate older payload shapes at their consumers. + return null; +} + export interface DashActionPayload { /** snooze horizon (ISO). */ until?: string; @@ -458,11 +489,15 @@ export function newClientToken(): string { export class ActionsStore { private actions: DashAction[] = []; + private fileExtras: Record = {}; private loadPromise: Promise | null = null; private writeChain: Promise = Promise.resolve(); private writeSeq = 0; - constructor(private readonly file: string) {} + constructor( + private readonly file: string, + private readonly archive: StoreArchive = archiveStoreBytes, + ) {} // The load is memoized as a single promise (#1509): the old // loaded-flag version let concurrent first callers proceed before @@ -480,12 +515,13 @@ export class ActionsStore { // 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; + let raw: Buffer; try { - raw = await readFile(this.file, "utf8"); + raw = await readFile(this.file); } catch (err) { if ((err as { code?: unknown })?.code === "ENOENT") { this.actions = []; // no store yet — the first write creates it + this.fileExtras = {}; return; } // #2980: a non-ENOENT read failure (EACCES, a transient I/O error, @@ -494,49 +530,60 @@ export class ActionsStore { // like the corrupt case below — quarantine the original bytes // before starting empty, and log loudly — so the next persist // cannot silently overwrite history the read never saw. - this.actions = []; - const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`; + let quarantined: string; try { - await rename(this.file, quarantined); - console.error( - `[actions] WARNING: actions store ${this.file} could not be read (${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.`, - ); + quarantined = await quarantineUnreadableStore(this.file); } catch (renameErr) { - console.error( - `[actions] WARNING: actions store ${this.file} could not be read (${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.`, + throw new Error( + `[actions] refusing to continue because ${this.file} could not be read or quarantined: ${renameErr instanceof Error ? renameErr.message : String(renameErr)}`, + { cause: err }, ); } + this.actions = []; + this.fileExtras = {}; + console.error( + `[actions] WARNING: actions store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}); ` + + `quarantined the original to ${quarantined} and started empty. The quarantined item holds the prior audit history — do not delete it.`, + ); return; } + + let parsed: unknown; 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) => isRecord(a) && typeof a.id === "string" && isRecord(a.payload), - ); + parsed = JSON.parse(raw.toString("utf8")); } catch (err) { + const quarantined = await quarantineWholeStore(this.file, raw, this.archive); 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.`, - ); - } + this.fileExtras = {}; + console.error(`[actions] WARNING: actions store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); quarantined original bytes to ${quarantined} and started empty.`); + return; + } + if (!isRecord(parsed) || !Array.isArray(parsed.actions)) { + const quarantined = await quarantineWholeStore(this.file, raw, this.archive); + this.actions = []; + this.fileExtras = {}; + console.error(`[actions] WARNING: actions store ${this.file} has the wrong envelope shape; quarantined original bytes to ${quarantined} and started empty.`); + return; + } + + this.fileExtras = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "version" && key !== "actions")); + const valid: DashAction[] = []; + const invalid: InvalidStoreRecord[] = []; + parsed.actions.forEach((action, index) => { + const reason = actionRecordProblem(action); + if (reason) invalid.push({ index, reason }); + else valid.push(action as DashAction); + }); + this.actions = valid; + if (invalid.length > 0) { + const quarantined = await this.archive(this.file, raw, invalid); + console.error( + `[actions] WARNING: quarantined ${invalid.length} malformed record(s) from ${this.file}; ` + + `original bytes: ${quarantined}; index/reason diagnostics: ${quarantined}.diagnostics.json.`, + ); + // Do not rewrite the active audit log until the original bytes and + // the per-record diagnostics are durable. + await this.persist(); } } @@ -544,7 +591,7 @@ export class ActionsStore { // CommentsStore.persist (#1509). private persist(): Promise { const run = this.writeChain.then(async () => { - const data: ActionsFile = { version: 1, actions: this.actions }; + const data = { ...this.fileExtras, version: 1 as const, actions: this.actions }; await mkdir(dirname(this.file), { recursive: true }); const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`; await writeFile(tmp, JSON.stringify(data, null, 2)); diff --git a/pm-stack/aggregator/src/comments.ts b/pm-stack/aggregator/src/comments.ts index 64f0727a1c..ecf21845e4 100644 --- a/pm-stack/aggregator/src/comments.ts +++ b/pm-stack/aggregator/src/comments.ts @@ -26,6 +26,8 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import type { DashAuthor, DashComment, DashCommentKind, RefKey } from "./model.ts"; import { refUrl } from "./model.ts"; +import { archiveStoreBytes, quarantineUnreadableStore, quarantineWholeStore, type InvalidStoreRecord, type StoreArchive } from "./store-recovery.ts"; +import { isNonEmptyString, isRecord, parseIsoDate } from "./validate.ts"; export interface CommentsFile { version: 1; @@ -33,6 +35,42 @@ export interface CommentsFile { } const GH_REF = /^[\w.-]+\/[\w.-]+#\d+$/; +const COMMENT_KINDS = new Set(["message", "note", "github"]); + +function commentRecordProblem(value: unknown): string | null { + if (!isRecord(value)) return "record must be an object"; + if (!isNonEmptyString(value.id)) return "id must be a non-empty string"; + if (!isObjectRef(value.objectRef)) return "objectRef must be a non-empty ref string"; + if (typeof value.kind !== "string" || !COMMENT_KINDS.has(value.kind as DashCommentKind)) { + return "kind must be message, note, or github"; + } + if (parseIsoDate(value.createdAt) === null) return "createdAt must be a valid ISO date/time string"; + if (!validateAuthor(value.author)) return "author must have a supported kind, id, and label"; + if (typeof value.body !== "string") return "body must be a string"; + if ( + value.kind === "message" && + value.triageState !== undefined && + value.triageState !== "new" && + value.triageState !== "triaged" + ) { + return "message triageState must be new or triaged"; + } + if (value.kind === "github") { + if (value.githubRef !== undefined && (typeof value.githubRef !== "string" || !GH_REF.test(value.githubRef))) { + return "githubRef must be owner/repo#N"; + } + if ( + value.githubState !== undefined && + value.githubState !== "pending" && + value.githubState !== "posted" && + value.githubState !== "failed" + ) { + return "githubState must be pending, posted, or failed"; + } + if (value.githubState === "pending" && value.githubRef === undefined) return "pending github comments require githubRef"; + } + return null; +} export function isObjectRef(s: unknown): s is string { return typeof s === "string" && s.length > 0 && s.length <= 300 && !/\s/.test(s); @@ -96,11 +134,15 @@ export function newCommentId(now = new Date()): string { export class CommentsStore { private comments: DashComment[] = []; + private fileExtras: Record = {}; private loadPromise: Promise | null = null; private writeChain: Promise = Promise.resolve(); private writeSeq = 0; - constructor(private readonly file: string) {} + constructor( + private readonly file: string, + private readonly archive: StoreArchive = archiveStoreBytes, + ) {} // The load is memoized as a single promise (#1509): the old // loaded-flag version let concurrent first callers proceed before @@ -118,12 +160,13 @@ export class CommentsStore { // 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; + let raw: Buffer; try { - raw = await readFile(this.file, "utf8"); + raw = await readFile(this.file); } catch (err) { if ((err as { code?: unknown })?.code === "ENOENT") { this.comments = []; // no store yet — the first write creates it + this.fileExtras = {}; return; } // #2980: a non-ENOENT read failure (EACCES, a transient I/O error, @@ -132,49 +175,60 @@ export class CommentsStore { // like the corrupt case below — quarantine the original bytes // before starting empty, and log loudly — so the next persist // cannot silently overwrite history the read never saw. - this.comments = []; - const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`; + let quarantined: string; try { - await rename(this.file, quarantined); - console.error( - `[comments] WARNING: comments store ${this.file} could not be read (${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.`, - ); + quarantined = await quarantineUnreadableStore(this.file); } catch (renameErr) { - console.error( - `[comments] WARNING: comments store ${this.file} could not be read (${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.`, + throw new Error( + `[comments] refusing to continue because ${this.file} could not be read or quarantined: ${renameErr instanceof Error ? renameErr.message : String(renameErr)}`, + { cause: err }, ); } + this.comments = []; + this.fileExtras = {}; + console.error( + `[comments] WARNING: comments store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}); ` + + `quarantined the original to ${quarantined} and started empty. The quarantined item holds the prior audit history — do not delete it.`, + ); return; } + + let parsed: unknown; 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", - ); + parsed = JSON.parse(raw.toString("utf8")); } catch (err) { + const quarantined = await quarantineWholeStore(this.file, raw, this.archive); 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.`, - ); - } + this.fileExtras = {}; + console.error(`[comments] WARNING: comments store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); quarantined original bytes to ${quarantined} and started empty.`); + return; + } + if (!isRecord(parsed) || !Array.isArray(parsed.comments)) { + const quarantined = await quarantineWholeStore(this.file, raw, this.archive); + this.comments = []; + this.fileExtras = {}; + console.error(`[comments] WARNING: comments store ${this.file} has the wrong envelope shape; quarantined original bytes to ${quarantined} and started empty.`); + return; + } + + this.fileExtras = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "version" && key !== "comments")); + const valid: DashComment[] = []; + const invalid: InvalidStoreRecord[] = []; + parsed.comments.forEach((comment, index) => { + const reason = commentRecordProblem(comment); + if (reason) invalid.push({ index, reason }); + else valid.push(comment as DashComment); + }); + this.comments = valid; + if (invalid.length > 0) { + const quarantined = await this.archive(this.file, raw, invalid); + console.error( + `[comments] WARNING: quarantined ${invalid.length} malformed record(s) from ${this.file}; ` + + `original bytes: ${quarantined}; index/reason diagnostics: ${quarantined}.diagnostics.json.`, + ); + // The exact source bytes and diagnostics are durable before this + // atomic rewrite removes malformed rows from the active store. + await this.persist(); } } @@ -188,7 +242,7 @@ export class CommentsStore { // does not poison the chain for later writes. private persist(): Promise { const run = this.writeChain.then(async () => { - const data: CommentsFile = { version: 1, comments: this.comments }; + const data = { ...this.fileExtras, version: 1 as const, comments: this.comments }; await mkdir(dirname(this.file), { recursive: true }); const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`; await writeFile(tmp, JSON.stringify(data, null, 2)); diff --git a/pm-stack/aggregator/src/store-recovery.ts b/pm-stack/aggregator/src/store-recovery.ts new file mode 100644 index 0000000000..1cd2646f5f --- /dev/null +++ b/pm-stack/aggregator/src/store-recovery.ts @@ -0,0 +1,46 @@ +import { randomUUID } from "node:crypto"; +import { rename, unlink, writeFile } from "node:fs/promises"; + +export interface InvalidStoreRecord { + index: number; + reason: string; +} + +export type StoreArchive = ( + file: string, + raw: Uint8Array, + invalidRecords?: readonly InvalidStoreRecord[], +) => Promise; + +function archivePath(file: string): string { + const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); + return `${file}.corrupt-${timestamp}-${randomUUID()}`; +} + +/** Preserve the exact source bytes before a parsed store is rewritten. */ +export const archiveStoreBytes: StoreArchive = async (file, raw, invalidRecords = []) => { + const archived = archivePath(file); + await writeFile(archived, raw, { flag: "wx" }); + if (invalidRecords.length > 0) { + await writeFile( + `${archived}.diagnostics.json`, + JSON.stringify({ source: file, archived, invalidRecords }, null, 2), + { flag: "wx" }, + ); + } + return archived; +}; + +/** Preserve an unreadable file/directory by moving it without reading it. */ +export async function quarantineUnreadableStore(file: string): Promise { + const archived = archivePath(file); + await rename(file, archived); + return archived; +} + +/** Archive a whole malformed store, then remove its active path. */ +export async function quarantineWholeStore(file: string, raw: Uint8Array, archive: StoreArchive): Promise { + const archived = await archive(file, raw); + await unlink(file); + return archived; +} diff --git a/pm-stack/aggregator/test/store-corrupt.test.ts b/pm-stack/aggregator/test/store-corrupt.test.ts index 3cf5ff4a9c..61322ce571 100644 --- a/pm-stack/aggregator/test/store-corrupt.test.ts +++ b/pm-stack/aggregator/test/store-corrupt.test.ts @@ -8,21 +8,55 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync import { tmpdir } from "node:os"; import { join } from "node:path"; import { ActionsStore, type NewAction } from "../src/actions.ts"; -import { CommentsStore } from "../src/comments.ts"; +import { CommentsStore, pendingCommentCounts } from "../src/comments.ts"; +import type { InvalidStoreRecord, StoreArchive } from "../src/store-recovery.ts"; const drew = { kind: "drew" as const, id: "drew", label: "Drew" }; let tokenSeq = 0; -const newAction = (): NewAction => ({ +const newAction = (over: Partial = {}): NewAction => ({ clientToken: `ct-corrupt-${++tokenSeq}-abcdefgh`, kind: "triage", verb: "acknowledge", objectRef: "orch:item-1", payload: {}, author: drew, + ...over, }); -const quarantinedIn = (dir: string, base: string) => readdirSync(dir).filter((f) => f.startsWith(`${base}.corrupt-`)); +const quarantinedIn = (dir: string, base: string) => + readdirSync(dir).filter((f) => f.startsWith(`${base}.corrupt-`) && !f.endsWith(".diagnostics.json")); +const diagnosticsIn = (dir: string, base: string) => + readdirSync(dir).filter((f) => f.startsWith(`${base}.corrupt-`) && f.endsWith(".diagnostics.json")); + +const validComment = (id: string, extra: Record = {}) => ({ + id, + objectRef: "gh:developing-today/code#2347", + kind: "note", + author: drew, + body: "historical note", + createdAt: "2026-10-30T12:00:00Z", + ...extra, +}); + +const validAction = (id: string, extra: Record = {}) => ({ + id, + clientToken: `ct-${id}`, + kind: "triage", + verb: "answer", + objectRef: "orch:legacy-item", + payload: { answers: "legacy payload shape" }, + author: drew, + createdAt: "2026-10-30T12:00:00Z", + state: "new", + ...extra, +}); + +function diagnosticEntries(dir: string, base: string): InvalidStoreRecord[] { + const files = diagnosticsIn(dir, base); + expect(files).toHaveLength(1); + return JSON.parse(readFileSync(join(dir, files[0]), "utf8")).invalidRecords; +} describe("actions store corruption handling (#1452)", () => { test("missing file -> empty store, no quarantine", async () => { @@ -101,6 +135,74 @@ describe("actions store corruption handling (#1452)", () => { expect((await reloaded.all()).length).toBe(1); expect(quarantinedIn(dir, "actions.json")).toEqual([]); }); + + test("mixed malformed records are archived byte-for-byte with diagnostics while valid history survives persistence", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-actions-records-")); + const file = join(dir, "actions.json"); + const source = { + version: 1, + extension: { source: "older-writer" }, + actions: [ + validAction("good-action", { historicalExtension: { retained: true } }), + { ...validAction("missing-created-at"), createdAt: undefined }, + { ...validAction("numeric-created-at"), createdAt: 123 }, + { ...validAction("missing-object-ref"), objectRef: undefined }, + { ...validAction("missing-kind"), kind: undefined }, + { ...validAction("missing-state"), state: undefined }, + { ...validAction("missing-payload"), payload: undefined }, + { ...validAction("legacy-no-token"), clientToken: undefined }, + ], + }; + const raw = Buffer.from(JSON.stringify(source)); + writeFileSync(file, raw); + + const store = new ActionsStore(file); + expect((await store.all()).map((action) => action.id)).toEqual(["good-action", "legacy-no-token"]); + expect((await store.forObject("orch:legacy-item")).map((action) => action.id)).toEqual(["good-action", "legacy-no-token"]); + expect((await store.byObject()).get("orch:legacy-item")?.map((action) => action.id)).toEqual(["good-action", "legacy-no-token"]); + expect(await store.pendingCounts()).toEqual({ triage: 2, statusRequests: 0, session: 0, preference: 0 }); + + const quarantine = quarantinedIn(dir, "actions.json"); + expect(quarantine).toHaveLength(1); + expect(readFileSync(join(dir, quarantine[0]))).toEqual(raw); + expect(diagnosticEntries(dir, "actions.json")).toEqual([ + { index: 1, reason: "createdAt must be a valid ISO date/time string" }, + { index: 2, reason: "createdAt must be a valid ISO date/time string" }, + { index: 3, reason: "objectRef must be a non-empty ref string" }, + { index: 4, reason: "kind must be triage, status-request, session, or preference" }, + { index: 5, reason: "state must be new, applied, rejected, or superseded" }, + { index: 6, reason: "payload must be an object" }, + ]); + + await store.add(newAction({ objectRef: "orch:legacy-item" })); + const persisted = JSON.parse(readFileSync(file, "utf8")); + expect(persisted.extension).toEqual({ source: "older-writer" }); + expect(persisted.actions.find((action: { id: string }) => action.id === "good-action").historicalExtension).toEqual({ + retained: true, + }); + expect(persisted.actions.find((action: { id: string }) => action.id === "legacy-no-token").clientToken).toBeUndefined(); + expect(persisted.actions.map((action: { id: string }) => action.id)).not.toContain("missing-created-at"); + // Deliberately retain old verb-specific payload shapes; consumers validate those safely. + expect(persisted.actions[0].payload).toEqual({ answers: "legacy payload shape" }); + expect(readFileSync(join(dir, quarantine[0]))).toEqual(raw); + }); + + test("archive failure rejects reads and writes without changing the source", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-actions-archive-failure-")); + const file = join(dir, "actions.json"); + const raw = Buffer.from(JSON.stringify({ version: 1, actions: [validAction("bad", { createdAt: 123 })] })); + writeFileSync(file, raw); + const archiveFails: StoreArchive = async () => { + throw new Error("simulated archive failure"); + }; + const store = new ActionsStore(file, archiveFails); + + await expect(store.all()).rejects.toThrow("simulated archive failure"); + expect(readFileSync(file)).toEqual(raw); + await expect(store.add(newAction())).rejects.toThrow("simulated archive failure"); + expect(readFileSync(file)).toEqual(raw); + expect(quarantinedIn(dir, "actions.json")).toEqual([]); + }); }); describe("comments store corruption handling (#1452)", () => { @@ -178,4 +280,76 @@ describe("comments store corruption handling (#1452)", () => { expect((await reloaded.all()).length).toBe(1); expect(quarantinedIn(dir, "comments.json")).toEqual([]); }); + + test("mixed malformed records are archived byte-for-byte with diagnostics while valid history survives persistence", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-comments-records-")); + const file = join(dir, "comments.json"); + const source = { + version: 1, + extension: { source: "older-writer" }, + comments: [ + validComment("good-comment", { historicalExtension: { retained: true } }), + { ...validComment("missing-created-at"), createdAt: undefined }, + { ...validComment("numeric-created-at"), createdAt: 123 }, + { ...validComment("missing-object-ref"), objectRef: undefined }, + { ...validComment("missing-kind"), kind: undefined }, + { ...validComment("missing-author"), author: undefined }, + { ...validComment("missing-body"), body: undefined }, + validComment("legacy-message-without-state", { kind: "message" }), + ], + }; + const raw = Buffer.from(JSON.stringify(source)); + writeFileSync(file, raw); + + const store = new CommentsStore(file); + expect((await store.all()).map((comment) => comment.id)).toEqual(["good-comment", "legacy-message-without-state"]); + expect((await store.forObject("gh:developing-today/code#2347")).map((comment) => comment.id)).toEqual([ + "good-comment", + "legacy-message-without-state", + ]); + expect([...((await store.byObject()).keys())]).toEqual(["gh:developing-today/code#2347"]); + expect([...((await store.counts()).entries())]).toEqual([["gh:developing-today/code#2347", 2]]); + expect(pendingCommentCounts(await store.all())).toEqual({ pendingMessages: 0, pendingGithub: 0, total: 2 }); + + const quarantine = quarantinedIn(dir, "comments.json"); + expect(quarantine).toHaveLength(1); + expect(readFileSync(join(dir, quarantine[0]))).toEqual(raw); + expect(diagnosticEntries(dir, "comments.json")).toEqual([ + { index: 1, reason: "createdAt must be a valid ISO date/time string" }, + { index: 2, reason: "createdAt must be a valid ISO date/time string" }, + { index: 3, reason: "objectRef must be a non-empty ref string" }, + { index: 4, reason: "kind must be message, note, or github" }, + { index: 5, reason: "author must have a supported kind, id, and label" }, + { index: 6, reason: "body must be a string" }, + ]); + + await store.add({ objectRef: "gh:developing-today/code#2347", kind: "note", author: drew, body: "new note" }); + const persisted = JSON.parse(readFileSync(file, "utf8")); + expect(persisted.extension).toEqual({ source: "older-writer" }); + expect(persisted.comments.find((comment: { id: string }) => comment.id === "good-comment").historicalExtension).toEqual({ + retained: true, + }); + expect(persisted.comments.find((comment: { id: string }) => comment.id === "legacy-message-without-state").triageState).toBeUndefined(); + expect(persisted.comments.map((comment: { id: string }) => comment.id)).not.toContain("missing-created-at"); + expect(readFileSync(join(dir, quarantine[0]))).toEqual(raw); + }); + + test("archive failure rejects reads and writes without changing the source", async () => { + const dir = mkdtempSync(join(tmpdir(), "agg-comments-archive-failure-")); + const file = join(dir, "comments.json"); + const raw = Buffer.from(JSON.stringify({ version: 1, comments: [validComment("bad", { createdAt: 123 })] })); + writeFileSync(file, raw); + const archiveFails: StoreArchive = async () => { + throw new Error("simulated archive failure"); + }; + const store = new CommentsStore(file, archiveFails); + + await expect(store.all()).rejects.toThrow("simulated archive failure"); + expect(readFileSync(file)).toEqual(raw); + await expect(store.add({ objectRef: "gh:developing-today/code#2347", kind: "note", author: drew, body: "blocked" })).rejects.toThrow( + "simulated archive failure", + ); + expect(readFileSync(file)).toEqual(raw); + expect(quarantinedIn(dir, "comments.json")).toEqual([]); + }); });