"use strict"; // Unit tests for utils/planner-done-reconcile.js — the durable catch-up sweep // for the planner done-flip (adpanel:planner-done-reconcile). // // The module must ONLY discover candidate pairs (active planner item x // terminal 'completed' planner job, joined on server_name + the stringified // item id, one row per item — its LATEST completed job) and hand each // qualifying pair to the INJECTED flip callback — it owns no flip SQL and no // lock discipline (the flip keeps exactly one implementation: // markPlannerItemDoneAfterAgentJob in index.js). These tests pin the // discovery contract — including the WINDOW-FREE shape (a completed_at // window would strand a lost flip older than the window forever) and the // RECENCY GUARD (adpanel:planner-reconcile-recency: an item touched after // its latest completed job finished is never re-archived — a user action // postdating the run means the completion is consumed or superseded — with // fail-closed NULL handling) — the exact-recomposition gate (so deliberately // skipped "prompt edited" flips are never force-flipped), the per-item // error isolation, and the fail-open posture. // // Run: node --test utils/planner-done-reconcile.test.js const test = require("node:test"); const assert = require("node:assert"); const { createPlannerDoneReconcile } = require("./planner-done-reconcile"); // Mock composer/sanitizer pair with the same shape contract as index.js's // buildPlannerAgentPrompt / sanitizeAiAgentPrompt: the sanitizer runs on the // composed snapshot, and the job's stored prompt must equal the SANITIZED // recomposition of the item's CURRENT text. function composePrompt(item, serverName) { if (item && item.title === "__THROW__") throw new Error("compose failure"); return `PLANNER[${serverName}]:${item.title || ""}|${item.prompt}`; } function sanitizePrompt(value) { return String(value ?? "").trim(); } function expectedStoredPrompt(item, serverName) { return sanitizePrompt(composePrompt(item, serverName)); } // A discovery result row in exactly the shape the module's JOIN returns. function candidateRow(overrides = {}) { const item = { id: 42, server_name: "srv-a", title: "Fix spawn", prompt: " Restart the server ", ...overrides.item, }; const job = { id: 9001, source: "scheduler_planner_next", server_name: item.server_name, source_ref: String(item.id), user_email: "creator@example.com", ...overrides.job, }; if (!Object.prototype.hasOwnProperty.call(overrides.job || {}, "prompt")) { job.prompt = expectedStoredPrompt({ title: item.title, prompt: item.prompt }, item.server_name); } return { item_id: item.id, item_server_name: item.server_name, item_title: item.title, item_prompt: item.prompt, job_id: job.id, job_source: job.source, job_server_name: job.server_name, job_source_ref: job.source_ref, job_prompt: job.prompt, job_user_email: job.user_email, }; } // Mock db whose query() records the SQL and returns the fixture rows. function mockDb(rows, { capture = null, failQuery = false } = {}) { const calls = []; return { calls, async query(sql, params) { calls.push({ sql, params }); if (capture) capture(sql, params); if (failQuery) throw new Error("db down"); return typeof rows === "function" ? rows(sql, params) : rows; }, }; } function makeDeps(db, flipLog, overrides = {}) { return { db, buildPlannerAgentPrompt: composePrompt, sanitizeAiAgentPrompt: sanitizePrompt, flipDone: async (row) => { if (overrides.flipBehavior) await overrides.flipBehavior(row); flipLog.push(row); }, logger: { warn: () => {} }, ...overrides.deps, }; } // A db mock that models the recency predicate the discovery SQL is pinned to // carry (adpanel:planner-reconcile-recency): each fixture is a candidateRow // plus the two timestamps that predicate compares, as SQL TIMESTAMP strings // ('YYYY-MM-DD HH:MM:SS' — lexicographic order is chronological). The mock // refuses SQL that lost the predicate fragments (without this the behavioral // pins below would pass vacuously if the predicate were deleted from // candidateSql) and then applies the same fail-closed three-valued filter // the database applies — an unexpected NULL never qualifies — so the pins // exercise the module's real path (discovery -> recomposition -> flip) with // the DB-side filter modeled at the module's only seam. function recencyAwareDb(fixtures) { return { async query(sql) { if ( !sql.includes("i.updated_at IS NOT NULL") || !sql.includes("j.completed_at IS NOT NULL") || !sql.includes("i.updated_at <= j.completed_at") ) { throw new Error("discovery SQL lost the recency predicate this mock models"); } return fixtures .filter((f) => f.itemUpdatedAt !== null && f.jobCompletedAt !== null && f.itemUpdatedAt <= f.jobCompletedAt) .map((f) => f.row); }, }; } // ─── discovery contract ────────────────────────────────────────────────────── test("discovery SQL pins the candidate family: active items x latest completed planner job, string-shaped source_ref join, NO completed_at window", async () => { let seenSql = ""; const db = mockDb([], { capture: (sql) => { seenSql = sql; } }); const recon = createPlannerDoneReconcile(makeDeps(db, [])); await recon.reconcile(); assert.ok(seenSql.includes("i.is_done = 0"), "only active (is_done = 0) items qualify — an already-flipped item is ignored"); assert.ok(seenSql.includes("j.status = 'completed'"), "only terminal 'completed' jobs qualify — queued/running jobs are the dedupe's domain, failed/cancelled runs must never consume an item"); assert.ok( seenSql.includes("'planner_send'") && seenSql.includes("'scheduler_planner_next'"), "both planner job sources are part of the candidate family" ); assert.ok( seenSql.includes("j.source_ref = CAST(i.id AS CHAR)"), "the join must compare the VARCHAR source_ref against the stringified item id (adpanel:source-ref-string-bind — a numeric bind would coerce the column and defeat the index)" ); // adpanel:planner-done-reconcile — the scan is ITEM-driven and WINDOW-FREE: // a completed_at window would strand a lost flip older than the window // forever (the dedupe matches only queued/running, so the pair re-runs // billably on every fire). One row per item — its LATEST completed job via // the NOT EXISTS anti-join — keeps the candidate set bounded by the // active-item count instead of job history; scanLimit stays the per-pass // drain bound. assert.ok( !seenSql.includes("completed_at >= DATE_SUB") && !/INTERVAL \d+ DAY/.test(seenSql), "discovery must not filter on a completed_at window — an old stranded flip must stay discoverable forever" ); assert.ok( seenSql.includes("NOT EXISTS (") && seenSql.includes("j2.completed_at > j.completed_at") && seenSql.includes("j2.completed_at = j.completed_at AND j2.id > j.id"), "the anti-join must keep only each item's LATEST completed job (completed_at DESC, id as the same-second tie-break) — one row per item bounds the scan by the active-item count" ); // adpanel:planner-reconcile-recency — the recency guard is part of the // qualification, IN SQL, so a touched-after-completion item never even // surfaces: a user action postdating the run (above all a deliberate // re-activation toggle — updated_at carries ON UPDATE CURRENT_TIMESTAMP) // means the completion is consumed or superseded and must never be // re-archived. The NULL guards are explicit and fail closed: an // unexpected NULL must skip the flip, never compare NULL-ambiguously. assert.ok( seenSql.includes("i.updated_at IS NOT NULL") && seenSql.includes("j.completed_at IS NOT NULL") && seenSql.includes("i.updated_at <= j.completed_at"), "the recency guard must qualify each pair in SQL (item not touched after the latest completed job finished) with explicit fail-closed NULL guards" ); assert.ok( /LIMIT 200/.test(seenSql), "the scan must keep a per-pass drain bound (default LIMIT 200 — the planner's own 200-active-items-per-server cap covers one full server worst case per pass)" ); }); test("an injected plannerJobSources family is used for the scan (no drift from index.js's PLANNER_AGENT_JOB_SOURCES)", async () => { let seenSql = ""; const db = mockDb([], { capture: (sql) => { seenSql = sql; } }); const recon = createPlannerDoneReconcile(makeDeps(db, [], { deps: { plannerJobSources: ["planner_send", "scheduler_planner_next"] }, })); await recon.reconcile(); assert.ok(seenSql.includes("IN ('planner_send','scheduler_planner_next')"), "the injected source family must appear in the scan"); }); // ─── the flip gate ─────────────────────────────────────────────────────────── test("an exact-prompt pair is flipped: the injected callback receives the job row shape the flip implementation expects", async () => { const row = candidateRow(); const flips = []; const recon = createPlannerDoneReconcile(makeDeps(mockDb([row]), flips)); const result = await recon.reconcile(); assert.strictEqual(result.ok, true); assert.strictEqual(result.scanned, 1); assert.strictEqual(result.flipped, 1); assert.strictEqual(result.failed, 0); assert.strictEqual(flips.length, 1); assert.deepStrictEqual(flips[0], { id: 9001, source: "scheduler_planner_next", server_name: "srv-a", source_ref: "42", prompt: expectedStoredPrompt({ title: "Fix spawn", prompt: " Restart the server " }, "srv-a"), user_email: "creator@example.com", }); assert.strictEqual(typeof flips[0].source_ref, "string", "source_ref must ride as the canonical digit STRING, mirroring the stored form"); }); test("an edited-prompt mismatch is skipped, never force-flipped (replicates the flip's own deliberate-skip guard)", async () => { // The item's CURRENT text differs from what the completed job executed — // exactly the "prompt edited since enqueue" family the flip skips; the // sweep must leave it alone (the new text is re-run later, not consumed). const row = candidateRow({ job: { prompt: expectedStoredPrompt({ title: "Fix spawn", prompt: "OLD text" }, "srv-a") } }); const flips = []; const recon = createPlannerDoneReconcile(makeDeps(mockDb([row]), flips)); const result = await recon.reconcile(); assert.strictEqual(result.ok, true); assert.strictEqual(result.scanned, 1); assert.strictEqual(result.flipped, 0); assert.strictEqual(flips.length, 0, "a mismatched snapshot must not reach the flip callback"); }); // ─── recency guard (adpanel:planner-reconcile-recency) ─────────────────────── test("an item touched after its latest completed job finished never surfaces: flipDone is not called (the re-activation regression)", async () => { // The regression this pins: item runs -> job completes -> flip lands -> // user toggles the item BACK to active (same text, byte-matching snapshot) // -> the next pass must NOT re-archive it. The re-activation toggle bumps // updated_at (ON UPDATE CURRENT_TIMESTAMP) past completed_at, so the pair // never surfaces: a user action postdating the run means the completion is // consumed or superseded, never re-archived. const row = candidateRow(); const flips = []; const recon = createPlannerDoneReconcile(makeDeps( recencyAwareDb([{ row, itemUpdatedAt: "2026-01-01 12:00:05", jobCompletedAt: "2026-01-01 12:00:00" }]), flips )); const result = await recon.reconcile(); assert.strictEqual(result.ok, true, "the mock must have modeled the predicate (a discovery failure here means the SQL drifted)"); assert.strictEqual(result.scanned, 0, "a touched-after-completion item must never surface as a candidate"); assert.strictEqual(flips.length, 0, "flipDone must not be called for a pair a user action postdates"); }); test("an item whose last touch predates the job's completion still flips", async () => { const row = candidateRow(); const flips = []; const recon = createPlannerDoneReconcile(makeDeps( recencyAwareDb([{ row, itemUpdatedAt: "2026-01-01 11:59:00", jobCompletedAt: "2026-01-01 12:00:00" }]), flips )); const result = await recon.reconcile(); assert.strictEqual(result.ok, true); assert.strictEqual(result.scanned, 1); assert.strictEqual(result.flipped, 1); assert.strictEqual(flips.length, 1, "a stranded flip no user action postdates must still be recovered"); }); test("equal timestamps still qualify: 'not touched after' is inclusive of the same second", async () => { const row = candidateRow(); const flips = []; const recon = createPlannerDoneReconcile(makeDeps( recencyAwareDb([{ row, itemUpdatedAt: "2026-01-01 12:00:00", jobCompletedAt: "2026-01-01 12:00:00" }]), flips )); const result = await recon.reconcile(); assert.strictEqual(result.ok, true); assert.strictEqual(result.scanned, 1); assert.strictEqual(result.flipped, 1, "the guard is i.updated_at <= j.completed_at — only a STRICTLY later touch suppresses the flip"); }); test("unexpected NULLs fail closed: a missing updated_at or completed_at never surfaces the pair", async () => { // Per the terminal-write contract a qualifying 'completed' job cannot // legitimately carry NULL completed_at (the status and the stamp land in // the same UPDATE), and updated_at is NOT NULL — but if an unforeseen NULL // ever appears, the guard must SKIP the flip, not compare NULL-ambiguously. const flips = []; const recon = createPlannerDoneReconcile(makeDeps( recencyAwareDb([ { row: candidateRow({ item: { id: 7 }, job: { id: 7001, source_ref: "7" } }), itemUpdatedAt: null, jobCompletedAt: "2026-01-01 12:00:00" }, { row: candidateRow({ item: { id: 8 }, job: { id: 8001, source_ref: "8" } }), itemUpdatedAt: "2026-01-01 11:00:00", jobCompletedAt: null }, ]), flips )); const result = await recon.reconcile(); assert.strictEqual(result.ok, true); assert.strictEqual(result.scanned, 0, "an unexpected NULL must keep the pair undiscovered (fail closed)"); assert.strictEqual(flips.length, 0, "an unexpected NULL must SKIP the flip, never compare NULL-comparably"); }); test("a pair whose item is already done never appears (the scan filters is_done = 0) — a filtered-out row is a no-op", async () => { // The SQL excludes done items; simulate the database having applied that // filter: the sweep receives nothing and must not call the flip. const flips = []; const recon = createPlannerDoneReconcile(makeDeps(mockDb([]), flips)); const result = await recon.reconcile(); assert.deepStrictEqual(result, { ok: true, skipped: false, scanned: 0, flipped: 0, failed: 0 }); assert.strictEqual(flips.length, 0); }); test("flip-callback errors are isolated per pair: one failure must not abort the sweep or throw", async () => { const good = candidateRow({ item: { id: 7, server_name: "srv-b" }, job: { id: 7001, source_ref: "7", server_name: "srv-b" } }); const bad = candidateRow({ item: { id: 8, server_name: "srv-c" }, job: { id: 8001, source_ref: "8", server_name: "srv-c" } }); const flips = []; const recon = createPlannerDoneReconcile(makeDeps(mockDb([bad, good]), flips, { flipBehavior: (row) => { if (row.id === 8001) throw new Error("lock wait timeout exceeded"); }, })); const result = await recon.reconcile(); assert.strictEqual(result.ok, true, "a per-pair flip failure must fail OPEN — never thrown to the caller"); assert.strictEqual(result.flipped, 1, "the surviving pair must still be flipped"); assert.strictEqual(result.failed, 1, "the failing pair must be counted"); assert.deepStrictEqual(flips.map((r) => r.id).sort(), [7001], "exactly the surviving pair reached the callback"); }); test("a composer throw on one pair is isolated and counted, not fatal", async () => { const good = candidateRow({ item: { id: 7, server_name: "srv-b" }, job: { id: 7001, source_ref: "7", server_name: "srv-b" } }); const broken = candidateRow({ item: { title: "__THROW__", server_name: "srv-c" }, job: { id: 8001, server_name: "srv-c", source_ref: "8", prompt: "unreachable comparison" }, }); const flips = []; const recon = createPlannerDoneReconcile(makeDeps(mockDb([broken, good]), flips)); const result = await recon.reconcile(); assert.strictEqual(result.ok, true); assert.strictEqual(result.flipped, 1); assert.strictEqual(result.failed, 1); assert.strictEqual(flips.length, 1); }); // ─── fail-open posture ─────────────────────────────────────────────────────── test("no completed planner jobs -> the pass is a no-op", async () => { const flips = []; const recon = createPlannerDoneReconcile(makeDeps(mockDb([]), flips)); const result = await recon.reconcile(); assert.deepStrictEqual(result, { ok: true, skipped: false, scanned: 0, flipped: 0, failed: 0 }); assert.strictEqual(flips.length, 0); }); test("a discovery failure fails open (warn, no throw, no flips)", async () => { const flips = []; const recon = createPlannerDoneReconcile(makeDeps(mockDb([], { failQuery: true }), flips)); const result = await recon.reconcile(); assert.deepStrictEqual(result, { ok: false, skipped: false, reason: "discovery_failed", flipped: 0, failed: 0 }); assert.strictEqual(flips.length, 0); }); test("a missing dep (no flip callback) is skipped, not thrown — the module never re-implements the flip", async () => { const db = mockDb([candidateRow()]); let queried = false; const recon = createPlannerDoneReconcile({ db: { query: async (sql) => { queried = true; throw new Error("must not query: " + sql); } }, buildPlannerAgentPrompt: composePrompt, sanitizeAiAgentPrompt: sanitizePrompt, logger: { warn: () => {} }, }); const result = await recon.reconcile(); assert.strictEqual(result.skipped, true); assert.strictEqual(result.reason, "not_configured"); assert.strictEqual(queried, false, "an unconfigured module must not even scan"); }); // ─── scheduling ────────────────────────────────────────────────────────────── test("start() schedules the boot pass + interval exactly once per process and stop() tears them down", async () => { const flips = []; const row = candidateRow(); const recon = createPlannerDoneReconcile(makeDeps(mockDb([row]), flips)); const started = recon.start({ bootDelayMs: 5, intervalMs: 15 }); assert.strictEqual(started, true, "the first start() arms the schedule"); assert.strictEqual(recon.start({ bootDelayMs: 5, intervalMs: 15 }), false, "a second start() must be a no-op — the schedule exists at most once per process"); // The boot pass fires after the (tiny) delay and the interval keeps sweeping. await new Promise((resolve) => setTimeout(resolve, 60)); assert.ok(flips.length >= 2, `boot pass + at least one interval pass must have flipped (got ${flips.length})`); recon.stop(); const afterStop = flips.length; await new Promise((resolve) => setTimeout(resolve, 50)); assert.strictEqual(flips.length, afterStop, "stop() must tear the timers down — no further passes"); }); // ─── re-entrancy ───────────────────────────────────────────────────────────── test("a reconcile pass that overlaps an in-flight one is skipped, not queued", async () => { let releaseDiscovery; const gate = new Promise((resolve) => { releaseDiscovery = resolve; }); const flips = []; const recon = createPlannerDoneReconcile(makeDeps({ async query() { await gate; return [candidateRow()]; }, }, flips)); const first = recon.reconcile(); const second = await recon.reconcile(); assert.deepStrictEqual(second, { ok: false, skipped: true, reason: "sweep_in_flight", flipped: 0, failed: 0 }); releaseDiscovery(); const firstResult = await first; assert.strictEqual(firstResult.ok, true); assert.strictEqual(firstResult.flipped, 1); });