471 lines
24 KiB
JavaScript
471 lines
24 KiB
JavaScript
"use strict";
|
||
|
||
// Pins for adpanel:scheduler-jobdata-bounds — the scheduler create route's
|
||
// Redis job data residency bounds.
|
||
//
|
||
// Background: jobData is stored verbatim in the scheduler's SHARED Redis
|
||
// (the same instance backs the queue and the rate-limit stores), and a
|
||
// scheduler_create holder could pin ~1 MB per field per job, bounded only by
|
||
// the global 1 MB JSON body parser × the per-server task quota:
|
||
// - scheduleValue/scheduleTime were stored RAW (a scheduler_create holder
|
||
// could pin ~1 MB in scheduleValue alone — the per-type floors only
|
||
// bound backup/agent actions, and a nested non-string object coerces to
|
||
// NaN but was still stored);
|
||
// - for every action the WHOLE client payload object was stored, so
|
||
// arbitrary sibling keys (payload.junk) rode into Redis untouched.
|
||
//
|
||
// Fix (mirroring the scheduler-file-content-cap pattern at the same
|
||
// validation region):
|
||
// (a) scheduleValue/scheduleTime: when PRESENT (non-null) they must be
|
||
// strings of at most SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH (64) chars.
|
||
// 64 is generous for every legitimate shape scheduleToCron consumes —
|
||
// seconds/minutes/hourly integer strings, weekly day index, daily/
|
||
// weekly "HH:MM" — and there is NO cron-expression type
|
||
// (validScheduleTypes is once/seconds/minutes/hourly/daily/weekly;
|
||
// scheduleToCron returns null for anything else), so a longer value
|
||
// can never be legitimate. The shipped client (bot.js) only ever sends
|
||
// short strings from inputs/selects, so a present non-string is
|
||
// rejected rather than stored raw.
|
||
// (b)+(c) jobData.payload is reduced at assembly to exactly the keys each
|
||
// action's executor reads (derived from the worker's case handlers):
|
||
// console_command → command; create_file/modify_file → filePath,
|
||
// content; backup → backupName, description; planner_next_to_agent →
|
||
// provider, model (the executor resolves the prompt text from the DB
|
||
// planner item, not the payload); agent_prompt → prompt, provider,
|
||
// model. server_start/server_stop store {} outright (the worker reads
|
||
// NO payload keys and the shipped client sends {} — the "left whole"
|
||
// follow-up landed as adpanel:scheduler-payload-value-caps). VALUES
|
||
// are capped too (same tag): backup's backupName/description are
|
||
// clamped to 120/500 AT CREATE TIME with the worker's IDENTICAL
|
||
// adpanel:log-injection-backup-name strip chain (String → trim → C0/C1
|
||
// strip → whitespace collapse → trim → slice, so the stored form
|
||
// cannot carry controls either; the fire-time clamp still runs and
|
||
// also covers pre-gate stored jobs), and file-action filePath is gated at 512 in
|
||
// the route (pinned in scheduler-file-actions-style slices there — see
|
||
// tests/scheduler-payload-value-caps.test.js). The repeatable name's
|
||
// payloadHash still hashes the pre-reduction (pre-clamp) payload, so
|
||
// repeatable identity (and re-create-replaces-old) is unchanged across
|
||
// the deploy for shipped clients, whose payload already carries
|
||
// exactly these keys.
|
||
//
|
||
// Technique (scheduler-timezone.test.js precedent): the REAL jobData + queue
|
||
// add branches are sliced from index.js and evaluated with injected fakes; a
|
||
// stub schedulerQueue captures the exact (name, data, opts) handed to
|
||
// BullMQ. The schedule-field gate is sliced the same way
|
||
// scheduler-file-actions' content gate is.
|
||
|
||
const test = require("node:test");
|
||
const assert = require("node:assert");
|
||
const fs = require("node:fs");
|
||
const path = require("node:path");
|
||
const crypto = require("node:crypto");
|
||
|
||
const ROOT = path.join(__dirname, "..");
|
||
const INDEX_JS = path.join(ROOT, "index.js");
|
||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||
|
||
// Strip full-line comments so prose mentioning the markers cannot satisfy
|
||
// the source-level assertions.
|
||
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);
|
||
}
|
||
|
||
// The shipped cap, read from source — not a test-local copy.
|
||
const CAP_MATCH = indexCode.match(/const SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH = (\d+);/);
|
||
assert.ok(CAP_MATCH, "SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH must be declared in index.js");
|
||
const SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH = parseInt(CAP_MATCH[1], 10);
|
||
|
||
// The REAL scheduleToCron (same slice as scheduler-interval-floor), so the
|
||
// legitimacy claims about short values are checked against shipped code.
|
||
const { scheduleToCron } = new Function(
|
||
sliceFrom(indexSource, "const SCHEDULER_MIN_INTERVAL_SECONDS", "\nasync function shutdownScheduler(", "scheduleToCron") +
|
||
"\nreturn { scheduleToCron };"
|
||
)();
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// (a) The REAL schedule-field gate, sliced from the create route (window
|
||
// ends exactly where scheduler-file-actions' content-gate slice begins, so
|
||
// the two harnesses stay independent).
|
||
// ---------------------------------------------------------------------------
|
||
|
||
const scheduleGateBody = sliceFrom(
|
||
indexCode,
|
||
"if ((scheduleValue != null &&",
|
||
'const fileContent = (actionType === "create_file"',
|
||
"create-route schedule-field gate"
|
||
);
|
||
|
||
const runScheduleGate = new Function(
|
||
"scheduleValue", "scheduleTime", "res", "SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH",
|
||
`"use strict";
|
||
${scheduleGateBody}
|
||
return null;`
|
||
);
|
||
|
||
function gateSchedule(scheduleValue, scheduleTime) {
|
||
const sent = {};
|
||
const res = {
|
||
status(code) {
|
||
sent.code = code;
|
||
return { json(body) { sent.body = body; return body; } };
|
||
}
|
||
};
|
||
const result = runScheduleGate(scheduleValue, scheduleTime, res, SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH);
|
||
return { result, sent };
|
||
}
|
||
|
||
test("the schedule-field cap is 64, declared once, before the route gate uses it", () => {
|
||
assert.strictEqual(SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH, 64);
|
||
const declCount = (indexCode.match(/const SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH = /g) || []).length;
|
||
assert.strictEqual(declCount, 1, "the cap must have exactly one declaration");
|
||
const declAt = indexCode.indexOf("const SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH = 64;");
|
||
const gateAt = indexCode.indexOf("scheduleValue.length > SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH");
|
||
assert.ok(gateAt > declAt, "the route gate must reference the declared constant");
|
||
});
|
||
|
||
test("schedule-field gate: every legitimate shape passes (checked against the real scheduleToCron)", () => {
|
||
const legit = [
|
||
// [scheduleValue, scheduleTime, scheduleType] — the exact shapes bot.js sends.
|
||
["30", undefined, "seconds"],
|
||
["5", undefined, "minutes"],
|
||
["1", undefined, "hourly"],
|
||
[undefined, "09:00", "daily"],
|
||
["6", "23:45", "weekly"],
|
||
[undefined, undefined, "once"],
|
||
[null, null, "once"],
|
||
];
|
||
for (const [value, time, type] of legit) {
|
||
const { result, sent } = gateSchedule(value, time);
|
||
assert.strictEqual(result, null, JSON.stringify({ value, time, type }));
|
||
assert.strictEqual(sent.code, undefined, JSON.stringify({ value, time, type }));
|
||
// And the value really is a legitimate input for the shipped converter.
|
||
if (type !== "once") {
|
||
assert.notStrictEqual(scheduleToCron(type, value, time), null, `scheduleToCron(${type}) must accept the shape the gate lets through`);
|
||
}
|
||
}
|
||
});
|
||
|
||
test("schedule-field gate: a string exactly at the cap passes; cap+1 is rejected with the sibling 400 shape", () => {
|
||
const ok = gateSchedule("x".repeat(SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH), undefined);
|
||
assert.strictEqual(ok.result, null, "exactly at the cap must pass");
|
||
assert.strictEqual(ok.sent.code, undefined);
|
||
|
||
const { result, sent } = gateSchedule("x".repeat(SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH + 1), undefined);
|
||
assert.deepStrictEqual(result, {
|
||
ok: false,
|
||
error: `scheduleValue and scheduleTime must be short text (${SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH} characters or fewer)`
|
||
});
|
||
assert.strictEqual(sent.code, 400);
|
||
|
||
const time = gateSchedule(undefined, "x".repeat(SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH + 1));
|
||
assert.strictEqual(time.sent.code, 400, "the cap fires for scheduleTime too");
|
||
});
|
||
|
||
test("schedule-field gate: a PRESENT non-string is rejected (the shipped client only ever sends strings)", () => {
|
||
for (const bad of [30, 12.5, true, { junk: "x" }, ["x"]]) {
|
||
const { result, sent } = gateSchedule(bad, undefined);
|
||
assert.strictEqual(sent.code, 400, JSON.stringify(bad));
|
||
assert.strictEqual(result.ok, false, JSON.stringify(bad));
|
||
}
|
||
for (const bad of [9, { hour: 9 }, ["09:00"]]) {
|
||
const { sent } = gateSchedule(undefined, bad);
|
||
assert.strictEqual(sent.code, 400, `scheduleTime ${JSON.stringify(bad)}`);
|
||
}
|
||
});
|
||
|
||
test("schedule-field gate runs above the create lock (request-shape garbage never pays the quota)", () => {
|
||
const route = sliceFrom(
|
||
indexCode,
|
||
'app.post("/api/scheduler/:serverName/tasks"',
|
||
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
|
||
"scheduler create route"
|
||
);
|
||
const gateAt = route.indexOf("scheduleValue.length > SCHEDULER_MAX_SCHEDULE_FIELD_LENGTH");
|
||
const lockAt = route.indexOf("withSchedulerCreateLock(");
|
||
assert.ok(gateAt > -1 && lockAt > -1 && gateAt < lockAt, "the schedule-field gate must sit above withSchedulerCreateLock");
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// (b)+(c) The REAL jobData assembly + queue.add branches, evaluated with the
|
||
// route's in-scope bindings injected (scheduler-timezone.test.js harness).
|
||
// A stub schedulerQueue captures the exact (name, data, opts) handed to
|
||
// BullMQ.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
const makeTaskCreator = new Function(
|
||
"taskName", "serverName", "canonicalServer", "actionType", "payload", "scheduleType",
|
||
"scheduleValue", "scheduleTime", "timezone", "scheduledTimestamp",
|
||
"user", "serverEntry", "email", "schedulerQueue", "crypto", "scheduleToCron", "res", "console",
|
||
"runCreateRedisStep", "preAddRepeatableKeys", "autoApproveFileEdits", "serverRepeatables", "isAgentSchedule", "onceRequestId",
|
||
`"use strict";
|
||
return async () => {
|
||
${sliceFrom(
|
||
indexSource,
|
||
"const jobData = {",
|
||
"const userIp = getRequestIp(req);",
|
||
"jobData + add branches"
|
||
)}
|
||
return { job, jobData };
|
||
};`
|
||
);
|
||
|
||
// adpanel:scheduler-create-deadline — the add branches are now deadline-raced
|
||
// through the route's shared helper, so the harness binds the REAL sliced
|
||
// helper (with the real raceWithDeadline). These tests resolve the add
|
||
// immediately, so the production deadline (15s) never fires here.
|
||
const { awaitSchedulerCreateRedisStep: deadlineStepForBounds } = new Function(
|
||
"raceWithDeadline", "schedulerQueue", "console",
|
||
sliceFrom(
|
||
indexSource,
|
||
"const SCHEDULER_CREATE_REDIS_DEADLINE_MS = 15000;",
|
||
"\n// Server-side twin of the scheduler UI's interval floor",
|
||
"create-deadline helpers"
|
||
) + "\nreturn { awaitSchedulerCreateRedisStep };"
|
||
)(
|
||
require("../utils/scheduler-failure-streak").raceWithDeadline,
|
||
{ removeRepeatableByKey: async () => 0 }, // never reached: no abandonment in these tests
|
||
{ warn() {}, error() {}, log() {} }
|
||
);
|
||
|
||
async function storedJobData({ actionType, payload, scheduleType = "seconds", scheduleValue = "30", scheduleTime,
|
||
serverEntry = { id: 7, name: "srv01" }, autoApproveFileEdits = false, repeatableJobs = [] }) {
|
||
const adds = [];
|
||
const schedulerQueue = {
|
||
add: async (name, data, opts) => {
|
||
adds.push({ name, data, opts });
|
||
return { id: `job-${adds.length}` };
|
||
}
|
||
};
|
||
const responses = [];
|
||
const res = {
|
||
status: (code) => ({ json: (body) => responses.push({ code, body }) })
|
||
};
|
||
// The route guarantees payload is an object (`rawPayload && typeof ===
|
||
// "object" ? rawPayload : {}`), so the harness mirrors that shape.
|
||
const routeShapedPayload = payload == null ? {} : payload;
|
||
const { resolveSchedulerRepeatablesForServer } = require("../services/scheduler-task-scope");
|
||
const serverRepeatables = (await resolveSchedulerRepeatablesForServer(schedulerQueue, repeatableJobs, "srv01", serverEntry.id))
|
||
.filter(({ owned }) => owned !== false);
|
||
const result = await makeTaskCreator(
|
||
"Bounds probe", "srv01", "srv01", actionType, routeShapedPayload,
|
||
scheduleType, scheduleValue, scheduleTime, null, undefined,
|
||
{ id: 42 }, serverEntry, "creator@example.com", schedulerQueue, crypto, scheduleToCron,
|
||
res, { log() {} }, (operation, ...options) => deadlineStepForBounds(operation(), ...options),
|
||
null, autoApproveFileEdits, serverRepeatables, require("../AgentWorker/feature-http").isAgentSchedule, null
|
||
)();
|
||
if (responses.length) return { responses, adds };
|
||
const { jobData } = result;
|
||
assert.strictEqual(adds.length, 1, "exactly one queue.add call expected");
|
||
assert.strictEqual(responses.length, 0, "no error response may be produced for these inputs");
|
||
return { jobData, add: adds[0] };
|
||
}
|
||
|
||
test("consent changes only the job data, and an existing identical Agent repeatable is not replaced or duplicated", async () => {
|
||
const input = { actionType: "agent_prompt", payload: { prompt: "Adjust the fixture setting.", provider: "openai", model: "fixture" }, scheduleValue: "300" };
|
||
const legacy = await storedJobData(input);
|
||
const authorized = await storedJobData({ ...input, autoApproveFileEdits: true });
|
||
assert.equal(legacy.jobData.autoApproveFileEdits, undefined);
|
||
assert.equal(authorized.jobData.autoApproveFileEdits, true);
|
||
assert.equal(authorized.add.name, legacy.add.name);
|
||
const { key: oldKey, ...oldRepeat } = legacy.add.opts.repeat;
|
||
const { key: newKey, ...newRepeat } = authorized.add.opts.repeat;
|
||
assert.match(oldKey, /^[a-f0-9-]{36}$/);
|
||
assert.match(newKey, /^[a-f0-9-]{36}$/);
|
||
assert.notEqual(oldKey, newKey);
|
||
assert.deepEqual(newRepeat, oldRepeat);
|
||
const existing = [{ name: legacy.add.name, every: "300000", key: oldKey }];
|
||
for (const autoApproveFileEdits of [true, false]) {
|
||
const duplicate = await storedJobData({ ...input, autoApproveFileEdits, repeatableJobs: existing });
|
||
assert.equal(duplicate.responses[0].code, 409);
|
||
assert.deepEqual(duplicate.adds, []);
|
||
}
|
||
});
|
||
|
||
test("new one-shot Agent schedules cannot reuse a previous task's occurrence identity", async () => {
|
||
const input = { actionType: "agent_prompt", scheduleType: "once", payload: { prompt: "Adjust the fixture setting.", provider: "openai", model: "fixture" } };
|
||
const first = await storedJobData(input);
|
||
const second = await storedJobData({ ...input, autoApproveFileEdits: true });
|
||
for (const result of [first, second]) assert.match(result.add.opts.jobId, /^[a-f0-9-]{36}$/);
|
||
assert.notEqual(first.add.opts.jobId, second.add.opts.jobId);
|
||
});
|
||
|
||
// adpanel:scheduler-jobdata-bounds — per-action stored-payload pins: junk
|
||
// keys dropped, consumed keys preserved, keyed off the worker's actual reads
|
||
// (documented at the jobData assembly).
|
||
test("file actions store ONLY { filePath, content } — junk sibling keys are dropped", async () => {
|
||
const junk = { junk: "x".repeat(4096), nested: { more: "junk" }, evil: [1, 2, 3] };
|
||
for (const actionType of ["create_file", "modify_file"]) {
|
||
const { jobData } = await storedJobData({
|
||
actionType,
|
||
payload: { filePath: "config/settings.yml", content: "hello", ...junk },
|
||
});
|
||
assert.deepStrictEqual(jobData.payload, { filePath: "config/settings.yml", content: "hello" }, actionType);
|
||
assert.deepStrictEqual(Object.keys(jobData.payload).sort(), ["content", "filePath"], actionType);
|
||
}
|
||
});
|
||
|
||
test("console_command stores ONLY { command } (the sanitized value the create route re-stamped)", async () => {
|
||
const { jobData } = await storedJobData({
|
||
actionType: "console_command",
|
||
payload: { command: "say hi", junk: "x".repeat(4096), script: "multi\nline" },
|
||
});
|
||
assert.deepStrictEqual(jobData.payload, { command: "say hi" });
|
||
});
|
||
|
||
test("backup stores ONLY { backupName, description } (the two keys the worker destructures)", async () => {
|
||
const { jobData } = await storedJobData({
|
||
actionType: "backup",
|
||
payload: { backupName: "Nightly", description: "rotating backup", junk: "x".repeat(4096), includeWorldsOnly: true },
|
||
});
|
||
assert.deepStrictEqual(jobData.payload, { backupName: "Nightly", description: "rotating backup" });
|
||
});
|
||
|
||
// adpanel:scheduler-payload-value-caps — the stored VALUES are clamped at
|
||
// create time with the worker's IDENTICAL adpanel:log-injection-backup-name
|
||
// strip chain (String → trim → C0/C1 strip → whitespace collapse → trim →
|
||
// slice, mirroring the fire-time clamp): an over-long or control-padded
|
||
// backupName/description used to ride into the shared Redis verbatim and was
|
||
// only clamped at FIRE time, after storage.
|
||
test("backup name/description are clamped to 120/500 AT CREATE TIME (stored form is the clamped form)", async () => {
|
||
// The shipped clamp chain, read from the assembly — not test-local copies.
|
||
// The chain must stay the IDENTICAL adpanel:log-injection-backup-name strip
|
||
// (trim → C0/C1 strip → collapse → trim → slice) the fire-time twin runs.
|
||
const nameClamp = indexCode.match(/storedSchedulerPayload\.backupName = String\(storedSchedulerPayload\.backupName \|\| ""\)\.trim\(\)\.replace\(\/\[\\u0000-\\u001f\\u007f-\\u009f\]\/g, " "\)\.replace\(\/\\s\+\/g, " "\)\.trim\(\)\.slice\(0, (\d+)\);/);
|
||
const descClamp = indexCode.match(/storedSchedulerPayload\.description = String\(storedSchedulerPayload\.description \|\| ""\)\.trim\(\)\.replace\(\/\[\\u0000-\\u001f\\u007f-\\u009f\]\/g, " "\)\.replace\(\/\\s\+\/g, " "\)\.trim\(\)\.slice\(0, (\d+)\);/);
|
||
assert.ok(nameClamp && descClamp, "the create-time backup clamps must live at the jobData assembly and carry the full strip chain");
|
||
assert.strictEqual(parseInt(nameClamp[1], 10), 120, "backupName clamp mirrors the fire-time 120 cap");
|
||
assert.strictEqual(parseInt(descClamp[1], 10), 500, "description clamp mirrors the fire-time 500 cap");
|
||
|
||
const { jobData } = await storedJobData({
|
||
actionType: "backup",
|
||
payload: { backupName: ` ${"x".repeat(300)} `, description: "y".repeat(1000) },
|
||
});
|
||
assert.strictEqual(jobData.payload.backupName.length, 120);
|
||
assert.strictEqual(jobData.payload.backupName, "x".repeat(120), "trim happens BEFORE the slice (whitespace-padded names cannot keep padding)");
|
||
assert.strictEqual(jobData.payload.description.length, 500);
|
||
assert.strictEqual(jobData.payload.description, "y".repeat(500));
|
||
});
|
||
|
||
test("backup name is control-stripped AT CREATE TIME too (adpanel:log-injection-backup-name: identical strip in both copies)", async () => {
|
||
// C0 controls in the stored payload previously survived to Redis (the
|
||
// strip ran only at fire time). The stored form is now the stripped form.
|
||
const { jobData } = await storedJobData({
|
||
actionType: "backup",
|
||
payload: { backupName: "night\u0007ly\n backup", description: "ok" },
|
||
});
|
||
assert.strictEqual(jobData.payload.backupName, "night ly backup", "C0 controls are stripped and whitespace collapsed BEFORE the stored slice");
|
||
});
|
||
|
||
test("backup absent/empty name and description stay empty strings after the clamp (the worker's fallbacks are unchanged)", async () => {
|
||
const { jobData } = await storedJobData({ actionType: "backup", payload: {} });
|
||
assert.deepStrictEqual(jobData.payload, { backupName: "", description: "" });
|
||
});
|
||
|
||
test("planner_next_to_agent stores ONLY { provider, model } (prompt text comes from the DB planner item, not the payload)", async () => {
|
||
const { jobData } = await storedJobData({
|
||
actionType: "planner_next_to_agent",
|
||
payload: { provider: "openai", model: "gpt-x", prompt: "ignored-at-fire-time", junk: "x".repeat(4096) },
|
||
});
|
||
assert.deepStrictEqual(jobData.payload, { provider: "openai", model: "gpt-x" });
|
||
});
|
||
|
||
test("agent_prompt stores ONLY { prompt, provider, model } (all three re-stamped by the create route)", async () => {
|
||
const { jobData } = await storedJobData({
|
||
actionType: "agent_prompt",
|
||
payload: { prompt: "Summarize the log", provider: "openai", model: "gpt-x", junk: "x".repeat(4096), temperature: 0.7 },
|
||
});
|
||
assert.deepStrictEqual(jobData.payload, { prompt: "Summarize the log", provider: "openai", model: "gpt-x" });
|
||
});
|
||
|
||
test("server_start/server_stop store {} — reduced (the worker reads NO payload keys; shipped client sends {})", async () => {
|
||
// adpanel:scheduler-payload-value-caps — the former "deliberately left
|
||
// whole for now" boundary is closed: arbitrary sibling keys no longer ride
|
||
// into the shared Redis under these actions.
|
||
for (const actionType of ["server_start", "server_stop"]) {
|
||
const { jobData } = await storedJobData({ actionType, payload: { junk: "dropped now" } });
|
||
assert.deepStrictEqual(jobData.payload, {}, `${actionType}: the stored payload is the empty object`);
|
||
}
|
||
const absent = await storedJobData({ actionType: "server_start", payload: undefined });
|
||
assert.deepStrictEqual(absent.jobData.payload, {}, "the payload || {} fallback is unchanged");
|
||
});
|
||
|
||
test("the repeatable definition keeps its original payload hash and carries the bound server identity", async () => {
|
||
const rawPayload = { filePath: "a.txt", content: "hi", junk: "x".repeat(1024) };
|
||
const { add } = await storedJobData({ actionType: "create_file", payload: rawPayload });
|
||
const nameData = JSON.parse(add.name);
|
||
assert.deepStrictEqual(
|
||
nameData.payloadHash,
|
||
crypto.createHash("sha256").update(JSON.stringify(rawPayload)).digest("hex"),
|
||
"the hash must cover the raw payload so duplicate detection still matches existing definitions"
|
||
);
|
||
// ...while the STORED payload is reduced (identity and residency decoupled).
|
||
assert.deepStrictEqual(Object.keys(add.data.payload), ["filePath", "content"]);
|
||
assert.strictEqual(nameData.serverId, add.data.serverId, "the template and its occurrences must bind the same server");
|
||
});
|
||
|
||
test("the jobData top-level key set is unchanged by the reduction (no key drift)", async () => {
|
||
const { jobData } = await storedJobData({ actionType: "console_command", payload: { command: "say hi" } });
|
||
assert.deepStrictEqual(
|
||
Object.keys(jobData).sort(),
|
||
// adpanel:scheduler-server-identity-bind added serverId — additive, listed
|
||
// consciously.
|
||
["actionType", "name", "payload", "scheduleType", "scheduleTime", "scheduleValue", "serverId", "serverName", "timezone", "userId", "userName"].sort()
|
||
);
|
||
});
|
||
|
||
// adpanel:scheduler-server-identity-bind — every action's stored jobData binds
|
||
// the resolved row's id, so a same-name delete+recreate is detectable at fire
|
||
// time for ALL action types (the binding is not a per-action payload key; it
|
||
// sits beside serverName).
|
||
test("every action type stores the resolved server row's id as jobData.serverId", async () => {
|
||
for (const actionType of ["console_command", "server_start", "server_stop", "create_file", "modify_file", "backup", "planner_next_to_agent", "agent_prompt"]) {
|
||
const { jobData } = await storedJobData({
|
||
actionType,
|
||
payload: actionType === "server_start" || actionType === "server_stop" ? undefined : { command: "x" },
|
||
});
|
||
assert.strictEqual(jobData.serverId, 7, actionType);
|
||
}
|
||
});
|
||
|
||
test("the reduction lives at the jobData assembly, keyed per action, inside the create lock callback", () => {
|
||
// Sliced from the RAW source so the constraint comment is visible too.
|
||
const jobDataLiteral = sliceFrom(indexSource, "const jobData = {", "let job;", "jobData literal");
|
||
assert.ok(
|
||
jobDataLiteral.includes("schedulerStoredPayloadKeys"),
|
||
"the per-action key allowlist must sit at the jobData assembly"
|
||
);
|
||
for (const mapping of [
|
||
"console_command: [\"command\"],",
|
||
"create_file: [\"filePath\", \"content\"],",
|
||
"modify_file: [\"filePath\", \"content\"],",
|
||
"backup: [\"backupName\", \"description\"],",
|
||
"planner_next_to_agent: [\"provider\", \"model\"],",
|
||
"agent_prompt: [\"prompt\", \"provider\", \"model\"],",
|
||
]) {
|
||
assert.ok(jobDataLiteral.includes(mapping), `missing allowlist entry: ${mapping}`);
|
||
}
|
||
assert.ok(
|
||
jobDataLiteral.includes("adpanel:scheduler-jobdata-bounds"),
|
||
"the reduction must carry the constraint comment"
|
||
);
|
||
// And the comment-stripped code slice still sees the allowlist (it is code,
|
||
// not prose).
|
||
assert.ok(
|
||
sliceFrom(indexCode, "const jobData = {", "let job;", "jobData code literal").includes("schedulerStoredPayloadKeys"),
|
||
"the allowlist must be live code at the assembly, not a comment"
|
||
);
|
||
});
|