"use strict"; // Source-level pins for the planner "send to agent" hardening. // // The send-agent route is the planner's most expensive mutation — every call // inserts an ai_agent_jobs row and starts a billable external model run — yet // it was the only planner mutation without plannerMutateRateLimiter, and its // catch forwarded raw internal err.message (DB driver text, SQL fragments) to // the browser. On the client, sendPlannerPromptToAgent had no in-flight guard, // so a double-click enqueued two identical billable jobs. This file pins all // three halves so deleting any piece of it fails a suite: // // 1. POST .../planner/:id/send-agent carries plannerMutateRateLimiter, the // same always-on abuse brake as its four sibling planner mutations; // 2. the four siblings still carry it (regression guard against drift); // 3. the route's catch forwards err.message ONLY for deliberately-crafted // errors (constructed with an integer err.status >= 400 — queue caps, // suspension, access denial) and otherwise returns the same fixed // generic 500 string the sibling planner routes return; // 4. sendPlannerPromptToAgent declares plannerSendAgentInFlight, refuses // re-entry after the re-runnable validation early-returns, and clears // the flag in a finally covering the whole remaining body; // 5. the client still suppresses alerting for err.isPlannerAuthError // (a 401 already raised the session-expired overlay); and // 6. the route's two mandatory version echoes — expectedUpdatedAt (the // second-precision fast path) and expectedPrompt (the content // byte-equality that is the actual anti-laundering gate) — exist on // BOTH the server gate and the bot.js send body, each failing closed // to the same 409 planner_prompt_changed shape. // // Third-audit frontend findings, pinned in the same spirit: // 7. the completion poll bounds itself on a wall-clock budget that covers // the server's job deadline + queue window (not an attempt count), // tiers its delays with age, and surfaces exhaustion on the board // (offline status + one final reconcile) instead of a silent bare // return — the poll is the planner board's SOLE completion surface; // 8. the send's model-save pre-step fails CLOSED: with a visible model // selection a failed save aborts the billable send before the POST // (through the try, so the finally releases the brake); with no // selection there is nothing to save and the persisted row governs. // // index.js is a ~55k-line application bundle (module side effects, DB and // network at require time) and bot.js is served raw, so these tests pin the // fixes structurally on well-anchored source windows, matching the // convention of the other route-level tests in this directory (e.g. // planner-access-gate.test.js, preflight-guard-sweep.test.js). const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); const BOT_SRC = fs.readFileSync(path.join(ROOT, "public", "js", "bot.js"), "utf8"); const SEND_AGENT_ANCHOR = 'app.post("/api/servers/:name/planner/:id/send-agent"'; const GENERIC_SEND_ERROR = "Failed to send planner prompt to ADPanel Agent"; const LIMITER = "plannerMutateRateLimiter"; function countOccurrences(haystack, needle) { let count = 0; let at = haystack.indexOf(needle); while (at !== -1) { count += 1; at = haystack.indexOf(needle, at + needle.length); } return count; } // Slice from a route registration anchor to its handler arrow — the window // where route-level middleware would have to appear. function routeRegistrationWindow(src, anchor, label) { const start = src.indexOf(anchor); assert.notStrictEqual(start, -1, `${label}: route not found: ${anchor}`); const end = src.indexOf("async (req, res)", start); assert.notStrictEqual(end, -1, `${label}: handler not found after: ${anchor}`); return src.slice(start, end); } // The full send-agent route body: from its registration to the next planner // route registration (reorder). function sendAgentRouteWindow(src) { const start = src.indexOf(SEND_AGENT_ANCHOR); assert.notStrictEqual(start, -1, "send-agent route not found"); const end = src.indexOf('app.post("/api/servers/:name/planner/reorder"', start); assert.notStrictEqual(end, -1, "reorder route (window end) not found after send-agent"); 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 (same discipline as the other // planner test files in this directory). 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); } // bot.js functions live inside a closure, so a function's closing brace is a // lone "}" at two-space indent — slice from the anchor to the first such line. function botFunctionWindow(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 + 4); } test("send-agent route registration includes plannerMutateRateLimiter", () => { // Exact registration: limiter as the second argument, matching sibling style. const exact = 'app.post("/api/servers/:name/planner/:id/send-agent", plannerMutateRateLimiter, async (req, res) => {'; assert.strictEqual( countOccurrences(INDEX_SRC, exact), 1, "send-agent must be registered with plannerMutateRateLimiter exactly once" ); // Resilient window form: limiter sits between the route anchor and its handler. const registration = routeRegistrationWindow(INDEX_SRC, SEND_AGENT_ANCHOR, "send-agent"); assert.ok( registration.includes(LIMITER), "send-agent registration must carry plannerMutateRateLimiter" ); }); test("the four sibling planner mutations still carry plannerMutateRateLimiter", () => { const siblings = [ ['app.post("/api/servers/:name/planner"', "create"], ['app.post("/api/servers/:name/planner/reorder"', "reorder"], ['app.put("/api/servers/:name/planner/:id"', "update"], ['app.delete("/api/servers/:name/planner/:id"', "delete"], ]; for (const [anchor, label] of siblings) { const registration = routeRegistrationWindow(INDEX_SRC, anchor, label); assert.ok( registration.includes(LIMITER), `${label} planner route must keep plannerMutateRateLimiter` ); } }); test("send-agent route keeps its resolvePlannerContext + hasAgentAccess gates", () => { const route = sendAgentRouteWindow(INDEX_SRC); assert.ok( route.includes("ctx = await resolvePlannerContext(req, res, req.params.name);"), "resolvePlannerContext pre-flight must stay" ); assert.ok( route.includes("await hasAgentAccess(req)"), "the hasAgentAccess re-check must stay" ); }); // Regression pin (adpanel:send-agent-version-echo, made mandatory): the // expectedUpdatedAt echo used to be opt-in by body-key presence — an ABSENT // field skipped the check entirely, so a client that never bound to a // version it saw executed whatever prompt was stored now (the // prompt-laundering path). Absence is now rejected with the SAME 409 // planner_prompt_changed shape as a mismatch, whose client handling // refreshes the board and re-sends cleanly (self-healing preserved). test("send-agent route makes the expectedUpdatedAt echo mandatory (absent or mismatched -> 409 planner_prompt_changed)", () => { const route = sendAgentRouteWindow(INDEX_SRC); const absentAt = route.indexOf("!Object.prototype.hasOwnProperty.call(body, 'expectedUpdatedAt') ||"); assert.notStrictEqual(absentAt, -1, "the absent-expectedUpdatedAt rejection is missing"); const mismatchAt = route.indexOf("!plannerUpdatedAtMatches(item.updated_at, body.expectedUpdatedAt)"); assert.notStrictEqual(mismatchAt, -1, "the version-mismatch comparison is missing"); const conflictAt = route.indexOf("error: 'planner_prompt_changed'"); assert.notStrictEqual(conflictAt, -1, "the 409 planner_prompt_changed response is missing"); assert.ok(absentAt < conflictAt && mismatchAt < conflictAt, "both absence and mismatch must feed the same 409"); // The message travels with the code: the client alerts it after refreshing // the board, so the 409 body shape must stay exactly this one. assert.ok( route.includes("message: 'This prompt changed since you viewed it. Refresh the board and review it before sending.'"), "the 409 body must keep the existing message" ); // The old opt-in form (absent field fell through to execution) must be // gone: the positive hasOwnProperty guard would short-circuit the check. assert.ok( !route.includes("Object.prototype.hasOwnProperty.call(body, 'expectedUpdatedAt') &&"), "the opt-in form of the expectedUpdatedAt guard must not come back" ); }); // Regression pin (adpanel:send-agent-version-echo, content half): the // updated_at echo is a FAST PATH only — MySQL TIMESTAMP carries second // precision, so a co-planner's PUT landing in the SAME wall-clock second // leaves updated_at unchanged while the stored prompt is different text, and // the job would execute that NEW text under the SENDER's identity (prompt // laundering). The byte-equality gate on expectedPrompt is the actual // laundering gate; absence must fail closed to the SAME 409 shape, and the // shipped board must echo the field or every send 409s forever. test("send-agent route gates on expectedPrompt content equality (the timestamp echo alone is bypassable same-second)", () => { const route = sendAgentRouteWindow(INDEX_SRC); const absentAt = route.indexOf("!Object.prototype.hasOwnProperty.call(body, 'expectedPrompt') ||"); assert.notStrictEqual(absentAt, -1, "the absent-expectedPrompt rejection is missing"); const equalityAt = route.indexOf("String(body.expectedPrompt) !== String(item.prompt ?? '')"); assert.notStrictEqual(equalityAt, -1, "the prompt content byte-equality gate is missing"); const conflictAt = route.indexOf("error: 'planner_prompt_changed'"); assert.notStrictEqual(conflictAt, -1, "the 409 planner_prompt_changed response is missing"); assert.ok(absentAt < conflictAt && equalityAt < conflictAt, "both absence and mismatch must feed the same 409"); // The timestamp check must not stand alone: if the content clause is ever // dropped while the timestamp clause remains, the same-second laundering // window reopens with the suite still green. assert.ok( route.includes("!plannerUpdatedAtMatches(item.updated_at, body.expectedUpdatedAt)"), "the expectedUpdatedAt fast path must remain alongside the content gate" ); // The shipped board must echo BOTH fields in the same request, or the // fail-closed gate 409s every send from a client that omits either. Pinned // inside the sendPlannerPromptToAgent window so a second, unrelated // occurrence of the literal elsewhere in bot.js cannot satisfy it. const sendFn = botFunctionWindow(BOT_SRC, "async function sendPlannerPromptToAgent(item) {", "sendPlannerPromptToAgent"); assert.ok( sendFn.includes("expectedUpdatedAt: item.updated_at ?? null"), "bot.js sendPlannerPromptToAgent must send expectedUpdatedAt" ); assert.ok( sendFn.includes("expectedPrompt: String(item.prompt ?? '')"), "bot.js sendPlannerPromptToAgent must send expectedPrompt alongside expectedUpdatedAt" ); }); test("send-agent catch forwards err.message only under the err.status invariant", () => { const route = sendAgentRouteWindow(INDEX_SRC); const insertCallAt = route.indexOf("await insertAiAgentChatJob("); assert.notStrictEqual(insertCallAt, -1, "insertAiAgentChatJob call missing from route"); // The body catch is the LAST catch in the route (the pre-flight guard has // its own earlier one). const catchAt = route.lastIndexOf("} catch (err) {"); assert.notStrictEqual(catchAt, -1, "body catch missing from send-agent route"); assert.ok(catchAt > insertCallAt, "the pinned catch must wrap the insertAiAgentChatJob call"); const catchBlock = route.slice(catchAt); // The real error stays logged server-side. assert.ok( catchBlock.includes('console.error("[planner] Send to agent error:"'), "the existing console.error must be kept" ); // Invariant branch: only deliberately-crafted errors (integer err.status // >= 400) are forwarded verbatim, with err.message alongside a generic // fallback. const branchAt = catchBlock.indexOf("if (err && Number.isInteger(err.status) && err.status >= 400) {"); assert.notStrictEqual(branchAt, -1, "the err.status invariant branch is missing"); assert.ok( catchBlock.includes(`res.status(err.status).json({ error: err.message || "${GENERIC_SEND_ERROR}" })`), "status-bearing errors must forward err.message with the generic fallback" ); // Everything else: fixed generic 500, same shape as the sibling planner // routes — no interpolation of err.message. const genericAt = catchBlock.indexOf(`return res.status(500).json({ error: "${GENERIC_SEND_ERROR}" });`); assert.notStrictEqual(genericAt, -1, "the fixed generic 500 return is missing"); assert.ok(genericAt > branchAt, "the generic 500 must follow the status-bearing branch"); assert.strictEqual( countOccurrences(catchBlock, "err.message"), 1, "err.message may appear only inside the status-bearing branch (console.error uses err?.message)" ); // The old leaky pattern is gone. assert.ok( !catchBlock.includes("err.status || 500"), "the unconditional err.status || 500 passthrough must not come back" ); }); // Regression pins (adpanel:planner-send-insert-atomic, adpanel:planner-send-completed, // adpanel:planner-agent-perms manual-send parity, adpanel:planner-control-strip): // the send route committed its verification transaction and inserted the job on // the pool afterwards — a delete-vs-enqueue race the DELETE route's retract // could lose; completed items were consumable; the job carried no author file // envelope; and invisible control/bidi characters rode the prompt verbatim. test("send-agent inserts the job inside its verification transaction and returns after commit", () => { const route = sendAgentRouteWindow(INDEX_SRC); const echoCheckAt = route.indexOf("String(body.expectedPrompt) !== String(item.prompt ?? '')"); const insertAt = route.indexOf("await insertAiAgentChatJob("); const commitAt = route.indexOf("await conn.commit();"); const responseAt = route.indexOf("return res.json(", commitAt); assert.notStrictEqual(echoCheckAt, -1, "the expectedPrompt echo gate is missing"); assert.notStrictEqual(insertAt, -1, "insertAiAgentChatJob call missing from route"); assert.notStrictEqual(commitAt, -1, "the transaction commit is missing"); assert.notStrictEqual(responseAt, -1, "the post-commit response is missing"); assert.ok( echoCheckAt < insertAt && insertAt < commitAt && commitAt < responseAt, "the echoed prompt check and durable insert must share a transaction before the panel acknowledges admission" ); assert.doesNotMatch(route, /\b(?:enqueueAiAgentJob|scheduleAiAgentPump)\s*\(/); // The conn option is what joins the insert (and its cap checks) to the // caller's transaction instead of a private one. const insertCall = route.slice(insertAt, route.indexOf("});", insertAt)); assert.ok( insertCall.split("\n").some((line) => line.trim() === "conn,"), "insertAiAgentChatJob must receive the route's transaction connection" ); assert.strictEqual( countOccurrences(route, "await conn.commit();"), 1, "exactly one commit — the insert must not open a second transaction on another connection" ); }); test("send-agent refuses completed items and captures the shared author file-perm envelope", () => { const route = sendAgentRouteWindow(INDEX_SRC); const selectAt = route.indexOf( '"SELECT id, title, prompt, is_done, updated_at, prompt_author_id, CAST(agent_edit_hold_job_id AS CHAR) AS agent_edit_hold FROM server_planner_items WHERE id = ? AND server_name = ? LIMIT 1 FOR UPDATE"' ); assert.notStrictEqual( selectAt, -1, "the locked item SELECT must load is_done, the bound prompt-author ID, and the current edit hold" ); const holdCheckAt = route.indexOf("if (item.agent_edit_hold && body.checkedAgentEditHold !== item.agent_edit_hold)"); const insertAt = route.indexOf("result = await insertAiAgentChatJob("); const transferHoldAt = route.indexOf("SET agent_edit_hold_job_id = ?"); assert.ok(selectAt < holdCheckAt && holdCheckAt < insertAt && insertAt < transferHoldAt && transferHoldAt < route.indexOf("await conn.commit();")); assert.match(route.slice(transferHoldAt), /\[result\.jobId, item\.id, ctx\.serverName, item\.agent_edit_hold\]/); const doneCheckAt = route.indexOf("if (Number(item.is_done) === 1) {"); // adpanel:planner-send-done-shape — this pin matches the wire reality: the // board's plannerRequest alerts err.error || err.message (bot.js), so the // human sentence must ride `error` directly (same shape as the dedupe 409). // The earlier machine-code + `message` body is pinned as ABSENT: its code // won that alert and users saw the literal "planner_item_done" while the // message field sat dead, and no client ever branched on the code, so it is // dropped entirely (machine codes stay reserved for 409s a client branches // on, e.g. planner_prompt_changed). const doneConflictAt = route.indexOf('error: "This prompt is already completed. It can no longer be sent to the ADPanel Agent."'); assert.notStrictEqual(doneCheckAt, -1, "the completed-item refusal is missing"); assert.notStrictEqual(doneConflictAt, -1, "the 409 body must carry the client-alertable sentence in `error` (the board alerts err.error || err.message)"); assert.strictEqual( route.indexOf('error: "planner_item_done"'), -1, "the dead planner_item_done machine code must not come back: it won the err.error || err.message alert and users saw the literal code" ); const rollbackAt = route.indexOf("await conn.rollback();", doneCheckAt); assert.ok( rollbackAt > doneCheckAt && rollbackAt < doneConflictAt, "the completed-item refusal must roll the transaction back before answering" ); // adpanel:planner-agent-perms — manual-send parity: the enqueue-time file // envelope is captured through the ONE shared helper the scheduler uses, // keyed on the locked row's author and the route's resolved server name. const envelopeAt = route.indexOf("await buildPlannerItemFilePermEnvelope({"); assert.notStrictEqual(envelopeAt, -1, "the send must capture the enqueue-time file envelope through the shared helper"); const envelopeCall = route.slice(envelopeAt, route.indexOf("});", envelopeAt)); assert.ok( envelopeCall.includes("authorId: item.prompt_author_id") && envelopeCall.includes("serverName: ctx.serverName,"), "the envelope must key on the LOCKED row's author and the resolved server name" ); assert.ok( route.includes("permFileEnvelope,"), "the captured envelope must ride the job insert" ); }); // adpanel:planner-send-completion — the done-flip // (markPlannerItemDoneAfterAgentJob) consumes BOTH planner job sources and // byte-compares sanitizeAiAgentPrompt(buildPlannerAgentPrompt(item, // serverName)) against the stored row.prompt. A planner_send row storing the // raw item text would mismatch that recomposition forever, so the flip would // silently never fire for manual sends: the route must store the SAME composed // snapshot the scheduler fire stores, composed with the canonical name the job // row will carry. test("send-agent stores the composed buildPlannerAgentPrompt snapshot so the done-flip byte-compare matches for planner_send rows", () => { const route = sendAgentRouteWindow(INDEX_SRC); const insertAt = route.indexOf("await insertAiAgentChatJob("); assert.notStrictEqual(insertAt, -1, "insertAiAgentChatJob call missing from route"); const insertCall = route.slice(insertAt, route.indexOf("});", insertAt)); assert.ok( insertCall.includes("prompt: buildPlannerAgentPrompt(item, ctx.serverName),"), "the stored job prompt must be composed through the ONE shared composer with the canonical ctx.serverName — a raw item.prompt would never byte-match the done-flip's recomposition and a completed manual send would never mark its item done" ); assert.ok( !insertCall.includes("prompt: item.prompt"), "the raw item text must not be stored as the job prompt anymore" ); }); test("planner sanitizers strip control/bidi characters through one shared, echo-safe class", () => { // adpanel:planner-control-strip — invisible characters are instruction // carriers in text that is echoed byte-for-byte and executed as agent task // data. Both write paths (create + PUT) sanitize through ONE class; the // strip must be idempotent so the GET list's stored values keep satisfying // the send-agent expectedPrompt echo. const titleBody = functionWindow(INDEX_SRC, "function sanitizePlannerTitle", "sanitizePlannerTitle"); const promptBody = functionWindow(INDEX_SRC, "function sanitizePlannerPrompt", "sanitizePlannerPrompt"); assert.ok( titleBody.includes("PLANNER_CONTROL_CHAR_RE") && promptBody.includes("PLANNER_CONTROL_CHAR_RE"), "both sanitizers must run the ONE shared strip class — two drifting character classes is the drift this pin exists to prevent" ); assert.strictEqual( countOccurrences(INDEX_SRC, "PLANNER_CONTROL_CHAR_RE"), 3, "the class is declared once and used exactly twice (every planner write fans in through these two functions)" ); // Functional check of the class itself, evaluated from the source so the // pin cannot rot away from the shipped pattern. const literal = INDEX_SRC.match(/const PLANNER_CONTROL_CHAR_RE = \/(.+?)\/([a-z]+);/); assert.ok(literal, "the shared strip class must be a regex literal"); const strip = new RegExp(literal[1], literal[2]); assert.strictEqual("a\u200Bb\uFEFFc".replace(strip, ""), "abc", "zero-width characters and BOM are stripped"); assert.strictEqual("a\u202Eb\u2066c\u2069d".replace(strip, ""), "abcd", "bidi overrides and isolates are stripped"); assert.strictEqual("a\u0000b\u0007c\u009Fd\u2028e".replace(strip, ""), "abcde", "NUL, C0, C1 controls and line/paragraph separators are stripped"); assert.strictEqual("a\nb\tc".replace(strip, ""), "a\nb\tc", "\\n and \\t survive the class itself — they are handled per-field below"); // Per-field semantics: prompts preserve \n (multi-line task data) but // rewrite tabs to spaces (a tab must not fuse two words into a different // instruction); titles collapse all whitespace as before. assert.ok(promptBody.includes(".replace(/\\t/g, ' ')"), "prompts must rewrite tabs to spaces, not delete them"); assert.ok(!promptBody.includes("replace(/\\s+/g"), "prompts must NOT collapse all whitespace — newlines are task-data structure"); assert.ok(titleBody.includes(".replace(/\\s+/g, ' ')"), "titles keep the whitespace collapse"); // adpanel:planner-sanitize-idempotence — both sanitizers finish CUT -> TRIM: // the strip/trim/collapse run before the cut, so the cut itself can land on // whitespace (a space, a tab-rewritten space, a preserved \n exactly at unit // 255/4000) and store a value whose re-sanitize trims differently — a // zero-diff PUT would compute contentChanged, spuriously re-stamping // created_by_email and retracting a queued job. The trailing trim makes // sanitize(stored) === stored provable. assert.ok( titleBody.includes("), PLANNER_TITLE_MAX_UNITS).trim();") && promptBody.includes("), PLANNER_PROMPT_MAX_UNITS).trim();"), "both sanitizers must trim AFTER the safe cut (cut -> trim), not only before it" ); // adpanel:surrogate-safe-cut — the caps moved from inline .slice literals // to the shared surrogate-safe cut: a plain .slice could split a surrogate // pair at the boundary, and the stored lone half renders as U+FFFD. The // cap VALUES stay pinned exactly (now at their single declaration site // instead of inside each body), and both sanitizers must route through the // shared helper — this replaces, without weakening, the former // "slice(0, 255)"/"slice(0, 4000)" body pins. const titleCapDecl = INDEX_SRC.match(/const PLANNER_TITLE_MAX_UNITS = (\d+);/); const promptCapDecl = INDEX_SRC.match(/const PLANNER_PROMPT_MAX_UNITS = (\d+);/); assert.ok(titleCapDecl && titleCapDecl[1] === "255", "the title cap is still 255 (declared once as PLANNER_TITLE_MAX_UNITS)"); assert.ok(promptCapDecl && promptCapDecl[1] === "4000", "the prompt cap is still 4000 (declared once as PLANNER_PROMPT_MAX_UNITS)"); assert.ok( titleBody.includes("PLANNER_TITLE_MAX_UNITS") && promptBody.includes("PLANNER_PROMPT_MAX_UNITS"), "both sanitizers must cap through the shared constants" ); assert.ok( titleBody.includes("safeTruncateUtf16(") && promptBody.includes("safeTruncateUtf16("), "both sanitizers must cut through the shared surrogate-safe helper, not a plain .slice" ); }); // adpanel:planner-sanitize-idempotence — functional proof that the sanitize // pipeline is idempotent AT the cap boundary: the cut can land on whitespace // the pre-cut trim cannot remove, so the trailing trim after the cut is what // makes sanitize(stored) === stored. The sanitizer bodies are evaluated from // the real index.js source in a sandbox with the shared cut helper injected // (same pattern as tests/template-store-install-review.test.js — index.js // cannot be required from a test). function buildPlannerSanitizers() { const reDecl = INDEX_SRC.match(/const PLANNER_CONTROL_CHAR_RE = .*;/); assert.ok(reDecl, "the shared strip class declaration must exist"); const titleCapDecl = INDEX_SRC.match(/const PLANNER_TITLE_MAX_UNITS = \d+;/); const promptCapDecl = INDEX_SRC.match(/const PLANNER_PROMPT_MAX_UNITS = \d+;/); assert.ok(titleCapDecl && promptCapDecl, "the cap constant declarations must exist"); const slice = [ "const safeTruncateUtf16 = __safeTruncateUtf16;", reDecl[0], titleCapDecl[0], promptCapDecl[0], functionWindow(INDEX_SRC, "function sanitizePlannerTitle", "sanitizePlannerTitle"), functionWindow(INDEX_SRC, "function sanitizePlannerPrompt", "sanitizePlannerPrompt"), ].join("\n"); const factory = new Function("__safeTruncateUtf16", `${slice}\nreturn { sanitizePlannerTitle, sanitizePlannerPrompt };`); return factory(require("../utils/safe-truncate").safeTruncateUtf16); } test("planner sanitize pipeline is idempotent when the cut lands on whitespace", () => { const { sanitizePlannerTitle, sanitizePlannerPrompt } = buildPlannerSanitizers(); // Prompt cap (4000): unit 4000 is the whitespace in each case — a plain // space, a preserved \n, and a tab rewritten to a space by the sanitizer. for (const [label, boundary] of [ ["space", " "], ["preserved newline", "\n"], ["tab rewritten to space", "\t"], ]) { const raw = `${"x".repeat(3999)}${boundary}tail`; const stored = sanitizePlannerPrompt(raw); assert.strictEqual( stored, "x".repeat(3999), `prompt whose unit 4000 is a ${label} must store the trimmed prefix` ); assert.ok(!/\s$/.test(stored), `stored prompt must not end with whitespace (${label})`); assert.ok(stored.length <= 4000, `stored prompt must respect the cap (${label})`); assert.strictEqual( sanitizePlannerPrompt(stored), stored, `sanitize(stored) === stored for the ${label} boundary — a zero-diff PUT must not compute contentChanged` ); } // Title cap (255): the cut lands on an interior space pushed to unit 255. const rawTitle = `${"x".repeat(254)} tail`; const storedTitle = sanitizePlannerTitle(rawTitle); assert.strictEqual(storedTitle, "x".repeat(254), "title whose unit 255 is a space must store the trimmed prefix"); assert.ok(!/\s$/.test(storedTitle), "stored title must not end with whitespace"); assert.strictEqual(sanitizePlannerTitle(storedTitle), storedTitle, "sanitize(stored) === stored for the title boundary"); // Property check over a whitespace-heavy corpus: cutting never breaks // idempotence, and the caps hold. const corpus = [ `${"word ".repeat(60)}`, `${"a\n".repeat(2100)}`, `${"x".repeat(4000)}`, `${"\t".repeat(4100)}`, `line1\n${"y".repeat(4050)}\nline3\t\tend`, `${"seg ".repeat(50)}\u{1F600}${" seg".repeat(60)}`, ]; for (const raw of corpus) { for (const sanitize of [sanitizePlannerTitle, sanitizePlannerPrompt]) { const stored = sanitize(raw); assert.ok(stored.length <= (sanitize === sanitizePlannerTitle ? 255 : 4000), "cap respected"); assert.ok(!/\s$/.test(stored), "no trailing whitespace after the cut -> trim finish"); assert.strictEqual(sanitize(stored), stored, "idempotent over the corpus"); } } }); test("sendPlannerPromptToAgent declares plannerSendAgentInFlight beside plannerSaveInFlight", () => { const saveDeclAt = BOT_SRC.indexOf("let plannerSaveInFlight = false;"); assert.notStrictEqual(saveDeclAt, -1, "plannerSaveInFlight declaration missing"); const declAt = BOT_SRC.indexOf("let plannerSendAgentInFlight = false;"); assert.notStrictEqual(declAt, -1, "plannerSendAgentInFlight declaration missing"); assert.ok(declAt > saveDeclAt, "plannerSendAgentInFlight must be declared after plannerSaveInFlight"); const fnAt = BOT_SRC.indexOf("async function sendPlannerPromptToAgent(item)"); assert.notStrictEqual(fnAt, -1, "sendPlannerPromptToAgent missing"); assert.ok(declAt < fnAt, "the guard variable must be declared before the function that uses it"); }); test("sendPlannerPromptToAgent guards re-entry before the async body and clears in finally", () => { const body = botFunctionWindow( BOT_SRC, "async function sendPlannerPromptToAgent(item)", "sendPlannerPromptToAgent" ); const emptyCheckAt = body.indexOf("if (!item || !String(item.prompt || '').trim()) {"); const accessCheckAt = body.indexOf("if (!hasAgentAccess()) {"); // The guard is a block: it surfaces the brake on the status line before // returning, so a repeat click is never a silent no-op. const guardAt = body.indexOf("if (plannerSendAgentInFlight) {"); const setAt = body.indexOf("plannerSendAgentInFlight = true;"); assert.notStrictEqual(emptyCheckAt, -1, "empty-prompt validation missing"); assert.notStrictEqual(accessCheckAt, -1, "agent-access validation missing"); assert.notStrictEqual(guardAt, -1, "in-flight re-entry guard missing"); assert.notStrictEqual(setAt, -1, "in-flight flag set missing"); assert.ok( emptyCheckAt < accessCheckAt && accessCheckAt < guardAt && guardAt < setAt, "order must be: validations (re-runnable) -> guard -> set flag" ); const guardBlock = body.slice(guardAt, setAt); assert.ok( guardBlock.includes("setPlannerStatus('A prompt is already being sent — wait for it to finish.', true)") && guardBlock.includes("return;"), "the in-flight guard must surface the brake on the status line before returning" ); // Exactly three references in the function: the guard, the set, the clear. assert.strictEqual( countOccurrences(body, "plannerSendAgentInFlight"), 3, "the flag must be referenced exactly three times: guard, set, finally clear" ); const finallyAt = body.indexOf("} finally {", setAt); assert.notStrictEqual(finallyAt, -1, "a finally covering the send body is missing"); const clearAt = body.indexOf("plannerSendAgentInFlight = false;", finallyAt); assert.notStrictEqual(clearAt, -1, "the flag must be cleared inside the finally"); }); test("sendPlannerPromptToAgent still suppresses alerting for planner auth errors", () => { const body = botFunctionWindow( BOT_SRC, "async function sendPlannerPromptToAgent(item)", "sendPlannerPromptToAgent" ); const catchAt = body.indexOf("} catch (err) {"); assert.notStrictEqual(catchAt, -1, "body catch missing"); const suppressAt = body.indexOf("if (!err.isPlannerAuthError) alert("); assert.notStrictEqual(suppressAt, -1, "isPlannerAuthError alert suppression missing"); assert.ok(suppressAt > catchAt, "the suppression must stay inside the catch"); assert.ok( body.includes("A 401 already raised the session-expired overlay in plannerRequest"), "the 401 double-prompt rationale comment must stay with the suppression" ); }); // Regression pin (adpanel:planner-send-gone): a 404 from the send route — the // row was deleted mid-flight, a real window because the confirm dialog sits // open between the click and the POST — used to alert the raw server message // and leave the dead card fully actionable, re-alerting on every send. The // board-is-authoritative recovery togglePlannerItem/deletePlannerItem apply // to their 404s covers the send too: reload the board, and on success say why // the card vanished on the status line instead of alerting. The 409 // planner_prompt_changed branch and the generic alert fallback stay, in that // order, with the auth-error suppression still last. test("sendPlannerPromptToAgent recovers a 404 like toggle/delete: reload, then 'Prompt no longer exists'", () => { const body = botFunctionWindow( BOT_SRC, "async function sendPlannerPromptToAgent(item)", "sendPlannerPromptToAgent" ); const catchAt = body.indexOf("} catch (err) {"); assert.notStrictEqual(catchAt, -1, "body catch missing"); const goneAt = body.indexOf("else if (err.status === 404) {", catchAt); assert.notStrictEqual(goneAt, -1, "the 404 recovery branch is missing from the send catch"); const reloadAt = body.indexOf("await loadPlannerItems();", goneAt); assert.notStrictEqual(reloadAt, -1, "the 404 branch must reload the board (await loadPlannerItems) so the dead card drops"); const statusAt = body.indexOf("setPlannerStatus('Prompt no longer exists');", goneAt); assert.notStrictEqual(statusAt, -1, "the 404 branch must set the delete path's 'Prompt no longer exists' wording instead of alerting the raw server message"); assert.ok( !body.slice(goneAt, statusAt).includes("alert("), "the 404 branch must not alert — the status line carries the recovery (a failed load reports itself)" ); const conflictAt = body.indexOf("err.status === 409 && err.message === 'planner_prompt_changed'", catchAt); const suppressAt = body.indexOf("if (!err.isPlannerAuthError) alert(", catchAt); assert.notStrictEqual(conflictAt, -1, "the 409 planner_prompt_changed branch is missing"); assert.notStrictEqual(suppressAt, -1, "the generic alert fallback is missing"); assert.ok( conflictAt < goneAt && goneAt < suppressAt, "branch order must stay: 409 prompt-changed -> 404 gone -> generic fallback (auth-error suppression last)" ); }); // adpanel:planner-send-completion — the completion poll used to cap itself at // 90 attempts (~3.6 min) and bare-return on exhaustion: the server allows runs // up to AI_AGENT_JOB_MAX_RUNTIME_MS (default 20 min, env-clamped 2–120) plus a // serial-queue wait behind up to 500 pending jobs, and this poll is the // planner board's SOLE completion surface, so any longer run left the board // stale forever — the user re-sent a dedupe-409ing card or toggle-completed an // already-flipped row and never saw the reply. The budget is now wall-clock // (one named constant, consumed by the loop) and the delays tier up with poll // age to bound request volume. GET /api/ai/jobs/:id carries a DEDICATED // always-on per-account limiter (shared Redis store, per-account email key, // ~45 req/60s — sized from the poll's own arithmetic: it fits roughly one // peak poller with headroom, while two tabs both in the 2.5s tier can brush // the ceiling and the 429 branch sheds that excess), while the conditional // GLOBAL per-IP limiters (security.rate_limiting, code default on: a // Redis-backed limiter over /api code-defaulted to 100 req/120s and shipped // at 300 req/120s in security.json, with an in-memory fallback code-defaulted // to 25 req/120s — both config-driven via security.limit) remain a second // layer beneath it: the poll's 2.5s tier (48 req/120s) fits inside the // Redis-backed limiter's defaults, while the in-memory fallback's own // 25/120s code default would bind — but it reads the same security.limit // (300 shipped) when engaged, and a tripped 429 sheds gracefully either // way. The poll still starts at 4000ms because // the seconds right after the send are where the user's own interactive // requests concentrate, and a 429 from EITHER limiter is treated as // THROTTLING: back off 30s on its own constant and continue, never a failure // strike. BOTH // non-settled exits are VISIBLE (exhaustion AND 3 consecutive failures: // offline status pointing at the AI panel plus ONE final fire-and-forget // board reconcile), and the settled-path chat repaint is best-effort so its // failure cannot skip the reconcile. test("pollAiAgentJob runs on a wall-clock budget outliving the server job deadline and surfaces exhaustion visibly", () => { const body = botFunctionWindow(BOT_SRC, "async function pollAiAgentJob(jobId", "pollAiAgentJob"); // The budget constant is declared once, beside the planner constants, ahead // of the function that consumes it — and the loop actually consumes it. const declAt = BOT_SRC.indexOf("const PLANNER_JOB_POLL_MAX_MS = 30 * 60 * 1000;"); assert.notStrictEqual(declAt, -1, "PLANNER_JOB_POLL_MAX_MS must be declared with its 30-minute value"); assert.ok(declAt < BOT_SRC.indexOf("async function pollAiAgentJob(jobId"), "the budget constant must be declared before pollAiAgentJob"); assert.ok(body.includes("elapsedMs >= PLANNER_JOB_POLL_MAX_MS"), "the loop must bound itself on elapsed wall-clock time against PLANNER_JOB_POLL_MAX_MS"); // The fixed attempt cap must be gone in every form: any attempt-count bound // reintroduces the silent ~3.6-minute abandon of runs the server still owns. assert.ok(!body.includes("attempt < "), "no attempt-count bound may gate the loop — only the wall-clock budget"); // Tiered delays: keyed on poll AGE (not attempt index), starting at 4000ms // (the seconds right after the send are where the user's own interactive // requests concentrate — the poll must not pile onto that burst by itself), // slower tiers with age. const tierAt = body.indexOf("const waitMs = elapsedMs < PLANNER_JOB_POLL_FAST_MS"); assert.notStrictEqual(tierAt, -1, "the delay tiers must key on poll age through the named tier constants"); assert.ok(BOT_SRC.includes("const PLANNER_JOB_POLL_FAST_DELAY_MS = 4000;"), "the fast tier delay must be 4000ms — the old 1200ms (~50 req/min) trips the global per-IP limiter and starves the user's interactive requests"); assert.ok( body.includes("PLANNER_JOB_POLL_FAST_DELAY_MS") && body.includes("PLANNER_JOB_POLL_SLOW_DELAY_MS") && body.includes("PLANNER_JOB_POLL_IDLE_DELAY_MS"), "all three delay tiers must be consumed (4000ms fast / 2500ms slow / 4000ms idle)" ); // The poll constants' comment must premise the NEW limiter truth: a // dedicated always-on per-account limiter covers GET /api/ai/jobs/:id with // a budget sized from the poll's own arithmetic, the conditional global // per-IP limiters remain a second layer, and the 429 backoff answers // either layer. Phrase-pinned (like the constraints they document) so the // comment cannot silently revert to the stale "no dedicated route limiter" // premise now that the backend limiter exists. assert.ok( BOT_SRC.includes("DEDICATED always-on per-account limiter") && BOT_SRC.includes("~45 req/60s") && BOT_SRC.includes("second layer beneath it"), "the poll constants comment must premise the dedicated always-on per-account limiter with its ~45 req/60s poll-arithmetic budget and the per-IP limiters as a second layer" ); assert.ok( !BOT_SRC.includes("/api/ai/jobs/:id carries NO"), "the stale 'GET /api/ai/jobs/:id carries NO dedicated route limiter' premise must stay gone from the poll constants comment" ); // Limiter awareness: a 429 is throttling, not a job-state failure — it must // back off on its own named constant and continue WITHOUT touching the // failure counter, ahead of the generic !ok throw. assert.ok(BOT_SRC.includes("const PLANNER_JOB_POLL_THROTTLED_DELAY_MS = 30 * 1000;"), "the 429 backoff must be a named 30s constant beside the tier constants"); const throttleAt = body.indexOf("if (response.status === 429) {"); assert.notStrictEqual(throttleAt, -1, "the poll must treat a 429 as throttling — the dedicated branch is missing"); const genericThrowAt = body.indexOf("if (!response.ok) throw", throttleAt); assert.notStrictEqual(genericThrowAt, -1, "other non-OK responses must still throw into the failure path after the 429 branch"); const throttleBranch = body.slice(throttleAt, genericThrowAt); assert.ok(throttleBranch.includes("PLANNER_JOB_POLL_THROTTLED_DELAY_MS"), "the 429 branch must back off on the named 30s constant"); assert.ok(throttleBranch.includes("continue"), "the 429 branch must continue polling after its backoff (the loop-top wall-clock check still governs)"); assert.ok(!throttleBranch.includes("consecutiveFailures"), "a 429 must not count toward the 3-consecutive-failure budget"); assert.ok(body.includes("consecutiveFailures += 1;"), "genuine failures must still increment the consecutive-failure counter"); // The 3-consecutive-failure abort stays (transient blips reset) and is now // VISIBLE like exhaustion: log, offline status naming the AI panel, ONE // final fire-and-forget reconcile, then return — never a silent bare return // (concrete trigger: server deleted mid-poll -> three 404s -> dead poll, // stale board). const failuresAt = body.indexOf("if (consecutiveFailures >= 3) {"); assert.notStrictEqual(failuresAt, -1, "the 3-consecutive-failure abort must stay"); assert.ok(failuresAt > genericThrowAt, "the failure counter must live in the catch, after the 429 branch"); assert.ok(body.includes("after 3 consecutive failures:"), "the failure-abort log must stay"); const strikeStatusAt = body.indexOf("setPlannerStatus(", failuresAt); assert.notStrictEqual(strikeStatusAt, -1, "the 3-strike exit must surface on the planner status line instead of bare-returning"); const strikeStatus = body.slice(strikeStatusAt, body.indexOf(");", strikeStatusAt) + 2); assert.ok(strikeStatus.includes(", true)"), "the 3-strike status must be offline-marked"); assert.ok(strikeStatus.includes("AI panel"), "the 3-strike sentence must point the user at the AI panel for live status"); const strikeReloadAt = body.indexOf("loadPlannerItems();", strikeStatusAt); assert.notStrictEqual(strikeReloadAt, -1, "the 3-strike exit must fire one final board reconcile"); const strikeReturnAt = body.indexOf("return;", strikeReloadAt); assert.notStrictEqual(strikeReturnAt, -1, "the 3-strike exit must end the poll after the reconcile"); assert.ok(strikeStatusAt < strikeReloadAt && strikeReloadAt < strikeReturnAt, "3-strike order must be: status -> reconcile -> return"); const strikeContinueAt = body.indexOf("continue;", strikeReturnAt); assert.ok(strikeReturnAt < strikeContinueAt, "the 3-strike branch must return before the catch's transient-blip continue"); // Exhaustion must be visible: offline status naming the AI panel, ONE final // fire-and-forget reconcile, then return — never a silent bare return. const exhaustAt = body.indexOf("elapsedMs >= PLANNER_JOB_POLL_MAX_MS"); const exhaustStatusAt = body.indexOf("setPlannerStatus(", exhaustAt); assert.notStrictEqual(exhaustStatusAt, -1, "exhaustion must surface on the planner status line"); const exhaustStatus = body.slice(exhaustStatusAt, body.indexOf(");", exhaustStatusAt) + 2); assert.ok(exhaustStatus.includes(", true)"), "the exhaustion status must be offline-marked"); assert.ok(exhaustStatus.includes("AI panel"), "the exhaustion sentence must point the user at the AI panel for live status"); const exhaustReloadAt = body.indexOf("loadPlannerItems();", exhaustStatusAt); assert.notStrictEqual(exhaustReloadAt, -1, "exhaustion must fire one final board reconcile"); const exhaustReturnAt = body.indexOf("return;", exhaustReloadAt); assert.notStrictEqual(exhaustReturnAt, -1, "exhaustion must end the poll after the reconcile"); assert.ok(exhaustStatusAt < exhaustReloadAt && exhaustReloadAt < exhaustReturnAt, "exhaustion order must be: status -> reconcile -> return"); // The terminal branch keeps its own fire-and-forget reconcile, after the // exhaustion block — and the chat repaint around it is best-effort: a throw // from switchToChat/loadChatsFromDb used to escape to the caller's .catch // and skip the reconcile, breaking the every-exit-visible contract. const terminalAt = body.indexOf("const status = String(data?.job?.status || '').toLowerCase();"); const terminalReloadAt = body.indexOf("loadPlannerItems();", terminalAt); assert.notStrictEqual(terminalReloadAt, -1, "the terminal branch must keep its fire-and-forget reconcile"); const terminalUi = body.slice(terminalAt, terminalReloadAt); assert.ok(terminalUi.includes("try {") && terminalUi.includes("catch (repaintErr) {"), "the settled-path chat repaint must be wrapped so its failure cannot skip the board reconcile"); assert.ok(terminalAt > exhaustReturnAt, "the settled-job handling must stay after the exhaustion block"); }); test("Planner submits the model captured before confirmation without saving a shared preference", () => { const body = botFunctionWindow( BOT_SRC, "async function sendPlannerPromptToAgent(item)", "sendPlannerPromptToAgent" ); const modelAt = body.indexOf("const sendModelValue = String(aiModelSelect?.value || '').trim();"); const confirmAt = body.indexOf("await storeConfirm("); const postAt = body.indexOf("plannerMutateRequest(`/${encodeURIComponent(item.id)}/send-agent`"); assert.ok(modelAt >= 0 && modelAt < confirmAt && confirmAt < postAt); assert.match(body.slice(postAt), /\.\.\.\(sendModelValue && \{ selection: sendModelValue \}\)/); assert.doesNotMatch(body, /saveSelectedAiModel/); assert.match(body.slice(postAt), /finally \{\s*plannerSendAgentInFlight = false;/); assert.match(INDEX_SRC, /resolveAiModelSelectionForUserId\(user\?\.id, req\.body\?\.selection\)[\s\S]*?provider: selection\.provider,\s+model: selection\.model,\s+source: "planner_send"/); }); // adpanel:planner-open-idempotent — re-opening an ALREADY-ACTIVE planner used // to run the full open path unconditionally: openPlannerModal's // clearPlannerEditState() wiped the hidden item id + plannerEditingUpdatedAt // (and bumped the epoch) while deliberately keeping the drafted text, so a // user who clicked Edit and then habitually re-clicked the active Planner // dock button — the dock capture handler (bot.ejs) gates on // disabled/installing but not on already-active, so the re-click re-runs the // page-init path (showInlinePage -> synthetic click) into openPlannerModal — // returned to Compose and their next Save POSTed a CREATE instead of a PUT: // a silent duplicate (the server has no duplicate detection by design). The // guard must sit BEFORE clearPlannerEditState inside openPlannerModal and key // on the one marker that only a COMPLETED open adds in either mode: modal // mode is .show alone; inline-page mode is .adpanel-page-active PLUS .show // (showInlinePage sets .adpanel-page-active BEFORE the synthetic dock click // reaches openPlannerModal — inside the boot-perm-gate window too — so an OR // over both classes would strand the first-ever open and the boot-gate flush // on the static template). A genuine reopen (modal hidden / page inactive: // .show stripped by animateClose.finish, showInlinePage's per-page strip, // showConsoleView, or the install-overlay teardown) still takes the full // reset path below the guard. test("openPlannerModal no-ops on an already-active planner BEFORE resetting edit state", () => { const body = botFunctionWindow(BOT_SRC, "function openPlannerModal()", "openPlannerModal"); const guardAt = body.indexOf("if (plannerModal.classList.contains('show')) return;"); assert.notStrictEqual( guardAt, -1, "the already-active guard is missing from openPlannerModal — a re-click while the planner is open resets edit identity and turns the next Save into a duplicate CREATE" ); const clearAt = body.indexOf("clearPlannerEditState();"); assert.notStrictEqual(clearAt, -1, "clearPlannerEditState must stay in openPlannerModal (genuine reopens still reset)"); assert.ok(clearAt > guardAt, "the guard must run BEFORE clearPlannerEditState — the reset must only fire when the planner was NOT already active"); // The guard is a total no-op (return on the guard's own line): an // already-active planner must not even switch tabs or reload the board. const guardLine = body.slice(guardAt, body.indexOf("\n", guardAt)); assert.ok(guardLine.endsWith("return;"), "the guard must return immediately — no reset, no tab switch, no board reload"); // Both mode markers must stay documented at the guard: .show is the // completed-open marker for BOTH modes, and the constraint comment explains // why .adpanel-page-active alone cannot discriminate (pre-set by // showInlinePage before the first open reaches this function). const rationale = body.slice(0, guardAt); assert.ok(rationale.includes("adpanel:planner-open-idempotent"), "the constraint comment must travel with the guard"); assert.ok( rationale.includes(".adpanel-page-active") && rationale.includes("showInlinePage"), "the guard's rationale must cover both mode markers (.show and .adpanel-page-active) and why the inline page class alone cannot discriminate" ); });