Files
Kelx/tests/planner-contract-sweep.test.js
T
2026-11-30 16:32:37 +00:00

620 lines
41 KiB
JavaScript

"use strict";
// Cross-layer contract sweep for the planner client (public/js/bot.js) and the
// planner server (index.js). The sibling planner tests pin one side of a fix in
// depth; this file pins the INVARIANTS THAT SPAN BOTH SIDES — the places where
// the browser client and the Express routes must agree byte-for-byte, because
// either side drifting alone breaks the feature silently (the server never runs
// the client, the client never runs the server, and no unit test covers the
// seam):
//
// 1. Reorder wire protocol: dragend sends exactly { itemId, aboveId,
// belowId } and the reorder route parses exactly those keys. If either
// side adds, drops, or renames a key, EVERY drag fails (or worse, parses
// a key the other side no longer sends).
// 2. fetchPlannerItemsForServer must SELECT updated_at: the Compose form
// snapshots item.updated_at and echoes it as expectedUpdatedAt on PUT; if
// the column ever drops from the SELECT, the client snapshots null and
// plannerUpdatedAtMatches(current, null) === false — every save 409-loops.
// 3. plannerRequest is the single fetch wrapper for ALL planner calls; every
// caller's error handling (the 409/404 drag-silencing, the 429 limiter
// alerting, the cap mapping, the auth-overlay UX) keys off the contract
// that it attaches err.status = response.status, carries the server's
// err.error/err.message text, and flags 401 with isPlannerAuthError.
// 4. getNextActivePlannerItem consumes is_done = 0 rows ordered by
// sort_order ASC — the invariant that makes the board's visual priority
// the agent's execution priority ("next up" on screen == next to run).
// 5. togglePlannerItem sends exactly { isDone }: the PUT route's
// hasOwnProperty field preservation (pinned by
// tests/planner-reorder-edit-integrity.test.js) exists precisely for this
// caller — a toggle must never carry content fields or the edit
// precondition.
// 6. The drag no-op baseline plannerLastActiveOrder has ONE derivation
// (syncPlannerLastActiveOrder: the active items of the current
// plannerItems snapshot, in board order). renderPlannerBoard refreshes
// it on every render, AND the dragend commit re-derives it after
// applying a reorder response whose newer-drag branches paint nothing —
// a stale baseline makes the user's next real (corrective) drag look
// like a no-op, and the settle reload silently repaints the older order
// over their move.
// 7. The send-agent route is BILLABLE: the rate limiter must sit in the
// route registration (runs before any gate) and the permission gates
// (resolvePlannerContext, hasAgentAccess) inside the handler — limiter
// after the gates would let unauthenticated traffic consume limiter
// budget; gates after the limiter is the only safe order.
// 8. The 200-item cap is a matched pair: the create route answers 409
// planner_item_limit_reached at PLANNER_MAX_ITEMS_PER_SERVER, and the
// client string-matches that exact code. Rename either side and the user
// sees a generic failure instead of the cap explanation.
// 9. Every planner mutation leaves an activity trail: each of the five
// mutation routes (create/send-agent/reorder/update/delete) records its
// "planner_item_*" action via recordActivity on its success path, keyed
// to the shared ctx (serverName, userEmail) and getRequestIp — the
// per-server activity feed must see board changes, and the action
// strings are the contract the reader renders generically.
// 10. The five mutation routes verify the session-bound action token
// (adpanel:planner-action-token) AFTER resolvePlannerContext and with the
// byte-exact action string + { serverName: ctx.serverName } resource the
// GET mints — the resource comparison is a stableStringify byte match, so
// a gate anchored before the context resolution (or on the raw URL name)
// would 403 every legitimate call, and a gate after body validation would
// let unverified traffic reach the write path.
// 11. The mutation token keys are a matched pair across the seam: the GET
// mints { plannerCreate, plannerSendAgent, plannerReorder, plannerUpdate,
// plannerDelete } and bot.js's plannerMutateRequest call sites read
// exactly those keys — a renamed key on either side silently sends no
// token (every mutation 403s) or attaches one no route verifies.
//
// index.js is a ~54k-line application bundle (module side effects, DB and
// network at require time — never require() it from a test) and public/js/bot.js
// is served raw to browsers, so both are pinned structurally on well-anchored
// source windows, matching the convention of tests/planner-access-gate.test.js
// and tests/planner-reorder-edit-integrity.test.js.
//
// Deliberately NOT pinned here (other work is in flight on those regions; the
// sibling test files own them): the PUT route's UPDATE statements and SELECT,
// the reorder route's error-message string values, savePlannerItem's catch
// chain, anything in processAiAgentJob or utils/planner-agent-perms.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 BOT_SRC = fs.readFileSync(path.join(ROOT, "public", "js", "bot.js"), "utf8");
// Window from an anchor to an explicit end anchor — deterministic slicing
// that survives unrelated edits elsewhere in these two large files.
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);
}
// Slice from an anchor to the function's closing brace at column zero — for
// index.js top-level function declarations only (nested/indented functions in
// bot.js close at an indent, so windowBetween + explicit end anchors is used
// there instead).
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);
}
// Extract the first balanced {...} object literal after an anchor — used to
// read a request BODY argument in isolation so comments mentioning field names
// ("title/prompt") in the surrounding function can never satisfy a key check.
function objectLiteralAfter(src, anchor, label) {
const at = src.indexOf(anchor);
assert.notStrictEqual(at, -1, `${label}: anchor not found: ${anchor}`);
const open = src.indexOf("{", at);
assert.notStrictEqual(open, -1, `${label}: no object literal after: ${anchor}`);
let depth = 0;
for (let i = open; i < src.length; i += 1) {
if (src[i] === "{") depth += 1;
if (src[i] === "}") {
depth -= 1;
if (depth === 0) return src.slice(open, i + 1);
}
}
assert.fail(`${label}: unbalanced object literal after: ${anchor}`);
}
// ─── 1. Reorder wire protocol: client body ↔ server parse ───────────────────
test("dragend wire body and reorder route parse agree on the three-key relative-move protocol", () => {
// Client side: the dragend handler is the ONLY producer of reorder bodies.
const dragend = windowBetween(
BOT_SRC,
"item.addEventListener('dragend'",
"plannerActiveList.dataset.dragBound",
"dragend handler"
);
const body = objectLiteralAfter(dragend, "body: JSON.stringify(", "dragend request body");
assert.match(body, /\bitemId\s*:/, "CLIENT CONTRACT BROKEN: the reorder body no longer names the dragged item as itemId — the server's parseInt(body.itemId) would yield NaN and reject every drag as a protocol error");
assert.match(body, /\baboveId\s*:/, "CLIENT CONTRACT BROKEN: the reorder body lost aboveId — the server can no longer anchor the dragged item's top edge and every drag fails or lands wrong");
assert.match(body, /\bbelowId\s*:/, "CLIENT CONTRACT BROKEN: the reorder body lost belowId — the server can no longer anchor the dragged item's bottom edge and every drag fails or lands wrong");
assert.ok(!/\bitemIds\b/.test(dragend), "CLIENT CONTRACT BROKEN: the legacy absolute-order itemIds body is back in the dragend handler — the server rejects itemIds with a protocol error, so every drag would 400 and self-heal-reload in a loop");
// Server side: the reorder route must parse exactly the keys the client
// sends. Scoped to the parse prologue (const body = ... up to the first
// handler try block) so later body reads can't muddy the key set.
const route = windowBetween(
INDEX_SRC,
'app.post("/api/servers/:name/planner/reorder"',
'app.put("/api/servers/:name/planner/:id"',
"reorder route"
);
const bodyAt = route.indexOf("const body = req.body || {};");
assert.notStrictEqual(bodyAt, -1, "SERVER CONTRACT BROKEN: the reorder route no longer reads req.body into a local — the wire protocol has no parse step at all");
const prologue = route.slice(bodyAt, route.indexOf("\n try {", bodyAt));
assert.notStrictEqual(route.indexOf("\n try {", bodyAt), -1, "reorder route: no handler try block after the parse prologue");
const readKeys = new Set([...prologue.matchAll(/body\.([A-Za-z_$][\w$]*)/g)].map((m) => m[1]));
for (const key of ["itemId", "aboveId", "belowId"]) {
assert.ok(
readKeys.has(key),
`SERVER CONTRACT BROKEN: the reorder route no longer parses body.${key} — the client still sends it, so every drag silently loses that half of the move (anchor mismatch, wrong landing slot, or protocol rejection)`
);
}
assert.ok(
prologue.includes("parseInt(body.itemId, 10)"),
"SERVER CONTRACT BROKEN: body.itemId is no longer numeric-parsed — non-numeric ids would flow into the reorder decision core"
);
const foreignKeys = [...readKeys].filter((key) => !["itemId", "itemIds", "aboveId", "belowId"].includes(key));
assert.deepStrictEqual(
foreignKeys,
[],
`SERVER CONTRACT BROKEN: the reorder route parses key(s) the client never sends: ${foreignKeys.join(", ")} — dead parse input means the two sides have drifted and the extra key is either a protocol change that forgot the client or a leftover`
);
// body.itemIds may appear ONLY as the legacy-body rejection read (pinned by
// tests/planner-reorder-edit-integrity.test.js); it must never be consumed
// as the current protocol.
assert.ok(!/\bitemIds\b/.test(body) && (readKeys.has("itemIds") || !prologue.includes("itemIds")), "SERVER CONTRACT BROKEN: itemIds is being treated as live protocol input — the current wire contract is the three-key relative move only");
});
// ─── 2. fetchPlannerItemsForServer SELECT feeds the 409 precondition ────────
test("fetchPlannerItemsForServer feeds the client both edit preconditions", () => {
const fn = functionWindow(INDEX_SRC, "async function fetchPlannerItemsForServer", "fetchPlannerItemsForServer");
assert.ok(
fn.includes(
"SELECT id, server_name, title, prompt, is_done, sort_order, created_by_email, updated_by_email, created_at, updated_at"
),
"SERVER CONTRACT BROKEN: fetchPlannerItemsForServer's column list changed — the client Compose form snapshots item.updated_at and echoes it as expectedUpdatedAt on PUT; if updated_at drops from this SELECT the snapshot becomes null and plannerUpdatedAtMatches(current, null) === false, so EVERY edit save 409-loops with 'changed by another user'"
);
assert.ok(fn.includes("FROM server_planner_items"), "fetchPlannerItemsForServer no longer reads server_planner_items — the board and every route response shape is built from this query");
assert.ok(fn.includes("${PLANNER_EDIT_VERSION_SQL} AS edit_version"), "the board must expose the same edit version that the SQL write checks");
for (const column of ["sort_order", "is_done", "created_by_email"]) {
assert.ok(
fn.includes(column),
`SERVER CONTRACT BROKEN: fetchPlannerItemsForServer no longer selects ${column} — sort_order drives the board's visual priority, is_done drives the active/done split, created_by_email drives the author label; the client renders from these columns`
);
}
// The consuming half of the pair (client side, form helpers — not the
// savePlannerItem catch chain): the snapshot the PUT echoes must come from
// this column.
assert.ok(
BOT_SRC.includes("plannerEditingSnapshot = item;"),
"fillPlannerForm must preserve the board item's timestamp and edit version"
);
});
// ─── 3. plannerRequest: the single fetch wrapper's status contract ──────────
test("plannerRequest attaches .status and the server error code, and flags 401 as isPlannerAuthError", () => {
const fn = windowBetween(BOT_SRC, "function plannerRequest", "function derivePlannerTitle", "plannerRequest");
const authAt = fn.indexOf("if (response.status === 401)");
const notOkAt = fn.indexOf("if (!response.ok)");
assert.notStrictEqual(authAt, -1, "CLIENT CONTRACT BROKEN: plannerRequest no longer special-cases 401 — session expiry would surface as a raw per-call alert instead of the shared sign-in overlay");
assert.notStrictEqual(notOkAt, -1, "CLIENT CONTRACT BROKEN: plannerRequest no longer branches on !response.ok — error bodies would fall through to the JSON success path and callers would read garbage as data");
assert.ok(authAt < notOkAt, "CLIENT CONTRACT BROKEN: the 401 branch must run BEFORE the generic !response.ok branch, or session expiry gets a generic status-carrying error and no isPlannerAuthError flag");
assert.ok(
fn.includes("err.isPlannerAuthError = true;"),
"CLIENT CONTRACT BROKEN: the 401 error no longer carries isPlannerAuthError — every planner caller (board load, drag, toggle, delete, send-to-agent, save) checks this flag to stay silent and let the overlay speak; without it users get stacked alerts"
);
assert.ok(
fn.includes("showPlannerSessionExpired()"),
"CLIENT CONTRACT BROKEN: plannerRequest no longer triggers the session-expired overlay on 401 — the user is left on a dead board with no way back in"
);
assert.ok(
fn.includes("failure.status = response.status;"),
"CLIENT CONTRACT BROKEN: non-OK responses no longer carry .status — the callers' error handling (drag's silent 409/404, save's 409 reload-and-refill, the limiter's 429 alerting) maps UX BY STATUS and would treat a conflict as a generic failure"
);
assert.ok(
fn.includes("err.error || err.message ||"),
"CLIENT CONTRACT BROKEN: plannerRequest no longer extracts the server's error code into the thrown Error message — the server answers { error: 'code' } and the client matches those codes verbatim (e.g. planner_item_limit_reached); losing this mapping breaks every code-based client branch"
);
});
// ─── 4. Scheduler consumption ordering ──────────────────────────────────────
test("getNextActivePlannerItem consumes the board's visual priority (is_done = 0, sort_order ASC)", () => {
const fn = functionWindow(INDEX_SRC, "async function getNextActivePlannerItem", "getNextActivePlannerItem");
assert.ok(
fn.includes("WHERE server_name = ? AND is_done = 0"),
"SERVER CONTRACT BROKEN: getNextActivePlannerItem no longer filters is_done = 0 — the agent would re-execute completed prompts forever, because 'done' on the board would no longer mean 'done' to the scheduler"
);
assert.ok(
fn.includes("ORDER BY sort_order ASC"),
"SERVER CONTRACT BROKEN: getNextActivePlannerItem no longer consumes by sort_order ASC — sort_order is the ONLY priority field the user can set (by dragging, pinned by pin 1 and 6), so any other order breaks the 'what you see on top is what runs next' invariant the whole board UI is built around"
);
assert.ok(
fn.includes("LIMIT 1"),
"SERVER CONTRACT BROKEN: getNextActivePlannerItem no longer takes a single row — the scheduler consumes one next step per hand-off, not a batch"
);
});
test("Scheduler preview uses the authorized Planner route and the same eligible-item selector as the worker", () => {
const readAt = INDEX_SRC.indexOf('app.get("/api/servers/:name/planner"');
const createAt = INDEX_SRC.indexOf('app.post("/api/servers/:name/planner"', readAt);
assert.ok(readAt >= 0 && createAt > readAt);
const route = INDEX_SRC.slice(readAt, createAt);
const contextAt = route.indexOf("if (!ctx) return;");
const previewAt = route.indexOf('if (req.query?.view === "next")');
assert.ok(contextAt >= 0 && previewAt > contextAt);
assert.match(route.slice(previewAt), /getNextActivePlannerItem\(ctx\.serverName\)[\s\S]*?nextPrompt: item\?\.prompt \|\| null/);
assert.match(functionWindow(INDEX_SRC, "async function getNextActivePlannerItem", "getNextActivePlannerItem"), /agent_edit_hold_job_id IS NULL/);
assert.match(BOT_SRC, /const \{ nextPrompt \} = await plannerRequest\('\?view=next'\);/);
});
// ─── 5. Toggle path: exactly { isDone }, nothing else ───────────────────────
test("togglePlannerItem sends exactly { isDone } and relies on server-side field preservation", () => {
const toggle = windowBetween(
BOT_SRC,
"async function togglePlannerItem",
"async function deletePlannerItem",
"togglePlannerItem"
);
const body = objectLiteralAfter(toggle, "body: JSON.stringify(", "toggle request body");
assert.match(body, /\bisDone\s*:/, "CLIENT CONTRACT BROKEN: togglePlannerItem no longer sends isDone — the PUT route has no other way to express a done-flip, so completing/restoring prompts breaks");
assert.ok(!/\btitle\s*:/.test(body), "CLIENT CONTRACT BROKEN: togglePlannerItem now sends title — the PUT route treats a present title as content to overwrite, so a toggle from a stale client cache would clobber a teammate's concurrent title edit (the field-preservation contract exists precisely to prevent this)");
assert.ok(!/\bprompt\s*:/.test(body), "CLIENT CONTRACT BROKEN: togglePlannerItem now sends prompt — same clobber hazard as title: a stale toggle would overwrite the canonical stored prompt");
assert.ok(!body.includes("expectedUpdatedAt"), "CLIENT CONTRACT BROKEN: togglePlannerItem now sends expectedUpdatedAt — the toggle path has no fresh snapshot (no form was filled), so the version check would compare null and every toggle would 409");
assert.strictEqual(
(toggle.match(/JSON\.stringify\(/g) || []).length,
1,
"CLIENT CONTRACT BROKEN: togglePlannerItem issues more than one request body — the toggle must remain a single PUT whose ENTIRE payload is the done flag"
);
});
// ─── 6. Board render recomputes the drag no-op baseline ─────────────────────
test("renderPlannerBoard recomputes plannerLastActiveOrder — the baseline the dragend no-op detector reads", () => {
const render = windowBetween(
BOT_SRC,
"function renderPlannerBoard",
"async function loadPlannerItems",
"renderPlannerBoard"
);
const activeAt = render.indexOf("const activeItems = plannerActiveItems();");
const baselineAt = render.indexOf("syncPlannerLastActiveOrder();");
assert.notStrictEqual(activeAt, -1, "CLIENT CONTRACT BROKEN: renderPlannerBoard no longer computes activeItems — the board has no active/done split to render");
assert.notStrictEqual(baselineAt, -1, "CLIENT CONTRACT BROKEN: renderPlannerBoard no longer refreshes the drag no-op baseline via syncPlannerLastActiveOrder — the dragend no-op detector compares the post-drop DOM order against plannerLastActiveOrder, so a stale baseline makes every real drag a 'no-op' (dropped silently) or every no-op a network request");
assert.ok(activeAt < baselineAt, "CLIENT CONTRACT BROKEN: renderPlannerBoard must refresh the baseline after computing the active items it renders — the baseline and the board must come from the same snapshot, or what the user sees desynchronizes from what the no-op detector expects");
// The ONE derivation lives in syncPlannerLastActiveOrder (shared with every
// site that reassigns plannerItems without a render): pin its exact shape
// so the baseline can never drift from the active items the board renders.
const helper = windowBetween(
BOT_SRC,
"function syncPlannerLastActiveOrder",
"function switchPlannerTab",
"syncPlannerLastActiveOrder"
);
assert.ok(
helper.includes("plannerLastActiveOrder = plannerActiveItems().map((item) => Number(item.id));"),
"CLIENT CONTRACT BROKEN: syncPlannerLastActiveOrder no longer derives the baseline from plannerActiveItems() — a baseline from any other source desynchronizes what the user sees from what the no-op detector expects"
);
// The no-render half of the contract (adpanel:planner-order-baseline): the
// dragend commit applies the reorder response to plannerItems and its
// newer-drag branches deliberately paint nothing (repainting mid-drag
// detaches the dragged node) — so the commit itself must re-derive the
// baseline, or the next drag is judged against the pre-drag order and the
// settle reload silently discards the user's corrective move.
const dragend = windowBetween(
BOT_SRC,
"item.addEventListener('dragend'",
"plannerActiveList.dataset.dragBound",
"dragend handler"
);
const commitAt = dragend.indexOf("plannerItems = Array.isArray(data.items) ? data.items : plannerItems;");
const commitSyncAt = dragend.indexOf("syncPlannerLastActiveOrder();", commitAt);
assert.notStrictEqual(commitAt, -1, "CLIENT CONTRACT BROKEN: the dragend commit no longer applies the reorder response's items to plannerItems");
assert.notStrictEqual(commitSyncAt, -1, "CLIENT CONTRACT BROKEN: the dragend commit no longer re-derives the no-op baseline after applying the server-confirmed order — the newer-drag branches below it paint nothing, so the next dragend compares against the stale pre-drag order and the settle reload silently discards the user's corrective move");
assert.ok(commitAt < commitSyncAt, "CLIENT CONTRACT BROKEN: the baseline must be re-derived AFTER the commit applies the new items to plannerItems");
assert.ok(
dragend.includes("JSON.stringify(orderedIds) === JSON.stringify(plannerLastActiveOrder)"),
"CLIENT CONTRACT BROKEN: dragend no longer compares the dropped DOM order against plannerLastActiveOrder — without the no-op detector every drag fires a reorder request even when nothing moved"
);
// adpanel:planner-null-items — on a committed reorder that answers items:
// null, plannerItems keeps its stale pre-drag snapshot, so deriving the
// baseline straight from it would desync the no-op detector from the
// committed DOM order: the next dragend would early-return as a "no-op" and
// the settle reload would silently repaint the older order over the user's
// corrective move. The null path must rebuild the active portion of
// plannerItems from the committed DOM order (orderedIds) BEFORE the baseline
// sync re-derives it.
const nullRebuildAt = dragend.indexOf("orderedIds.map((id) => activeById.get(id)).filter(Boolean)");
assert.notStrictEqual(nullRebuildAt, -1, "CLIENT CONTRACT BROKEN: the dragend null-items path no longer rebuilds plannerItems' active order from the committed DOM (orderedIds) — the baseline then derives from the stale pre-drag snapshot, the next dragend no-ops the user's corrective move, and the settle reload silently repaints the older order");
assert.ok(commitAt < nullRebuildAt && nullRebuildAt < commitSyncAt, "CLIENT CONTRACT BROKEN: the null-items rebuild must sit between the commit assignment and the baseline sync so the re-derived baseline tracks the committed order");
});
// ─── 7. Send-agent route: limiter at the door, gates inside ─────────────────
test("send-agent route: the rate limiter guards the door before the permission gates", () => {
assert.ok(
INDEX_SRC.includes("const plannerMutateRateLimiter = rateLimit({"),
"SERVER CONTRACT BROKEN: plannerMutateRateLimiter is no longer defined — all five planner mutation routes rely on it as the shared write-rate budget (express-rate-limit config lives where the limiter is created)"
);
const route = windowBetween(
INDEX_SRC,
'app.post("/api/servers/:name/planner/:id/send-agent"',
'app.post("/api/servers/:name/planner/reorder"',
"send-agent route"
);
const firstLineEnd = route.indexOf("\n");
const registration = route.slice(0, firstLineEnd === -1 ? route.length : firstLineEnd);
assert.ok(
registration.includes("plannerMutateRateLimiter"),
"SERVER CONTRACT BROKEN: the send-agent route is registered WITHOUT plannerMutateRateLimiter — send-to-agent triggers a billable agent job, and the limiter must run as middleware BEFORE any handler code so unauthenticated/gated traffic still consumes the budget instead of bypassing it"
);
const contextAt = route.indexOf("ctx = await resolvePlannerContext(req, res, req.params.name);");
const agentAccessAt = route.indexOf("hasAgentAccess(req)");
assert.notStrictEqual(contextAt, -1, "SERVER CONTRACT BROKEN: the send-agent route no longer calls resolvePlannerContext — planner_access/session/server checks are gone and any authenticated user could enqueue agent jobs on any server");
assert.notStrictEqual(agentAccessAt, -1, "SERVER CONTRACT BROKEN: the send-agent route no longer re-checks hasAgentAccess — the planner-specific agent gate is gone (resolvePlannerContext alone does not verify agent permissions)");
assert.ok(contextAt < agentAccessAt, "SERVER CONTRACT BROKEN: hasAgentAccess must be re-checked AFTER resolvePlannerContext inside the handler — the context gate narrows to (user, server) first, then the agent permission applies to that context");
const forbiddenAt = route.indexOf('res.status(403).json({ error: "no agent access" })');
assert.notStrictEqual(forbiddenAt, -1, "SERVER CONTRACT BROKEN: the send-agent route no longer answers 403 on missing agent access — the client keys its error UX off the rejection, and a silent pass-through would enqueue jobs for users without agent permission");
});
// ─── 8. The 200-item cap: server 409 code ↔ client string match ─────────────
test("Planner create admits only the live authorized server before reading or writing its board", async () => {
const route = windowBetween(
INDEX_SRC,
'app.post("/api/servers/:name/planner", plannerMutateRateLimiter',
'app.post("/api/servers/:name/planner/:id/send-agent"',
"create route"
);
const server = { id: 7, name: "fixture-server", status: "stopped", suspended: 0 };
for (const [row, expected] of [[null, 409], [{ ...server, id: 8 }, 409],
[{ ...server, status: "deleting" }, 409], [{ ...server, suspended: 1 }, 423], [server, 200]]) {
const operations = [];
const connection = {
beginTransaction: async () => operations.push("begin"),
rollback: async () => operations.push("rollback"),
commit: async () => operations.push("commit"),
release: () => operations.push("release"),
execute: async (statement, values) => {
if (statement.includes("FROM servers")) {
assert.match(statement, /WHERE name = \? FOR UPDATE$/);
assert.deepEqual(values, [server.name]);
operations.push("server");
return [row ? [row] : []];
}
if (statement.startsWith("SELECT COUNT")) {
operations.push("count");
return [[{ item_count: 0 }]];
}
if (statement.startsWith("INSERT INTO server_planner_items")) {
operations.push("insert");
return [{ insertId: 2 }];
}
assert.match(statement, /FROM server_planner_items.*FOR UPDATE$/);
return [[]];
},
};
let handler;
const dependencies = {
app: { post(_path, _limiter, routeHandler) { handler = routeHandler; } },
plannerMutateRateLimiter: () => {},
resolvePlannerContext: async () => ({ serverName: server.name, userEmail: "planner@example.test", serverRowId: server.id }),
requireActionTokenOr403: async () => true,
sanitizePlannerPrompt: (prompt) => prompt,
sanitizePlannerTitle: (title) => title,
db: { pool: { getConnection: async () => connection } },
isServerSuspended: (entry) => Boolean(entry.suspended),
sendSuspendedServerJson: (res) => res.status(423).json({ error: "suspended" }),
PLANNER_MAX_ITEMS_PER_SERVER: 200,
recordActivity: () => {},
getRequestIp: () => "127.0.0.1",
fetchPlannerItemsForServer: async () => [],
};
new Function(...Object.keys(dependencies), route)(...Object.values(dependencies));
const res = { code: 200, status(code) { this.code = code; return this; }, json() {} };
await handler({ params: { name: server.name }, body: { prompt: "fixture", title: "Fixture" }, currentUser: { id: 1 } }, res);
assert.equal(res.code, expected);
assert.deepEqual(operations, expected === 200
? ["begin", "server", "count", "insert", "commit", "release"]
: ["begin", "server", "rollback", "release"]);
}
});
test("index sync retires a removed server's Planner rows before releasing the name", async () => {
const source = windowBetween(INDEX_SRC, "async function saveServersIndex(list)", "\n// Serialization for read-modify-write cycles", "index sync");
for (const failCleanup of [false, true]) {
const operations = [];
const connection = {
beginTransaction: async () => operations.push("begin"),
rollback: async () => operations.push("rollback"),
commit: async () => operations.push("commit"),
release: () => operations.push("release"),
execute: async (statement, values) => {
if (statement === "SELECT name FROM servers") return [[{ name: "removed" }]];
if (statement.startsWith("SELECT name, legacy_id, bot")) {
assert.match(statement, /FOR UPDATE$/);
return [[{ name: "removed", legacy_id: "legacy" }]];
}
if (statement.startsWith("DELETE FROM servers")) operations.push("remove server");
if (statement.startsWith("DELETE FROM server_planner_items")) {
assert.deepEqual(values, ["removed", "legacy"]);
assert.match(statement, /NOT EXISTS \(\s*SELECT 1 FROM servers/);
operations.push("remove planner");
if (failCleanup) throw Object.assign(new Error("fixture cleanup unavailable"), { code: "ER_LOCK_WAIT_TIMEOUT" });
}
return [{ affectedRows: 1 }];
},
};
const save = new Function("db", "sqlPlaceholders", "invalidateServerIndexCache", "console", `${source}\nreturn saveServersIndex;`)(
{ pool: { getConnection: async () => connection } },
(items) => items.map(() => "?").join(","),
() => operations.push("invalidate"),
{ error() {} }
);
assert.equal(await save([]), !failCleanup);
assert.deepEqual(operations, failCleanup
? ["begin", "remove server", "remove planner", "rollback", "release"]
: ["begin", "remove server", "remove planner", "commit", "invalidate", "release"]);
}
});
test("create route answers 409 planner_item_limit_reached at PLANNER_MAX_ITEMS_PER_SERVER", () => {
const capDeclAt = INDEX_SRC.indexOf("const PLANNER_MAX_ITEMS_PER_SERVER = ");
assert.notStrictEqual(capDeclAt, -1, "SERVER CONTRACT BROKEN: PLANNER_MAX_ITEMS_PER_SERVER is no longer defined — the cap check would throw a ReferenceError inside the create transaction, rolling back every create");
assert.match(
INDEX_SRC.slice(capDeclAt, capDeclAt + 80),
/const PLANNER_MAX_ITEMS_PER_SERVER = \d+;/,
"SERVER CONTRACT BROKEN: PLANNER_MAX_ITEMS_PER_SERVER must stay a numeric const declaration — an inline magic number in the route (or a non-constant) would desynchronize the cap from its documented audit trail"
);
const route = windowBetween(
INDEX_SRC,
'app.post("/api/servers/:name/planner", plannerMutateRateLimiter',
'app.post("/api/servers/:name/planner/:id/send-agent"',
"create route"
);
const capCheckAt = route.indexOf(">= PLANNER_MAX_ITEMS_PER_SERVER");
const conflictAt = route.indexOf("res.status(409).json({ error: 'planner_item_limit_reached' })");
assert.notStrictEqual(capCheckAt, -1, "SERVER CONTRACT BROKEN: the create route no longer compares the row count against PLANNER_MAX_ITEMS_PER_SERVER — the per-server queue can grow unboundedly again");
assert.notStrictEqual(conflictAt, -1, "SERVER CONTRACT BROKEN: the create route no longer answers 409 planner_item_limit_reached — the cap must be a 409 with THIS exact code, because the client string-matches it to show the cap explanation instead of a generic failure");
const insertAt = route.indexOf("INSERT INTO server_planner_items");
assert.notStrictEqual(insertAt, -1, "create route: INSERT INTO server_planner_items not found");
assert.ok(capCheckAt < insertAt, "SERVER CONTRACT BROKEN: the cap check must run BEFORE the INSERT — checking after inserting makes the cap advisory and lets the (N+1)-th row land anyway");
// Client half of the matched pair: the client must still know the code
// verbatim. Pinned as a bare string-presence check ONLY — the structural
// mapping (which branch alerts, in what order) lives in savePlannerItem's
// catch chain, which is under concurrent edit and pinned by
// tests/planner-reorder-edit-integrity.test.js.
assert.ok(
BOT_SRC.includes("planner_item_limit_reached"),
"CLIENT CONTRACT BROKEN: bot.js no longer references planner_item_limit_reached — the server still 409s with that code, so users hitting the 200-item cap now get a generic failure message instead of the cap explanation (rename one side without the other and this pair breaks)"
);
});
// ─── 9. Planner mutations leave an activity trail ───────────────────────────
test("each planner mutation route records exactly its planner_item_* activity action", () => {
// Each mutation route's window is sliced between its own registration
// anchor and the next route's (or the next top-level declaration after the
// delete route), so the action string can only be satisfied by a
// recordActivity call INSIDE that route's handler.
const expectations = [
["create", 'app.post("/api/servers/:name/planner", plannerMutateRateLimiter', 'app.post("/api/servers/:name/planner/:id/send-agent"', "planner_item_create"],
["send-agent", 'app.post("/api/servers/:name/planner/:id/send-agent"', 'app.post("/api/servers/:name/planner/reorder"', "planner_item_send_agent"],
["reorder", 'app.post("/api/servers/:name/planner/reorder"', 'app.put("/api/servers/:name/planner/:id"', "planner_item_reorder"],
["update", 'app.put("/api/servers/:name/planner/:id"', 'app.delete("/api/servers/:name/planner/:id"', "planner_item_update"],
["delete", 'app.delete("/api/servers/:name/planner/:id"', "const DATABASE_CONFIG_FILE", "planner_item_delete"],
];
for (const [label, startAnchor, endAnchor, action] of expectations) {
const route = windowBetween(INDEX_SRC, startAnchor, endAnchor, `${label} route`);
const marker = `recordActivity(ctx.serverName, "${action}", `;
const hits = route.split(marker).length - 1;
assert.ok(
hits >= 1,
`SERVER CONTRACT BROKEN: the ${label} route no longer records "${action}" — every planner mutation must leave an activity trail on its success path (actor ctx.userEmail, ip getRequestIp) or the per-server activity feed goes blind to board changes`
);
assert.strictEqual(
hits,
1,
`SERVER CONTRACT BROKEN: the ${label} route records "${action}" ${hits} times — a committing success path must record exactly once (double entries flood the activity feed, zero entries hide the change)`
);
}
});
// ─── 10. The five mutations verify the session-bound action token ───────────
test("each planner mutation route verifies its action token after resolvePlannerContext, with the GET-minted action string and resource", () => {
// The gate call is pinned byte-exact: the action string IS the mint/verify
// contract (verifyActionToken compares payload.act and the
// stableStringify'd resource), so a renamed action string would 403 every
// call the GET minted for. ctx.serverName is the canonical name
// resolvePlannerContext resolved — the same value the GET minted against.
const expectations = [
["create", 'app.post("/api/servers/:name/planner", plannerMutateRateLimiter', 'app.post("/api/servers/:name/planner/:id/send-agent"',
'requireActionTokenOr403(req, res, "POST /api/servers/:name/planner", { serverName: ctx.serverName })'],
["send-agent", 'app.post("/api/servers/:name/planner/:id/send-agent"', 'app.post("/api/servers/:name/planner/reorder"',
'requireActionTokenOr403(req, res, "POST /api/servers/:name/planner/:id/send-agent", { serverName: ctx.serverName })'],
["reorder", 'app.post("/api/servers/:name/planner/reorder"', 'app.put("/api/servers/:name/planner/:id"',
'requireActionTokenOr403(req, res, "POST /api/servers/:name/planner/reorder", { serverName: ctx.serverName })'],
["update", 'app.put("/api/servers/:name/planner/:id"', 'app.delete("/api/servers/:name/planner/:id"',
'requireActionTokenOr403(req, res, "PUT /api/servers/:name/planner/:id", { serverName: ctx.serverName })'],
["delete", 'app.delete("/api/servers/:name/planner/:id"', "const DATABASE_CONFIG_FILE",
'requireActionTokenOr403(req, res, "DELETE /api/servers/:name/planner/:id", { serverName: ctx.serverName })'],
];
for (const [label, startAnchor, endAnchor, gate] of expectations) {
const route = windowBetween(INDEX_SRC, startAnchor, endAnchor, `${label} route`);
const ctxAt = route.indexOf("ctx = await resolvePlannerContext(req, res, req.params.name);");
const gateAt = route.indexOf(`if (!(await ${gate})) return;`);
assert.notStrictEqual(ctxAt, -1, `SERVER CONTRACT BROKEN: the ${label} route no longer resolves the planner context — the token gate's resource and the whole permission chain key on it`);
assert.notStrictEqual(gateAt, -1, `SERVER CONTRACT BROKEN: the ${label} route no longer verifies the session-bound action token with the exact GET-minted pair (${gate}) — a cross-site page holding a victim session could drive this mutation from an allowed-host origin`);
assert.ok(
ctxAt < gateAt,
`SERVER CONTRACT BROKEN: the ${label} route's token gate must verify AFTER resolvePlannerContext — the gate's resource is the canonical ctx.serverName, so an earlier gate would compare a name the route never resolved (and skip the auth/planner_access gates)`
);
}
// The GET is the minter: the five session-bound tokens ride every
// successful board read, keyed for the client's plannerMutateRequest.
const getRoute = windowBetween(
INDEX_SRC,
'app.get("/api/servers/:name/planner"',
'app.post("/api/servers/:name/planner", plannerMutateRateLimiter',
"planner GET route"
);
for (const key of ["plannerCreate", "plannerSendAgent", "plannerReorder", "plannerUpdate", "plannerDelete"]) {
assert.ok(
getRoute.includes(`${key}: issueActionToken(req,`),
`SERVER CONTRACT BROKEN: the planner GET no longer mints the ${key} action token — the mutation routes 403 ACTION_TOKEN_INVALID on every call until the client's one-shot retry exhausts`
);
}
// Repeatable, not one-time: the client re-sends after the CAS 409s, and a
// nonce-burning token would break those self-healing retries. Pinned on the
// opts-literal shape, not the word, so the adpanel prose cannot satisfy it.
assert.ok(!getRoute.includes("oneTime: true"), "SERVER CONTRACT BROKEN: the planner GET mints a one-time token — planner mutations retry after CAS 409s and a burned nonce would kill the retry");
});
// ─── 11. The token keys agree across the client/server seam ─────────────────
test("bot.js plannerMutateRequest call sites read exactly the token keys the GET mints", () => {
const serverKeys = ["plannerCreate", "plannerSendAgent", "plannerReorder", "plannerUpdate", "plannerDelete"];
// Anchor on the call sites themselves (statement-scoped: no semicolon can
// appear between the opening paren and the trailing token-key argument) so
// the DOM id strings ('plannerModal' etc.) can never masquerade as keys.
const clientKeys = new Set(
[...BOT_SRC.matchAll(/plannerMutateRequest\([^;]*?'(planner[A-Za-z]+)'\);/g)].map((m) => m[1])
);
for (const key of serverKeys) {
assert.ok(
clientKeys.has(key),
`CLIENT CONTRACT BROKEN: no bot.js plannerMutateRequest call site reads the '${key}' token key — the server mints it, so those mutations send no x-action-token and every call 403s (the key names are the mint/read contract across the seam)`
);
}
const unknownKeys = [...clientKeys].filter((key) => !serverKeys.includes(key));
assert.deepStrictEqual(
unknownKeys,
[],
`CLIENT CONTRACT BROKEN: bot.js reads planner token key(s) the GET never mints: ${unknownKeys.join(", ")} — those mutations would send an empty token and rely on the retry loop forever`
);
});