"use strict"; // Source-level pins for the agent-job suspension gate (adpanel:agent-job- // suspension-gate) and the permission-revocation jobs-side retract // (adpanel:planner-access-job-retract). // // The audited hole: suspension cancelled the target's BullMQ schedules only // (cancelSchedulesCreatedBy) — their QUEUED ai_agent_jobs rows survived, and // resumeQueuedAiAgentJobs re-enqueued them at every boot, so a suspended // user's job could execute after suspension with the executing user's LIVE // server perms (the executor's gate userCanUseAdpanelAgent checked only // admin || agent_access, unlike hasAgentAccess's "suspended accounts must not // mint or use agent access" doctrine). planner_access revocation had the same // shape: schedules were re-validated at the grant-perms route, queued // planner-source jobs were not. // // The fixes pinned here: // // 1. userCanUseAdpanelAgent — the ONE predicate every ADPanel Agent // authorization surface consults (executor fire-time gate, enqueue // paths, scheduler create/fire-time re-checks) now orders it exactly // like hasAgentAccess: admins pass FIRST, then agent_access AND NOT // suspended. This cannot lock out admins (the suspension route refuses // admin targets and its UPDATE carries AND admin = 0), and every caller // loads the user row through findUserById/findUserByEmail/ // resolveSchedulerAgentUser, which all select the suspended column. // 2. A gate-failed job is a CLEAN TERMINAL failure, never a requeue loop: // claimAiAgentJob flips queued->running unconditionally-recoverably, the // gate throws, and the catch path's writeRunScopedFailure marks the row // 'failed' with the error — while the resume and pump lookups select // ONLY status = 'queued', so a failed/cancelled row can never be // re-enqueued (also what makes "unsuspend does not resurrect" hold). // 3. cancelQueuedAiAgentJobsForUser is the ONE cancel helper (suspension: // ALL sources; planner_access revocation: the two PLANNER_AGENT_JOB_SOURCES // origins scoped to the server whose grant changed) — transactional, // SELECT ... FOR UPDATE pinning ONLY status = 'queued' rows (a RUNNING // job keeps its enqueue-time authorization — the cancel can never touch // running/completed rows), terminal write with completed_at + error, // keyed on user_id (NOT NULL under FK ON DELETE CASCADE and set by the // single INSERT writer, so the lock is served by the leading column of // idx_ai_agent_jobs_user instead of full-scanning the unindexed // user_email queued range), a TRIGGER-ACCURATE terminal assistant note // composed from the same reason recorded on the job rows at this ONE // composing site (the planner-item wording survives only as the fallback // for planner-item-shaped reasons — the four retract sites keep their // string byte-identical), and the note targets pinned with a chat FOR // UPDATE locked AFTER the job rows (the jobs->chats lock direction). // 4. The suspension route cancels the queued jobs right beside its // cancelSchedulesCreatedBy sibling, best-effort with warn, and the // grant-perms route cancels planner-source jobs for that server exactly // when the reauthorize pass's OWN predicate // (schedulerActionStillAuthorizedAfterPermChange — the ONE home of the // server-access / required-permission / ADPanel-Agent layers, shared with // shouldRemoveForReauthorize, never a second inline copy) would remove // the user's schedules there — mirroring the schedule re-validation // precedent without inventing a broader contract. // 5. The scheduler DELETE route retracts the deleted schedule's still-queued // scheduler_planner_next job (adpanel:schedule-delete-retract) through // ONE best-effort wrapper (cancelQueuedSchedulerPlannerJobsForSchedule) // that delegates to the shared cancel helper with the schedule_deleted // terminal reason — the last pull-based stop trigger in an otherwise // push-based retract contract; the helper's note composer carries the // trigger-accurate sentence for it. // 6. The executor's fire-time gate block re-checks the RUNNER's effective // planner_access for the PLANNER_AGENT_JOB_SOURCES sources // (adpanel:planner-runner-access-gate) — the layer the scheduler path // re-verifies for planner_next_to_agent schedules — through the ONE // effective-perms helper the other gates consume, failing closed; a // failed check is a clean terminal 403-class failure, never a requeue. // 7. The access-remove route runs the SAME two sibling passes // (adpanel:access-remove-retract): schedule re-validation plus the // predicate-gated queued planner-job retract, scoped to the removed // server (sweeping the servers index for the "all" wildcard row), // best-effort with warn. // // index.js is a ~56k-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/ai-agent-job-reclaim.test.js and // 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"); const WORKER_RUN = fs.readFileSync(path.join(ROOT, "AgentWorker", "run-job.js"), "utf8"); const WORKER_STORE = fs.readFileSync(path.join(ROOT, "AgentWorker", "job-store.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); } // Window from an anchor to an explicit end anchor — deterministic slicing // that survives unrelated edits elsewhere in the bundle. 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 gate itself ────────────────────────────────────────────────────── test("userCanUseAdpanelAgent rejects suspended users (admin first, then agent_access AND NOT suspended)", () => { const body = functionWindow(INDEX_SRC, "function userCanUseAdpanelAgent", "userCanUseAdpanelAgent"); assert.ok( body.includes("return !!(user && (user.admin || (!user.suspended && user.agent_access)));"), "the gate must order it like hasAgentAccess: admin passes first, agent_access only on an unsuspended row — a suspended user with a still-set agent_access flag must be rejected everywhere the predicate is consulted" ); // The constraint comment sits directly above the function (documenting the // hasAgentAccess doctrine it mirrors) — assert it is attached to THIS // function, not just somewhere in the file. const fnAt = INDEX_SRC.indexOf("function userCanUseAdpanelAgent"); const commentAt = INDEX_SRC.lastIndexOf("// adpanel:agent-job-suspension-gate — Suspended accounts must not mint", fnAt); assert.ok( commentAt !== -1 && fnAt - commentAt < 1600, "the gate must carry the adpanel:agent-job-suspension-gate constraint comment directly above it (hasAgentAccess's doctrine mirrored)" ); // The hasAgentAccess doctrine this mirrors must still exist unchanged. const hasAgentAccess = functionWindow(INDEX_SRC, "async function hasAgentAccess", "hasAgentAccess"); assert.ok( hasAgentAccess.includes("!user.suspended && user.agent_access"), "hasAgentAccess's suspension doctrine must stay — the executor gate mirrors it, it does not replace it" ); }); test("the panel's claim authorization consults the shared entitlement and the worker fails terminally", () => { const body = functionWindow(INDEX_SRC, "async function authorizeAgentJobClaim", "authorizeAgentJobClaim"); const gateAt = body.indexOf("if (!userCanUseAdpanelAgent(user) ||"); assert.notStrictEqual(gateAt, -1, "the executor must gate the run on userCanUseAdpanelAgent (which now embeds the suspension check)"); // A gate failure must land in the catch path's run-scoped terminal write — // the row is marked 'failed' with the error, NOT requeued: claimAiAgentJob // already flipped it to 'running', so without the terminal write it would // strand (and the stale reaper would requeue it into the same gate). assert.ok( WORKER_RUN.includes('const context = await call("context");') && WORKER_RUN.includes("await failAgentClaim(db, row, reason);"), "the catch path must mark the run failed through writeRunScopedFailure — a suspended user's resumed job is a clean terminal failure, never a requeue loop" ); // The boot wake-up and ordinary polls use the same queued-only selection, so a failed or // cancelled row can never be re-enqueued (this is also what makes // "unsuspend does not resurrect" hold for the cancelled rows). const queueSource = require("node:fs").readFileSync(require.resolve("../services/server-agent-queue"), "utf8"); assert.ok( queueSource.includes("SELECT id FROM ai_agent_jobs WHERE status = 'queued'"), "the pump's next-job lookup must select ONLY status = 'queued' rows — the terminal statuses stay out of the queue" ); const claimBody = functionWindow(WORKER_STORE, "async function claimAgentJob", "claimAgentJob"); assert.ok( claimBody.includes("WHERE id = ? AND status = 'queued' AND ${AGENT_JOB_GENERATION_SQL}"), "the claim must flip only queued rows — a cancelled row can never be claimed after the cancel commits" ); }); // ─── 2. The ONE cancel helper ──────────────────────────────────────────────── test("cancelQueuedAiAgentJobsForUser cancels ONLY queued rows, transactionally, with the retract note shape", () => { const body = functionWindow(INDEX_SRC, "async function cancelQueuedAiAgentJobsForUser", "cancelQueuedAiAgentJobsForUser"); // The constraint comment sits directly above the helper. const fnAt = INDEX_SRC.indexOf("async function cancelQueuedAiAgentJobsForUser"); const commentAt = INDEX_SRC.lastIndexOf("// adpanel:agent-job-suspension-gate — ONE home for cancelling", fnAt); assert.ok( commentAt !== -1 && fnAt - commentAt < 3600, "the helper must carry the adpanel:agent-job-suspension-gate constraint comment directly above it" ); // Keyed on the job rows' user_id (ai_agent_jobs.user_id is NOT NULL with FK // ON DELETE CASCADE and the single INSERT writer insertAiAgentChatJob always // sets it) and pinned to queued rows only: the SELECT ... // FOR UPDATE serializes against claimAiAgentJob's queued->running flip, so // a RUNNING job is never visible here and can never be marked cancelled — // running/completed rows are untouchable by construction. assert.ok( body.includes('"status = \'queued\'"') && body.includes("FOR UPDATE`"), "the helper must SELECT ... FOR UPDATE with a status = 'queued' filter — a claimed/running/completed row must never be cancelled" ); assert.ok( body.includes("user_id = ?") && !body.includes("user_email = ?"), "the helper must key the cancel on user_id — NOT NULL under FK ON DELETE CASCADE, so every queueable row has one, and the predicate is served by the leading column of idx_ai_agent_jobs_user instead of next-key-locking the whole unindexed user_email queued range" ); assert.ok( body.includes("Number.isInteger(targetUserId)"), "a user row that does not resolve must cancel 0 rows — the FK cascades the job rows away with the user, so a missing id can never miss a cancellable row" ); assert.ok( body.includes("`UPDATE ai_agent_jobs SET status = 'cancelled', completed_at = NOW(), error = ? WHERE id IN (${idPlaceholders})`"), "the terminal write must set status = 'cancelled' with completed_at + the error reason on exactly the pinned ids" ); // The SAME terminal assistant note shape the retract machinery writes (the // enqueue committed a user prompt the runner will never answer), and the // note targets are pinned with a chat FOR UPDATE locked AFTER the job rows // (jobs -> chats, the direction the account-delete retract establishes), so // a concurrently deleted chat can neither FK-abort the cancel nor orphan a // note. assert.ok( body.includes("INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model)"), "each cancelled job's chat must get the terminal assistant note — same shape as cancelQueuedPlannerAgentJobs" ); // The note text is TRIGGER-ACCURATE, composed from the same reason recorded // on the job rows, at this ONE composing site: the planner wording ("the // item was deleted, modified, or completed") is only true for a // planner-item retract, so the account-level triggers get accurate // sentences and the planner wording survives only as the fallback for // planner-item-shaped reasons. assert.ok( body.includes("const cancelNote =") && body.includes('cancelReason === "account_suspended"') && body.includes('cancelReason === "planner_access_revoked"') && body.includes('cancelReason === "schedule_deleted"'), "the note must be composed per trigger from the cancel reason at one composing site inside the helper" ); assert.ok( body.includes("Your account is suspended, so this task was cancelled before the agent ran it.") && body.includes("Planner access was revoked on this server, so this task was cancelled before the agent ran it.") && body.includes("The schedule that queued this task was deleted, so it was cancelled before the agent ran it.") && body.includes("Planner task retracted before the agent ran it: the item was deleted, modified, or completed."), "suspension, planner-access revocation and schedule deletion must get accurate sentences; the planner-item wording must survive as the fallback" ); assert.ok( body.includes("[row.chat_id, cancelNote, row.model || null]"), "the note INSERT must use the composed note with the same shape/role/model handling as the retract machinery" ); // adpanel:retract-note-wording — the planner-worded string stays byte- // identical at exactly its FIVE homes across BOTH files it lives in: // index.js's four (the account-delete retract, the boot sweep, // cancelQueuedPlannerAgentJobs, this helper's planner-item fallback) PLUS // the byte-identical CLI mirror in scripts/create-user.js --delete. The CLI // retract is a separate process that rides NO helper, so an index-only // count cannot see it — a reworded CLI copy used to ship green. The // cross-file total makes a reword anywhere fail. const CLI_SRC = fs.readFileSync(path.join(ROOT, "scripts", "create-user.js"), "utf8"); const plannerNoteSentence = "Planner task retracted before the agent ran it: the item was deleted, modified, or completed."; assert.strictEqual( INDEX_SRC.split(plannerNoteSentence).length - 1 + CLI_SRC.split(plannerNoteSentence).length - 1, 5, "one shared wording across every retract/cancel site, the CLI mirror included: index.js's four homes (account-delete retract, boot sweep, cancelQueuedPlannerAgentJobs, this helper's planner-item fallback) plus scripts/create-user.js's fifth (its --delete retract rides no helper and is invisible to an index-only count) — a reworded copy anywhere fails" ); const jobsLockAt = body.indexOf("FROM ai_agent_jobs"); const chatLockAt = body.indexOf("FROM ai_chats"); assert.ok( jobsLockAt !== -1 && chatLockAt !== -1 && jobsLockAt < chatLockAt, "lock direction must stay jobs -> chats — locking the chat rows before the job rows would invert against the account-delete retract and reopen the AB-BA pair" ); assert.ok( body.includes("SELECT id FROM ai_chats WHERE id IN (${chatPlaceholders}) FOR UPDATE`"), "the note-target chats must be pinned with FOR UPDATE inside the transaction (adpanel:retract-note-chat-toctou shape)" ); assert.ok( body.includes("await conn.commit();") && body.includes("await conn.rollback();") && body.includes("conn.release();"), "the transaction must commit on success, roll back on error and always release the connection" ); // Optional scoping for the revocation caller: server_name and the planner // source list are parameter filters, never interpolated. assert.ok( body.includes("source IN (${sourceList.map(() => \"?\").join(\",\")})"), "the planner-source filter must be a parameterized IN list, never an interpolated string" ); assert.ok( body.includes('serverName = null') && body.includes('sources = null') && body.includes('error = "account_suspended"'), "suspension (all sources, no server scope, error account_suspended) must be the default contract; revocation narrows via the options" ); }); // ─── 3. Wiring: suspension route ───────────────────────────────────────────── test("the suspension route cancels the user's queued agent jobs beside cancelSchedulesCreatedBy, best-effort", () => { const routeStart = INDEX_SRC.indexOf('app.post("/api/settings/accounts/:email/suspension"'); assert.notStrictEqual(routeStart, -1, "the suspension route must exist"); const routeEnd = INDEX_SRC.indexOf("\napp.", routeStart + 1); const body = INDEX_SRC.slice(routeStart, routeEnd); const schedulesAt = body.indexOf('cancelSchedulesCreatedBy(targetUser, { reason: "account suspended" })'); const jobsAt = body.indexOf('cancelQueuedAiAgentJobsForUser(targetUser.id, { userEmail: targetEmailLower, error: "account_suspended" })'); assert.notStrictEqual(schedulesAt, -1, "the schedule cancellation must stay"); assert.notStrictEqual(jobsAt, -1, "the queued-jobs cancellation must sit in the suspension route, keyed on the target row's user_id (served by the leading column of idx_ai_agent_jobs_user) with the lowercased target email for the log and the account_suspended reason"); assert.ok( schedulesAt < jobsAt, "the jobs cancel rides the SAME nextSuspended block as the sibling schedule cancellation (schedules first, then the queued rows)" ); // Best-effort with warn, matching the sibling's error handling. assert.ok( body.includes('console.warn("[account-suspension] Failed to cancel user\'s queued agent jobs:", jobsErr?.message || jobsErr)'), "a failed jobs cancel must warn and never fail the suspension — matching the schedule cancellation's error handling" ); // The cancel must run ONLY on suspend (inside the nextSuspended block): // unsuspend leaves the rows removed, consistent with schedules. const blockStart = body.indexOf("if (nextSuspended) {"); const blockEnd = body.indexOf("const graceExpiresAt", blockStart); assert.ok( blockStart !== -1 && blockEnd !== -1 && jobsAt > blockStart && jobsAt < blockEnd, "the jobs cancel must live inside the `if (nextSuspended)` block — unsuspending must not touch (nor resurrect) anything" ); assert.ok( body.includes("adpanel:agent-job-suspension-gate"), "the suspension wiring must carry the adpanel:agent-job-suspension-gate constraint comment (suspension cancels schedules only; queued rows survived)" ); }); // ─── 4. Wiring: grant-perms revocation ─────────────────────────────────────── test("the grant-perms route retracts the user's queued planner-source jobs for that server exactly when planner_access no longer resolves", () => { // Window from the schedule re-validation call (the revocation site the task // anchors on) to the end of the jobs retract's own catch. const revocationSite = INDEX_SRC.indexOf('reason: "server permissions changed"'); assert.notStrictEqual(revocationSite, -1, "the grant-perms schedule re-validation must exist"); const windowStart = INDEX_SRC.lastIndexOf(" // After changing this user's permissions on the server", revocationSite); const catchAnchor = INDEX_SRC.indexOf("} catch (jobsErr) {", revocationSite); assert.notStrictEqual(catchAnchor, -1, "the jobs retract's best-effort catch must exist"); const body = INDEX_SRC.slice(windowStart, INDEX_SRC.indexOf("\n", INDEX_SRC.indexOf("jobsErr?.message || jobsErr", catchAnchor))); assert.ok( body.includes('schedulerActionStillAuthorizedAfterPermChange(email, "planner_next_to_agent", canonicalServer)'), "the revocation gate must reuse the SAME predicate the schedule reauthorize pass applies per job (planner_next_to_agent is a queued planner job's schedule shape) — server access, required permission and the ADPanel Agent gate, never a second inline copy" ); assert.ok( body.includes("if (!plannerJobsStillAuthorized) {"), "the retract fires exactly when the shared predicate says the work is no longer authorized on that server — kept when everything still resolves (no broader permission contract)" ); assert.ok( body.includes("cancelQueuedAiAgentJobsForUser(jobsTargetUser?.id || 0, {"), "the revocation cancel must pass the target row's user_id (ai_agent_jobs.user_id is NOT NULL under FK ON DELETE CASCADE — a row that does not resolve means nothing can be queued)" ); assert.ok( body.includes("serverName: canonicalServer") && body.includes("sources: PLANNER_AGENT_JOB_SOURCES") && body.includes('error: "planner_access_revoked"'), "the revocation cancel must be scoped to the changed server and the two planner job sources, with the planner_access_revoked terminal reason" ); assert.ok( body.includes('console.warn("[grant-perms] Failed to retract the user\'s queued planner agent jobs:", jobsErr?.message || jobsErr)'), "a failed revocation retract must warn and never fail the grant — matching the schedule pass's error handling" ); // The permission layers live in the ONE shared predicate — the reauthorize // pass consumes it too, so the jobs-side gate cannot drift from the // schedule-side removal test. const predicateBody = functionWindow(INDEX_SRC, "async function schedulerActionStillAuthorizedAfterPermChange", "schedulerActionStillAuthorizedAfterPermChange"); assert.ok( predicateBody.includes("userHasAccessToServer(email, accessServerName)") && predicateBody.includes("schedulerRequiredPermissionForAction(actionType)") && predicateBody.includes("getEffectivePermsForUserOnServer(email, accessServerName)") && predicateBody.includes("userCanUseAdpanelAgent(u)"), "the shared predicate must carry all three reauthorize layers (server access, required permission, ADPanel Agent gate) in one home" ); assert.strictEqual( INDEX_SRC.split("async function schedulerActionStillAuthorizedAfterPermChange").length - 1, 1, "the shared reauthorize predicate must be defined exactly once" ); const schedulesBody = functionWindow(INDEX_SRC, "async function cancelSchedulesCreatedBy", "cancelSchedulesCreatedBy"); assert.ok( schedulesBody.includes("schedulerActionStillAuthorizedAfterPermChange(target, data?.actionType, data?.serverName)") && !schedulesBody.includes("userHasAccessToServer(target"), "shouldRemoveForReauthorize must delegate to the shared predicate — the former inline permission-layer copy is extracted, not forked" ); // The ONE shared helper does the cancelling — no second implementation. // Four call sites beside the definition: suspension, grant-perms, the // access-remove route's scoped sweep (adpanel:access-remove-retract), and // the schedule-delete retract wrapper (adpanel:schedule-delete-retract). assert.ok( INDEX_SRC.split("cancelQueuedAiAgentJobsForUser(").length - 1 === 5, "cancelQueuedAiAgentJobsForUser must be called from exactly four sites (suspension + grant-perms + the access-remove route's scoped sweep + the schedule-delete retract wrapper) beside its single definition — no forked cancel implementations" ); }); // ─── 5. Wiring: scheduler DELETE route (adpanel:schedule-delete-retract) ──── test("the scheduler DELETE route retires the schedule and retracts only its queued Agent jobs", () => { assert.strictEqual( INDEX_SRC.split("async function cancelQueuedSchedulerAgentJobsForSchedule").length - 1, 1, "the schedule-delete retract wrapper must be defined exactly once" ); const helperBody = functionWindow(INDEX_SRC, "async function cancelQueuedSchedulerAgentJobsForSchedule", "cancelQueuedSchedulerAgentJobsForSchedule"); assert.ok( helperBody.includes('"scheduler_planner_next"') && helperBody.includes('"scheduler_prompt"') && helperBody.includes('sources: [source]') && helperBody.includes('error: "schedule_deleted"'), "the wrapper must scope cancellation to the matching Agent source and carry the schedule_deleted terminal reason" ); assert.ok( helperBody.includes("return cancelQueuedAiAgentJobsForUser(") && !helperBody.includes("catch ("), "the wrapper must delegate to the shared cancel helper and propagate a retirement failure" ); assert.ok(helperBody.includes("!scheduleRef || !server") && helperBody.includes("serverName: server,"), "a missing schedule identity or scoped server must not fall back to a broad cancel"); const routeStart = INDEX_SRC.indexOf('app.delete("/api/scheduler/:serverName/tasks/:taskId"'); assert.notStrictEqual(routeStart, -1, "the scheduler DELETE route must exist"); const routeEnd = INDEX_SRC.indexOf("\napp.", routeStart + 1); const route = INDEX_SRC.slice(routeStart, routeEnd); const repeatCall = "cancelQueuedSchedulerAgentJobsForSchedule({ actionType, repeatKey: repeatable.key }, accessServerName)"; const onceCall = "cancelQueuedSchedulerAgentJobsForSchedule({ actionType, taskId: job.id ?? taskId, repeatKey }, accessServerName)"; const nameOnlyCall = "cancelQueuedSchedulerAgentJobsForSchedule({ actionType: nameData.actionType, repeatKey: repeatable.key }, accessServerName)"; assert.strictEqual( route.split(repeatCall).length - 1 + route.split(onceCall).length - 1 + route.split(nameOnlyCall).length - 1, 3, "each successful deletion must pass its schedule identity and the raw stored server name" ); const pathARemoveAt = route.indexOf("removeRepeatableByKey(repeatable.key)"); const pathACallAt = route.indexOf(repeatCall); const pathBRemoveAt = route.indexOf("await job.remove();", route.indexOf("await job.remove();") + 1); const pathBCallAt = route.indexOf(onceCall); const pathCRemoveAt = route.indexOf("removeRepeatableByKey(taskId)"); const pathCCallAt = route.indexOf(nameOnlyCall); const activeCheckAt = route.indexOf("if (await job.isActive())"); assert.notStrictEqual(pathARemoveAt, -1, "path A (repeatable removal) is missing"); assert.notStrictEqual(pathBRemoveAt, -1, "path B (one-shot job removal) is missing"); assert.notStrictEqual(pathCRemoveAt, -1, "path C (repeatable-by-taskId removal) is missing"); assert.ok( pathACallAt >= 0 && pathACallAt < pathARemoveAt && pathARemoveAt < activeCheckAt && activeCheckAt < pathBCallAt && pathBCallAt < pathBRemoveAt && pathBRemoveAt < pathCCallAt && pathCCallAt < pathCRemoveAt, "retire each schedule before losing its Redis identity, and refuse an active one-shot before retiring it" ); // The retract must run BEFORE the success response on path B (it is inside // the same handler tail, ahead of the final return res.json({ ok: true })). const pathBReturnAt = route.indexOf("return res.json({ ok: true });", pathBCallAt); assert.notStrictEqual(pathBReturnAt, -1, "path B's success response is missing"); assert.ok( pathBCallAt < pathBReturnAt, "the retract must precede the success response — a deleted schedule must not answer ok while its queued run survives" ); }); // ─── 6. Wiring: executor fire-time planner_access re-check ────────────────── test("claim authorization re-checks the runner's planner_access for the planner job sources and fails terminally", () => { // adpanel:planner-runner-access-gate — the revoke-time retracts are // best-effort and a claim can slip past them in-window, so the executor // itself must refuse a queued planner job whose runner lost planner_access: // the same layer the scheduler path re-verifies for planner_next_to_agent // schedules (schedulerRequiredPermissionForAction maps that action to // planner_access). Additive to the author-side clamp, which stays untouched. const body = functionWindow(INDEX_SRC, "async function authorizeAgentJobClaim", "authorizeAgentJobClaim"); const accessGateAt = body.indexOf('new Error("User no longer has access to this server.")'); const gateAt = body.indexOf("adpanel:planner-runner-access-gate"); const itemGateAt = body.indexOf('new Error("Planner item no longer exists.")'); assert.notStrictEqual(gateAt, -1, "the runner-side planner_access fire-time gate is missing"); assert.ok( accessGateAt !== -1 && accessGateAt < gateAt && gateAt < itemGateAt, "the planner_access gate must sit in the fire-time gate block — after the server-access gate and before the item-existence gate" ); const gateWindow = body.slice(gateAt, itemGateAt); // Scoped to the ONE planner source family via the shared constant — never a // forked second list: every other source runs the executing user's own // typed text, which never depended on a planner grant. assert.ok( gateWindow.includes('PLANNER_AGENT_JOB_SOURCES.has(String(row.source || ""))'), "the gate must apply only to the PLANNER_AGENT_JOB_SOURCES family via the shared constant" ); // The runner's EFFECTIVE perms through the ONE helper the other gates // consume, resolved like them (user.email against the canonical server // name) and failing CLOSED: a suspended or unresolvable user projects the // zero template and a lookup error projects null — both refuse the run. assert.ok( gateWindow.includes("getEffectivePermsForUserOnServer(user.email, serverName).catch(() => null)"), "the gate must read effective planner_access through getEffectivePermsForUserOnServer and fail closed on lookup error" ); assert.ok( gateWindow.includes("!runnerPlannerPerms || !runnerPlannerPerms.planner_access"), "a missing perms projection or a false planner_access must refuse the run — never default-open" ); assert.ok( gateWindow.includes('new Error("Planner access was revoked on this server.")') && gateWindow.includes("error.status = 403;"), "the refusal must be a 403-class terminal gate error whose wording matches the retract note convention ('Planner access was revoked...')" ); // Terminal, never requeued: the throw lands in the catch path's run-scoped // failure write (pinned with the sibling gate above), and the resume/pump // lookups select only queued rows, so the failed row can never re-execute. assert.ok( WORKER_RUN.includes("await failAgentClaim(db, row, reason);"), "the gate throw must land in the run-scoped failed write — a revocation mid-queue is a clean terminal failure, never a requeue loop" ); }); // ─── 7. Wiring: access-remove route (adpanel:access-remove-retract) ───────── test("the access-remove route retracts the user's schedules and queued planner jobs like the sibling revocations", () => { // Removing an access row ended neither the target's schedules nor their // queued planner-source agent jobs: the rows lingered as phantom pending // budget holding the item's dedupe slot and polling as live, while // grant-perms and suspension each ran BOTH passes. The remove route must // mirror them through the SAME shared helpers — no forked passes. const routeStart = INDEX_SRC.indexOf('app.post("/api/settings/accounts/:email/remove"'); assert.notStrictEqual(routeStart, -1, "the access-remove route must exist"); const routeEnd = INDEX_SRC.indexOf("\napp.", routeStart + 1); const body = INDEX_SRC.slice(routeStart, routeEnd); const mutationAt = body.indexOf("changeAccountAccess(db, currentUser, targetUser, server, false)"); const schedulesAt = body.indexOf("cancelSchedulesCreatedBy(targetUser"); const jobsAt = body.indexOf("cancelQueuedAiAgentJobsForUser(targetUser.id"); assert.notStrictEqual(mutationAt, -1, "the access-row removal must stay"); assert.notStrictEqual(schedulesAt, -1, "the schedule re-validation pass is missing"); assert.notStrictEqual(jobsAt, -1, "the queued planner-job retract pass is missing"); assert.ok( mutationAt < schedulesAt && schedulesAt < jobsAt, "the passes must run AFTER the access row is removed (schedules first, then the queued rows) — mirroring the sibling ordering" ); // The jobs pass is gated by the ONE shared predicate (grant-perms's own // gate — kept when the target still resolves as authorized, e.g. a surviving // wildcard row) and scoped to the removed server + the planner job sources // with the planner_access_revoked terminal reason. assert.ok( body.includes('schedulerActionStillAuthorizedAfterPermChange(emailLower, "planner_next_to_agent"'), "the jobs retract must be gated by the shared reauthorize predicate (planner_next_to_agent is a queued planner job's schedule shape), never a second inline copy" ); assert.ok( body.includes("sources: PLANNER_AGENT_JOB_SOURCES") && body.includes('error: "planner_access_revoked"'), "the retract must be scoped to the planner job sources with the planner_access_revoked terminal reason" ); assert.ok( body.includes('reason: "server access removed"'), "the schedule pass must carry a removal-specific reason for the scheduler log" ); // The wildcard row covered every server, so the passes must not scope to a // server literally named "all" (no schedule or job row carries it): the // schedule pass revalidates across ALL the target's schedules (reauthorize // keeps authorized ones) and the jobs pass sweeps the servers index, // retracting per server only where the predicate fails. assert.ok( body.includes("jobsRetractServers = isWildcard") && body.includes("loadServersIndex()"), "the wildcard ('all') removal must widen the sweep to the servers index instead of scoping by a server name no schedule/job row carries" ); // Best-effort with warn, never failing the removal — matching the sibling // wiring's error handling. assert.ok( body.includes('console.warn("[account-access-remove] Failed to re-validate user schedules:"') && body.includes("console.warn(\"[account-access-remove] Failed to retract the user's queued planner agent jobs:\""), "a failed pass must warn and never fail the removal — matching the sibling error handling" ); });