import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { ProposalStore } from "../src/core/proposal-store.js"; const identity = { botId: "test-bot", platform: "qq" }; const input = { title: "Refactor store", goal: "Move to assistant proposals", steps: ["design", "implement", "test"], ownerChatKey: "qq:chat", requesterUserId: "user-1" }; test("creates, updates and reloads proposals with 0600 atomic file", async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "gori-proposals-")); const file = path.join(dir, "proposals.json"); const first = new ProposalStore(file, identity); await first.open(); const created = await first.create(input); assert.equal(created.status, "proposed"); assert.ok(created.id.length > 0); assert.equal(created.createdAt, created.updatedAt); const confirmedAt = created.createdAt + 1000; const updated = await first.update(created.id, { status: "pending", confirmedAt, startedAt: confirmedAt + 1, workerNativeSessionId: "native-1", workerProcessGroup: { pgid: 4321, token: "worker-token" }, pending: { summary: "needs dirty confirm", question: "overwrite?", workspaceDirty: true, receivedAt: confirmedAt + 2 }, lastWorkerSummary: "half done" }); assert.equal(updated.status, "pending"); assert.ok(updated.updatedAt >= created.updatedAt); const finished = await first.update(created.id, { status: "finished", finishKind: "done", finishNote: "wrapped up", pending: undefined, finishedAt: confirmedAt + 3 }); assert.equal(finished.finishKind, "done"); await first.close(); assert.equal((await fs.promises.readdir(dir)).some((name) => name.endsWith(".tmp")), false); assert.equal((await fs.promises.stat(file)).mode & 0o777, 0o600); const persisted = JSON.parse(await fs.promises.readFile(file, "utf8")); assert.equal(persisted.version, 2); assert.equal(persisted.botId, "test-bot"); assert.equal(persisted.platform, "qq"); assert.equal(persisted.proposals[created.id].workerProcessGroup.pgid, 4321); const second = new ProposalStore(file, identity); await second.open(); const loaded = second.get(created.id); assert.deepEqual(loaded, finished); assert.deepEqual(second.list().map((proposal) => proposal.id), [created.id]); assert.deepEqual(second.list({ status: "finished" }).map((proposal) => proposal.id), [created.id]); assert.equal(second.list({ status: "queued" }).length, 0); assert.equal(second.stats().proposals, 1); await second.close(); }); test("orders list by confirmation time for queued proposals", async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "gori-proposals-order-")); const file = path.join(dir, "proposals.json"); const store = new ProposalStore(file, identity); await store.open(); const firstCreated = await store.create({ ...input, title: "first created" }); const secondCreated = await store.create({ ...input, title: "second created" }); await store.update(secondCreated.id, { status: "queued", confirmedAt: 100 }); await store.update(firstCreated.id, { status: "queued", confirmedAt: 200 }); assert.deepEqual(store.list({ status: "queued" }).map((proposal) => proposal.title), ["second created", "first created"]); await store.close(); }); test("validates proposal fields on create and update", async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "gori-proposals-invalid-")); const file = path.join(dir, "proposals.json"); const store = new ProposalStore(file, identity); await store.open(); await assert.rejects(store.create({ ...input, title: "" }), /title/); await assert.rejects(store.create({ ...input, steps: ["ok", ""] }), /steps/); const created = await store.create(input); await assert.rejects(store.update(created.id, { status: "bogus" as never }), /status/); await assert.rejects(store.update(created.id, { workerProcessGroup: { pgid: 1, token: "t" } }), /workerProcessGroup/); await assert.rejects(store.update(created.id, { pending: { summary: "s" } as never }), /pending/); await assert.rejects(store.update(created.id, { pending: { summary: "s", receivedAt: "now" } as never }), /pending/); await assert.rejects(store.update(created.id, { finishKind: "bogus" as never }), /finishKind/); await assert.rejects(store.update("missing", { status: "queued" }), /unknown proposal/); assert.equal(store.get(created.id)?.status, "proposed"); await store.close(); }); test("rejects identity or version mismatch and preserves corrupt state", async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "gori-proposals-id-")); const file = path.join(dir, "proposals.json"); const wrongVersion = '{"version":3,"botId":"test-bot","platform":"qq","proposals":{}}\n'; await fs.promises.writeFile(file, wrongVersion); await assert.rejects(new ProposalStore(file, identity).open(), /expected version 2/); assert.equal(await fs.promises.readFile(file, "utf8"), wrongVersion); await fs.promises.writeFile(file, JSON.stringify({ version: 2, botId: "other", platform: "qq", proposals: {} })); await assert.rejects(new ProposalStore(file, identity).open(), /identity mismatch/); await fs.promises.writeFile(file, JSON.stringify({ version: 2, botId: "test-bot", platform: "feishu", proposals: {} })); await assert.rejects(new ProposalStore(file, identity).open(), /identity mismatch/); await fs.promises.writeFile(file, "not-json"); await assert.rejects(new ProposalStore(file, identity).open(), /original file was preserved/); assert.equal(await fs.promises.readFile(file, "utf8"), "not-json"); await fs.promises.writeFile(file, JSON.stringify({ version: 2, botId: "test-bot", platform: "qq", proposals: { abc: { id: "other" } } })); await assert.rejects(new ProposalStore(file, identity).open(), /invalid proposal/); }); function v1Proposal(id: string, status: string, extra: Record = {}) { return { id, title: `title-${id}`, goal: "goal", steps: ["step"], ownerChatKey: "qq:chat", requesterUserId: "user-1", status, createdAt: 1, updatedAt: 2, ...extra }; } test("migrates a v1 store: backs up the original file and maps every legacy status", async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "gori-proposals-migrate-")); const file = path.join(dir, "proposals.json"); const v1 = { version: 1, botId: "test-bot", platform: "qq", proposals: { success: v1Proposal("success", "awaiting_user_confirmation", { pending: { kind: "success", summary: "all done" } }), failure: v1Proposal("failure", "awaiting_user_confirmation", { pending: { kind: "failure", summary: "it broke" } }), step: v1Proposal("step", "awaiting_user_confirmation", { pending: { kind: "step", summary: "dirty target", question: "overwrite?", nextStep: "edit" } }), done: v1Proposal("done", "completed", { finishedAt: 10 }), broken: v1Proposal("broken", "failed", { finishedAt: 11, lastWorkerSummary: "worker blew up" }), dropped: v1Proposal("dropped", "cancelled", { finishedAt: 12 }), fresh: v1Proposal("fresh", "proposed"), lined: v1Proposal("lined", "queued", { confirmedAt: 5 }), busy: v1Proposal("busy", "working", { startedAt: 6, workerNativeSessionId: "native-9", workerProcessGroup: { pgid: 4321, token: "tok" } }) } }; const raw = `${JSON.stringify(v1, null, 2)}\n`; await fs.promises.writeFile(file, raw, { mode: 0o600 }); const store = new ProposalStore(file, identity); await store.open(); const backups = (await fs.promises.readdir(dir)).filter((name) => name.startsWith("proposals.json.v1-") && name.endsWith(".bak")); assert.equal(backups.length, 1); assert.equal((await fs.promises.stat(path.join(dir, backups[0]!))).mode & 0o777, 0o600); assert.equal(await fs.promises.readFile(path.join(dir, backups[0]!), "utf8"), raw); const persisted = JSON.parse(await fs.promises.readFile(file, "utf8")); assert.equal(persisted.version, 2); assert.equal((await fs.promises.stat(file)).mode & 0o777, 0o600); const success = store.get("success")!; assert.equal(success.status, "pending"); assert.deepEqual(success.pending, { summary: "all done", receivedAt: 2 }); assert.equal(success.pending?.workspaceDirty, undefined); const failure = store.get("failure")!; assert.equal(failure.status, "pending"); assert.equal(failure.pending?.summary, "it broke"); assert.equal(failure.pending?.workspaceDirty, true); const step = store.get("step")!; assert.equal(step.status, "pending"); assert.equal(step.pending?.summary, "dirty target"); assert.equal(step.pending?.question, "overwrite?"); assert.equal((step.pending as unknown as Record).nextStep, undefined); const done = store.get("done")!; assert.equal(done.status, "finished"); assert.equal(done.finishKind, "done"); assert.equal(done.finishedAt, 10); const broken = store.get("broken")!; assert.equal(broken.status, "finished"); assert.equal(broken.finishKind, "done"); assert.equal(broken.finishNote, "worker blew up"); const dropped = store.get("dropped")!; assert.equal(dropped.status, "finished"); assert.equal(dropped.finishKind, "cancelled"); assert.equal(store.get("fresh")!.status, "proposed"); assert.equal(store.get("lined")!.status, "queued"); const busy = store.get("busy")!; assert.equal(busy.status, "working"); assert.equal(busy.workerNativeSessionId, "native-9"); assert.deepEqual(busy.workerProcessGroup, { pgid: 4321, token: "tok" }); await store.close(); // The migrated store reloads as a plain v2 file without creating another backup. const reloaded = new ProposalStore(file, identity); await reloaded.open(); assert.equal(reloaded.stats().proposals, 9); await reloaded.close(); const backupsAfter = (await fs.promises.readdir(dir)).filter((name) => name.endsWith(".bak")); assert.equal(backupsAfter.length, 1); }); test("a v1 store with a mismatched identity is rejected before any backup is written", async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "gori-proposals-migrate-id-")); const file = path.join(dir, "proposals.json"); const raw = `${JSON.stringify({ version: 1, botId: "other-bot", platform: "qq", proposals: {} })}\n`; await fs.promises.writeFile(file, raw, { mode: 0o600 }); await assert.rejects(new ProposalStore(file, identity).open(), /identity mismatch/); assert.equal(await fs.promises.readFile(file, "utf8"), raw); assert.equal((await fs.promises.readdir(dir)).filter((name) => name.endsWith(".bak")).length, 0); }); test("refuses a second writer and recovers a stale lock", async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "gori-proposals-lock-")); const file = path.join(dir, "proposals.json"); const first = new ProposalStore(file, identity); await first.open(); await assert.rejects(new ProposalStore(file, identity).open(), /locked by another/); await first.close(); await fs.promises.writeFile(`${file}.lock`, "2147483647\n", { mode: 0o600 }); const recovered = new ProposalStore(file, identity); await recovered.open(); await recovered.close(); assert.equal(fs.existsSync(`${file}.lock`), false); });