Files
Kelx/tests/ai-job-server-identity.test.js
2026-11-30 16:32:37 +00:00

676 lines
36 KiB
JavaScript

"use strict";
// Source-level pins and real-sliced behavioral drives for the ai_agent_jobs
// enqueue/claim identity bind (adpanel:ai-job-server-identity).
//
// The audited hole: a queued ai_agent_jobs row carried NO server identity —
// only server_name. The row is inserted at fire/enqueue time authorized
// against the server row resolved THEN (insertAiAgentChatJob's findServer +
// 404 + access + suspension gates), but processAiAgentJob later re-resolves
// the server BY NAME and re-checks existence/suspension/access/capability
// without being able to compare identity — so an admin-creator's queued row
// could execute on a same-name recreate landing between enqueue and claim
// (seconds-to-minutes under the enqueue/claim concurrency caps — the same
// consequence class the fire-time identity binds
// (adpanel:scheduler-server-identity-bind) closed for the BullMQ jobs, at a
// different binding point: the queued DB row itself).
//
// The fix pinned here:
//
// 1. ai_agent_jobs.server_id (VARCHAR(120) NULL) exists in ALL THREE DDL
// surfaces in lockstep — mysql-schema.sql, the runtime CREATE TABLE and
// the idempotent boot ALTER (AFTER server_name in every one, so fresh
// installs and migrated tables are byte-identical in column order).
// VARCHAR(120) is the composed id's own domain (servers.legacy_id is
// VARCHAR(120), else the BIGINT id's 20-digit string).
// 2. The ONE INSERT site (insertAiAgentChatJob — every source: interactive,
// planner_send, scheduler_prompt, scheduler_planner_next) stamps
// server_id = String(entry.id): the composed legacy_id-first id of the
// row findServer resolved above the 404 — the SAME field the fire-time
// BullMQ bind stores as job.data.serverId.
// 3. processAiAgentJob re-binds identity at claim time through the ONE
// shared String-coerced comparison core
// (schedulerServerIdentityMismatch — the same core the fire path
// consumes, stored arm only: the authz arm is passed null because the
// job ROW is the authorization record here). Checked FIRST after the
// server resolution, before the state gates, so the outcome never
// depends on the recreated row's state; a mismatch is a 403-class CLEAN
// TERMINAL failure (run-scoped failed write + chat note — never a
// requeue), and a NULL/absent stored id (pre-migration rows) skips the
// gate and drains naturally. String coercion preserves the same-row
// legacy_id backfill pass (number vs String of the same id).
//
// index.js is a ~56k-line application bundle (module side effects, DB and
// network at require time — never require() it from a test), so the
// behavioral cases drive the REAL sliced functions evaluated with injected
// fakes, matching the convention of tests/scheduler-hardening.test.js; the
// structural pins follow tests/planner-job-retract.test.js's DDL-lockstep
// pattern.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const { createRequire } = require("node:module");
const { agentScheduleRef, storeAgentSubmission } = require("../AgentWorker/admission");
const { createAgentDiagnostics } = require("../AgentWorker/panel-diagnostics");
const ROOT = path.join(__dirname, "..");
const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
const SCHEMA_SRC = fs.readFileSync(path.join(ROOT, "mysql-schema.sql"), "utf8");
const LEADER_SRC = fs.readFileSync(path.join(ROOT, "utils", "scheduler-leader.js"), "utf8");
const ADMISSION_SRC = fs.readFileSync(require.resolve("../AgentWorker/admission"), "utf8");
const RUNNER_PATH = require.resolve("../AgentWorker/run-job");
const RUNNER_SRC = fs.readFileSync(RUNNER_PATH, "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 server_id column exists in every DDL surface ────────────────────
const COLUMN_DECL = "server_id VARCHAR(120) NULL";
test("ai_agent_jobs.server_id exists in the runtime DDL, mysql-schema.sql (same position) and the boot ALTER", () => {
// adpanel:ai-job-server-identity — the bind column must exist on fresh
// installs (both CREATE paths) AND on pre-existing tables (the boot ALTER),
// in the SAME position everywhere, or the INSERT that names it fails.
const createWindow = windowBetween(
INDEX_SRC,
"CREATE TABLE IF NOT EXISTS ai_agent_jobs (",
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"ai_agent_jobs runtime DDL"
);
assert.ok(
createWindow.includes(COLUMN_DECL),
"the runtime CREATE TABLE for ai_agent_jobs must declare server_id — the one INSERT names the column"
);
const schemaWindow = windowBetween(
SCHEMA_SRC,
"CREATE TABLE IF NOT EXISTS ai_agent_jobs (",
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
"ai_agent_jobs schema DDL"
);
assert.ok(
schemaWindow.includes(COLUMN_DECL),
"mysql-schema.sql must declare server_id in lockstep with the runtime DDL — fresh installs build from this file"
);
// Same position in BOTH create paths: directly AFTER server_name, matching
// the boot ALTER's AFTER clause, so fresh and migrated tables are
// byte-identical in column order.
const runtimeNameAt = createWindow.indexOf("server_name VARCHAR(120) NOT NULL");
const schemaNameAt = schemaWindow.indexOf("server_name VARCHAR(120) NOT NULL");
assert.notStrictEqual(runtimeNameAt, -1, "runtime DDL must keep server_name");
assert.notStrictEqual(schemaNameAt, -1, "schema DDL must keep server_name");
assert.ok(
createWindow.indexOf(COLUMN_DECL) > runtimeNameAt && schemaWindow.indexOf(COLUMN_DECL) > schemaNameAt,
"server_id must sit AFTER server_name in BOTH create paths (same position as the boot ALTER's AFTER clause)"
);
// Boot ALTER for pre-existing tables — must stay, idempotent, and its
// failure must be loud: the ONE insert names the column, so a swallowed
// failure means EVERY agent job enqueue fails.
assert.strictEqual(
(INDEX_SRC.match(/ALTER TABLE ai_agent_jobs ADD COLUMN server_id VARCHAR\(120\) NULL AFTER server_name/g) || []).length,
1,
"the boot ALTER must exist exactly once"
);
const alterWindow = windowBetween(
INDEX_SRC,
"ALTER TABLE ai_agent_jobs ADD COLUMN server_id VARCHAR(120) NULL AFTER server_name`",
"// adpanel:planner-job-retract — widen the status ENUM",
"server_id boot ALTER"
);
assert.ok(
alterWindow.includes("alterErr.message.includes('Duplicate column')"),
"the boot ALTER must tolerate the Duplicate column race (idempotent re-runs on the lazy init path)"
);
assert.ok(
alterWindow.includes("console.error('[ai-chat] Could not add server_id to ai_agent_jobs — agent job enqueues will fail until the column exists:'"),
"a failed boot ALTER must log at error level with the enqueue-impact message — the INSERT names the column"
);
});
// ─── 2. The stamp: ONE insert site carries the bind for every source ────────
test("the ONE ai_agent_jobs INSERT stamps server_id with the composed id of the enqueue-resolved row", () => {
assert.strictEqual(
(INDEX_SRC + ADMISSION_SRC + RUNNER_SRC).split("INSERT INTO ai_agent_jobs").length - 1,
1,
"exactly ONE producer exists — the resume/requeue/terminal/retract paths all UPDATE; a second INSERT would bypass the stamp"
);
const insertWindow = windowBetween(
ADMISSION_SRC,
"INSERT INTO ai_agent_jobs",
"await tx.execute(\"UPDATE ai_chats",
"insert stamp"
);
assert.ok(
insertWindow.includes("server_name, server_id, provider"),
"the INSERT must name server_id directly after server_name (the composed id of the row findServer resolved above the 404)"
);
assert.ok(
insertWindow.includes("chatId, user.id, String(user.email || \"\").trim().toLowerCase(), serverName, serverId") &&
functionWindow(INDEX_SRC, "async function insertAiAgentChatJob", "enqueue adapter").includes("serverId: entry.id == null ? null : String(entry.id)"),
"the stamped value must be String(entry.id) — the same composed legacy_id-first field mapServerRow projects and the fire-time BullMQ bind stores; null only on the defensive no-id arm"
);
assert.ok(
functionWindow(INDEX_SRC, "async function insertAiAgentChatJob", "enqueue adapter").includes("adpanel:ai-job-stamp-single-resolution"),
"the adapter must document why it carries the verified server identity"
);
});
// The REAL sliced insertAiAgentChatJob, driven with fakes, records its
// executed statements. The private-transaction path is used (no external
// conn): GET_LOCK, the capacity read and all three INSERTs share the
// connection, then commit + the post-commit pump. run(overrides) threads the
// optional serverEntry option (adpanel:ai-job-stamp-single-resolution);
// without it the harness call is byte-identical to the pre-option shape and
// the internal findServer drives the stamp. findServer counts its calls so
// the single-resolution discrimination is observable.
function makeInsertRunner({ findServerRow, stats = {}, maxPending = 500, maxPendingPerAccount = 20 } = {}) {
const executed = [];
const committed = [];
const released = [];
const capacityReads = [];
const receipts = new Map();
let findServerCalls = 0;
const conn = {
beginTransaction: async () => {},
execute: async (sql, params) => {
executed.push({ sql, params });
if (sql.includes("FROM ai_agent_worker_state")) return [[{ enabled: 1, generation: "1" }]];
if (sql.includes("FROM ai_agent_schedule_receipts")) {
const [scheduleRef, occurrenceRef] = params;
return [[...receipts.values()].filter((receipt) => receipt.schedule_ref === scheduleRef &&
(receipt.occurrence_ref === "" || receipt.occurrence_ref === occurrenceRef))];
}
if (sql.includes("INSERT INTO ai_agent_schedule_receipts")) {
const [schedule_ref, occurrence_ref = "", job_id, chat_id] = params;
const key = `${schedule_ref}/${occurrence_ref}`;
if (occurrence_ref) assert.equal(receipts.has(key), false);
receipts.set(key, { schedule_ref, occurrence_ref, job_id: String(job_id), chat_id: String(chat_id) });
return [{}];
}
if (sql.includes("SELECT user_id, source")) {
capacityReads.push({ sql, params });
return [Array.from({ length: Number(stats.pending_count || 0) }, (_, index) => ({
user_id: index < Number(stats.account_pending_count || 0) ? 42 : 21, source: "live_chat",
}))];
}
if (sql.includes("INSERT INTO ai_chats")) return [{ insertId: 55 }];
if (sql.includes("INSERT INTO ai_messages")) return [{ insertId: 44 }];
if (sql.includes("INSERT INTO ai_agent_jobs")) return [{ insertId: 99 }];
return [{}];
},
commit: async () => { committed.push(true); },
rollback: async () => {},
release: () => { released.push(true); },
};
const body = functionWindow(INDEX_SRC, "async function insertAiAgentChatJob", "insertAiAgentChatJob");
const insertAiAgentChatJob = new Function(
"userCanUseAdpanelAgent", "assertAiProviderReady", "sanitizeAiAgentPrompt",
"findServer", "userHasAccessToServer", "isServerSuspended", "ensureAiChatTablesReady",
"normalizeFilePermEnvelope", "safeTruncateUtf16", "deriveAiAgentChatTitle",
"formatAiMessageModelLabel", "sanitizeAiAgentSource", "sanitizeAiAgentSourceRef",
"AI_AGENT_MAX_PENDING_JOBS", "AI_AGENT_MAX_PENDING_JOBS_PER_USER", "agentRuntime",
"db", "storeAgentSubmission", "pinnedPlannerAuthorIdFromEnvelope",
body + "\nreturn insertAiAgentChatJob;"
)(
() => true,
(provider, model) => ({ provider, model, settings: {} }),
(p) => String(p || ""),
async () => { findServerCalls += 1; return findServerRow; },
async () => true,
() => false,
async () => {},
() => null,
(s) => String(s),
() => "derived title",
() => "model-label",
(s) => String(s || "manual"),
(s) => s,
maxPending,
maxPendingPerAccount,
{ requireReady: () => ({ generation: "1" }) },
{ pool: { getConnection: async () => conn }, query: async () => assert.fail("Admission must use the transaction connection") },
storeAgentSubmission,
new Function(functionWindow(INDEX_SRC, "function pinnedPlannerAuthorIdFromEnvelope", "planner author ID parser") + "\nreturn pinnedPlannerAuthorIdFromEnvelope;")(),
);
return {
run: (overrides = {}) => insertAiAgentChatJob({
user: { id: 42, email: "creator@example.com", admin: false, agent_access: true, suspended: false },
serverName: "srv01",
prompt: "do the thing",
provider: "openai",
model: "gpt-x",
source: "scheduler_prompt",
...overrides,
}),
executed, committed, released, capacityReads, conn,
findServerCalls: () => findServerCalls,
};
}
test("the real insert stamps server_id = String(entry.id) of the resolved row", async () => {
const runner = makeInsertRunner({ findServerRow: { id: 77, name: "srv01" } });
const result = await runner.run();
assert.strictEqual(result.jobId, 99, "the job insert must succeed");
assert.strictEqual(
runner.findServerCalls(),
1,
"a caller with no pre-resolved row must resolve internally exactly once — the enqueue→stamp behavior of every non-scheduled source is unchanged"
);
const jobInsert = runner.executed.find((c) => c.sql.includes("INSERT INTO ai_agent_jobs"));
assert.notStrictEqual(jobInsert, undefined, "the job INSERT must execute on the connection");
assert.ok(
jobInsert.sql.includes("server_name, server_id, provider, model"),
"the executed INSERT must name server_id after server_name"
);
const nameAt = jobInsert.params.indexOf("srv01");
assert.notStrictEqual(nameAt, -1, "the stored server_name must be bound");
assert.strictEqual(
jobInsert.params[nameAt + 1],
"77",
"the very next bound value must be the COMPOSED id's String form — the same field the fire-time BullMQ bind stores"
);
assert.strictEqual(runner.committed.length, 1, "the job and prompt must commit together");
});
test("scheduled Agent jobs keep the Planner item and the schedule identity in separate fields", async () => {
const repeatKey = "shared-test-key";
for (const [occurrence, reference] of [
[null, null],
[{ id: repeatKey, timestamp: Date.now() }, agentScheduleRef(repeatKey)],
[{ id: "iteration", repeatJobKey: repeatKey, timestamp: Date.now() }, agentScheduleRef(null, repeatKey)]
]) {
const runner = makeInsertRunner({ findServerRow: { id: 77, name: "srv01" } });
const source = occurrence ? "scheduler_planner_next" : "planner_send";
await runner.run({ source, sourceRef: "31", occurrence });
const { sql, params } = runner.executed.find((call) => call.sql.includes("INSERT INTO ai_agent_jobs"));
assert.match(sql, /source, source_ref,/);
assert.match(sql, /schedule_ref, auto_file_edit_generation\)/);
assert.equal((sql.match(/\?/g) || []).length, params.length);
assert.equal(params[params.indexOf(source) + 1], "31");
assert.equal(params.at(-2), reference);
assert.equal(params.at(-1), null);
}
assert.notEqual(agentScheduleRef(repeatKey), agentScheduleRef(null, repeatKey));
});
test("redelivery reuses the admitted firing and retirement blocks later firings of only that schedule", async () => {
const { retireAgentSchedule } = require("../AgentWorker/queue-state");
const runner = makeInsertRunner({ findServerRow: { id: 77, name: "srv01" } });
const occurrence = { id: "iteration-one", repeatJobKey: "recurrence", timestamp: Date.now(),
data: { autoApproveFileEdits: true, userId: 42, serverId: 77 } };
const run = (firing) => runner.run({ occurrence: firing,
user: { id: 42, email: "creator@example.test", session_epoch: 1 } });
const original = await run(occurrence);
assert.deepEqual(await run(occurrence), { jobId: String(original.jobId), chatId: String(original.chatId),
skipped: true, reason: "agent_occurrence_already_admitted" });
assert.equal(runner.executed.filter(({ sql }) => sql.includes("INSERT INTO ai_agent_jobs")).length, 1);
await retireAgentSchedule(runner.conn, agentScheduleRef(null, occurrence.repeatJobKey));
await assert.rejects(run({ ...occurrence, id: "iteration-two" }), { code: "agent_occurrence_skipped" });
await run({ ...occurrence, repeatJobKey: "different-schedule" });
assert.equal(runner.executed.filter(({ sql }) => sql.includes("INSERT INTO ai_agent_jobs")).length, 2);
});
test("Agent admission does not infer consent from an old schedule, live chat, or a client flag on a scheduled job", async () => {
const user = { id: 42, email: "creator@example.test", session_epoch: 1 };
const oldOccurrence = { id: "scheduler-job", timestamp: Date.now(), data: {} };
const authorizedOccurrence = { ...oldOccurrence, data: { autoApproveFileEdits: true, userId: 42, serverId: 77 } };
for (const [options, consent] of [
[{ source: "planner_send", autoApproveFileEdits: true }, true],
[{ source: "planner_send", autoApproveFileEdits: "true" }, false],
[{ source: "planner_send", autoApproveFileEdits: true, user: { ...user, session_epoch: null } }, false],
[{ source: "scheduler_prompt", occurrence: oldOccurrence, autoApproveFileEdits: true }, false],
[{ source: "scheduler_planner_next", occurrence: authorizedOccurrence }, true],
[{ source: "scheduler_prompt", occurrence: authorizedOccurrence }, true],
[{ source: "scheduler_prompt", occurrence: { ...authorizedOccurrence, data: { ...authorizedOccurrence.data, userId: 43 } } }, false],
[{ source: "scheduler_prompt", occurrence: { ...authorizedOccurrence, data: { ...authorizedOccurrence.data, serverId: 78 } } }, false],
[{ source: "live_chat", autoApproveFileEdits: true, occurrence: authorizedOccurrence }, false],
]) {
const runner = makeInsertRunner({ findServerRow: { id: 77, name: "srv01" } });
await runner.run({ user, ...options });
const { sql, params } = runner.executed.find((call) => call.sql.includes("INSERT INTO ai_agent_jobs"));
assert.match(sql, /read_only, auto_approve_file_edits,\s+schedule_ref, auto_file_edit_generation\)/);
assert.equal(params.at(-3), consent);
assert.equal(params[11] === null, consent, "the legacy generation must be NULL only for fenced automatic jobs");
assert.equal(params.at(-1) !== null, consent, "only automatic jobs use the separate generation");
}
});
test("Agent admission still honors the fixed pending queue limit, independently of active capacity", async () => {
for (const [pending, ceiling, admitted] of [
[200, 500, true], [499, 500, true], [500, 500, false], [202, 202, false],
]) {
const runner = makeInsertRunner({ findServerRow: { id: 77, name: "srv01" }, maxPending: ceiling, stats: {
pending_count: String(pending),
} });
if (admitted) assert.equal((await runner.run()).jobId, 99);
else await assert.rejects(runner.run(), { status: 503, message: /queue is full/ });
assert.equal(runner.committed.length, admitted ? 1 : 0);
assert.equal(runner.executed.some(({ sql }) => sql.includes("INSERT INTO ai_chats")), admitted);
assert.equal(runner.capacityReads.length, 1);
const [read] = runner.capacityReads;
assert.match(read.sql, /WHERE status IN \('queued','running'\) LIMIT \d+ FOR UPDATE/);
}
});
test("transactional Planner enqueues preserve the per-account pending-job limit", async () => {
const runner = makeInsertRunner({ findServerRow: { id: 77, name: "srv01" }, stats: {
pending_count: 200, account_pending_count: 20,
} });
await assert.rejects(runner.run({ source: "planner_send", conn: runner.conn }), { status: 503, message: /per-user queue limit/ });
assert.equal(runner.capacityReads.length, 1);
assert.equal(runner.executed.some(({ sql }) => sql.includes("INSERT INTO ai_agent_jobs")), false);
assert.deepEqual(runner.released, []);
assert.deepEqual(runner.committed, []);
});
test("a null/absent serverEntry keeps the internal-resolution fallback byte-identical", async () => {
// adpanel:ai-job-stamp-single-resolution — the option is opt-in per call:
// planner_send and every other caller pass nothing (or a null unresolved
// fallback row from a helper), and the insert must resolve internally and
// stamp that row exactly as before the option existed.
for (const serverEntry of [null, undefined]) {
const runner = makeInsertRunner({ findServerRow: { id: 77, name: "srv01" } });
const result = await runner.run({ serverEntry });
assert.strictEqual(result.jobId, 99, "the job insert must succeed");
assert.strictEqual(runner.findServerCalls(), 1, "the internal resolution must run for a falsy serverEntry");
const jobInsert = runner.executed.find((c) => c.sql.includes("INSERT INTO ai_agent_jobs"));
const nameAt = jobInsert.params.indexOf("srv01");
assert.strictEqual(jobInsert.params[nameAt + 1], "77", "the stamp must come from the internal resolution");
}
});
test("single-resolution: the scheduled path stamps the GATE-verified row — a second resolution (the recreated row) is never consulted, and the claim against it refuses", async () => {
// The full scheduled chain, end to end: authz findServer (bind) -> gate
// findServer verifies row N -> insert stamps N with NO second lookup ->
// claim re-resolves the name to the recreated M and the stored-arm bind
// refuses N-vs-M terminally. The insert's internal findServer is rigged to
// return the RECREATED row: before this fix the re-resolution stamped 200,
// the claim compared it against the same recreated row and passed, and the
// stored prompt executed once on the different-owner server.
const GATE_ROW = { id: 100, name: "srv01" };
const RECREATED_ROW = { id: 200, name: "srv01" };
const runner = makeInsertRunner({ findServerRow: RECREATED_ROW });
const result = await runner.run({ serverEntry: GATE_ROW });
assert.strictEqual(result.jobId, 99, "the job insert must succeed");
assert.strictEqual(
runner.findServerCalls(),
0,
"a supplied gate-verified row must REPLACE the internal resolution — the second lookup was the insert-time recreate micro-window"
);
const jobInsert = runner.executed.find((c) => c.sql.includes("INSERT INTO ai_agent_jobs"));
const nameAt = jobInsert.params.indexOf("srv01");
assert.strictEqual(
jobInsert.params[nameAt + 1],
"100",
"the stamp must be the GATE row's composed id (100) — never the recreated row's id (200) the internal resolution would have returned"
);
// Downstream half: the claim re-resolves by name to M=200 while the row is
// stamped N=100 — the ONE shared core's stored arm refuses, terminally,
// before any billable call.
const claim = makeClaimRunner({
row: { ...BASE_ROW, server_id: "100" },
findServerRow: RECREATED_ROW,
});
await claim.run();
assert.strictEqual(claim.providerReached(), 0, "the recreated server must not inherit the billable run");
const failedWrite = claim.queries.find((q) => q.sql.includes("UPDATE ai_agent_jobs SET status = 'failed'"));
assert.notStrictEqual(failedWrite, undefined, "the claim must terminally refuse once the name resolves to the recreated row");
assert.strictEqual(failedWrite.params[0], "agent_authority_revoked");
});
// ─── 3. The claim-time re-bind ───────────────────────────────────────────────
// The REAL shared comparison core, sliced from between its doctrine comment
// and the next comment anchor (the same window scheduler-hardening.test.js
// slices) — both the enqueue gates and the new claim gate must decide through
// this ONE implementation, never a re-implemented compare.
function sliceIdentityCore() {
const src = windowBetween(
INDEX_SRC,
"function schedulerServerIdentityMismatch(",
"\n// adpanel:planner-access-job-retract",
"identity comparison core"
);
return new Function(`${src}\nreturn schedulerServerIdentityMismatch;`)();
}
const realIdentityCore = sliceIdentityCore();
test("the claim gate reuses the ONE shared comparison core and fails closed, terminally, first", () => {
const body = functionWindow(INDEX_SRC, "async function authorizeAgentJobClaim", "authorizeAgentJobClaim");
// Placement: after the server resolution's 404, BEFORE the state gates —
// the outcome must not depend on the recreated row's state (a suspended
// impostor must not turn the refusal into "Server is suspended."), and the
// state gates keep their exact positions for every matching row.
const notFoundAt = body.indexOf('new Error("Server not found.")');
const identityAt = body.indexOf("schedulerServerIdentityMismatch(entry.id, null, row.server_id)");
const suspendedAt = body.indexOf("if (isServerSuspended(entry)) {");
const plannerGateAt = body.indexOf("adpanel:planner-runner-access-gate");
assert.notStrictEqual(notFoundAt, -1, "the server-not-found gate must stay");
assert.notStrictEqual(identityAt, -1, "the identity re-bind must call the ONE shared core (candidate = the RESOLVED row's composed id; stored arm only — null authz row)");
assert.notStrictEqual(suspendedAt, -1, "the suspension gate must stay");
assert.ok(
notFoundAt < identityAt && identityAt < suspendedAt && suspendedAt < plannerGateAt,
"order must be: server resolution/404 -> identity re-bind -> state gates (suspension, access, planner/scheduler revoke gates — untouched and additive-to)"
);
assert.ok(
body.includes("error.status = 403;") &&
body.includes("`Scheduled server identity mismatch (same-name recreate): resolved ${identityMismatch.resolvedIdentity} vs ${identityMismatch.comparedAgainst}.`"),
"a mismatch must be a 403-class terminal gate error in the established fire-time message family"
);
assert.ok(
RUNNER_SRC.includes('const context = await call("context");') &&
RUNNER_SRC.includes("await failAgentClaim(db, row, reason);"),
"the gate throw must land in the run-scoped failed write — never a requeue (the resume/pump lookups select ONLY queued rows)"
);
assert.ok(
body.includes("adpanel:ai-job-server-identity"),
"the claim gate must carry the adpanel:ai-job-server-identity constraint comment"
);
});
// The REAL sliced processAiAgentJob, driven with fakes bound to the REAL
// identity core. The fake db records every query so the assertions can see
// the terminal writes; completeAiChatConversation is a counter — a gate
// refusal must never reach the billable provider call.
function makeClaimRunner({ row, findServerRow, revokeDuringModel = false } = {}) {
const queries = [];
let providerCalls = 0;
let postProcessCalls = 0;
row = { ...row, started_at: new Date(), feature_generation: "1" };
const connection = {
beginTransaction: async () => {}, commit: async () => {}, rollback: async () => {}, release: () => {},
execute: async (sql, params) => {
queries.push({ sql, params });
if (sql.includes("FROM ai_agent_worker_state")) return [[{ enabled: 1, generation: "1" }]];
if (sql.includes("SELECT running.id")) return [[]];
if (sql.includes("SET status = 'running'")) row.claim_token = params[0];
if (sql.startsWith("SELECT * FROM ai_agent_jobs")) return [[row]];
if (sql.startsWith("SELECT id FROM ai_chats")) return [[{ id: row.chat_id }]];
return [{ affectedRows: 1, insertId: 10 }];
},
};
const db = {
pool: { getConnection: async () => connection },
query: async (sql, params) => {
queries.push({ sql, params });
if (sql.includes("UPDATE ai_agent_jobs SET status = 'failed'")) return { affectedRows: 1 };
if (sql.startsWith("SELECT job.*")) return [row];
if (sql.startsWith("SELECT 1 FROM ai_agent_jobs")) return [{}];
assert.fail(`Unexpected query: ${sql}`);
},
};
const user = { id: 42, email: "creator@example.com", admin: false, suspended: false, agent_access: true };
const authority = functionWindow(INDEX_SRC, "async function authorizeAgentJobClaim", "authorizeAgentJobClaim");
const authorizeAgentJobClaim = new Function(
"db", "findUserById", "userCanUseAdpanelAgent",
"findServer", "schedulerServerIdentityMismatch", "isServerSuspended", "userHasAccessToServer",
"PLANNER_AGENT_JOB_SOURCES", "getEffectivePermsForUserOnServer",
"resolveSchedulerPlannerAuthorForJob", "buildBackgroundAgentRequest", "createServerAgentJobPermissionReader", "assertAiAgentJobDeadline",
authority + "\nreturn authorizeAgentJobClaim;"
)(
db,
async (accountId) => { assert.equal(accountId, user.id); return { ...user }; },
(u) => !!(u && (u.admin || (!u.suspended && u.agent_access))),
async () => findServerRow,
realIdentityCore,
() => false,
async () => true,
new Set(["scheduler_planner_next", "planner_send"]),
async () => ({ planner_access: true, scheduler_access: true }),
async () => ({ authorId: null, authorResolved: false }),
() => ({}),
require("../services/server-agent-job-auth").createServerAgentJobPermissionReader,
require("../AgentWorker/run-deadline").assertAiAgentJobDeadline,
);
const callPanel = createAgentDiagnostics({ db, featureEnabled: () => true, authorizeAgentJobClaim,
getAccessibleServerEntriesForAi: async () => [findServerRow], applyAiAgentPermClamp: async (_req, permissions) => permissions,
postProcessAiAgentResponse: async () => { postProcessCalls += 1; return "ran"; },
});
const runnerModule = { exports: {} };
const requireRunner = createRequire(RUNNER_PATH);
new Function("module", "require", RUNNER_SRC)(runnerModule, (name) => name === "./conversation" ? {
createAgentConversation: () => async () => {
providerCalls += 1;
if (revokeDuringModel) user.agent_access = false;
return { content: "FILE_LIST:." };
},
} : requireRunner(name));
const processAiAgentJob = runnerModule.exports.createAgentJobRunner({
db, generation: "1", active: new Map(), callPanel, stopping: () => false, assertDeadline: () => {},
getProviderSettings: (provider, model) => ({ provider, model, settings: {} }), formatModelLabel: () => "fixture",
});
return {
run: () => processAiAgentJob(row.id),
authorize: () => authorizeAgentJobClaim(row, Date.now() + 5000, new AbortController().signal),
queries,
providerReached: () => providerCalls,
postProcessReached: () => postProcessCalls,
};
}
test("Agent access revoked during completion blocks all subsequent file post-processing", async () => {
const runner = makeClaimRunner({ row: { ...BASE_ROW, server_id: "32" }, findServerRow: { id: 32, name: BASE_ROW.server_name }, revokeDuringModel: true });
await runner.run();
assert.equal(runner.providerReached(), 1);
assert.equal(runner.postProcessReached(), 0);
assert.ok(runner.queries.some(({ sql }) => sql.includes("SET status = 'failed'")));
});
const BASE_ROW = {
id: 9,
chat_id: 3,
user_id: 42,
user_email: "creator@example.com",
started_at: "2026-01-01 00:00:00",
status: "running",
source: "manual",
server_name: "srv01",
prompt: "do the thing",
provider: "openai",
model: "gpt-x",
};
test("claim mismatch is a terminal authority refusal with no provider call or assistant write", async () => {
// The row was authorized against server row 100; the name now resolves to a
// RECREATED row 200 — the queued run must not inherit the recreate.
const runner = makeClaimRunner({
row: { ...BASE_ROW, server_id: "100" },
findServerRow: { id: 200, name: "srv01" },
});
await assert.rejects(runner.authorize(), { status: 403, message: /resolved 200 vs 100/ });
await runner.run();
assert.strictEqual(
runner.providerReached(),
0,
"the run must be refused BEFORE any provider call — a same-name recreate must never inherit the billable run"
);
const failedWrite = runner.queries.find((q) => q.sql.includes("UPDATE ai_agent_jobs SET status = 'failed'"));
assert.notStrictEqual(failedWrite, undefined, "the run-scoped failed write must land");
assert.match(failedWrite.sql, /WHERE id = \? AND status = 'running' AND claim_token = \? AND feature_generation = \?/);
assert.strictEqual(failedWrite.params[0], "agent_authority_revoked");
assert.ok(!runner.queries.some(({ sql }) => sql.includes("INSERT INTO ai_messages")));
assert.strictEqual(
runner.queries.filter((q) => q.sql.includes("SET status = 'completed'")).length,
0,
"a refused run must never reach the completed write"
);
});
test("a legacy NULL stored id skips the identity gate and the run proceeds through the established gates", async () => {
// Pre-migration rows carry no bind: the population is transient (terminal
// rows drain within the runtime cap and are pruned), so the gate skips and
// every other gate still applies — the run completes normally here.
const runner = makeClaimRunner({
row: { ...BASE_ROW, server_id: null },
findServerRow: { id: 100, name: "srv01" },
});
await runner.run();
assert.strictEqual(runner.providerReached(), 1, "the run must proceed to the provider call");
const completedWrite = runner.queries.find((q) => q.sql.includes("SET status = 'completed'"));
assert.notStrictEqual(completedWrite, undefined, "the run-scoped completed write must land");
assert.strictEqual(
runner.queries.filter((q) => q.sql.includes("UPDATE ai_agent_jobs SET status = 'failed'")).length,
0,
"a NULL stored id must never fail the run"
);
});
test("a same-row backfill coercion passes: numeric resolved id vs String stored id for the SAME row", async () => {
// The composed id is not immutable on the row: a legacy_id backfill landing
// mid-queue flips entry.id from the number N to the string "N" of the SAME
// row. The core's String coercion must read that as a match — only a
// DIFFERENT row (never-reused AUTO_INCREMENT id) is a recreate.
const runner = makeClaimRunner({
row: { ...BASE_ROW, server_id: "100" },
findServerRow: { id: 100, name: "srv01" },
});
await runner.run();
assert.strictEqual(runner.providerReached(), 1, "the run must proceed");
assert.strictEqual(
runner.queries.filter((q) => q.sql.includes("UPDATE ai_agent_jobs SET status = 'failed'")).length,
0,
"a same-row backfill must never fail the run"
);
});
// ─── 4. The scheduler-leader TTL sentence matches the module's own behavior ─
test("the scheduler-leader header no longer claims the TTL is only a PID-probe fail-safe", () => {
// isOwnerStale (utils/cross-process-mutex.js) checks the staleAfterMs TTL
// BEFORE the PID probes, so the steal also fires for a live holder whose
// heartbeat stalled past the TTL — the module's own DEPOSED paragraph
// states this correctly; the FAILOVER bullet used to contradict it.
assert.ok(
!LEADER_SRC.includes("is only the fail-safe for\ndeaths the PID probes cannot see"),
"the factually wrong 'only the fail-safe' framing must stay gone"
);
assert.ok(
LEADER_SRC.includes("is checked BEFORE the PID\n// probes (isOwnerStale tests it first)"),
"the header must state the real order: the TTL is checked before the PID probes (live-but-stalled holders steal too)"
);
assert.ok(
LEADER_SRC.includes("DEPOSED holders (only possible when a holder's event loop is blocked\n// past the TTL)"),
"the DEPOSED paragraph (the correct account) must stay untouched"
);
});