import assert from "node:assert/strict" import { test } from "node:test" import { executeMcpDatabaseMaintenance } from "./database-maintenance.js" test("restore invalidates access after durable intent and before target database work", async () => { const calls: string[] = [] assert.deepEqual(await executeMcpDatabaseMaintenance(async () => { calls.push("restore"); return { restored: true } }, { record: async state => { calls.push(state) }, invalidateAccess: async () => { calls.push("invalidate") }, close: async () => { calls.push("close") } }), { restored: true }) assert.deepEqual(calls, ["intent", "invalidate", "restore", "applied", "close"]) }) test("failed intent or generation invalidation prevents restore", async () => { for (const stage of ["intent", "invalidate"]) { let writes = 0 await assert.rejects(executeMcpDatabaseMaintenance(async () => { writes++; return {} }, { record: async state => { if (stage === state) throw new Error(stage) }, invalidateAccess: async () => { if (stage === "invalidate") throw new Error(stage) }, close: async () => {} }), new RegExp(stage)) assert.equal(writes, 0) } }) test("post-restore audit errors remain warnings and never trigger command replay", async () => { let writes = 0 const result = await executeMcpDatabaseMaintenance(async () => { writes++; return { restored: true } }, { record: async state => { if (state === "applied") throw new Error("disk") }, invalidateAccess: async () => {}, close: async () => {} }) assert.equal(writes, 1); assert.equal(result.restored, true); assert.match(result.maintenanceError!, /Не повторяйте/) }) test("an applied archive with failed migrations writes durable unconfirmed maintenance", async () => { const states: string[] = [], outcome = { restored: true, migrationError: "Pending migration failed" } const result = await executeMcpDatabaseMaintenance(async () => outcome, { record: async state => { states.push(state) }, invalidateAccess: async () => {}, close: async () => {}, }) assert.deepEqual(result, outcome) assert.deepEqual(states, ["intent", "unconfirmed"]) }) test("unconfirmed-journal and close failures preserve a failed restore's original error", async () => { const original = new Error("restore failed") await assert.rejects(executeMcpDatabaseMaintenance(async () => { throw original }, { record: async state => { if (state === "unconfirmed") throw new Error("journal") }, invalidateAccess: async () => {}, close: async () => { throw new Error("close") } }), error => error === original) })