"use strict"; // Regression tests for the DELETE /api/scheduler/:server/tasks/:taskId // hardening pass (two findings against index.js). // // Finding 1 (deleting a task that was mid-run answered a bare 500): // BullMQ's Job.remove() THROWS while a worker holds the job's lock — // node_modules/bullmq dist/cjs/classes/job.js remove() rejects with // "Job could not be removed because it is locked by another worker" // (the removeJob Lua script returns 0 for locked jobs and job.js converts // the falsy result into exactly that throw; script error codes go through // finishedErrors and carry err.code instead). The handler's unguarded // one-time `await job.remove();` let the lock rejection bubble into the // outer catch, so deleting a running task returned a generic // "internal error". Fix: the one-time remove is wrapped; the lock // rejection becomes a 409 "task is currently running; try again when it // finishes" with NO recordActivity (nothing was deleted). Any other // rejection (Redis outage, script error codes carrying err.code) is // rethrown and keeps the outer 500 semantics. // // A stale iteration may be removed, but it cannot delete a different // repeatable with the same display name. The stored key is authoritative. // // index.js boots servers on require and cannot be loaded in-process, so — // same technique as scheduler-interval-floor / scheduler-hardening — the // REAL route is sliced from source, evaluated with injected fakes (an app // stub captures the handler; a stub schedulerQueue injects the BullMQ // behaviors under test) and exercised behaviorally, plus source-level // assertions on comment-stripped code so prose in comments cannot satisfy // them. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const { agentScheduleRef } = require("../AgentWorker/admission"); const { retireAgentSchedule } = require("../AgentWorker/queue-state"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); function stripFullLineComments(src) { return src .split("\n") .filter((line) => !/^\s*\/\//.test(line)) .join("\n"); } const indexCode = stripFullLineComments(indexSource); function sliceFrom(source, startMarker, endMarker, label) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`); const end = source.indexOf(endMarker, start); assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`); return source.slice(start, end); } const deleteRouteSource = sliceFrom( indexSource, 'app.delete("/api/scheduler/:serverName/tasks/:taskId"', 'app.get("/api/scheduler/status"', "scheduler delete route" ); const deleteRouteCode = stripFullLineComments(deleteRouteSource); const retractSource = sliceFrom( indexSource, "async function cancelQueuedAiAgentJobsForUser", "async function markPlannerItemDoneAfterAgentJob", "scheduled Agent retract" ); // --------------------------------------------------------------------------- // Behavioral harness: the REAL route evaluated with injected bindings // --------------------------------------------------------------------------- // The app stub captures the async handler; every module-level identifier the // route closes over is injected; a stub schedulerQueue injects the BullMQ // behaviors under test (locked removal, repeatable listings). // adpanel:scheduler-canonical-name - the route canonicalizes the URL server // name via findServer/getCanonicalServerName before matching job data, so the // harness injects those two too; the stubs echo the requested name back (the // tests pin delete semantics, not casing). function makeDeleteHandler(queue, retractSchedule = null) { const calls = { activities: [], logs: [], errors: [], retracts: [] }; const { schedulerJobBelongsToServer, resolveSchedulerRepeatablesForServer } = require("../services/scheduler-task-scope"); // The route now mounts schedulerMutateRateLimiter before the handler, so // capture the LAST registered function: the harness keeps exercising the // real handler while the limiter itself is stubbed below and never runs. const app = { delete(_path, ...handlers) { app.handler = handlers[handlers.length - 1]; } }; new Function( "isAuthenticated", "sanitizeServerName", "userHasAccessToServer", "getEffectivePermsForUserOnServer", "schedulerQueue", "getRequestIp", "recordActivity", "app", "console", "findServer", "getCanonicalServerName", "schedulerMutateRateLimiter", "requireActionTokenOr403", "cancelQueuedSchedulerAgentJobsForSchedule", "isAgentSchedule", "schedulerStateRedis", "resetSchedulerFailureStreak", "schedulerJobBelongsToServer", "resolveSchedulerRepeatablesForServer", `"use strict";\n${deleteRouteSource}\nreturn app.handler;` )( async () => true, (s) => s, async () => true, async () => ({ scheduler_delete: true }), queue, () => "127.0.0.1", (serverName, type, detail) => calls.activities.push({ serverName, type, detail }), app, { log: (...a) => calls.logs.push(a), warn: (...a) => calls.logs.push(a), error: (...a) => calls.errors.push(a) }, async (n) => ({ id: 7, name: String(n || "") }), (entry, fallback = "") => entry?.name || fallback, // Limiter stub (never invoked — the capture above takes the last handler). (_req, _res, next) => next(), // Token gate stub: allow-all mirrors the isAuthenticated stub. The gate's // own semantics live in the shared requireActionTokenOr403 helper and are // exercised by the fs/backup step-up suites — these tests pin DELETE // semantics (locked-job 409, ambiguous legacy 409, activity records). async () => true, retractSchedule || (async (schedule, serverName) => { if (["agent_prompt", "planner_next_to_agent"].includes(schedule.actionType)) calls.retracts.push({ schedule, serverName }); return 0; }), require("../AgentWorker/feature-http").isAgentSchedule, // adpanel:scheduler-redis-decouple / scheduler-failure-streak — the two // delete paths clear the deleted schedule's failure streak (fire-and- // forget, like the real calls). The harness has no scheduler Redis: a // null client with the real helper no-ops exactly like a Redis outage. null, async () => true, schedulerJobBelongsToServer, resolveSchedulerRepeatablesForServer ); return { handler: app.handler, calls }; } function makeQueue({ job, repeatables = [], occurrences = new Map(), removeRepeatableByKey } = {}) { const removed = []; return { removed, repeat: Promise.resolve(require("bullmq").Repeat.prototype), getJob: async (id) => occurrences.get(id) || (job ? { isActive: async () => false, ...job, data: { serverId: 7, ...job.data } } : null), getRepeatableJobs: async () => repeatables, removeRepeatableByKey: removeRepeatableByKey || (async (key) => removed.push(key)) }; } async function runDelete(handler, { taskId = "job-1", serverName = "srv01" } = {}) { const responses = []; const res = { json: (payload) => responses.push({ code: 200, payload }), status: (code) => ({ json: (payload) => responses.push({ code, payload }) }) }; await handler({ params: { serverName, taskId }, session: { user: "user@example.com" } }, res); return responses; } // The exact BullMQ rejection text for removing a locked/active job // (dist/cjs/classes/job.js remove()). const lockError = (id) => new Error(`Job ${id} could not be removed because it is locked by another worker`); // Omit serverId to model a template that predates the ownership binding. const legacyName = (extra = {}) => JSON.stringify({ serverName: "srv01", serverId: 7, name: "Nightly restart", actionType: "console_command", ...extra }); // Two same-named, same-action schedules with DIFFERENT payloads — the exact // scenario the loose fallback could not tell apart. const legacyTwins = [ { key: "rk-a", name: legacyName({ payloadHash: "hash-of-payload-a" }) }, { key: "rk-b", name: legacyName({ payloadHash: "hash-of-payload-b" }) } ]; // --------------------------------------------------------------------------- // Finding 1 — removing a locked one-time job // --------------------------------------------------------------------------- test("one-time tasks from a previous server of the same name are not deletable", async () => { const queue = makeQueue({ job: { data: { serverName: "srv01", serverId: 8, actionType: "agent_prompt" }, remove() { assert.fail("the other server's job must not be removed"); }, } }); const { handler, calls } = makeDeleteHandler(queue); assert.deepStrictEqual(await runDelete(handler), [{ code: 404, payload: { ok: false, error: "task not found" } }]); assert.deepStrictEqual(calls.retracts, []); assert.deepStrictEqual(calls.activities, []); }); test("recurring deletes are refused when the current occurrence belongs to another server or is missing", async () => { const key = "older-template"; const next = 1_700_000_000_000; for (const serverId of [7, 8, undefined]) { const occurrences = new Map(); if (serverId !== undefined) occurrences.set(`repeat:${key}:${next}`, { repeatJobKey: key, opts: { prevMillis: next }, data: { serverName: "srv01", serverId }, }); const queue = makeQueue({ occurrences, repeatables: [{ key, next, name: legacyName({ serverId: undefined, actionType: "agent_prompt" }) }], }); const { handler, calls } = makeDeleteHandler(queue); const [response] = await runDelete(handler, { taskId: key }); const owned = serverId === 7; assert.equal(response.code, owned ? 200 : 404); assert.deepStrictEqual(queue.removed, owned ? [key] : []); assert.equal(calls.retracts.length, owned ? 1 : 0); } }); test("deleting a one-time task that is currently running answers 409, not a bare 500", async () => { const queue = makeQueue({ job: { id: "job-1", data: { serverName: "srv01", name: "One shot", actionType: "console_command" }, remove: async () => { throw lockError("job-1"); } } }); const { handler, calls } = makeDeleteHandler(queue); const responses = await runDelete(handler); assert.strictEqual(responses.length, 1); assert.strictEqual(responses[0].code, 409); assert.deepStrictEqual(responses[0].payload, { ok: false, error: "task is currently running; try again when it finishes" }); assert.deepStrictEqual( calls.activities, [], "a refused delete must NOT be recorded as scheduler_delete — nothing was deleted" ); }); test("a non-lock removal failure still rethrows to the outer catch as a 500", async () => { const queue = makeQueue({ job: { id: "job-2", data: { serverName: "srv01", name: "One shot", actionType: "console_command" }, remove: async () => { throw new Error("Connection is closed."); } } }); const { handler, calls } = makeDeleteHandler(queue); const responses = await runDelete(handler, { taskId: "job-2" }); assert.strictEqual(responses.length, 1); assert.strictEqual(responses[0].code, 500); assert.deepStrictEqual(responses[0].payload, { ok: false, error: "internal error" }); assert.strictEqual(calls.errors.length, 1, "the rethrown error must reach the outer catch's log"); assert.deepStrictEqual(calls.activities, []); }); test("a successful one-time delete still returns 200 and records the activity", async () => { let removed = false; const queue = makeQueue({ job: { id: "job-3", data: { serverName: "srv01", name: "One shot", actionType: "console_command" }, remove: async () => { removed = true; } } }); const { handler, calls } = makeDeleteHandler(queue); const responses = await runDelete(handler, { taskId: "job-3" }); assert.strictEqual(removed, true); assert.deepStrictEqual(responses, [{ code: 200, payload: { ok: true } }]); assert.strictEqual(calls.activities.length, 1); assert.strictEqual(calls.activities[0].type, "scheduler_delete"); }); test("deleting a non-Agent schedule leaves the creator's queued Planner work alone", async () => { const cancellations = []; const retractSchedule = loadScheduleRetract({ pool: { async getConnection() { cancellations.push("connection"); throw new Error("non-Agent tasks must not open a cancellation transaction"); } } }); const job = { id: "job-backup", data: { serverName: "srv01", name: "Backup", actionType: "backup", userId: 7 }, remove: async () => { } }; for (const [taskId, queue] of [ [job.id, makeQueue({ job })], [job.id, makeQueue({ job: { ...job, repeatJobKey: "rk-backup" }, repeatables: [ { key: "rk-backup", name: legacyName({ actionType: "backup", userName: "creator@example.com" }) } ] })], ["rk-backup", makeQueue({ repeatables: [ { key: "rk-backup", name: legacyName({ actionType: "backup", userName: "creator@example.com" }) } ] })] ]) { const { handler } = makeDeleteHandler(queue, retractSchedule); assert.deepStrictEqual(await runDelete(handler, { taskId }), [{ code: 200, payload: { ok: true } }]); } assert.deepStrictEqual(cancellations, []); }); function loadScheduleRetract(db) { return new Function("agentScheduleRef", "retireAgentSchedule", "db", "console", `${retractSource}\nreturn cancelQueuedSchedulerAgentJobsForSchedule;`)( agentScheduleRef, retireAgentSchedule, db, { log() { } } ); } test("only queued Agent jobs from the deleted schedule are cancelled", async () => { for (const [actionType, source] of [["planner_next_to_agent", "scheduler_planner_next"], ["agent_prompt", "scheduler_prompt"]]) { const scheduleRef = agentScheduleRef(null, "rk-target"); const target = { server_name: "srv01", source, schedule_ref: scheduleRef, status: "queued", model: "test" }; const rows = [ { ...target, id: 1, chat_id: 11 }, { ...target, id: 2, chat_id: 12, status: "running" }, { ...target, id: 3, chat_id: 13, schedule_ref: agentScheduleRef("unrelated-once") }, { ...target, id: 4, chat_id: 14, source: "planner_send" }, { ...target, id: 5, chat_id: 15, server_name: "another-server" }, { ...target, id: 6, chat_id: 16, schedule_ref: null } ]; const notes = []; const warnings = []; let retired = false; let commits = 0; const retractSchedule = loadScheduleRetract({ pool: { async getConnection() { return { async beginTransaction() { }, async execute(sql, params) { if (sql.includes("FROM ai_agent_worker_state")) { assert.match(sql, /FOR UPDATE/); return [[{ enabled: 1, generation: "1" }]]; } if (sql.startsWith("INSERT INTO ai_agent_schedule_receipts")) { assert.deepStrictEqual(params, [scheduleRef]); retired = true; return [{}]; } if (sql.includes("FROM ai_agent_jobs")) { assert.equal(retired, true); const predicates = sql.match(/(?:schedule_ref|server_name) = \?|source IN \(\?\)|status = 'queued'/g); assert.deepStrictEqual(predicates, ["schedule_ref = ?", "status = 'queued'", "server_name = ?", "source IN (?)"]); assert.match(sql, /FOR UPDATE/); const [ref, serverName, jobSource] = params; return [rows.filter(row => row.schedule_ref === ref && row.server_name === serverName && row.source === jobSource && row.status === "queued")]; } if (sql.startsWith("UPDATE ai_agent_jobs")) { const [reason, ...ids] = params; assert.strictEqual(reason, "schedule_deleted"); for (const row of rows) if (ids.includes(row.id)) row.status = "cancelled"; } else if (sql.includes("FROM ai_chats")) { return [params.map(id => ({ id }))]; } else { assert.match(sql, /INSERT INTO ai_messages/); notes.push(params[0]); } return [{}]; }, async commit() { commits += 1; }, async rollback() { warnings.push("rollback"); }, release() { } }; } } }); const queue = makeQueue({ repeatables: [{ key: "rk-target", name: legacyName({ actionType }) }] }); const { handler } = makeDeleteHandler(queue, retractSchedule); assert.deepStrictEqual(await runDelete(handler, { taskId: "rk-target" }), [{ code: 200, payload: { ok: true } }]); assert.deepStrictEqual(rows.map(row => row.status), ["cancelled", "running", "queued", "queued", "queued", "queued"]); assert.deepStrictEqual(notes, [11]); assert.deepStrictEqual(warnings, []); assert.strictEqual(commits, 1); } }); test("failed SQL retirement leaves either kind of Agent schedule available for a retry", async () => { for (const recurring of [false, true]) { const taskId = "retry-schedule"; let retired = false; let present = true; const remove = async () => { assert.equal(retired, true); present = false; }; const queue = { getJob: async () => present && !recurring ? { id: taskId, data: { serverName: "srv01", serverId: 7, actionType: "agent_prompt" }, isActive: async () => false, remove } : null, getRepeatableJobs: async () => present && recurring ? [{ key: taskId, name: legacyName({ actionType: "agent_prompt" }) }] : [], removeRepeatableByKey: remove, }; const dbUnavailable = loadScheduleRetract({ pool: { async getConnection() { throw new Error("fixture SQL unavailable"); } } }); const { handler, calls } = makeDeleteHandler(queue, async (...args) => { if (!retired) return dbUnavailable(...args); }); assert.equal((await runDelete(handler, { taskId }))[0].code, 500); assert.equal(present, true); assert.deepStrictEqual(calls.activities, []); retired = true; assert.equal((await runDelete(handler, { taskId }))[0].code, 200); assert.equal(present, false); assert.equal(calls.activities.length, 1); } }); // --------------------------------------------------------------------------- // Recurring schedule identity // --------------------------------------------------------------------------- test("a stale iteration leaves both same-name repeatables intact", async () => { let removedIteration = false; const queue = makeQueue({ job: { id: "job-4", repeatJobKey: "rk-gone", // exact key matches nothing data: { serverName: "srv01", name: "Nightly restart", actionType: "console_command" }, remove: async () => { removedIteration = true; } }, repeatables: legacyTwins }); const { handler, calls } = makeDeleteHandler(queue); const responses = await runDelete(handler, { taskId: "job-4" }); assert.deepStrictEqual(responses, [{ code: 200, payload: { ok: true } }]); assert.deepStrictEqual(queue.removed, []); assert.strictEqual(removedIteration, true); assert.strictEqual(calls.activities.length, 1); }); test("a stale iteration must not delete even a single same-name schedule", async () => { let removedIteration = false; const queue = makeQueue({ job: { id: "job-5", repeatJobKey: "rk-gone", data: { serverName: "srv01", name: "Nightly restart", actionType: "console_command" }, remove: async () => { removedIteration = true; } }, repeatables: [ { key: "rk-a", name: legacyName({ payloadHash: "hash-of-payload-a" }) }, { key: "rk-other", name: legacyName({ serverName: "elsewhere", payloadHash: "x" }) } ] }); const { handler, calls } = makeDeleteHandler(queue); const responses = await runDelete(handler, { taskId: "job-5" }); assert.deepStrictEqual(queue.removed, [], "the remaining repeatable belongs to a different identity"); assert.strictEqual(removedIteration, true); assert.deepStrictEqual(responses, [{ code: 200, payload: { ok: true } }]); assert.strictEqual(calls.activities.length, 1); assert.strictEqual(calls.activities[0].type, "scheduler_delete"); }); test("only the exact repeatable is deleted when there are same-name schedules", async () => { const queue = makeQueue({ job: { id: "job-6", repeatJobKey: "rk-exact", opts: { prevMillis: 1000 }, data: { serverName: "srv01", name: "Nightly restart", actionType: "console_command" }, remove: async () => { } }, repeatables: [{ key: "rk-exact", next: 1000, name: legacyName({ payloadHash: "exact" }) }, ...legacyTwins] }); const { handler } = makeDeleteHandler(queue); const responses = await runDelete(handler, { taskId: "job-6" }); assert.deepStrictEqual(queue.removed, ["rk-exact"], "only the exact-key repeatable may be removed"); assert.deepStrictEqual(responses, [{ code: 200, payload: { ok: true } }]); }); test("a stale iteration cannot remove or retract a legacy recurrence whose key was reused", async () => { for (const [next, finishedOn] of [[2000, undefined], [1000, 1001]]) { const queue = makeQueue({ job: { id: "old-job", repeatJobKey: "legacy-reused", opts: { prevMillis: 1000 }, finishedOn, data: { serverName: "srv01", actionType: "agent_prompt" }, remove: async () => {} }, repeatables: [{ key: "legacy-reused", next, name: legacyName({ actionType: "agent_prompt" }) }], }); const { handler, calls } = makeDeleteHandler(queue); assert.deepStrictEqual(await runDelete(handler, { taskId: "old-job" }), [{ code: 200, payload: { ok: true } }]); assert.deepStrictEqual(queue.removed, []); assert.deepStrictEqual(calls.retracts, []); } }); // --------------------------------------------------------------------------- // adpanel:schedule-delete-retract — the queued-run retract on every success // path // --------------------------------------------------------------------------- test("each success path passes the deleted schedule's identity and stored server name to queued-run cleanup", async () => { const oneShot = makeDeleteHandler(makeQueue({ job: { id: "job-r1", data: { serverName: "srv01", name: "One shot", actionType: "planner_next_to_agent" }, remove: async () => { } } })); assert.deepStrictEqual(await runDelete(oneShot.handler, { taskId: "job-r1" }), [{ code: 200, payload: { ok: true } }]); assert.deepStrictEqual(oneShot.calls.retracts, [ { schedule: { actionType: "planner_next_to_agent", taskId: "job-r1", repeatKey: null }, serverName: "srv01" } ], "a one-shot run must carry the job ID"); // Recurring path via the exact repeatable key: the retract rides the // repeatable removal. const recurring = makeDeleteHandler(makeQueue({ job: { id: "job-r2", repeatJobKey: "rk-exact", opts: { prevMillis: 1000 }, data: { serverName: "srv01", name: "Nightly prompt", actionType: "agent_prompt" }, remove: async () => { } }, repeatables: [{ key: "rk-exact", next: 1000, name: legacyName({ actionType: "agent_prompt", payloadHash: "exact" }) }] })); assert.deepStrictEqual(await runDelete(recurring.handler, { taskId: "job-r2" }), [{ code: 200, payload: { ok: true } }]); assert.deepStrictEqual(recurring.calls.retracts, [ { schedule: { actionType: "agent_prompt", repeatKey: "rk-exact" }, serverName: "srv01" } ], "a recurring run must carry the repeatable key, not the iteration ID"); const boundTemplate = makeDeleteHandler(makeQueue({ job: null, repeatables: [{ key: "rk-legacy", name: legacyName({ payloadHash: "legacy", actionType: "planner_next_to_agent" }) }] })); assert.deepStrictEqual(await runDelete(boundTemplate.handler, { taskId: "rk-legacy" }), [{ code: 200, payload: { ok: true } }]); assert.deepStrictEqual(boundTemplate.calls.retracts, [ { schedule: { actionType: "planner_next_to_agent", repeatKey: "rk-legacy" }, serverName: "srv01" } ], "the bound template proves ownership even when its iteration is gone"); }); test("a known running Agent job or locked stale iteration is refused without retiring it", async () => { const locked = makeDeleteHandler(makeQueue({ job: { id: "job-r3", isActive: async () => true, data: { serverName: "srv01", name: "One shot", actionType: "agent_prompt", userId: 7, userName: "creator@example.com" }, remove: async () => { assert.fail("a known running one-time job must not be removed"); } } })); const responses = await runDelete(locked.handler, { taskId: "job-r3" }); assert.strictEqual(responses[0].code, 409); assert.deepStrictEqual(locked.calls.retracts, [], "a refused delete must not retract the queued run"); const stale = makeDeleteHandler(makeQueue({ job: { id: "job-r4", repeatJobKey: "rk-gone", data: { serverName: "srv01", name: "Nightly restart", actionType: "console_command", userId: 7, userName: "creator@example.com" }, remove: async () => { throw lockError("job-r4"); } }, repeatables: legacyTwins })); const staleResponses = await runDelete(stale.handler, { taskId: "job-r4" }); assert.strictEqual(staleResponses[0].code, 409); assert.deepStrictEqual(stale.calls.retracts, [], "a locked stale iteration must not retract any queued run"); }); test("a deferred backup remains removable even when it has a previous processing timestamp", async () => { let removed = false; const { handler, calls } = makeDeleteHandler(makeQueue({ job: { id: "job-backup", processedOn: 1000, data: { serverName: "srv01", name: "Deferred backup", actionType: "backup" }, remove: async () => { removed = true; } } })); assert.deepStrictEqual(await runDelete(handler, { taskId: "job-backup" }), [{ code: 200, payload: { ok: true } }]); assert.strictEqual(removed, true); assert.deepStrictEqual(calls.retracts, []); }); // --------------------------------------------------------------------------- // adpanel:schedule-delete-error-propagation — the repeatable-by-taskId branch // (job: null; the pending iteration's job is gone and only the repeatable // entry remains). Only the name-JSON parse gets its own catch there: a failing // removeRepeatableByKey must propagate to the outer catch's 500, never fall // through to the misleading 404 "task not found" — the repeatable EXISTS and // was matched, the failure is Redis-side, and a 404 would invite retrying a // delete that actually succeeded in matching. // --------------------------------------------------------------------------- test("the repeatable-by-taskId delete answers 500 (never the misleading 404) when the repeatable removal fails", async () => { const queue = makeQueue({ job: null, repeatables: [{ key: "rk-legacy", name: legacyName({ payloadHash: "legacy", userName: "nightly@example.com" }) }], removeRepeatableByKey: async () => { throw new Error("Connection is closed."); } }); const { handler, calls } = makeDeleteHandler(queue); const responses = await runDelete(handler, { taskId: "rk-legacy" }); assert.strictEqual(responses.length, 1); assert.strictEqual(responses[0].code, 500); assert.deepStrictEqual(responses[0].payload, { ok: false, error: "internal error" }); assert.strictEqual(calls.errors.length, 1, "the removal failure must reach the outer catch's log"); assert.deepStrictEqual( calls.activities, [], "a failed removal must NOT be recorded as scheduler_delete — nothing was deleted" ); assert.deepStrictEqual(calls.retracts, [], "a failed removal must not retract the queued run"); }); test("the repeatable-by-taskId success sibling: removal ok answers 200 with the activity record and the retract", async () => { const queue = makeQueue({ job: null, repeatables: [{ key: "rk-legacy", name: legacyName({ payloadHash: "legacy", actionType: "planner_next_to_agent" }) }] }); const { handler, calls } = makeDeleteHandler(queue); const responses = await runDelete(handler, { taskId: "rk-legacy" }); assert.deepStrictEqual(queue.removed, ["rk-legacy"], "the matched repeatable must be removed by its key"); assert.deepStrictEqual(responses, [{ code: 200, payload: { ok: true } }]); assert.strictEqual(calls.activities.length, 1); assert.strictEqual(calls.activities[0].type, "scheduler_delete"); assert.strictEqual(calls.activities[0].detail.recurring, true); assert.deepStrictEqual(calls.retracts, [ { schedule: { actionType: "planner_next_to_agent", repeatKey: "rk-legacy" }, serverName: "srv01" } ], "the success sibling retracts the queued run by its repeatable key"); }); // --------------------------------------------------------------------------- // Source-level wiring (comment-stripped, so prose cannot satisfy these) // --------------------------------------------------------------------------- test("the running-job 409 remains present in the shipped route", () => { assert.ok( deleteRouteCode.includes('"task is currently running; try again when it finishes"'), "the running-task 409 message must exist in code" ); }); test("the one-time job.remove() is wrapped: 409 fires from its catch, before recordActivity", () => { // The one-time call sits on its own line inside try/catch (removeErr); the // repeatable path's removal is the inline `try { await job.remove(); } // catch { }`, which this newline-anchored match does not hit. const posRemove = deleteRouteCode.indexOf("\n await job.remove();\n } catch (removeErr) {"); assert.ok(posRemove > 0, "the one-time remove must be immediately followed by its catch (removeErr) block"); const posRethrow = deleteRouteCode.indexOf("throw removeErr;", posRemove); const pos409 = deleteRouteCode.indexOf("res.status(409)", posRemove); const posActivity = deleteRouteCode.indexOf("recordActivity(", posRemove); assert.ok(posRethrow > posRemove, "non-lock failures must rethrow to the outer catch (500 semantics)"); assert.ok(pos409 > posRemove, "the lock failure must answer 409 from inside the catch"); assert.ok(posActivity > pos409, "recordActivity must come after the 409 return — a refused delete is not recorded"); }); test("the exact key and current occurrence gate removal of a repeatable by iteration ID", () => { const matchAt = deleteRouteCode.indexOf("const repeatable = repeatables.find(r => r.key === repeatKey && occurrenceAt > 0 && Number(r.next) === occurrenceAt);"); const guardAt = deleteRouteCode.indexOf("if (repeatable) {", matchAt); const removeAt = deleteRouteCode.indexOf("removeRepeatableByKey(repeatable.key)"); assert.ok(matchAt > 0 && guardAt > matchAt && removeAt > guardAt); });