Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

@@ -0,0 +1,496 @@
"use strict";
// Source-level pins for the email-keyed user-data cleanup
// (adpanel:user-delete-email-keyed-cleanup).
//
// USER_OWNED_TABLES covers only the tables keyed by users(id) (the
// user_id-keyed CASCADE loop), so account deletion never touched the two
// email-keyed surfaces: server_planner_items (created_by_email) and ai_chats
// (user_email). A deleted co-user's planner items therefore persisted on
// every shared board forever and their chat history was never reaped.
//
// Fixes pinned here:
// 1. deleteUserAccountAtomically deletes BOTH email-keyed surfaces (and
// their ai_messages) inside the same transaction as the users row —
// emailLower is stored lowercased on every write side, so an exact
// match is the correct key;
// 2. ai_messages is deleted BEFORE ai_chats, keyed by the doomed chat ids:
// the runtime CREATE TABLE for the two carries no foreign key, so the
// schema file's fk_ai_messages_chat ON DELETE CASCADE cannot be relied
// on (the same "deletion behaves identically without the constraint"
// rule the user_id loop follows);
// 3. cleanupOrphanedUserRecords sweeps the same three surfaces for
// out-of-process account deletions (the CLI user tooling never runs the
// endpoint's transaction), best-effort per statement exactly like the
// user_id-keyed loop; and
// 4. USER_OWNED_TABLES stays strictly user_id-keyed — the email-keyed
// tables must never be added to that array, whose loop deletes
// `WHERE user_id = ?` and would crash on (or silently miss) them; and
// 5. the email-keyed DELETE's key carries an index
// (idx_server_planner_author on server_planner_items.created_by_email) in
// all three DDL surfaces in lockstep (runtime CREATE TABLE,
// mysql-schema.sql, boot ALTER) — without it the email-keyed delete
// full-scans and next-key-locks every row and gap under REPEATABLE READ,
// blocking concurrent planner writes on every server for the
// transaction's duration (adpanel:planner-item-cascade-retract); and
// 6. deleteUserAccountAtomically retracts the queued planner jobs of OTHER
// users that point at the deleted user's items before deleting those
// items — a queued job must never outlive its item — taking the
// ai_agent_jobs row locks BEFORE the ai_messages/ai_chats writes (the
// same direction cancelQueuedPlannerAgentJobs locks in, so the delete
// cannot deadlock against a concurrent retract)
// (adpanel:planner-item-cascade-retract); and
// 7. scripts/create-user.js --delete — which never runs
// deleteUserAccountAtomically (separate process, own transaction) —
// mirrors the same retract + email-keyed cleanup on that transaction,
// keyed on the script's normalized lowercase email, and replays the
// panel's ai_agent_jobs.status ENUM-widening ALTER in the setup phase,
// BEFORE the transaction opens (MySQL DDL causes an implicit commit).
// The CLI connects to the database at require time, so its pins slice
// scripts/create-user.js structurally instead of require()ing it.
//
// index.js is a ~56k-line application bundle (module side effects, DB and
// network at require time — never require() it from a test), so these tests
// pin the fixes structurally on well-anchored source windows.
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 CLI_SRC = fs.readFileSync(path.join(ROOT, "scripts", "create-user.js"), "utf8");
const PLANNER_OWNER = "prompt_author_id = ? OR (prompt_author_id IS NULL AND created_by_email = ?)";
const PLANNER_ORPHAN = "prompt_author_id NOT IN (SELECT id FROM users) OR (prompt_author_id IS NULL AND created_by_email NOT IN (SELECT email FROM users))";
function functionWindow(src, anchor, label) {
const start = src.indexOf(anchor);
assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`);
const end = src.indexOf("\n}", start);
assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`);
return src.slice(start, end + 2);
}
// Window from an anchor to an explicit end anchor — deterministic slicing
// that survives unrelated edits elsewhere in the bundle (same helper as
// tests/planner-job-retract.test.js).
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);
}
test("USER_OWNED_TABLES stays strictly user_id-keyed (email-keyed tables must never join the user_id loop)", () => {
const declStart = INDEX_SRC.indexOf("const USER_OWNED_TABLES = [");
assert.notStrictEqual(declStart, -1, "the USER_OWNED_TABLES declaration is missing");
const declEnd = INDEX_SRC.indexOf("];", declStart);
assert.notStrictEqual(declEnd, -1, "the USER_OWNED_TABLES array close is missing");
const list = INDEX_SRC.slice(declStart, declEnd);
for (const table of ["user_access", "user_status", "sftp_credentials", "user_ai_model_selections", "destructive_action_grants", "ai_agent_jobs"]) {
assert.ok(
list.includes(`"${table}"`),
`USER_OWNED_TABLES must keep "${table}" — the account delete relies on the explicit loop`
);
}
// server_planner_items and ai_chats have no user_id column: inside the
// `DELETE FROM ${table} WHERE user_id = ?` loop they would error (unknown
// column) and abort the whole atomic delete. Their cleanup is pinned below.
assert.ok(
!list.includes("server_planner_items") && !list.includes("ai_chats"),
"the email-keyed surfaces must stay OUT of USER_OWNED_TABLES — the loop deletes WHERE user_id = ?"
);
});
test("deleteUserAccountAtomically deletes planner items and account-ID bound chats inside the account transaction", () => {
const body = functionWindow(INDEX_SRC, "async function deleteUserAccountAtomically", "deleteUserAccountAtomically");
const loopAt = body.indexOf("for (const table of USER_OWNED_TABLES) {");
const usersDeleteAt = body.indexOf('await conn.execute("DELETE FROM users WHERE id = ?", [userId]);');
const chatsAt = body.indexOf("await deleteAccountServerAgentChats(conn, userId);");
const plannerAt = body.indexOf(`"DELETE FROM server_planner_items WHERE ${PLANNER_OWNER}"`);
assert.notStrictEqual(loopAt, -1, "the user_id-keyed table loop is missing");
assert.notStrictEqual(usersDeleteAt, -1, "the users row delete is missing");
assert.notStrictEqual(chatsAt, -1, "chat and message cleanup must use the account ID on the transaction connection");
assert.notStrictEqual(plannerAt, -1, "planner cleanup must use the author ID first");
// Every email-keyed delete must run ON the transaction connection and sit
// inside the begin/commit window — a pool query here would commit outside
// the atomic delete's rollback scope, and a delete after the users-row
// race check would run for an account that was concurrently deleted.
assert.ok(
loopAt < usersDeleteAt,
"precondition: the user_id loop precedes the users delete"
);
// The promised pin: the email-keyed deletes must precede the users-row
// delete. That delete is the transaction's race check (affectedRows !== 1
// rolls everything back), so an email-keyed delete ordered after it would
// run for an account a concurrent admin had already removed.
assert.ok(
loopAt < chatsAt && chatsAt < plannerAt && plannerAt < usersDeleteAt,
"chat/message and planner cleanup must run after the user_id loop and before the users delete"
);
assert.ok(
body.includes("adpanel:user-delete-email-keyed-cleanup"),
"the email-keyed pass must carry the adpanel:user-delete-email-keyed-cleanup constraint comment"
);
});
test("cleanupOrphanedUserRecords sweeps planner items and chats with missing account IDs, best-effort per statement", () => {
const body = functionWindow(INDEX_SRC, "async function cleanupOrphanedUserRecords", "cleanupOrphanedUserRecords");
const plannerAt = body.indexOf(`DELETE FROM server_planner_items WHERE ${PLANNER_ORPHAN}`);
const messagesAt = body.indexOf("DELETE FROM ai_messages WHERE chat_id IN (SELECT id FROM ai_chats WHERE created_by NOT IN (SELECT id FROM users))");
const chatsAt = body.indexOf("DELETE FROM ai_chats WHERE created_by NOT IN (SELECT id FROM users)");
assert.notStrictEqual(plannerAt, -1, "the orphan sweep must check author IDs and use email only for legacy rows");
assert.notStrictEqual(messagesAt, -1, "the orphan sweep must reap messages of chats whose bound account ID no longer resolves");
assert.notStrictEqual(chatsAt, -1, "the orphan sweep must reap chats whose bound account ID no longer resolves");
assert.ok(
messagesAt < chatsAt,
"ai_messages must be swept BEFORE ai_chats (no runtime FK cascade to rely on)"
);
// Best-effort per statement, exactly like the user_id-keyed loop above it:
// a failure is logged and skipped, never fatal (startup hygiene).
const sweepAt = body.indexOf("const orphanCleanups = [");
assert.notStrictEqual(sweepAt, -1, "the sweep list is missing");
assert.ok(
body.indexOf("adpanel:user-delete-email-keyed-cleanup", 0) !== -1,
"the sweep's email-keyed pass must carry the adpanel:user-delete-email-keyed-cleanup comment"
);
const emailBlock = body.slice(sweepAt);
assert.ok(
emailBlock.includes("try {") && emailBlock.includes('console.warn(`[db] Orphaned ${table} cleanup skipped:`, err?.message || err);'),
"each email-keyed sweep statement must be best-effort — log and skip, never fail startup"
);
assert.ok(
emailBlock.includes("if (removed > 0) console.log(`[db] Removed ${removed} orphaned ${table} row(s) for deleted users`);"),
"the sweep must log how many orphaned rows it removed, matching the user_id loop's reporting"
);
});
// ─── adpanel:planner-item-cascade-retract ────────────────────────────────────
test("deleteUserAccountAtomically retracts queued planner jobs for the deleted user's items before deleting those items", () => {
// A queued planner job must never outlive its item: a co-user's queued
// ai_agent_jobs row (planner_send / scheduler_planner_next) for the deleted
// user's item no longer runs the enqueue-time prompt once the item is gone
// (planner-source rows fail terminally at processAiAgentJob's
// item-existence gate), but the retract — not a fire-time 404 — is what
// keeps the jobs table consistent with the items and frees the queued slot
// immediately instead of leaving it queued only to die at fire time. The
// retract is inlined on the account transaction's OWN connection
// (cancelQueuedPlannerAgentJobs opens its own connection and cannot ride
// this transaction) with that helper's exact shape.
const body = functionWindow(INDEX_SRC, "async function deleteUserAccountAtomically", "deleteUserAccountAtomically");
const itemSelectAt = body.indexOf(`"SELECT id, server_name FROM server_planner_items WHERE ${PLANNER_OWNER}"`);
const queuedSelectAt = body.indexOf("AND source IN ('planner_send','scheduler_planner_next')\n AND status = 'queued'\n FOR UPDATE`");
const cancelUpdateAt = body.indexOf("`UPDATE ai_agent_jobs SET status = 'cancelled', completed_at = NOW(), error = ? WHERE id IN (${retractPlaceholders})`");
const notesFilterAt = body.indexOf("SELECT id FROM ai_chats WHERE id IN (${chatPlaceholders}) AND created_by <> ? FOR UPDATE`");
const chatsDeleteAt = body.indexOf("await deleteAccountServerAgentChats(conn, userId);");
const plannerDeleteAt = body.indexOf(`"DELETE FROM server_planner_items WHERE ${PLANNER_OWNER}"`);
assert.notStrictEqual(itemSelectAt, -1, "the authored-items SELECT (ids + server_names) is missing");
assert.notStrictEqual(queuedSelectAt, -1, "the queued-jobs SELECT ... FOR UPDATE scoped to the two planner sources AND status = 'queued' is missing — the queued-only predicate plus the FOR UPDATE pin is what keeps a RUNNING job from ever being marked cancelled");
assert.notStrictEqual(cancelUpdateAt, -1, "the cancel UPDATE (status = 'cancelled' with completed_at + error) is missing");
assert.notStrictEqual(notesFilterAt, -1, "the note chat-existence check excluding the deleted account ID is missing");
assert.match(body, /created_by <> \? FOR UPDATE`,\s*\[\.\.\.jobChatIds, userId\]/);
// The doomed items pair to their queued jobs through a JOIN over the items
// table — a constant placeholder count — instead of an OR clause per
// authored item: the OR-chain scaled 2 placeholders per item toward
// mysql2's 65,535-placeholder ceiling, past which the SELECT threw inside
// this transaction and rolled back the WHOLE account delete. The join keys
// the same rows (server_name + the stringified item id,
// adpanel:source-ref-string-bind).
assert.ok(
body.includes("FROM ai_agent_jobs j") &&
body.includes("JOIN server_planner_items i") &&
body.includes("j.source_ref = CAST(i.id AS CHAR)") &&
body.includes("WHERE (i.prompt_author_id = ? OR (i.prompt_author_id IS NULL AND i.created_by_email = ?))"),
"the queued-jobs SELECT must derive the doomed pairs via a JOIN over server_planner_items (constant placeholder count) — a per-item OR-chain hits mysql2's 65,535-placeholder ceiling and bricks the delete"
);
assert.ok(
!body.includes('join(" OR ")') && !body.includes("pairClauses"),
"the account transaction must no longer build per-item OR clauses — that is the ceiling the JOIN replaces"
);
// adpanel:retract-note-chat-toctou — the survivor read must be a locking
// read: a chat deleted concurrently between a plain SELECT and the note
// INSERT would FK-abort the whole account delete (schema installs) or
// orphan the note (FK-less installs). FOR UPDATE pins the surviving rows so
// the concurrent delete blocks until this transaction commits; the lock
// direction stays jobs -> chats (the job rows are locked above).
assert.ok(
notesFilterAt !== -1 && notesFilterAt > cancelUpdateAt,
"the note-target chat SELECT must run inside the transaction AFTER the job-row locks and carry FOR UPDATE — a non-locking survivor read reopens the chat-delete TOCTOU"
);
assert.ok(
itemSelectAt < queuedSelectAt && queuedSelectAt < cancelUpdateAt && cancelUpdateAt < notesFilterAt && notesFilterAt < chatsDeleteAt && chatsDeleteAt < plannerDeleteAt,
"order must be: authored-items SELECT -> queued-jobs FOR UPDATE -> cancel UPDATE -> notes -> ai_messages delete -> ai_chats delete -> items delete — the ai_agent_jobs row locks must precede the ai_messages/ai_chats writes (the same job-rows-first direction cancelQueuedPlannerAgentJobs uses, so the delete cannot deadlock against a concurrent retract), and the retract must precede the items delete so no queued job outlives its item"
);
assert.ok(
body.includes('["planner_item_deleted", ...queuedPlannerJobs.map((jobRow) => jobRow.id)]'),
"the bulk cancel must write the route-vocabulary reason 'planner_item_deleted'"
);
assert.ok(
notesFilterAt !== -1 && body.includes("INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model)"),
"the retract must leave the same terminal assistant note as cancelQueuedPlannerAgentJobs, and only on a chat that survives the transaction — the note query excludes the doomed user_email (the doomed chats still exist at that point) and requires the chat to exist, so a legacy dangling job row can neither orphan a message nor FK-abort the delete"
);
assert.ok(
body.includes("adpanel:planner-item-cascade-retract"),
"the retract must carry the adpanel:planner-item-cascade-retract constraint comment"
);
});
test("cleanupOrphanedUserRecords retracts queued planner jobs for orphaned items before its planner delete, best-effort", () => {
const body = functionWindow(INDEX_SRC, "async function cleanupOrphanedUserRecords", "cleanupOrphanedUserRecords");
const retractSelectAt = body.indexOf(`"SELECT id, server_name FROM server_planner_items WHERE ${PLANNER_ORPHAN}"`);
const sweepListAt = body.indexOf("const orphanCleanups = [");
const plannerDeleteAt = body.indexOf(`"DELETE FROM server_planner_items WHERE ${PLANNER_ORPHAN}"`);
assert.notStrictEqual(retractSelectAt, -1, "the orphaned-items SELECT is missing");
assert.notStrictEqual(plannerDeleteAt, -1, "the orphan sweep's planner delete is missing");
assert.ok(
retractSelectAt < sweepListAt && sweepListAt < plannerDeleteAt,
"the retract must run BEFORE the email-keyed sweep list — a queued job must never outlive its item, so the retract cannot follow the delete"
);
// Same JOIN-over-items shape as the account transaction's retract (same
// mysql2 placeholder ceiling the per-item OR-chain carried): the sweep's
// queued-jobs SELECT keys the same rows with a constant placeholder count.
assert.ok(
body.includes("FROM ai_agent_jobs j") &&
body.includes("JOIN server_planner_items i") &&
body.includes("j.source_ref = CAST(i.id AS CHAR)") &&
body.includes("WHERE (i.prompt_author_id NOT IN (SELECT id FROM users) OR (i.prompt_author_id IS NULL AND i.created_by_email NOT IN (SELECT email FROM users)))"),
"the orphan retract's queued-jobs SELECT must use the JOIN-over-items shape (constant placeholder count) — the per-item OR-chain had the same 65,535-placeholder ceiling risk"
);
assert.ok(
!body.includes("orphanPairClauses"),
"the orphan sweep must no longer build per-item OR clauses — that is the ceiling the JOIN replaces"
);
// No FOR UPDATE pin outside a transaction: the cancel UPDATE must carry the
// status predicate itself, or a job claimed between the read and the write
// would be marked cancelled mid-claim.
assert.ok(
body.includes("WHERE id IN (${orphanRetractPlaceholders}) AND status = 'queued' AND source IN ('planner_send','scheduler_planner_next')"),
"the sweep's cancel UPDATE must repeat the status = 'queued' AND planner-source predicate — the pool runs outside any transaction, so the claim gate is not pinned by a FOR UPDATE here"
);
assert.ok(
body.includes('SELECT id FROM ai_chats WHERE id IN (${orphanChatPlaceholders}) AND created_by IN (SELECT id FROM users)'),
"the sweep's notes must ride only on chats whose owner still exists — the doomed chats are swept by the list below and must not receive a note"
);
// adpanel:retract-note-chat-toctou — the sweep runs in AUTOCOMMIT, so the
// survivor read above is not a lock: the note INSERT must carry a targeted
// catch for the chat-missing FK error (errno 1452 / ER_NO_REFERENCED_ROW_2)
// and continue, so a concurrent chat delete can neither abort the sweep nor
// orphan the note. Any other failure must still propagate to the sweep's
// own catch.
assert.ok(
body.includes("if (Number(noteErr?.errno) !== 1452 && noteErr?.code !== \"ER_NO_REFERENCED_ROW_2\") throw noteErr;"),
"the sweep's note INSERT must catch exactly the FK error (1452 / ER_NO_REFERENCED_ROW_2) and continue — best-effort by design, while every other error still surfaces"
);
assert.ok(
body.includes("adpanel:retract-note-chat-toctou"),
"the sweep's note write must carry the adpanel:retract-note-chat-toctou constraint comment"
);
assert.ok(
body.includes('console.warn("[db] Orphaned planner job retract skipped:"'),
"the sweep's retract must be best-effort — log and skip, never fail startup"
);
});
// ─── DDL lockstep: the email-keyed delete's key must be indexed ─────────────
test("server_planner_items carries idx_server_planner_author (created_by_email) in the runtime DDL, mysql-schema.sql and the boot ALTER", () => {
// adpanel:planner-item-cascade-retract — the email-keyed DELETEs (the
// account transaction and the orphan sweep) key on created_by_email:
// without the index they full-scan and next-key-lock every row and gap
// under REPEATABLE READ, blocking concurrent planner writes on every server
// for the delete's duration and inverting against the scheduler fire's
// range lock (planner range lock -> ai_chats writes). All three DDL
// surfaces must stay in lockstep, like the 'cancelled' ENUM and the
// perm_file_envelope pins in tests/planner-job-retract.test.js.
const keyDecl = "KEY idx_server_planner_author (created_by_email)";
// Runtime CREATE TABLE — windowed on the server_planner_items CREATE TABLE
// itself so the boot ALTER string cannot satisfy a narrowed CREATE TABLE.
const createWindow = windowBetween(
INDEX_SRC,
"CREATE TABLE IF NOT EXISTS server_planner_items (",
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"server_planner_items runtime DDL"
);
assert.ok(
createWindow.includes(keyDecl),
"the runtime CREATE TABLE for server_planner_items must declare idx_server_planner_author — the email-keyed deletes key on created_by_email"
);
// mysql-schema.sql — the checked-in schema must match the runtime DDL.
const schemaSrc = fs.readFileSync(path.join(ROOT, "mysql-schema.sql"), "utf8");
const schemaWindow = windowBetween(
schemaSrc,
"CREATE TABLE IF NOT EXISTS server_planner_items (",
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
"server_planner_items schema DDL"
);
assert.ok(
schemaWindow.includes(keyDecl),
"mysql-schema.sql must declare idx_server_planner_author in lockstep with the runtime DDL — fresh installs build from this file"
);
// Boot ALTER for pre-existing tables — without it every pre-index install
// keeps the email-keyed delete's full-scan lock footprint live.
assert.ok(
INDEX_SRC.includes("ALTER TABLE server_planner_items ADD INDEX idx_server_planner_author (created_by_email)"),
"the boot ALTER must add the author index for server_planner_items tables created before it existed"
);
});
// ─── CLI parity: scripts/create-user.js --delete ─────────────────────────────
//
// The CLI delete path never runs deleteUserAccountAtomically (separate
// process, own transaction), so the same retract + email-keyed cleanup live
// in a second surface that would ship green with zero pin coverage. The
// window below spans the whole --delete branch — from its first statement
// (the setup-phase ENUM hardening, which the branch shares) to the success
// log — so both the ALTER gate and the transaction body sit inside it.
function cliDeleteWindow() {
return windowBetween(
CLI_SRC,
"if (args.delete) {",
"console.log(`User deleted: ${email}`);",
"create-user.js --delete block"
);
}
test("create-user.js --delete retracts before removing account-bound chats and planner items", () => {
const body = cliDeleteWindow();
const cancelAt = body.indexOf("`UPDATE ai_agent_jobs SET status = 'cancelled', completed_at = NOW(), error = ? WHERE id IN (${retractPlaceholders})`");
const chatsAt = body.indexOf("await deleteAccountServerAgentChats(conn, existing.id);");
const plannerAt = body.indexOf(`"DELETE FROM server_planner_items WHERE ${PLANNER_OWNER}"`);
assert.notStrictEqual(cancelAt, -1, "the retract's cancel UPDATE is missing from the CLI delete path");
assert.notStrictEqual(chatsAt, -1, "the CLI must delete chats and messages by the locked account ID");
assert.notStrictEqual(plannerAt, -1, "the CLI must delete planner items by author ID for bound rows");
assert.ok(
cancelAt < chatsAt && chatsAt < plannerAt,
"order must be: retract (cancel UPDATE) -> ai_messages -> ai_chats -> server_planner_items — moving the retract after the chat/message deletes reopens the AB-BA pair against cancelQueuedPlannerAgentJobs (an ai_messages write before the ai_agent_jobs row locks), and the items delete must never outrun the retract or a queued job outlives its item"
);
// Only legacy planner items still use the normalized email as their key.
assert.ok(
CLI_SRC.includes('const email = String(args.email || "").trim().toLowerCase();'),
"the script must normalize the email (trim + lowercase) before any keyed delete"
);
assert.ok(
body.includes(`"DELETE FROM server_planner_items WHERE ${PLANNER_OWNER}", [existing.id, email]`),
"the planner delete must use the locked account ID and the normalized legacy email"
);
assert.ok(
body.includes("adpanel:user-delete-email-keyed-cleanup"),
"the CLI's email-keyed pass must carry the adpanel:user-delete-email-keyed-cleanup constraint comment"
);
});
test("create-user.js --delete retracts queued planner jobs with the panel's exact claim-gate shape", () => {
const body = cliDeleteWindow();
const itemSelectAt = body.indexOf(`"SELECT id, server_name FROM server_planner_items WHERE ${PLANNER_OWNER}"`);
const queuedSelectAt = body.indexOf("AND source IN ('planner_send','scheduler_planner_next')\n AND status = 'queued'\n FOR UPDATE`");
const cancelUpdateAt = body.indexOf("`UPDATE ai_agent_jobs SET status = 'cancelled', completed_at = NOW(), error = ? WHERE id IN (${retractPlaceholders})`");
const notesGateAt = body.indexOf("if (!survivingChatIds.has(Number(jobRow.chat_id))) continue;");
const messagesDeleteAt = body.indexOf("await deleteAccountServerAgentChats(conn, existing.id);");
assert.notStrictEqual(itemSelectAt, -1, "the authored-items SELECT (ids + server_names) is missing");
assert.notStrictEqual(queuedSelectAt, -1, "the queued-jobs SELECT ... FOR UPDATE scoped to the two planner sources AND status = 'queued' is missing — dropping FOR UPDATE unpins the rows from the claim gate, and dropping the queued-only predicate lets a RUNNING job be marked cancelled mid-claim (it would lose its enqueue-time authorization without ever having run)");
assert.notStrictEqual(cancelUpdateAt, -1, "the cancel UPDATE (status = 'cancelled' with completed_at + error) is missing");
assert.notStrictEqual(notesGateAt, -1, "the note-survivor gate is missing — without it the note lands on a chat this transaction deletes (orphaned message) or FK-aborts the delete");
assert.notStrictEqual(messagesDeleteAt, -1, "the ai_messages delete is missing");
assert.ok(
itemSelectAt < queuedSelectAt && queuedSelectAt < cancelUpdateAt && cancelUpdateAt < notesGateAt && notesGateAt < messagesDeleteAt,
"order must be: authored-items SELECT -> queued-jobs FOR UPDATE -> cancel UPDATE -> note gate -> ai_messages delete — the ai_agent_jobs row locks must precede the ai_messages/ai_chats writes (the same direction cancelQueuedPlannerAgentJobs locks in, so the delete cannot deadlock against a concurrent retract)"
);
// The doomed items pair to their queued jobs through a JOIN over the items
// table — a constant placeholder count — instead of an OR clause per
// authored item: the OR-chain scaled 2 placeholders per item toward
// mysql2's 65,535-placeholder ceiling, past which the SELECT threw inside
// this transaction and rolled back the WHOLE account delete. The join keys
// the same rows (server_name + the stringified item id,
// adpanel:source-ref-string-bind) — the same shape the panel copy's pins
// assert above — and the authored item ids never touch the SQL text (the
// only bound value is the author email).
assert.ok(
body.includes("FROM ai_agent_jobs j") &&
body.includes("JOIN server_planner_items i") &&
body.includes("j.source_ref = CAST(i.id AS CHAR)") &&
body.includes("WHERE (i.prompt_author_id = ? OR (i.prompt_author_id IS NULL AND i.created_by_email = ?))"),
"the queued-jobs SELECT must derive the doomed pairs via a JOIN over server_planner_items (constant placeholder count) — a per-item OR-chain hits mysql2's 65,535-placeholder ceiling and bricks the CLI delete"
);
assert.ok(
!body.includes('join(" OR ")') && !body.includes("pairClauses"),
"the CLI delete must no longer build per-item OR clauses — that is the ceiling the JOIN replaces"
);
assert.ok(
body.includes('["planner_item_deleted", ...queuedPlannerJobs.map((jobRow) => jobRow.id)]'),
"the bulk cancel must write the route-vocabulary reason 'planner_item_deleted'"
);
assert.ok(
body.includes("const survivingChatIds = new Set();") &&
body.includes("INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model)"),
"the retract must leave the terminal assistant note only via the survivorship filter — a note may only land on a chat this transaction does NOT delete (the doomed chats still exist at that point)"
);
// adpanel:retract-note-chat-toctou — the CLI survivor read mirrors the
// panel's shape exactly (same pin style as the panel copy's notesFilterAt):
// a locking SELECT ... FOR UPDATE excluding the doomed user_email, placed
// AFTER the queued-jobs FOR UPDATE so the lock direction stays jobs ->
// chats. Removing FOR UPDATE, re-keying the exclusion, or moving the read
// ahead of the job-row locks must fail these pins — a non-locking survivor
// read reopens the chat-delete TOCTOU: a chat deleted concurrently between
// the read and the note INSERT FK-aborts the whole CLI delete (schema
// installs) or orphans the note (FK-less installs).
const survivorSelectAt = body.indexOf("SELECT id FROM ai_chats WHERE id IN (${chatPlaceholders}) AND created_by <> ? FOR UPDATE`");
assert.notStrictEqual(
survivorSelectAt,
-1,
"the survivor-chat read must be a locking SELECT ... FOR UPDATE excluding the doomed user_email — a plain read reopens the chat-delete TOCTOU (FK-abort on schema installs, orphaned note on FK-less installs)"
);
assert.ok(
survivorSelectAt > queuedSelectAt && survivorSelectAt > cancelUpdateAt,
"the survivor-chat FOR UPDATE must sit AFTER the queued-jobs FOR UPDATE (and the cancel UPDATE) — the lock direction must stay jobs -> chats, the same order the panel copy and cancelQueuedPlannerAgentJobs lock in, or the delete can deadlock against a concurrent retract"
);
assert.ok(
/`SELECT id FROM ai_chats WHERE id IN \(\$\{chatPlaceholders\}\) AND created_by <> \? FOR UPDATE`,\s*\[\.\.\.jobChatIds, existing\.id\]/.test(body),
"the survivor read must exclude the same locked account ID used by chat cleanup"
);
assert.ok(
body.includes("adpanel:planner-item-cascade-retract"),
"the CLI's retract must carry the adpanel:planner-item-cascade-retract constraint comment"
);
});
test("create-user.js replays the panel's ai_agent_jobs.status ENUM-widening ALTER before the delete transaction opens", () => {
// The retract UPDATE writes status = 'cancelled', whose ENUM member exists
// only after the panel boot's widening ALTER (or a fresh mysql-schema.sql
// install): ensureSchema's CREATE TABLE IF NOT EXISTS never widens an
// existing table, so on a pre-retract install the UPDATE raises 1265 under
// STRICT_TRANS_TABLES and the transaction's catch rolls back the ENTIRE
// delete. The CLI must therefore replay the panel's ALTER — byte-identical
// member list — in the setup phase, OUTSIDE the transaction (MySQL DDL
// causes an implicit commit).
const ALTER_RE = /ALTER TABLE ai_agent_jobs MODIFY COLUMN status ENUM\(([^)]*)\) NOT NULL DEFAULT 'queued'/;
const panelAlter = INDEX_SRC.match(ALTER_RE);
assert.ok(panelAlter, "precondition: the panel's boot ALTER for ai_agent_jobs.status is present in index.js");
const cliAlter = CLI_SRC.match(ALTER_RE);
assert.ok(
cliAlter,
"the CLI must replay the panel's ENUM-widening ALTER before its retract writes status = 'cancelled' — without it a pre-retract install makes the account undeletable via the CLI"
);
assert.strictEqual(
cliAlter[0],
panelAlter[0],
"the CLI's ALTER must be byte-identical to the panel's boot ALTER — the ENUM member lists must never drift between the two surfaces"
);
const beginTxAt = CLI_SRC.indexOf("await conn.beginTransaction();");
const commitAt = CLI_SRC.indexOf("await conn.commit();");
assert.ok(beginTxAt !== -1 && commitAt !== -1, "precondition: the delete transaction anchors are present");
assert.ok(
CLI_SRC.indexOf(cliAlter[0]) < beginTxAt,
"the ALTER must run BEFORE the delete transaction opens — MySQL DDL causes an implicit commit, which would silently split the atomic delete"
);
assert.ok(
!CLI_SRC.slice(beginTxAt, commitAt).includes("ALTER TABLE"),
"the ALTER must never run between beginTransaction and commit (a DDL implicit commit would split the atomic delete)"
);
assert.ok(
CLI_SRC.includes("adpanel:planner-job-retract"),
"the CLI's ENUM widening must carry the adpanel:planner-job-retract constraint comment, in lockstep with the panel's identical migration"
);
});