"use strict"; // Source-level pins for the ai_agent_jobs terminal-row retention prune // (adpanel:ai-agent-job-retention). // // The audited hole: terminal rows (completed / failed / cancelled) were never // pruned — the only caps are PENDING-only (AI_AGENT_MAX_PENDING_JOBS*), and // scheduler_prompt has no dedupe/done-flip, so one recurring schedule alone // grows the table by ~105k rows/year at a 5-minute cadence and every boot // sweep full-scans the growth. The prune deletes ONLY terminal rows past a // completed_at cutoff, batched and bounded per pass, best-effort — and it // deliberately never touches ai_chats / ai_messages (user-visible chat // history is a product decision: users manage their own chats; the jobs // table is the operational record). // // index.js is a ~57k-line application bundle (module side effects, DB and // network at require time — never require() it from a test), so these tests // pin the fixes structurally on well-anchored source windows, matching the // convention of tests/planner-job-retract.test.js. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); function functionWindow(src, anchor, label) { const start = src.indexOf(anchor); assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`); const end = src.indexOf("\n}", start); assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`); return src.slice(start, end + 2); } function windowBetween(src, startAnchor, endAnchor, label) { const start = src.indexOf(startAnchor); assert.notStrictEqual(start, -1, `${label}: start anchor not found: ${startAnchor}`); const end = src.indexOf(endAnchor, start + startAnchor.length); assert.notStrictEqual(end, -1, `${label}: end anchor not found after start: ${endAnchor}`); return src.slice(start, end); } // ─── 1. The prune's predicate ──────────────────────────────────────────────── test("pruneTerminalAiAgentJobs deletes ONLY terminal rows past the completed_at cutoff, batched and bounded", () => { const body = functionWindow(INDEX_SRC, "async function pruneTerminalAiAgentJobs", "pruneTerminalAiAgentJobs"); // Terminal-only predicate: queued rows are live work (the resume, the pump // and the claim all key on status = 'queued') and running rows keep their // enqueue-time authorization — the prune can never touch either. assert.ok( body.includes("status IN ('completed','failed','cancelled')"), "the DELETE must predicate on the three TERMINAL statuses — a queued or running row can never match" ); assert.ok( body.includes("completed_at IS NOT NULL") && body.includes("completed_at < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ${AI_AGENT_JOB_RETENTION_DAYS} DAY)"), "the cutoff must be completed_at-based and explicitly non-null — a terminal row without a completion timestamp can never be pruned" ); // Batching: DELETE ... LIMIT with a short-batch break, bounded per pass so // a huge backlog can neither hold the boot prologue nor the daily timer // hostage with one giant delete. assert.ok( body.includes("for (let batch = 0; batch < AI_AGENT_JOB_RETENTION_PRUNE_MAX_BATCHES; batch++)") && body.includes("LIMIT ${AI_AGENT_JOB_RETENTION_PRUNE_BATCH}`") && body.includes("if (removed < AI_AGENT_JOB_RETENTION_PRUNE_BATCH) break;"), "the prune must batch its DELETEs with a LIMIT and stop when a short batch drains the backlog, bounded by the max-batches constant" ); // The two interpolated values are server-side clamped integer constants, // never user input (the reason interpolation is safe here). The sentence // lives in the prune's constraint comment, directly above the function. const pruneDoc = windowBetween( INDEX_SRC, "adpanel:ai-agent-job-retention — ONE home for the terminal-row prune", "daily continuation of the boot prune", "prune constraint comment" ); assert.ok( pruneDoc.includes("clamped server-side integer constants"), "the comment must document why interpolating the retention constants is safe" ); // User-visible chat history is deliberately out of scope (product // decision): only the jobs table is pruned. FK direction makes that safe — // fk_ai_agent_jobs_chat cascades from chats to jobs, never the reverse. assert.ok( !body.includes("ai_chats") && !body.includes("ai_messages"), "the prune must not delete ai_chats/ai_messages rows — user-visible chat history is deliberately out of scope" ); // Best-effort: a failure warns and returns the rows removed so far; it must // never break the boot prologue or the daily timer. assert.ok( body.includes("console.warn(") && body.includes("return removedTotal;"), "the prune must be best-effort (warn, partial-progress return) — it runs in the boot prologue" ); }); // ─── 2. The retention constant ─────────────────────────────────────────────── test("AI_AGENT_JOB_RETENTION_DAYS defaults to 30 with env override clamped to sane bounds", () => { const decl = windowBetween( INDEX_SRC, "const AI_AGENT_JOB_RETENTION_DAYS =", ";", "retention constant" ); assert.ok( decl.includes('process.env.AI_AGENT_JOB_RETENTION_DAYS || "30"'), "the retention window must default to 30 days and be env-overridable" ); assert.ok( decl.includes("Math.max(1, Math.min(365,"), "the env override must be clamped to 1..365 days — a garbage value can neither disable retention entirely nor prune fresh terminal rows" ); }); // ─── 3. Wiring: boot pass after the widen, daily unref'd continuation ──────── test("the boot prune runs AFTER the eager ENUM widen in startServers and the daily sweeper is unref'd", () => { const prologue = windowBetween( INDEX_SRC, "async function startServers", "await cleanupOrphanedUserRecords();", "startServers prologue" ); const widenAt = prologue.indexOf("await ensureAiAgentJobsStatusEnumWide();"); const pruneAt = prologue.indexOf("await pruneTerminalAiAgentJobs();"); const sweeperAt = prologue.indexOf("startAiAgentJobRetentionSweeper();"); assert.notStrictEqual(widenAt, -1, "the eager ENUM widen call is missing"); assert.notStrictEqual(pruneAt, -1, "the boot prune call is missing"); assert.notStrictEqual(sweeperAt, -1, "the daily sweeper start is missing"); // Order matters: the widen is DDL and must complete before the prune's // DELETEs touch ai_agent_jobs — the ALTER must never queue behind the // prune's deleted-row locks, and the prune must observe the final schema. assert.ok( widenAt < pruneAt && pruneAt < sweeperAt, "order must be: eager ENUM widen -> boot prune -> sweeper start (the DDL must never queue behind the prune's row locks)" ); const sweeperBody = functionWindow(INDEX_SRC, "function startAiAgentJobRetentionSweeper", "startAiAgentJobRetentionSweeper"); assert.ok( sweeperBody.includes("setInterval") && sweeperBody.includes('timer.unref'), "the daily continuation must be an unref'd interval — the timer must never hold the process open" ); assert.ok( sweeperBody.includes("if (aiAgentRetentionSweeperStarted) return;"), "the sweeper must be started exactly once per process" ); });