Files
Kelx/tests/server-op-guard.test.js
T
2026-11-30 16:32:37 +00:00

986 lines
55 KiB
JavaScript

"use strict";
// Tests for the F5 remediation: transfer, delete and reinstall (admin
// template change + user reinstall) did not check each other's in-flight
// state. The transfer flagged servers.status = 'transferring' and nothing
// re-validated it: a delete killed the container and removed the index row
// mid-transfer, and a template change / reinstall wiped the server directory
// on the node while the transfer was still exporting it — every overlap
// producing a partial state.
//
// The remediation claims the servers.status column with a conditional UPDATE
// (utils/server-op-guard.js) so exactly one guarded operation can own a
// server row at a time:
// transferring / deleting / reinstalling
// with:
// - fail-closed refusals (unverifiable state never proceeds),
// - mysql2 changed-rows semantics handled (idempotent re-delete, but a
// second transfer/reinstall is refused even when its own marker holds),
// - anti-clobber: suspension and EULA accept never overwrite the markers,
// - crash recovery: 'reinstalling' flags orphaned by a dead panel process
// are restored by the sweeper (mirrors transfer-recovery F6).
//
// utils/server-op-guard.js and utils/server-delete.js are policy-only (deps
// injected), so behaviour is tested directly with fakes; the index.js wiring
// is locked with source-order assertions because index.js boots servers on
// require and cannot be loaded in-process (same technique as
// transfer-recovery / server-delete-verified-alias / reinstall-route-protection).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { randomUUID } = require("node:crypto");
const guard = require("../utils/server-op-guard");
const { deleteServerByName } = require("../utils/server-delete");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const NODES_JS = path.join(ROOT, "nodes.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const nodesSource = fs.readFileSync(NODES_JS, "utf8");
// ---------------------------------------------------------------------------
// Fakes
// ---------------------------------------------------------------------------
// Exercise both matched-row (mysql2 default) and changed-row reporting;
// ownership must depend on the SQL condition, never a driver flag.
function makeGuardDeps({
rows = {}, // name -> { status, suspended }
dbError = null,
failSecondHeartbeatGet = false,
matchedRows = true,
} = {}) {
const calls = { updates: [], selects: [] };
const redisStore = new Map();
const db = {
async query(sql, params = []) {
if (dbError) throw dbError;
const normalized = sql.replace(/\s+/g, " ").trim();
if (/^SELECT name FROM servers WHERE LOWER\(status\) =/.test(normalized)) {
calls.selects.push({ sql: normalized, params });
const found = Object.entries(rows)
.filter(([, row]) => String(row.status || "").toLowerCase() === String(params[0]).toLowerCase())
.map(([name]) => ({ name }));
return found;
}
if (/^SELECT status FROM servers WHERE name =/.test(normalized)) {
calls.selects.push({ sql: normalized, params });
const row = rows[params[0]];
if (!row) return [];
return [{ status: row.status }];
}
if (/^UPDATE servers SET status = \? WHERE name = \? AND \(status IS NULL OR LOWER\(status\) NOT IN/.test(normalized)) {
// [marker, name, ...forbidden]
calls.updates.push({ kind: "claim", params });
const [marker, name, ...forbidden] = params;
const row = rows[name];
if (!row) return { affectedRows: 0 };
const current = String(row.status || "").trim().toLowerCase();
if (current && forbidden.map((f) => String(f).toLowerCase()).includes(current)) {
return { affectedRows: 0 };
}
row.status = marker;
return { affectedRows: matchedRows || current !== String(marker).toLowerCase() ? 1 : 0 };
}
if (/^UPDATE servers SET status = \? WHERE name = \? AND LOWER\(status\) = \?(?: AND updated_at < DATE_SUB\(NOW\(\), INTERVAL \? SECOND\))?$/.test(normalized)) {
calls.updates.push({ kind: "release", params });
const [next, name, marker] = params;
const row = rows[name];
if (!row) return { affectedRows: 0 };
const current = String(row.status || "").trim().toLowerCase();
if (current !== String(marker).toLowerCase()) return { affectedRows: 0 };
row.status = next;
return { affectedRows: 1 };
}
if (/^UPDATE servers SET status = \? WHERE name = \?$/.test(normalized)) {
calls.updates.push({ kind: "restore", params });
const [next, name] = params;
const row = rows[name];
if (!row) return { affectedRows: 0 };
row.status = next;
return { affectedRows: 1 };
}
throw new Error(`unexpected query: ${normalized}`);
},
};
return {
calls,
rows,
db,
log: console,
findServer: async (name) => rows[name] ? { name, suspended: rows[name].suspended } : null,
redis: () => ({
set: async (key, value, opts) => { redisStore.set(key, value); return "OK"; },
get: async (key) => {
if (failSecondHeartbeatGet && /alive/.test(key)) {
// second get in a claim attempt reports no live owner
return redisStore.get(key) ?? null;
}
return redisStore.get(key) ?? null;
},
del: async (key) => { redisStore.delete(key); },
}),
bootId: "test-boot",
ownerTimers: new Map(),
};
}
// ---------------------------------------------------------------------------
// claim / release semantics
// ---------------------------------------------------------------------------
test("claim succeeds on a clean row and records the previous status", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "running" } } });
const claim = await guard.claimServerOperationStatus(deps, { name: "alpha", marker: "transferring" });
assert.equal(claim.ok, true);
assert.equal(claim.prevStatus, "running");
assert.equal(deps.rows.alpha.status, "transferring");
});
test("claim refuses while a DIFFERENT guarded marker owns the row (transfer vs delete)", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "transferring" } } });
const claim = await guard.claimServerOperationStatus(deps, { name: "alpha", marker: "deleting" });
assert.equal(claim.ok, false);
assert.equal(claim.blockedBy, "transferring");
assert.equal(deps.rows.alpha.status, "transferring");
});
test("claim refuses reinstalling vs transferring in both directions", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
const toTransfer = await guard.claimServerOperationStatus(deps, { name: "alpha", marker: "transferring" });
assert.equal(toTransfer.ok, false);
assert.equal(toTransfer.blockedBy, "reinstalling");
const deps2 = makeGuardDeps({ rows: { beta: { status: "transferring" } } });
const toReinstall = await guard.claimServerOperationStatus(deps2, { name: "beta", marker: "reinstalling" });
assert.equal(toReinstall.ok, false);
assert.equal(toReinstall.blockedBy, "transferring");
});
test("claim on a missing row reports missing (fail closed)", async () => {
const deps = makeGuardDeps({ rows: {} });
const claim = await guard.claimServerOperationStatus(deps, { name: "ghost", marker: "deleting" });
assert.equal(claim.ok, false);
assert.equal(claim.missing, true);
});
test("claim with an invalid marker is refused", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "running" } } });
const claim = await guard.claimServerOperationStatus(deps, { name: "alpha", marker: "running" });
assert.equal(claim.ok, false);
assert.equal(deps.rows.alpha.status, "running");
});
test("claim treats a NULL status row as unclaimed", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: null } } });
const claim = await guard.claimServerOperationStatus(deps, { name: "alpha", marker: "deleting" });
assert.equal(claim.ok, true);
assert.equal(claim.prevStatus, null);
});
test("re-claiming 'deleting' is idempotent (retried delete keeps going)", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "deleting" } } });
const claim = await guard.claimServerOperationStatus(deps, { name: "alpha", marker: "deleting" });
assert.equal(claim.ok, true);
assert.equal(claim.alreadyOwned, true);
});
test("re-claiming 'transferring'/'reinstalling' by the same marker is REFUSED (second op must not pile on)", async () => {
for (const marker of ["transferring", "reinstalling"]) {
for (const matchedRows of [false, true]) {
const deps = makeGuardDeps({ rows: { alpha: { status: marker } }, matchedRows });
const claim = await guard.claimServerOperationStatus(deps, { name: "alpha", marker });
assert.equal(claim.ok, false, marker);
assert.equal(claim.blockedBy, marker, marker);
assert.equal(claim.alreadyOwned, true, marker);
}
}
});
test("simultaneous reinstall claims have exactly one winner with mysql2 matched rows", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "stopped" } } });
const claims = await Promise.all([
guard.claimServerOperationStatus(deps, { name: "alpha", marker: "reinstalling" }),
guard.claimServerOperationStatus(deps, { name: "alpha", marker: "reinstalling" }),
]);
assert.equal(claims.filter((claim) => claim.ok).length, 1);
assert.equal(claims.find((claim) => !claim.ok).blockedBy, "reinstalling");
});
test("release restores the whitelisted previous status only while the marker is ours", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
const out = await guard.releaseServerOperationStatus(deps, { name: "alpha", marker: "reinstalling", restoreStatus: "running" });
assert.equal(out.restored, true);
assert.equal(out.status, "running");
assert.equal(deps.rows.alpha.status, "running");
// Second release no-ops: the marker is gone.
const again = await guard.releaseServerOperationStatus(deps, { name: "alpha", marker: "reinstalling", restoreStatus: "running" });
assert.equal(again.restored, false);
assert.equal(deps.rows.alpha.status, "running");
});
test("release never restores a non-restorable previous status", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
const out = await guard.releaseServerOperationStatus(deps, { name: "alpha", marker: "reinstalling", restoreStatus: "deleting" });
assert.equal(out.restored, true);
assert.equal(out.status, "stopped");
});
test("release forces 'stopped' when the server was suspended while the marker was held", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling", suspended: 1 } } });
const out = await guard.releaseServerOperationStatus(deps, { name: "alpha", marker: "reinstalling", restoreStatus: "running" });
assert.equal(out.restored, true);
assert.equal(out.status, "stopped");
});
test("release does not overwrite a status that moved on legitimately", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "stopped" } } });
const out = await guard.releaseServerOperationStatus(deps, { name: "alpha", marker: "reinstalling", restoreStatus: "running" });
assert.equal(out.restored, false);
assert.equal(deps.rows.alpha.status, "stopped");
});
// ---------------------------------------------------------------------------
// delete flow honours the guard (utils/server-delete.js)
// ---------------------------------------------------------------------------
function makeDeleteDeps({ markOutcome, markError = null }) {
const calls = { marks: [], kills: [], deletes: [], indexRemovals: [], schedules: [] };
return {
calls,
deps: {
findServer: async () => ({
name: "alpha",
bot: "alpha-node-1",
legacyId: "legacy-9",
nodeId: "node-1",
status: "running",
}),
isRemoteEntry: (entry) => !!(entry && entry.nodeId && entry.nodeId !== "local"),
findNodeByIdOrName: async () => ({ id: "node-1", address: "127.0.0.1", api_port: 8080 }),
dbQuery: async () => [],
buildNodeBaseUrl: () => "http://127.0.0.1:8080",
nodeUnderCloudflare: () => false,
nodeAuthHeadersFor: () => ({}),
httpRequestJson: async (url, method) => {
if (/\/kill$/.test(url)) { calls.kills.push(url); return { status: 200, json: { ok: true } }; }
if (method === "DELETE") { calls.deletes.push(url); return { status: 200, json: { ok: true } }; }
if (/\/delete-status$/.test(url)) return { status: 200, json: { deleteStatus: true, deleted: true } };
if (method === "GET") return { status: 404, json: { error: "not found" } };
return { status: 404, json: { error: "not found" } };
},
deleteServerSchedules: async (n) => calls.schedules.push(n),
removeServerIndexEntry: async (n) => calls.indexRemovals.push(n),
removeAccessForServerName: async () => { },
withReinstallSuspensionLock: async (_name, _busy, operation) => operation(),
markServerDeletingStatus: async (n, canonical) => {
calls.marks.push({ n, canonical });
if (markError) throw markError;
return markOutcome;
},
enqueueServerDeleteJob: async () => { },
kickServerDeleteWorker: () => { },
},
};
}
test("delete aborts while a transfer owns the row (409, nothing destructive runs)", async () => {
const { calls, deps } = makeDeleteDeps({
markOutcome: { ok: false, statusCode: 409, error: "cannot delete server: server is being transferred to another node (or a crashed transfer is awaiting recovery); try again once it settles", operation: "transferring" },
});
const result = await deleteServerByName(deps, "alpha");
assert.equal(result.ok, false);
assert.equal(result.statusCode, 409);
assert.equal(result.operation, "transferring");
assert.deepEqual(calls.kills, []);
assert.deepEqual(calls.deletes, []);
assert.deepEqual(calls.indexRemovals, []);
});
test("delete aborts fail-closed when the mark times out (unverifiable state)", async () => {
const { calls, deps } = makeDeleteDeps({ markError: new Error("mark-delete-status-timeout") });
const result = await deleteServerByName(deps, "alpha");
assert.equal(result.ok, false);
assert.equal(result.statusCode, 503);
assert.deepEqual(calls.kills, []);
assert.deepEqual(calls.deletes, []);
});
test("delete proceeds when the mark claims the row, and passes the canonical name", async () => {
const { calls, deps } = makeDeleteDeps({ markOutcome: { ok: true } });
const result = await deleteServerByName(deps, "alpha");
assert.equal(result.ok, true);
assert.equal(calls.marks.length, 1);
assert.equal(calls.marks[0].canonical, "alpha");
assert.equal(calls.deletes.length, 1);
assert.equal(calls.indexRemovals.length, 1);
});
test("delete refuses a stale target that disappeared before the claim", async () => {
const { calls, deps } = makeDeleteDeps({ markOutcome: { ok: true, missing: true } });
const result = await deleteServerByName(deps, "alpha");
assert.equal(result.statusCode, 409);
assert.equal(calls.marks.length, 1);
assert.deepEqual(calls.deletes, []);
assert.deepEqual(calls.indexRemovals, []);
});
test("legacy delete deps without markServerDeletingStatus still work (dep is optional)", async () => {
const { calls, deps } = makeDeleteDeps({ markOutcome: { ok: true } });
delete deps.markServerDeletingStatus;
const result = await deleteServerByName(deps, "alpha");
assert.equal(result.ok, true);
assert.deepEqual(calls.marks, []);
});
// ---------------------------------------------------------------------------
// reinstall flag crash recovery
// ---------------------------------------------------------------------------
test("sweeper restores an orphaned 'reinstalling' flag to 'stopped'", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.deepEqual(outcome, { scanned: 1, restored: 1 });
assert.equal(deps.rows.alpha.status, "stopped");
});
test("sweeper skips a flag whose owner heartbeat is live", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
await deps.redis().set(guard.reinstallOwnerAliveKey("alpha"), "boot-x", { EX: 45 });
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.deepEqual(outcome, { scanned: 1, restored: 0 });
assert.equal(deps.rows.alpha.status, "reinstalling");
});
test("sweeper skips when the in-process active set claims the name", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
deps.isReinstallActive = (name) => name === "alpha";
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.deepEqual(outcome, { scanned: 1, restored: 0 });
assert.equal(deps.rows.alpha.status, "reinstalling");
});
test("sweeper treats a redis outage as unknown and hands off (fail-safe)", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
deps.redis = () => { throw new Error("redis down"); };
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.deepEqual(outcome, { scanned: 1, restored: 0 });
assert.equal(deps.rows.alpha.status, "reinstalling");
});
test("sweeper survives a db listing failure", async () => {
const deps = makeGuardDeps({ dbError: new Error("db down") });
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.deepEqual(outcome, { scanned: 0, restored: 0 });
});
// ---------------------------------------------------------------------------
// index.js wiring (source-order assertions)
// ---------------------------------------------------------------------------
test("transfer route claims the transferring flag via the guard claim (no unconditional write)", () => {
assert.ok(
!indexSource.includes('await db.query("UPDATE servers SET status = ? WHERE name = ?", ["transferring", lockedEntry.name])'),
"transfer must not write the transferring flag unconditionally"
);
assert.match(indexSource, /claimServerOperationStatus\(serverOpGuardDeps, \{\s*\n\s*name: lockedEntry\.name,\s*\n\s*marker: "transferring",/);
// Claim-failure path: the prepared job record is dropped, but the heartbeat
// is NEVER stopped here — it was never started for this attempt, and a
// losing claimant must not tear down the winner's liveness (BUG #1 class).
const failureIdx = indexSource.indexOf("if (!transferClaim.ok) {");
const failureWindow = indexSource.slice(failureIdx, failureIdx + 600);
const artifactsIdx = indexSource.indexOf("clearTransferJobArtifacts(name);", failureIdx);
assert.ok(failureIdx > 0 && artifactsIdx > failureIdx, "failure path drops the job record");
assert.ok(!failureWindow.includes("stopTransferOwnerHeartbeat"), "failure path must not stop the owner heartbeat");
});
test("transfer route refuses a reinstalling row on both the fast path and the locked re-check", () => {
const fast = indexSource.indexOf("if (String(serverEntry.status || \"\").trim().toLowerCase() === \"reinstalling\")");
const locked = indexSource.indexOf("if (String(lockedEntry.status || \"\").trim().toLowerCase() === \"reinstalling\")");
assert.ok(fast > 0, "fast-path reinstall refusal missing");
assert.ok(locked > fast, "locked re-check reinstall refusal missing");
});
test("delete mark is a guarded claim and deleteServerByName aborts on refusal", () => {
assert.match(indexSource, /async function markServerDeletingStatus\(name, canonicalName, entry\)/);
assert.match(indexSource, /serverOpGuard\.claimServerOperationStatus\(serverOpGuardDeps, \{ name: canonical, marker: "deleting", expectedRow: entry \}\)/);
// server-delete.js: refusal and timeout must abort before any destructive call
const deleteSource = fs.readFileSync(path.join(ROOT, "utils", "server-delete.js"), "utf8");
assert.match(deleteSource, /withLifecycleLock\(target\.name \|\| name, busy, async \(\) => \{[\s\S]*?return deleteResolvedServer\(deps, name, entry, reportClaimFailure\)/);
assert.match(deleteSource, /deps\.markServerDeletingStatus\(name, entry\.name \|\| name, entry\)/);
const markIdx = deleteSource.indexOf("deps.markServerDeletingStatus");
const killIdx = deleteSource.indexOf("await requestRemoteDeleteAndConfirm(deps, {");
const loopIdx = deleteSource.indexOf("for (const candidate of deleteNameCandidates");
assert.ok(markIdx > 0 && loopIdx > markIdx, "mark must run before the candidate loop");
assert.ok(killIdx > loopIdx, "destructive calls come after the candidate loop");
assert.match(deleteSource, /withTimeout\(pendingClaim, 5000, "mark-delete-status-timeout"\)/);
assert.match(deleteSource, /reportClaimFailure\(failure\);\s*await pendingClaim\.catch/);
assert.match(deleteSource, /ok: false,\s*\n\s*statusCode: 503,\s*\n\s*error: "could not verify server state before delete; try again"/);
});
test("admin template change route is wrapped in a reinstall claim with a finally release", () => {
const routeIdx = indexSource.indexOf('app.post("/api/settings/servers/:name/template"');
const claimIdx = indexSource.indexOf("claimReinstallOperation(claimName, entry)", routeIdx);
const finallyIdx = indexSource.indexOf("await releaseReinstallClaim({ releaseReinstallOperation, setCachedServerStatus }, claimName, templateClaim.prevStatus,", claimIdx);
const endIdx = indexSource.indexOf('app.post("/api/servers/:name/reinstall"', routeIdx);
assert.ok(routeIdx > 0 && claimIdx > routeIdx && finallyIdx > claimIdx && endIdx > finallyIdx,
"template change route must claim 'reinstalling' and release it in a finally");
assert.match(indexSource, /const conflict = serverOperationConflict\(templateClaim\.blockedBy, "Template change"\);/);
});
test("user reinstall route is wrapped in a reinstall claim with a finally release", () => {
const routeIdx = indexSource.indexOf('app.post("/api/servers/:name/reinstall"');
const claimIdx = indexSource.indexOf("claimReinstallOperation(claimName)", routeIdx);
const finallyIdx = indexSource.indexOf("await releaseReinstallClaim({ releaseReinstallOperation, setCachedServerStatus }, claimName, reinstallClaim.prevStatus,", claimIdx);
assert.ok(routeIdx > 0 && claimIdx > routeIdx && finallyIdx > claimIdx,
"user reinstall route must claim 'reinstalling' and release it in a finally");
const cleanupSource = fs.readFileSync(path.join(ROOT, "utils", "server-reinstall.js"), "utf8");
assert.match(cleanupSource, /async function releaseReinstallClaim\([\s\S]*?try \{\s*const release = await releaseReinstallOperation\(serverName, powerState \|\| prevStatus\);[\s\S]*?\} catch/,
"the shared release helper must await the injected operation release and contain cleanup rejections");
});
test("suspension cannot overwrite a guarded marker or a moved server", () => {
assert.match(indexSource, /serverOpGuard\.withReinstallSuspensionLock\(name,[\s\S]*?serverOpGuard\.claimServerOperationStatus\(serverOpGuardDeps, \{ name, marker: "reinstalling", expectedRow \}\)/);
assert.match(indexSource, /serverOpGuard\.withSuspensionAgainstReinstall\(\{ findServer \}, requested,/);
assert.match(indexSource, /UPDATE servers SET suspended = \?, suspended_at = \?, suspended_by = \?, status = \? WHERE id = \? AND node_id <=> \? AND \(status IS NULL OR LOWER\(status\) NOT IN \('transferring', 'deleting', 'reinstalling'\)\)/);
});
test("suspension rejects a replacement row under the lifecycle lock", async () => {
const expected = { name: `suspension-target-${randomUUID()}`, rowId: 42, nodeId: "node-1", status: "running" };
const deps = { findServer: async () => ({ ...expected, rowId: 43 }) };
const result = await guard.withSuspensionAgainstReinstall(deps, expected.name, () => {
assert.fail("suspension must not mutate the replacement row");
}, expected);
assert.equal(result.statusCode, 409);
assert.equal(result.error, "server state changed; reload servers and try again");
});
test("reinstall admission and suspension exclude each other on the canonical server", async () => {
const name = `suspension-${randomUUID()}`;
const entry = { name, rowId: 42, status: "running" };
const deps = { findServer: async () => ({ ...entry }) };
const refused = { ok: false, blockedBy: null };
let beginSuspend;
let finishSuspend;
const suspended = new Promise((resolve) => { beginSuspend = resolve; });
const finish = new Promise((resolve) => { finishSuspend = resolve; });
const pending = guard.withSuspensionAgainstReinstall(deps, "legacy-alias", async () => {
beginSuspend();
await finish;
return { ok: true };
});
try {
await suspended;
const claim = await guard.withReinstallSuspensionLock(name.toUpperCase(), refused, () => assert.fail("reinstall must not claim during suspension"));
assert.equal(claim, refused);
} finally {
finishSuspend();
assert.deepEqual(await pending, { ok: true });
}
for (const status of ["reinstalling", "transferring", "deleting"]) {
entry.status = status;
const result = await guard.withSuspensionAgainstReinstall(deps, name, () => assert.fail(`suspension must not force-stop during ${status}`));
assert.equal(result.statusCode, 409);
assert.equal(result.error, guard.BLOCKED_REASON[status]);
}
});
test("start dispatch refuses suspended, transferred, or replaced servers under the lifecycle lock", async () => {
const expected = { name: `power-suspension-${randomUUID()}`, rowId: 42, nodeId: "node-1", status: "stopped" };
for (const [current, status] of [
[{ ...expected, suspended: true }, 423], [{ ...expected, status: "transferring" }, 409],
[{ ...expected, nodeId: "node-2" }, 409], [{ ...expected, rowId: 43 }, 409],
]) {
const denied = await guard.withServerPowerStart({ findServer: async () => current }, expected,
() => assert.fail("the changed server must not receive a start"));
assert.equal(denied.conflict.status, status);
}
const deps = { findServer: async () => expected };
const allowed = await guard.withServerPowerStart(deps, expected, async () => {
const suspended = await guard.withSuspensionAgainstReinstall(deps, expected.name, () => assert.fail("suspension must wait for dispatch"));
assert.equal(suspended.statusCode, 409);
return "started";
});
assert.deepEqual(allowed, { result: "started" });
});
test("power observations cannot rewrite suspension or other settings", async () => {
const start = indexSource.indexOf("async function upsertServerStatusLabelUnlessGuarded(");
const source = indexSource.slice(start, indexSource.indexOf("\n}\n", start) + 2);
const entry = { rowId: 9, nodeId: "node", name: "alpha", status: "stopped" };
const writes = [];
const writer = new Function("findServer", "isServerSuspended", "serverOpGuard", "db", "invalidateServerIndexCache",
`return (${source});`)(async () => entry, (server) => !!server.suspended, guard, { async query(sql, params) {
assert.match(sql, /^UPDATE servers SET status = \? WHERE id = \? AND node_id <=> \? AND suspended = 0/);
assert.match(sql, /NOT IN \('transferring', 'deleting', 'reinstalling'\)/);
writes.push(params);
return { affectedRows: 1 };
} }, () => {});
assert.equal(await writer("alpha", "starting"), true);
entry.suspended = true;
assert.equal(await writer("alpha", "online"), false);
assert.deepEqual(writes, [["starting", 9, "node"]]);
});
test("user template flip cannot write guarded rows or reconcile other servers", () => {
const routeIdx = indexSource.indexOf('app.post("/api/servers/:bot/template"');
const route = indexSource.slice(routeIdx, indexSource.indexOf("\n});", routeIdx));
const checkIdx = route.indexOf("serverOpGuard.isGuardedServerStatus(status)");
const saveIdx = route.indexOf("UPDATE servers SET template = ? WHERE ${target}");
assert.ok(routeIdx > 0 && checkIdx > 0 && saveIdx > checkIdx);
assert.match(route, /id = \? AND node_id <=> \? AND .*NOT IN \('transferring', 'deleting', 'reinstalling'\)/);
assert.doesNotMatch(route, /saveServersIndex/);
});
test("resources PATCH route refuses guarded rows before touching the node", () => {
const routeIdx = indexSource.indexOf('app.patch("/api/settings/servers/:name/resources"');
const checkIdx = indexSource.indexOf("resourcesRouteStatus === \"transferring\"", routeIdx);
const nodeIdx = indexSource.indexOf("findNodeByIdOrName(serverEntry.nodeId)", routeIdx);
assert.ok(routeIdx > 0 && checkIdx > 0 && nodeIdx > checkIdx, "refusal must precede node lookups/calls");
});
test("suspension verifies the canonical daemon name and refuses shared storage", async () => {
const { sanitizeNodeStorageName } = require("../utils/server-name");
const { scanNodeStorageCollisions } = require("../services/server-create");
const start = indexSource.indexOf("async function forceStopServerForSuspension(");
const end = indexSource.indexOf("async function setServerSuspensionState(", start);
assert.ok(start >= 0 && end > start);
const entry = { name: "_fixture", nodeId: "fixture-node" };
const calls = [];
let rows = [entry, { name: "fixture" }];
const context = vm.createContext({
isRemoteEntry: () => true, findNodeByIdOrName: async () => ({ id: entry.nodeId }),
buildNodeRequestContext: () => ({ baseUrl: "https://fixture.invalid", headers: {} }),
sanitizeNodeStorageName, serverCreateService: { scanNodeStorageCollisions },
db: { query: async () => rows }, SERVER_SUSPENSION_KILL_TIMEOUT_MS: 100,
SERVER_SUSPENSION_VERIFY_TIMEOUT_MS: 100,
httpRequestJson: async (url) => { calls.push(new URL(url).pathname); return { status: 200, json: { ok: true } }; },
getNodeServerPowerState: async (_node, name) => { calls.push(name); return { ok: true, state: "stopped" }; },
});
vm.runInContext(indexSource.slice(start, end), context, { timeout: 1000 });
assert.equal((await context.forceStopServerForSuspension(entry)).statusCode, 409);
assert.deepStrictEqual(calls, []);
rows = [entry];
assert.equal((await context.forceStopServerForSuspension(entry)).ok, true);
assert.deepStrictEqual(calls, ["/v1/servers/fixture/kill", "fixture"]);
});
test("a busy resources or suspension lock prevents a delete claim", async () => {
const outcome = await deleteServerByName({
findServer: async () => ({ name: "fixture", rowId: 7 }),
withReinstallSuspensionLock: async (name, busy) => { assert.equal(name, "fixture"); return busy; },
markServerDeletingStatus: () => assert.fail("a held lifecycle lock must prevent a deletion claim"),
}, "alias");
assert.equal(outcome.statusCode, 409);
});
test("eula consent never starts the server or overwrites a guarded marker", () => {
const start = nodesSource.indexOf("async function performPanelEulaAccept(");
const end = nodesSource.indexOf("async function performPanelEulaStatus(", start);
assert.ok(start >= 0 && end > start);
const consent = nodesSource.slice(start, end);
assert.match(consent, /\{ autostart: false \}/);
assert.doesNotMatch(consent, /UPDATE servers|upsertServerStatus/);
assert.doesNotMatch(nodesSource, /UPDATE servers SET[^\n`]*setupStatus/);
});
test("reinstall flag sweeper is started beside the transfer recovery sweeper", () => {
const transferSweeperIdx = indexSource.indexOf("transferRecovery.startTransferRecoverySweeper(transferRecoveryDeps);");
const guardSweeperIdx = indexSource.indexOf("serverOpGuard.startReinstallFlagSweeper(serverOpGuardDeps);");
assert.ok(transferSweeperIdx > 0 && guardSweeperIdx > transferSweeperIdx);
});
test("guarded statuses never leak into loadServersIndexFresh filtering assumptions", () => {
// 'deleting' rows are filtered from the index; 'transferring'/'reinstalling'
// must remain visible while in flight.
assert.match(indexSource, /String\(e\.status \|\| ''\)\.toLowerCase\(\) !== 'deleting'/);
});
// ---------------------------------------------------------------------------
// BUG CRITIC regression tests (#1-#4)
// ---------------------------------------------------------------------------
test("BUG #1: claimReinstallOperation registers liveness only after the claim wins", () => {
const fnIdx = indexSource.indexOf("async function claimReinstallOperation");
const fnEnd = indexSource.indexOf("async function releaseReinstallOperation");
const body = indexSource.slice(fnIdx, fnEnd);
const preCheck = body.indexOf("activeReinstallOperations.has(name)");
const claimCall = body.indexOf("claimServerOperationStatus");
const addIdx = body.indexOf("activeReinstallOperations.add(name)");
const startIdx = body.indexOf("startReinstallOwnerHeartbeat");
assert.ok(fnIdx > 0 && fnEnd > fnIdx, "helper present");
assert.ok(preCheck > 0 && preCheck < claimCall, "local pre-check precedes the claim");
assert.ok(addIdx > claimCall && startIdx > claimCall, "liveness registered only after the claim");
assert.ok(!body.includes("activeReinstallOperations.delete(name)"), "failure path must not delete the active set entry");
assert.ok(!body.includes("stopReinstallOwnerHeartbeat"), "failure path must not stop the heartbeat");
});
test("BUG #2: stopReinstallOwnerHeartbeat deletes the redis key only when this worker owns it", async () => {
const store = new Map();
let dels = 0;
const deps = {
bootId: "boot-A",
ownerTimers: new Map(),
ownerTtlSec: 10,
redis: () => ({
set: async (k, v) => { store.set(k, v); return "OK"; },
get: async (k) => store.get(k) ?? null,
del: async (k) => { dels += 1; store.delete(k); },
}),
};
guard.startReinstallOwnerHeartbeat(deps, "alpha");
await new Promise((r) => setImmediate(r));
guard.stopReinstallOwnerHeartbeat(deps, "alpha");
await new Promise((r) => setImmediate(r));
assert.equal(dels, 1, "owner may remove its own key");
assert.equal(store.has(guard.reinstallOwnerAliveKey("alpha")), false);
assert.equal(deps.ownerTimers.has("alpha"), false);
});
test("BUG #2: stopReinstallOwnerHeartbeat never deletes another worker's heartbeat key", async () => {
const store = new Map();
store.set(guard.reinstallOwnerAliveKey("alpha"), "boot-OTHER-WORKER");
let dels = 0;
const deps = {
bootId: "boot-A",
ownerTimers: new Map(), // this worker never started a heartbeat for alpha
redis: () => ({
get: async (k) => store.get(k) ?? null,
del: async () => { dels += 1; },
}),
};
guard.stopReinstallOwnerHeartbeat(deps, "alpha");
await new Promise((r) => setImmediate(r));
assert.equal(dels, 0);
assert.equal(store.has(guard.reinstallOwnerAliveKey("alpha")), true, "foreign key untouched");
});
test("BUG #3: status-poll setup reconciliation never overwrites guarded markers", () => {
assert.match(
indexSource,
/UPDATE servers SET status = \? WHERE LOWER\(name\) = \? AND \(status IS NULL OR LOWER\(status\) NOT IN \('transferring', 'deleting', 'reinstalling'\)\)/
);
// adpanel:setup-status-column — the servers table has no setupStatus column,
// so the reconciliation must stay a single-purpose status UPDATE: the old
// `setupStatus = ?` fragment was an unknown column and failed the whole
// statement on the live DB, silently dropping the status flip too.
assert.doesNotMatch(
indexSource,
/UPDATE servers SET[^\n`]*setupStatus/
);
});
test("BUG #4: reinstall claim dbError surfaces as 503 in both reinstall routes", () => {
const tplIdx = indexSource.indexOf('app.post("/api/settings/servers/:name/template"');
const tplDbErr = indexSource.indexOf("if (templateClaim.dbError)", tplIdx);
const tpl503 = indexSource.indexOf("res.status(503)", tplDbErr);
assert.ok(tplIdx > 0 && tplDbErr > tplIdx && tpl503 > tplDbErr, "template change route returns 503 on dbError");
const reIdx = indexSource.indexOf('app.post("/api/servers/:name/reinstall"');
const reDbErr = indexSource.indexOf("if (reinstallClaim.dbError)", reIdx);
const re503 = indexSource.indexOf("res.status(503)", reDbErr);
assert.ok(reIdx > 0 && reDbErr > reIdx && re503 > reDbErr, "user reinstall route returns 503 on dbError");
});
test("reinstall sweeper age-gates the flag listing (updated_at floor)", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
const seen = [];
const realQuery = deps.db.query.bind(deps.db);
deps.db.query = async (sql, params) => {
seen.push({ sql, params });
return realQuery(sql, params);
};
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.deepEqual(outcome, { scanned: 1, restored: 1 });
assert.match(seen[0].sql, /updated_at < DATE_SUB\(NOW\(\), INTERVAL \? SECOND\)/);
assert.ok(Number(seen[0].params[1]) >= 60, "age floor is at least one heartbeat TTL");
assert.equal(deps.rows.alpha.status, "stopped");
});
test("reinstall sweeper cannot clear a fresh claim after its orphan snapshot", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
const realQuery = deps.db.query.bind(deps.db);
let staleListing = false;
deps.db.query = async (sql, params) => {
if (sql.startsWith("SELECT name")) {
staleListing = true;
return [{ name: "alpha" }];
}
if (sql.startsWith("UPDATE") && /updated_at < DATE_SUB\(NOW\(\), INTERVAL \? SECOND\)/.test(sql)) {
return { affectedRows: 0 };
}
return realQuery(sql, params);
};
deps.redis = () => ({
get: async () => {
assert.equal(staleListing, true);
deps.rows.alpha.status = "stopped";
const freshClaim = await guard.claimServerOperationStatus(deps, { name: "alpha", marker: "reinstalling" });
assert.equal(freshClaim.ok, true);
return null;
},
});
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.equal(outcome.restored, 0, "a stale orphan snapshot must not release a new claim");
assert.equal(deps.rows.alpha.status, "reinstalling");
});
test("reinstall sweeper refuses unsafe recovery when updated_at is unavailable", async () => {
const deps = makeGuardDeps({ rows: { alpha: { status: "reinstalling" } } });
const attempts = [];
const realQuery = deps.db.query.bind(deps.db);
deps.db.query = async (sql, params) => {
attempts.push(sql);
if (/updated_at/.test(sql)) throw new Error("Unknown column 'updated_at'");
return realQuery(sql, params);
};
const outcome = await guard.sweepStaleReinstallingFlags(deps);
assert.deepEqual(outcome, { scanned: 0, restored: 0 });
assert.equal(deps.rows.alpha.status, "reinstalling", "unverifiable ownership must stay guarded");
assert.equal(attempts.length, 1, "no unguarded fallback read or write may run");
});
test("transfer-recovery sweeper age-gates the transferring listing with a fallback", () => {
const rec = fs.readFileSync(path.join(ROOT, "utils", "transfer-recovery.js"), "utf8");
assert.match(rec, /SELECT name FROM servers WHERE status = \? AND updated_at < DATE_SUB\(NOW\(\), INTERVAL \? SECOND\)/);
assert.match(rec, /SELECT name FROM servers WHERE status = \?", \["transferring"\]/);
});
// ---------------------------------------------------------------------------
// H2: unrelated status writers must never clobber guarded markers
// ---------------------------------------------------------------------------
//
// The console-room status watcher (started by any user with console access on
// socket join, polling every 4s) and the socket run/stop handlers wrote the
// daemon-reported label through upsertServerIndexEntry, whose
// `status = VALUES(status)` had no marker condition: a transfer/reinstall/
// delete marker could be overwritten to "stopped" mid-operation, after which
// claimServerOperationStatus passes and a concurrent delete/second transfer
// proceeds — exactly the partial-state races F5 exists to prevent.
//
// Fix is two layers:
// 1. the shared index upserts keep a stored marker atomically in SQL
// (status = IF(LOWER(status) IN (...), status, VALUES(status))),
// 2. the label writers route through upsertServerStatusLabelUnlessGuarded,
// which re-reads the row and drops the write while a marker is held.
test("H2: isGuardedServerStatus recognizes exactly the guarded markers", () => {
for (const marker of guard.GUARDED_STATUSES) {
assert.equal(guard.isGuardedServerStatus(marker), true, marker);
assert.equal(guard.isGuardedServerStatus(marker.toUpperCase()), true, `${marker} uppercase`);
assert.equal(guard.isGuardedServerStatus(` ${marker} `), true, `${marker} padded`);
}
for (const plain of [null, undefined, "", " ", "running", "stopped", "starting", "installing", "offline", "unknown", "transferrin", "TRANSFER"]) {
assert.equal(guard.isGuardedServerStatus(plain), false, String(plain));
}
});
test("H2: both shared index upserts keep a stored marker atomically in SQL", () => {
const conditional = /status = IF\(LOWER\(status\) IN \('transferring', 'deleting', 'reinstalling'\), status, VALUES\(status\)\)/;
const upsertIdx = indexSource.indexOf("async function upsertServerIndexEntryUnlocked");
const upsertEnd = indexSource.indexOf("async function insertServerIndexEntryUnlocked");
assert.ok(upsertIdx > 0 && upsertEnd > upsertIdx, "upsert function boundaries");
const upsertBody = indexSource.slice(upsertIdx, upsertEnd);
assert.match(upsertBody, conditional, "upsertServerIndexEntryUnlocked must keep a guarded marker on duplicate");
// The INSERT branch (no existing row) cannot clobber a marker; the
// conditional lives only in the ON DUPLICATE KEY UPDATE path.
assert.match(upsertBody, /status = IF\(LOWER\(status\) IN/, "conditional evaluated against the STORED row");
const saveIdx = indexSource.indexOf("async function saveServersIndex");
assert.ok(saveIdx > 0, "saveServersIndex present");
const saveBody = indexSource.slice(saveIdx, saveIdx + 6000);
assert.match(saveBody, conditional, "saveServersIndex must keep a guarded marker on duplicate");
});
test("H2: power-state labels are written only through the guarded helper", () => {
// The four former unconditional writers must route through the helper…
assert.match(indexSource, /await upsertServerStatusLabelUnlessGuarded\(room, label\)/, "watcher label-change write");
assert.match(indexSource, /await upsertServerStatusLabelUnlessGuarded\(room, "stopped"\)/, "watcher connection-failure write");
assert.match(indexSource, /await upsertServerStatusLabelUnlessGuarded\(botName, "starting"\)/, "socket run write");
assert.match(indexSource, /if \(r\.json\.stopped === true \|\| r\.json\.note === "not running"\) \{\s+await upsertServerStatusLabelUnlessGuarded\(botName, "stopped"\)/, "socket stop writes only confirmed shutdowns");
// …and no stale snapshot-label upsert remains anywhere.
assert.ok(
!indexSource.includes("upsertServerIndexEntry({ ...entry, status: label })"),
"watcher must not upsert a label from a caller-held snapshot"
);
assert.ok(
!indexSource.includes('upsertServerIndexEntry({ ...cur, status: "starting" })'),
"socket run must not upsert a label from a caller-held snapshot"
);
assert.ok(
!indexSource.includes('upsertServerIndexEntry({ ...cur, status: "stopped" })'),
"socket stop must not upsert a label from a caller-held snapshot"
);
});
test("H2: the guarded label helper re-reads the row and drops writes on markers", () => {
const helperIdx = indexSource.indexOf("async function upsertServerStatusLabelUnlessGuarded");
assert.ok(helperIdx > 0, "helper present");
const helperEnd = indexSource.indexOf("// M4: insert-only index commit", helperIdx);
const body = indexSource.slice(helperIdx, helperEnd);
const readIdx = body.indexOf("await findServer(name)");
const guardIdx = body.indexOf("isGuardedServerStatus(entry.status)");
const writeIdx = body.indexOf("UPDATE servers SET status = ?");
assert.ok(readIdx > 0, "helper re-reads the row from the DB (not the index cache)");
assert.ok(guardIdx > readIdx, "guard check runs on the freshly read row");
assert.ok(writeIdx > guardIdx, "the write happens only after the guard check");
assert.doesNotMatch(body, /await upsertServerIndexEntry\(/);
assert.match(body, /serverOpGuard\.isGuardedServerStatus/, "guard predicate comes from utils/server-op-guard.js");
});
test("H2: watcher label writes live inside startRoomStatusWatcher (all remote joins share the fix)", () => {
const watcherIdx = indexSource.indexOf("function startRoomStatusWatcher");
const watcherEnd = indexSource.indexOf("const LIVE_STATUS_TTL_MS", watcherIdx);
assert.ok(watcherIdx > 0 && watcherEnd > watcherIdx, "watcher boundaries");
const body = indexSource.slice(watcherIdx, watcherEnd);
assert.match(body, /upsertServerStatusLabelUnlessGuarded\(room, label\)/);
assert.match(body, /upsertServerStatusLabelUnlessGuarded\(room, "stopped"\)/);
});
// adpanel:daemon-dial-canonical — the daemon derives identity from the URL
// key (main.go dispatch), so the console join must thread the canonical
// storage name it resolved into BOTH downstream dials (watcher status dial,
// SSE tail dial) while the room keys and the tail registry stay on the join
// alias. Source pin: index.js cannot be loaded in-process and no harness
// executes the join handler.
test("daemon-dial-canonical: the console join threads the canonical storage name into the watcher and tail dials", () => {
const joinIdx = indexSource.indexOf('socket.on("join"');
assert.ok(joinIdx > 0, "join handler present");
const joinEnd = indexSource.indexOf('socket.on("dashboard:watch"', joinIdx);
assert.ok(joinEnd > joinIdx, "join handler window bounded");
const joinBody = indexSource.slice(joinIdx, joinEnd);
const threadedIdx = joinBody.indexOf("const dialName = sanitizeNodeStorageName(entry.name || name)");
const watcherCallIdx = joinBody.indexOf("startRoomStatusWatcher(name, baseUrl, headers, dialName)");
const tailCallIdx = joinBody.indexOf("tailLogsRemote(name, baseUrl, headers, { dialName })");
assert.ok(threadedIdx > 0, "the join handler must resolve the canonical storage name once from the row it found");
assert.ok(watcherCallIdx > threadedIdx, "the watcher call must receive the threaded dial name");
assert.ok(tailCallIdx > watcherCallIdx, "the tail call must receive the threaded dial name");
const watcherIdx = indexSource.indexOf("function startRoomStatusWatcher");
const watcherEnd = indexSource.indexOf("const LIVE_STATUS_TTL_MS", watcherIdx);
const watcherBody = indexSource.slice(watcherIdx, watcherEnd);
assert.ok(watcherBody.includes("encodeURIComponent(rec.dialServerName)"), "the watcher's status dial must use the threaded canonical name stored on the watcher record");
assert.ok(!watcherBody.includes("encodeURIComponent(room)"), "the watcher's dial must not dial the raw room key");
assert.ok(watcherBody.includes("dialServerName: dialName || room"), "watchers created without a dial name keep their pre-threading behavior");
const tailIdx = indexSource.indexOf("function tailLogsRemote");
const tailEnd = indexSource.indexOf("function stopTailLogsRemote", tailIdx);
const tailBody = indexSource.slice(tailIdx, tailEnd);
assert.ok(tailBody.includes("encodeURIComponent(dialServerName)"), "the SSE tail dial must use the threaded canonical name");
assert.ok(tailBody.includes("const dialServerName = (options && options.dialName) || name"), "tail callers passing no dialName dial exactly as before");
assert.ok(tailBody.includes("remoteLogClients[name] = req"), "the tail registry stays keyed by the room name (stopTailLogsRemote(room) must keep matching)");
});
// adpanel:daemon-dial-canonical — the socket power (action) and command
// handlers resolved the server row for their suspension/permission gates but
// still dialed the daemon with the raw client alias; the daemon re-derives
// identity from the URL key, so both handlers must derive the canonical
// storage name from the row they found and carry it on every server-scoped
// dial (the action dials, the /command dial, the watcher/tail seeds and the
// force re-attaches) while rooms, permission checks and emits stay on the
// alias. Source pin: same technique as the join pin above (index.js cannot
// be loaded in-process and no harness executes the socket handlers).
test("daemon-dial-canonical: the socket power and command handlers dial and thread the canonical storage name", () => {
const actionIdx = indexSource.indexOf('socket.on("action"');
assert.ok(actionIdx > 0, "action handler present");
const commandIdx = indexSource.indexOf('socket.on("command"', actionIdx);
assert.ok(commandIdx > actionIdx, "command handler present after the action handler");
const commandEnd = indexSource.indexOf("let httpsServer", commandIdx);
assert.ok(commandEnd > commandIdx, "command handler window bounded");
const actionBody = indexSource.slice(actionIdx, commandIdx);
const commandBody = indexSource.slice(commandIdx, commandEnd);
// Both handlers derive the dial name once from the row they resolved.
assert.ok(actionBody.includes("const dialName = sanitizeNodeStorageName(entry.name || botName)"), "the action handler must resolve the canonical storage name from the row it found");
assert.ok(commandBody.includes("const dialName = sanitizeNodeStorageName(entry.name || botName)"), "the command handler must resolve the canonical storage name from the row it found");
// The five server-scoped dials carry the canonical name, never the raw alias.
for (const suffix of ["start?wait=false", "stop", "restart", "kill", "command"]) {
const body = suffix === "command" ? commandBody : actionBody;
assert.ok(body.includes(`encodeURIComponent(dialName)}/${suffix}`), `the ${suffix} dial must carry the canonical storage name`);
}
assert.ok(!actionBody.includes("encodeURIComponent(botName)") && !commandBody.includes("encodeURIComponent(botName)"), "neither handler may dial the daemon with the raw alias");
// The watcher/tail seeds and the post-action force re-attaches thread it too.
assert.ok(actionBody.includes("startRoomStatusWatcher(botName, baseUrl, headers, dialName)"), "the action handler's watcher seed must receive the threaded dial name");
assert.ok(actionBody.includes("tailLogsRemote(botName, baseUrl, headers, { dialName })"), "the action handler's tail seed must receive the threaded dial name");
assert.strictEqual((actionBody.match(/force: true, dialName/g) || []).length, 2, "both post-action force re-attaches must dial the canonical name");
assert.ok(commandBody.includes("startRoomStatusWatcher(botName, baseUrl, headers, dialName)"), "the command handler's watcher seed must receive the threaded dial name");
assert.ok(commandBody.includes("? { dialName }") && commandBody.includes("{ force: true, dialName, tail: CONSOLE_COMMAND_BACKFILL_TAIL }"), "both command-handler tail branches must thread the dial name");
// Rooms stay on the alias the client joined (the watcher/tail registry is
// keyed by it, see the join pin above).
assert.ok(actionBody.includes("socket.join(getServerStatusRoom(botName))"), "the action handler subscribes to the alias's server-status room only");
assert.ok(commandBody.includes("getConsoleRoom(botName)"), "the command handler's room join stays on the alias");
});
// adpanel:daemon-dial-canonical — the console-history and resource helpers
// resolved the server row for their gates but dialed the daemon with the raw
// row name; the daemon derives identity from the URL key, so for legacy
// non-fixed-point rows (token form ≠ storage form) it resolved a different
// storage name than the row's own — silently empty history/resource fetches
// and a missed history reset. Every dial below must carry the storage form of
// the row it resolved. Source pin: same technique as the join pin above
// (index.js cannot be loaded in-process and no harness executes these
// helpers).
test("daemon-dial-canonical: the history/resource helpers dial the storage form of the row they resolved", () => {
// fetchResourceStatsFromNode: the resource poll dial wraps the row name it
// is handed.
const resIdx = indexSource.indexOf("async function fetchResourceStatsFromNode");
assert.ok(resIdx > 0, "resource stats helper present");
const resEnd = indexSource.indexOf("function buildResourcePayload", resIdx);
assert.ok(resEnd > resIdx, "resource stats helper window bounded");
const resBody = indexSource.slice(resIdx, resEnd);
assert.ok(resBody.includes("encodeURIComponent(sanitizeNodeStorageName(serverName))"), "the resource poll dial must wrap the row name in the storage sanitizer");
assert.ok(!/encodeURIComponent\(serverName\)/.test(resBody), "the resource poll dial must never carry the bare row name");
// fetchRecentConsoleHistoryFromNode: one derivation feeds BOTH the snapshot
// and the full-log dial.
const histIdx = indexSource.indexOf("async function fetchRecentConsoleHistoryFromNode");
assert.ok(histIdx > 0, "console history fetch helper present");
const histEnd = indexSource.indexOf("async function getConsoleHistorySnapshot", histIdx);
assert.ok(histEnd > histIdx, "console history fetch helper window bounded");
const histBody = indexSource.slice(histIdx, histEnd);
const histDialIdx = histBody.indexOf("const dialName = sanitizeNodeStorageName(entry.name || requestedName)");
assert.ok(histDialIdx > 0, "the history fetcher must derive the storage form from the row it resolved");
assert.ok(histBody.indexOf("encodeURIComponent(dialName)}/logs/snapshot") > histDialIdx, "the snapshot dial must carry the derived storage name");
assert.ok(histBody.indexOf("encodeURIComponent(dialName)}/logs?") > histDialIdx, "the full-log dial must carry the derived storage name");
assert.ok(!histBody.includes("encodeURIComponent(entry.name"), "the history fetcher must never dial the bare row name");
// resetNodeConsoleHistory: the /logs/reset dial wraps the resolved row name.
const resetIdx = indexSource.indexOf("async function resetNodeConsoleHistory");
assert.ok(resetIdx > 0, "history reset helper present");
const resetEnd = indexSource.indexOf("async function fetchConsoleServerStatusLabel", resetIdx);
assert.ok(resetEnd > resetIdx, "history reset helper window bounded");
const resetBody = indexSource.slice(resetIdx, resetEnd);
assert.ok(resetBody.includes("encodeURIComponent(sanitizeNodeStorageName(entry.name || requestedName))}/logs/reset"), "the reset dial must carry the storage form of the resolved row");
assert.ok(!resetBody.includes("encodeURIComponent(entry.name"), "the reset dial must never carry the bare row name");
// fetchConsoleServerState: the state dial wraps the resolved row name.
const stateIdx = indexSource.indexOf("async function fetchConsoleServerState");
assert.ok(stateIdx > 0, "console state helper present");
const stateEnd = indexSource.indexOf("async function clearConsoleHistoryForServer", stateIdx);
assert.ok(stateEnd > stateIdx, "console state helper window bounded");
const stateBody = indexSource.slice(stateIdx, stateEnd);
assert.ok(stateBody.includes("encodeURIComponent(sanitizeNodeStorageName(entry.name || requestedName))"), "the state dial must carry the storage form of the resolved row");
assert.ok(!stateBody.includes("encodeURIComponent(entry.name"), "the state dial must never carry the bare row name");
});
test("H2: delete-job alias-abandon releases only its own 'deleting' claim", () => {
// The abandon path must keep releasing 'deleting' (its own marker) but must
// never clobber a transfer/reinstall marker re-claimed after a racing
// release — same conditioning the delete alias sweep uses.
assert.match(
indexSource,
/UPDATE servers SET status = 'stopped' WHERE id = \? AND node_id <=> \? AND LOWER\(status\) = 'deleting'/
);
});