@nodii/dev 0.6.208 → 0.6.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/drill.js ADDED
@@ -0,0 +1,1081 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { execFileSync, spawn } from "node:child_process";
3
+ import { randomBytes } from "node:crypto";
4
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
5
+ import { appendFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { coordinatorHome } from "./coordinator-board.js";
10
+ import { CliError, configPath, devRequest, encode, readConfig } from "./core.js";
11
+ import { laneConfigName } from "./lane-env.js";
12
+ import { launchRuntime } from "./runtime-launcher.js";
13
+
14
+ /**
15
+ * DEV-PROCESS-1 must-item 1: `nodii-dev harness drill lanes`, the frozen done
16
+ * check's Part A. About an hour on the stub runtime, no model and no code
17
+ * typed. It is run by the machine's coordinator (or the operator) from the
18
+ * installed release, never by the lane that built it.
19
+ *
20
+ * It starts scratch ("stub") lanes that run this package's drill-stub.js,
21
+ * finds their processes by scanning `ps` for the lane key (never from a list
22
+ * of its own), reads Dev through the routes any CLI uses, prints every pid,
23
+ * run id and Dev record it read, and exits 1 unless checks 1 to 12 all hold.
24
+ *
25
+ * The fixtures are the planner's, frozen in FIXTURES; a missing fixture fails
26
+ * the check that needs it. Every route the drill calls is recorded, and check
27
+ * 11 fails if one is a Prod or release route.
28
+ *
29
+ * Changing an assertion, a control, a fixture or this file needs a person's
30
+ * word (DEV-PROCESS-1, Done check).
31
+ */
32
+
33
+ export const FIXTURES = join(homedir(), "Projects", "_handoff", "dev-process-2026-11-23", "evidence", "o1");
34
+ const ENTRY = fileURLToPath(new URL("nodii-dev.js", import.meta.url));
35
+ // The shell launcher: `nodii-dev heavy run` is handled there, not in nodii-dev.js.
36
+ const CLI_BIN = fileURLToPath(new URL("../bin/nodii-dev", import.meta.url));
37
+ const SECOND = 1000;
38
+ const MINUTE = 60 * SECOND;
39
+ // The drill's whole run: an hour on the stub, plus room for Dev's orphan limit.
40
+ const DRILL_BUDGET_MS = 95 * MINUTE;
41
+ const REPLAYS = ["weekly-limit", "subscription-403", "limit-while-blocked", "limit-after-agent-ended", "unreported", "signalled", "expired-signin"];
42
+ const PROD_ROUTE = /\/(?:promot|rollback|releases?\/[^/]+\/(?:promote|ship))|[?&/]env(?:ironment)?=?prod\b|\/prod(?:uction)?\//i;
43
+ /** Dev's edge: the drill runs against dev Dev only. */
44
+ export const DEV_EDGE = "https://platform.nucleus-cloud.in";
45
+
46
+ /**
47
+ * A module preloaded into every CLI the drill spawns: it records the host and
48
+ * path of each request (never a query, header or body), so check 11 reads the
49
+ * routes those commands really called.
50
+ */
51
+ export const recorderSource = (logPath) => `import { appendFileSync } from "node:fs";
52
+ const real = globalThis.fetch;
53
+ globalThis.fetch = (input, init) => {
54
+ try {
55
+ const url = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url);
56
+ const method = String(init?.method ?? (typeof input === "object" && input?.method) ?? "GET").toUpperCase();
57
+ appendFileSync(${JSON.stringify(logPath)}, method + " " + url.host + url.pathname + "\\n");
58
+ } catch {}
59
+ return real(input, init);
60
+ };
61
+ `;
62
+
63
+ /**
64
+ * The environment every process the drill starts carries: Node preloads the
65
+ * recorder through NODE_OPTIONS and Bun through BUN_OPTIONS, so the CLI
66
+ * commands, the supervisor, the stub and its jobs (a heavy-slot job included)
67
+ * all record their routes into one log for check 11.
68
+ */
69
+ export function recordingEnv(env, recorder) {
70
+ const add = (current, flag) => [current, flag].filter(Boolean).join(" ");
71
+ return { ...env, NODE_OPTIONS: add(env.NODE_OPTIONS, `--import=${recorder}`), BUN_OPTIONS: add(env.BUN_OPTIONS, `--preload=${recorder}`) };
72
+ }
73
+
74
+ /**
75
+ * Each check runs with its own abort signal. When the check's time is up (or
76
+ * the drill is interrupted) the signal aborts: every wait in it ends at once
77
+ * with a failure, and it starts no further stub lane or command, so nothing
78
+ * it would start outlives the cleanup.
79
+ */
80
+ const running = new AsyncLocalStorage();
81
+ const checkSignal = () => running.getStore()?.signal ?? null;
82
+ class Aborted extends Error {}
83
+ const throwIfAborted = () => { if (checkSignal()?.aborted) throw new Aborted("the check was stopped: its time was up or the drill was interrupted"); };
84
+
85
+ const sleep = (ms) => new Promise((resolve, reject) => {
86
+ const signal = checkSignal();
87
+ if (signal?.aborted) return reject(new Aborted("the check was stopped: its time was up or the drill was interrupted"));
88
+ const timer = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(); }, ms);
89
+ function stop() { clearTimeout(timer); reject(new Aborted("the check was stopped: its time was up or the drill was interrupted")); }
90
+ signal?.addEventListener("abort", stop, { once: true });
91
+ });
92
+
93
+ /** A failed assertion, with what was read. */
94
+ class Failed extends Error {}
95
+ const must = (condition, message) => { if (!condition) throw new Failed(message); };
96
+
97
+ // ---- Dev, as any CLI reads it ------------------------------------------------
98
+
99
+ function devClient(request, calls) {
100
+ return async (method, path, body) => {
101
+ calls.push(`${method} ${path}`);
102
+ try {
103
+ return { ok: true, data: (await request(method, path, body))?.data };
104
+ } catch (error) {
105
+ return { ok: false, code: error?.code ?? "ERROR", message: String(error?.message ?? error) };
106
+ }
107
+ };
108
+ }
109
+
110
+ /** The CLI itself, from this release, under the caller's own config. */
111
+ export function cliRunner({ entry = ENTRY, execPath = process.execPath, env = process.env, calls, recorder = null }) {
112
+ return (args, { timeoutMs = 3 * MINUTE } = {}) => new Promise((resolve, reject) => {
113
+ if (checkSignal()?.aborted) return reject(new Aborted("the check was stopped before it ran nodii-dev " + args.slice(0, 2).join(" ")));
114
+ calls.push(`nodii-dev ${args.join(" ")}`);
115
+ const child = spawn(execPath, [...(recorder ? ["--import", recorder] : []), entry, ...args, "--json"], { env, stdio: ["ignore", "pipe", "pipe"] });
116
+ let stdout = "";
117
+ let stderr = "";
118
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
119
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
120
+ const timer = setTimeout(() => child.kill("SIGTERM"), timeoutMs);
121
+ child.on("close", (code) => {
122
+ clearTimeout(timer);
123
+ let json = null;
124
+ try { json = JSON.parse(stdout); } catch {}
125
+ if (!json) try { json = JSON.parse(stderr); } catch {}
126
+ const error = json?.error ?? null;
127
+ resolve({ code, json, error, ok: code === 0, text: `${stdout}${stderr}`.trim().slice(0, 4000) });
128
+ });
129
+ });
130
+ }
131
+
132
+ // ---- ps, scanned for a lane's key --------------------------------------------
133
+
134
+ /** `ps` rows: pid, parent, state and the command line. */
135
+ export function psRows(text) {
136
+ const rows = [];
137
+ for (const line of String(text ?? "").split("\n")) {
138
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
139
+ if (match) rows.push({ pid: Number(match[1]), ppid: Number(match[2]), stat: match[3], command: match[4] });
140
+ }
141
+ return rows;
142
+ }
143
+
144
+ const readPs = () => execFileSync("ps", ["-A", "-ww", "-o", "pid=,ppid=,stat=,command="], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
145
+
146
+ /**
147
+ * A stub lane's processes, found in `ps` by its key alone: the runtime (its
148
+ * script is <root>/<key>.json), the supervisor (the runtime's parent), and each
149
+ * job (`nodii-drill-job <key> <role>`). Exact: a key that extends this one is
150
+ * another lane.
151
+ */
152
+ export function scanLane(rows, key, root) {
153
+ const script = `${join(root, key)}.json`;
154
+ const runtime = rows.find((row) => row.command.includes("drill-stub.js") && row.command.includes(`--script ${script}`));
155
+ const parent = runtime ? rows.find((row) => row.pid === runtime.ppid) : null;
156
+ const supervisor = parent && /__lane-supervisor/.test(parent.command) ? parent : null;
157
+ const jobs = {};
158
+ for (const row of rows) {
159
+ const match = /\bnodii-drill-job (\S+) (child|nohup|setsid|heavy)\s*$/.exec(row.command);
160
+ if (match && match[1] === key && !/heavy-slot|nodii-dev\b.*\bheavy\b/.test(row.command)) jobs[match[2]] = row;
161
+ }
162
+ return { runtime: runtime ?? null, supervisor, jobs };
163
+ }
164
+
165
+ const stopped = (row) => /^T/.test(row?.stat ?? "");
166
+ const describe = (found) => [
167
+ `runtime ${found.runtime ? `${found.runtime.pid} ${found.runtime.stat}` : "none"}`,
168
+ `supervisor ${found.supervisor ? `${found.supervisor.pid} ${found.supervisor.stat}` : "none"}`,
169
+ ...Object.entries(found.jobs).map(([role, row]) => `${role} ${row.pid} ${row.stat}`),
170
+ ].join(", ");
171
+
172
+ // ---- The drill's context -----------------------------------------------------
173
+
174
+ export async function drillContext({ request = devRequest, config = readConfig, env = process.env, now = () => new Date() } = {}) {
175
+ const calls = [];
176
+ const dev = devClient(request, calls);
177
+ const c = await config();
178
+ // Dev's edge on dev only, refused before anything starts.
179
+ if (c.edgeUrl !== DEV_EDGE)
180
+ throw new CliError("USAGE", `The drill runs against dev Dev only (${DEV_EDGE}); this config points at ${c.edgeUrl ?? "no edge"}.`, 2);
181
+ const agent = await dev("GET", `/api/v1/agents/${encode(c.agentId)}`);
182
+ if (!agent.ok || agent.data?.role !== "coordinator" || !agent.data?.machineId)
183
+ throw new CliError("COORDINATOR_REQUIRED", "The drill runs as this machine's coordinator (its config), so it can start and stop stub lanes.", 2);
184
+ const machine = await dev("GET", `/api/v1/machines/${encode(agent.data.machineId)}`);
185
+ const stamp = now().toISOString().replace(/[-:]/g, "").slice(2, 13).toLowerCase();
186
+ const runId = `${stamp}-${randomBytes(2).toString("hex")}`;
187
+ const root = join(homedir(), ".nodii", "drill", runId);
188
+ await mkdir(root, { recursive: true, mode: 0o700 });
189
+ const routesLog = join(root, "cli-routes.log");
190
+ const recorder = join(root, "route-recorder.mjs");
191
+ await writeFile(recorder, recorderSource(routesLog));
192
+ await writeFile(routesLog, "");
193
+ const childEnv = recordingEnv(env, recorder);
194
+ return {
195
+ runId,
196
+ root,
197
+ edgeUrl: c.edgeUrl,
198
+ authUrl: c.authUrl,
199
+ agentId: c.agentId,
200
+ agentName: agent.data?.name ?? null,
201
+ routesLog,
202
+ machineId: agent.data.machineId,
203
+ machineName: machine.data?.name ?? null,
204
+ configPath: configPath(),
205
+ dev,
206
+ childEnv,
207
+ cli: cliRunner({ env: childEnv, calls }),
208
+ calls,
209
+ ps: () => psRows(readPs()),
210
+ lanes: [],
211
+ accounts: [],
212
+ log: [],
213
+ started: Date.now(),
214
+ };
215
+ }
216
+
217
+ /** A stub lane key: drill-<run>-<name>. */
218
+ export const stubKey = (ctx, name) => `drill-${ctx.runId}-${name}`;
219
+
220
+ /**
221
+ * Start a stub lane the way `lane launch` starts a lane: Dev registers it,
222
+ * then the supervisor runs the stub. Ruling A: no override, outside the cap,
223
+ * no repository, account, Figma file or change set.
224
+ */
225
+ export async function startStub(ctx, name, script = {}, extra = {}) {
226
+ throwIfAborted();
227
+ const key = stubKey(ctx, name);
228
+ const scriptPath = `${join(ctx.root, key)}.json`;
229
+ const worktree = join(ctx.root, `${key}-wt`);
230
+ await mkdir(worktree, { recursive: true });
231
+ await writeFile(scriptPath, JSON.stringify({ cli: CLI_BIN, ...script }));
232
+ // The lane's Dev identity is the coordinator's own (ruling A): its config, under the lane's name. No secret is in it.
233
+ const devConfigPath = join(dirname(ctx.configPath), "agents", laneConfigName(key));
234
+ await mkdir(dirname(devConfigPath), { recursive: true, mode: 0o700 });
235
+ await writeFile(devConfigPath, await readFile(ctx.configPath, "utf8"), { mode: 0o600 });
236
+ const coordinatorRun = await ctx.dev("GET", `/api/v1/run-watchdog?machine=${encode(ctx.machineId)}`);
237
+ const coordinatorRunId = (coordinatorRun.data?.liveRuns ?? []).find((run) => run.kind === "coordinator")?.id ?? null;
238
+ const body = {
239
+ phase: "register",
240
+ key,
241
+ doneCheck: "drill stub lane: the drill ends it",
242
+ kind: "dev_fix",
243
+ side: "backend",
244
+ issueIds: [],
245
+ agentId: ctx.agentId,
246
+ machineId: ctx.machineId,
247
+ coordinatorRunId,
248
+ repositories: [],
249
+ runtime: "stub",
250
+ stubScript: scriptPath,
251
+ model: "drill-stub",
252
+ devConfigPath,
253
+ subagentQuota: 0,
254
+ workClass: "no_build",
255
+ figmaScopes: [],
256
+ preflight: {},
257
+ expectedHeartbeatSeconds: 60,
258
+ via: "nodii-dev",
259
+ ...extra,
260
+ };
261
+ const registered = await ctx.dev("POST", "/api/v1/lanes/launch", body);
262
+ const lane = { key, name, scriptPath, worktree, devConfigPath, registered, startedAt: Date.now() };
263
+ ctx.lanes.push(lane);
264
+ if (!registered.ok) return lane;
265
+ lane.laneId = registered.data?.lane?.id;
266
+ lane.runId = registered.data?.run?.id;
267
+ try {
268
+ lane.launched = await launchRuntime({
269
+ runId: lane.runId, laneKey: key, runtime: "stub", model: "drill-stub", cwd: worktree, devConfigPath,
270
+ addDirs: [], prompt: registered.data?.brief ?? `Drill stub lane ${key}.`, stubScript: scriptPath, ...(extra.profile ? { profileHome: extra.profile } : {}),
271
+ }, { env: ctx.childEnv ?? process.env });
272
+ } catch (error) {
273
+ lane.launchError = String(error?.message ?? error);
274
+ }
275
+ return lane;
276
+ }
277
+
278
+ /** A started stub lane, or a failure naming Dev's refusal. */
279
+ async function needStub(ctx, name, script, extra) {
280
+ const lane = await startStub(ctx, name, script, extra);
281
+ must(lane.registered.ok, `Dev did not admit stub lane ${lane.key}: ${lane.registered.code} ${lane.registered.message}`);
282
+ must(!lane.launchError, `stub lane ${lane.key} did not start: ${lane.launchError}`);
283
+ return lane;
284
+ }
285
+
286
+ async function until(check, ms, every = 5 * SECOND) {
287
+ const end = Date.now() + ms;
288
+ for (;;) {
289
+ throwIfAborted();
290
+ const value = await check();
291
+ if (value) return value;
292
+ if (Date.now() >= end) return null;
293
+ await sleep(every);
294
+ }
295
+ }
296
+
297
+ const laneRecord = async (ctx, key) => (await ctx.dev("GET", `/api/v1/lanes/${encode(key)}`)).data ?? null;
298
+ const runRecord = async (ctx, runId) => (await ctx.dev("GET", `/api/v1/runs/${encode(runId)}`)).data ?? null;
299
+
300
+ async function settings(ctx) {
301
+ const read = await ctx.dev("GET", "/api/v1/run-watchdog/settings");
302
+ return { orphanAfterMs: (read.data?.orphanAfterSeconds ?? 2700) * SECOND, quietAfterMs: (read.data?.quietAfterSeconds ?? 900) * SECOND };
303
+ }
304
+
305
+ async function jobsUp(ctx, lane, roles = ["child", "nohup", "setsid", "heavy"]) {
306
+ return until(() => {
307
+ const found = scanLane(ctx.ps(), lane.key, ctx.root);
308
+ return found.runtime && roles.every((role) => found.jobs[role]) ? found : null;
309
+ }, 60 * SECOND, 2 * SECOND);
310
+ }
311
+
312
+ async function writeEnd(lane, ending) {
313
+ const dir = join(dirname(lane.scriptPath), lane.key);
314
+ await mkdir(dir, { recursive: true });
315
+ await writeFile(join(dir, "end.json"), JSON.stringify(ending));
316
+ }
317
+
318
+ const starts = (lane) => {
319
+ try { return readFileSync(join(dirname(lane.scriptPath), lane.key, "runtime.starts"), "utf8").split("\n").filter(Boolean); } catch { return []; }
320
+ };
321
+
322
+ const kill = (pid, signal) => { try { process.kill(pid, signal); return true; } catch { return false; } };
323
+
324
+ /**
325
+ * A stub account's usage with no headroom for long work (85%: warning). Only
326
+ * check 7's accounts are ok (10%), and check 7's lanes do long work, so a
327
+ * resume there never lands on another check's account, nor theirs on its.
328
+ */
329
+ const WARNING_USAGE = { windows: { fiveHour: { utilization: 85 }, sevenDay: { utilization: 85 } } };
330
+
331
+ /** A stub account: a drill folder registered through Dev's account route, runtime stub. */
332
+ async function registerStubAccount(ctx, name, usage = WARNING_USAGE) {
333
+ const profile = join(ctx.root, "accounts", name);
334
+ await mkdir(profile, { recursive: true });
335
+ await writeFile(join(profile, "usage.json"), JSON.stringify(usage));
336
+ const registered = await ctx.dev("POST", "/api/v1/runners", { kind: "account", machineId: ctx.machineId, runtime: "stub", profile, status: "online" });
337
+ if (registered.ok) ctx.accounts?.push(profile);
338
+ return { ...registered, profile };
339
+ }
340
+
341
+ /** The account a run ran on, wherever Dev's run row keeps it. */
342
+ const runProfile = (run) => run?.profile ?? run?.launch?.profile ?? run?.metadata?.launch?.profileHome ?? run?.metadata?.launch?.profile ?? null;
343
+
344
+ /** This machine's account rows, as Dev lists them (the route `machine accounts list` reads). */
345
+ const machineAccounts = async (ctx) => ((await ctx.dev("GET", "/api/v1/runners?kind=account")).data ?? []).filter((runner) => runner.machineId === ctx.machineId);
346
+
347
+ /**
348
+ * When the machine's watchdog last reported a run alive after `after` (ms),
349
+ * from Dev's watchdog state for this machine; waits up to 3 minutes (it
350
+ * sweeps every minute). Null if it never did.
351
+ */
352
+ async function watchdogSaw(ctx, runId, after) {
353
+ return until(async () => {
354
+ const state = await ctx.dev("GET", `/api/v1/run-watchdog?machine=${encode(ctx.machineId)}`);
355
+ const seen = (state.data?.watchdogObservations ?? [])
356
+ .map((row) => row.event ?? row)
357
+ .filter((event) => event.runId === runId && event.observation === "process_alive" && Date.parse(event.observedAt) > after);
358
+ return seen.length ? seen.map((event) => event.observedAt).sort().at(-1) : null;
359
+ }, 3 * MINUTE, 20 * SECOND);
360
+ }
361
+
362
+ /** The routes the spawned CLI commands called, as host and path. */
363
+ const recordedRoutes = (ctx) => { try { return readFileSync(ctx.routesLog, "utf8").split("\n").filter(Boolean); } catch { return []; } };
364
+
365
+ // ---- The checks ---------------------------------------------------------------
366
+
367
+ /** 1. Bounds. */
368
+ async function checkBounds(ctx, say) {
369
+ const lane = await needStub(ctx, "bounds");
370
+ say(`stub lane ${lane.key}: admitted, lane ${lane.laneId}, run ${lane.runId}, runtime pid ${lane.launched?.pid}`);
371
+ const admitted = await laneRecord(ctx, lane.key);
372
+ const account = runProfile(lane.registered.data?.run) ?? admitted?.launch?.profile ?? admitted?.launch?.profileHome ?? null;
373
+ say(`the admitted stub lane's account: ${account ?? "none"}`);
374
+ must(account === null, `the admitted stub lane carries an account (${account})`);
375
+ const machine = await ctx.dev("GET", `/api/v1/machines/${encode(ctx.machineId)}`);
376
+ const cap = machine.data?.laneCapState;
377
+ must(machine.ok && Array.isArray(cap?.lanes), `Dev's lane cap could not be read with its counted lanes (${machine.code ?? "no laneCapState.lanes"})`);
378
+ const counted = cap.lanes.map((row) => row.key);
379
+ say(`lane cap: count ${cap.count}, counted ${counted.join(", ") || "none"}`);
380
+ must(!counted.includes(lane.key), "the stub lane is counted in the lane cap");
381
+ const refusals = [
382
+ ["a repository", { repositories: [{ repo: "nodii-clis", branch: `drill/${ctx.runId}`, worktree: join(ctx.root, "repo-wt"), baseRef: "origin/main" }] }],
383
+ ["a Figma scope", { figmaScopes: [{ fileKey: "drillfigmafile", componentSets: [] }] }],
384
+ ["a real account", { profile: join(homedir(), ".claude") }],
385
+ ["a real runtime called the stub", { runtime: "claude" }],
386
+ ];
387
+ for (const [what, extra] of refusals) {
388
+ const refused = await startStub(ctx, `bounds-${what.replace(/\W+/g, "-")}`, {}, extra);
389
+ say(`stub lane with ${what}: ${refused.registered.ok ? "ADMITTED" : `${refused.registered.code}`}`);
390
+ must(!refused.registered.ok && refused.registered.code === "STUB_LANE_BOUNDS", `Dev did not refuse a stub lane ${what} STUB_LANE_BOUNDS`);
391
+ }
392
+ const changeSet = await ctx.dev("POST", "/api/v1/design/files/drillfigmafile/lock", { laneKey: lane.key, title: "drill", via: "nodii-dev" });
393
+ say(`change set for the stub lane: ${changeSet.ok ? "CREATED" : changeSet.code}`);
394
+ must(!changeSet.ok && changeSet.code === "STUB_LANE_BOUNDS", "Dev did not refuse the stub lane a change set STUB_LANE_BOUNDS");
395
+ // A stub account: Dev takes it for a drill folder and refuses it for a real account's profile. No real account is touched.
396
+ const stubAccount = await registerStubAccount(ctx, "bounds");
397
+ say(`stub account at a drill folder: ${stubAccount.ok ? `registered ${stubAccount.data?.id}` : stubAccount.code}`);
398
+ must(stubAccount.ok, `Dev did not register a stub account for a drill folder (${stubAccount.code})`);
399
+ const accounts = await ctx.dev("GET", "/api/v1/runners?kind=account");
400
+ const realProfile = (accounts.data ?? []).find((runner) => runner.machineId === ctx.machineId && ["claude", "codex"].includes(runner.runtime))?.profile;
401
+ must(realProfile, "no real account is registered on this machine to name in the refusal");
402
+ const stubForReal = await ctx.dev("POST", "/api/v1/runners", { kind: "account", machineId: ctx.machineId, runtime: "stub", profile: realProfile, status: "online" });
403
+ say(`stub account naming real profile ${realProfile}: ${stubForReal.ok ? "REGISTERED" : stubForReal.code}`);
404
+ must(!stubForReal.ok && stubForReal.code === "STUB_LANE_BOUNDS", "Dev did not refuse a stub account (a stub reading) for a real account STUB_LANE_BOUNDS");
405
+ const ungranted = `drill-ungranted-${ctx.runId}`;
406
+ const preflight = await ctx.dev("POST", "/api/v1/lanes/launch", {
407
+ phase: "preflight", key: stubKey(ctx, "grant"), doneCheck: "drill", kind: "dev_fix", side: "backend", issueIds: [], agentId: ctx.agentId,
408
+ machineId: ctx.machineId, repositories: [{ repo: ungranted, branch: "drill", worktree: join(ctx.root, "ungranted"), baseRef: "origin/main" }],
409
+ runtime: "claude", profile: join(ctx.root, "accounts", "no-account"), model: "drill", devConfigPath: lane.devConfigPath, subagentQuota: 0, workClass: "no_build", figmaScopes: [], preflight: {}, via: "nodii-dev",
410
+ });
411
+ say(`preflight with ungranted repository ${ungranted}: ${preflight.ok ? "READY" : `${preflight.code}: ${preflight.message}`}`);
412
+ must(!preflight.ok && preflight.code === "REPO_NOT_GRANTED", `an ungranted repository was not refused REPO_NOT_GRANTED (${preflight.code ?? "ready"})`);
413
+ must(preflight.message.includes(ungranted) && (preflight.message.includes(ctx.agentId) || (ctx.agentName && preflight.message.includes(ctx.agentName))),
414
+ "REPO_NOT_GRANTED does not name both the agent and the repository");
415
+ const stop = await ctx.cli(["lane", "stop", lane.key, "--reason", "drill: the coordinator stops a stub lane with no code", "--no-closeout"]);
416
+ say(`coordinator stop of ${lane.key} with no code: ${stop.ok ? "stopped" : stop.error?.code ?? stop.text}`);
417
+ must(stop.ok, "the coordinator could not stop a stub lane with no code");
418
+ }
419
+
420
+ /** 2. Dead, with its control (silent past the orphan limit, child running). */
421
+ async function checkDead(ctx, say) {
422
+ const { orphanAfterMs } = await settings(ctx);
423
+ const dead = await needStub(ctx, "dead");
424
+ const silent = await needStub(ctx, "silent", { silentAfterTicks: 3, jobs: ["child"] });
425
+ const found = await jobsUp(ctx, dead);
426
+ must(found, `the dead lane's jobs did not start: ${describe(scanLane(ctx.ps(), dead.key, ctx.root))}`);
427
+ say(`${dead.key} run ${dead.runId}: ${describe(found)}`);
428
+ await sleep(90 * SECOND);
429
+ kill(found.runtime.pid, "SIGKILL");
430
+ if (found.supervisor) kill(found.supervisor.pid, "SIGKILL");
431
+ const killedAt = Date.now();
432
+ say(`killed runtime ${found.runtime.pid} and supervisor ${found.supervisor?.pid ?? "none"}; its jobs left running`);
433
+ const accepted = await until(async () => {
434
+ const lane = await laneRecord(ctx, dead.key);
435
+ const live = (lane?.runs ?? []).some((run) => run.status === "running" && ["active", "quiet"].includes(run.livenessState));
436
+ if (live) return null;
437
+ const resume = await ctx.cli(["lane", "resume", dead.key]);
438
+ return resume.ok ? { lane, resume } : null;
439
+ }, 2 * MINUTE, 15 * SECOND);
440
+ say(`${accepted ? `resume accepted ${Math.round((Date.now() - killedAt) / SECOND)} s after the kill` : "no live-free record and accepted resume within 2 minutes"}`);
441
+ must(accepted, "within 2 minutes of the kill Dev did not show the lane dead and accept lane resume");
442
+ // Control: a runtime alive but silent past the orphan limit, its child running, is live.
443
+ const quietUntil = silent.startedAt + orphanAfterMs + MINUTE;
444
+ await until(() => Date.now() > quietUntil, orphanAfterMs + 2 * MINUTE, 30 * SECOND);
445
+ const silentNow = scanLane(ctx.ps(), silent.key, ctx.root);
446
+ say(`${silent.key} run ${silent.runId}: ${describe(silentNow)}`);
447
+ must(silentNow.runtime && silentNow.jobs.child, "the silent control's runtime or child is gone");
448
+ const control = await ctx.cli(["lane", "resume", silent.key]);
449
+ say(`resume of the silent lane: ${control.ok ? "ACCEPTED" : `${control.error?.code}: ${control.error?.message ?? ""}`.slice(0, 300)}`);
450
+ must(!control.ok && control.error?.code === "LANE_PROCESS_LIVE" && String(control.error?.message).includes(silent.runId) && String(control.error?.message).includes(String(silentNow.runtime.pid)),
451
+ "the silent lane with a running child was not refused LANE_PROCESS_LIVE naming its run and pid");
452
+ }
453
+
454
+ /** 3. Stopped: two harness-ended runs do not stop relaunch; two unplanned exits do. */
455
+ async function checkStopped(ctx, say) {
456
+ const ended = await needStub(ctx, "harness-ended", { jobs: [] });
457
+ for (let round = 1; round <= 2; round += 1) {
458
+ const found = await jobsUp(ctx, ended, []);
459
+ must(found?.supervisor, `round ${round}: the harness-ended lane has no supervisor in ps`);
460
+ // The harness ends the run: its supervisor is told to stop, as lane pause, lane stop and a coordinator's end do.
461
+ kill(found.supervisor.pid, "SIGTERM");
462
+ say(`round ${round}: SIGTERM to supervisor ${found.supervisor.pid} (runtime ${found.runtime.pid})`);
463
+ await until(() => !scanLane(ctx.ps(), ended.key, ctx.root).runtime, MINUTE, 2 * SECOND);
464
+ const resume = await ctx.cli(["lane", "resume", ended.key]);
465
+ say(`round ${round}: lane resume ${resume.ok ? "accepted" : resume.error?.code}`);
466
+ must(resume.ok, `round ${round}: a harness-ended run stopped relaunch (${resume.error?.code})`);
467
+ }
468
+ const lane = await laneRecord(ctx, ended.key);
469
+ const runs = (lane?.runs ?? []).filter((run) => run.kind === "lane");
470
+ const recorded = runs.filter((run) => run.harnessEnd?.by && run.harnessEnd?.reason);
471
+ say(`runs of ${ended.key}: ${runs.map((run) => `${run.id} ${run.status} harnessEnd=${JSON.stringify(run.harnessEnd ?? null)}`).join("; ")}`);
472
+ must(recorded.length >= 2, "Dev does not record who ended the harness-ended runs and why (harnessEnd.by, harnessEnd.reason)");
473
+ // Control: two unplanned exits with one non-account fingerprint still stop relaunch.
474
+ const crash = await needStub(ctx, "unplanned", { jobs: [], ending: { afterTicks: 5, code: 2 } });
475
+ await until(() => starts(crash).length >= 1 && !scanLane(ctx.ps(), crash.key, ctx.root).runtime, 2 * MINUTE, 3 * SECOND);
476
+ await sleep(20 * SECOND);
477
+ const first = await ctx.cli(["lane", "resume", crash.key]);
478
+ say(`unplanned exit 1: resume ${first.ok ? "accepted" : first.error?.code}`);
479
+ must(first.ok, `the first unplanned exit was not resumed (${first.error?.code})`);
480
+ await until(() => starts(crash).length >= 2 && !scanLane(ctx.ps(), crash.key, ctx.root).runtime, 2 * MINUTE, 3 * SECOND);
481
+ await sleep(20 * SECOND);
482
+ const second = await ctx.cli(["lane", "resume", crash.key]);
483
+ say(`unplanned exit 2: resume ${second.ok ? "ACCEPTED" : second.error?.code}`);
484
+ must(!second.ok && second.error?.code === "AUTOMATIC_RELAUNCH_STOPPED", "two unplanned exits with one fingerprint did not stop relaunch");
485
+ }
486
+
487
+ /** 4. Paused, then stopped, with its controls. */
488
+ async function checkPaused(ctx, say) {
489
+ const lane = await needStub(ctx, "paused");
490
+ const longer = await needStub(ctx, "paused-x");
491
+ const found = await jobsUp(ctx, lane);
492
+ const foundLonger = await jobsUp(ctx, longer);
493
+ must(found && foundLonger, "the paused lane's or its control's jobs did not start");
494
+ // A process sitting in a sibling worktree, of no lane.
495
+ const sibling = join(ctx.root, `${lane.key}-wt-sibling`);
496
+ await mkdir(sibling, { recursive: true });
497
+ const decoy = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)", "nodii-drill-decoy", ctx.runId], { cwd: sibling, stdio: "ignore", detached: true });
498
+ decoy.unref();
499
+ try {
500
+ // Two controls, each found on its own: the cap keepalive is a process; the
501
+ // watchdog is the machine's periodic sweep, seen through what it reports to
502
+ // Dev about the control lane's run (process_alive) after each act.
503
+ const machine = () => ctx.ps().filter((row) => /cap-keepalive|coordinator watch run|watchdog sweep/.test(row.command));
504
+ const controlsBefore = machine();
505
+ const keepalives = controlsBefore.filter((row) => /cap-keepalive/.test(row.command));
506
+ must(keepalives.length > 0, "no cap keepalive process runs on this machine to serve as a control");
507
+ const watchdogSince = (at) => watchdogSaw(ctx, longer.runId, at);
508
+ must(await watchdogSince(Date.now() - 5 * MINUTE), "the machine's watchdog reported no sweep of the control lane, so it cannot serve as a control");
509
+ say(`${lane.key}: ${describe(found)}`);
510
+ say(`controls: ${longer.key} ${describe(foundLonger)}; decoy ${decoy.pid} in ${sibling}; machine jobs ${controlsBefore.map((row) => `${row.pid}`).join(", ") || "none running"}`);
511
+ const pause = await ctx.cli(["lane", "pause", lane.key, "--reason", "drill: pause"]);
512
+ say(`lane pause: ${pause.ok ? "ok" : `${pause.error?.code}: ${pause.error?.message ?? pause.text}`.slice(0, 300)}`);
513
+ must(pause.ok, `lane pause failed (${pause.error?.code ?? "no such verb"})`);
514
+ await sleep(2 * SECOND);
515
+ const paused = scanLane(ctx.ps(), lane.key, ctx.root);
516
+ say(`after pause: ${describe(paused)}`);
517
+ must([paused.runtime, paused.supervisor, ...Object.values(paused.jobs)].every(stopped) && Object.keys(paused.jobs).length === 4, "not every process of the paused lane reads stopped (T) in ps");
518
+ const controlsPaused = scanLane(ctx.ps(), longer.key, ctx.root);
519
+ must(![controlsPaused.runtime, ...Object.values(controlsPaused.jobs)].some(stopped), "a process of the lane whose key extends this one's was stopped");
520
+ must(!stopped(ctx.ps().find((row) => row.pid === decoy.pid)), "the sibling worktree's process was stopped");
521
+ must(machine().every((row) => !stopped(row)), "a cap keepalive or watchdog process was stopped");
522
+ const pausedAt = Date.now();
523
+ const sweptPaused = await watchdogSince(pausedAt);
524
+ say(`watchdog after the pause: ${sweptPaused ? `swept the control lane at ${sweptPaused}` : "NO SWEEP"}`);
525
+ must(sweptPaused, "the machine's watchdog did not sweep within 3 minutes of lane pause");
526
+ const go = await ctx.cli(["lane", "continue", lane.key]);
527
+ say(`lane continue: ${go.ok ? "ok" : go.error?.code ?? "no such verb"}`);
528
+ must(go.ok, "lane continue failed");
529
+ await sleep(2 * SECOND);
530
+ const running = scanLane(ctx.ps(), lane.key, ctx.root);
531
+ say(`after continue: ${describe(running)}`);
532
+ for (const role of Object.keys(found.jobs)) must(running.jobs[role]?.pid === found.jobs[role].pid && !stopped(running.jobs[role]), `${role} does not run again with the same pid`);
533
+ must(running.runtime?.pid === found.runtime.pid && !stopped(running.runtime), "the runtime does not run again with the same pid");
534
+ const stoppedAt = Date.now();
535
+ const stop = await ctx.cli(["lane", "stop", lane.key, "--reason", "drill: stop", "--no-closeout"]);
536
+ say(`lane stop: ${stop.ok ? "ok" : stop.error?.code}`);
537
+ must(stop.ok, "lane stop failed");
538
+ const gone = await until(() => {
539
+ const now = scanLane(ctx.ps(), lane.key, ctx.root);
540
+ return !now.runtime && !now.supervisor && !Object.keys(now.jobs).length ? now : null;
541
+ }, MINUTE, 2 * SECOND);
542
+ say(`after stop: ${describe(scanLane(ctx.ps(), lane.key, ctx.root))}`);
543
+ must(gone, "a process of the stopped lane is still running a minute after lane stop");
544
+ const controlsAfter = scanLane(ctx.ps(), longer.key, ctx.root);
545
+ must(controlsAfter.runtime && Object.keys(controlsAfter.jobs).length === 4, "lane stop ended a process of the lane whose key extends this one's");
546
+ must(ctx.ps().some((row) => row.pid === decoy.pid), "lane stop ended the sibling worktree's process");
547
+ must(controlsBefore.every((row) => ctx.ps().some((now) => now.pid === row.pid)), "lane stop ended a cap keepalive or watchdog process");
548
+ const sweptStopped = await watchdogSince(stoppedAt);
549
+ say(`watchdog after the stop: ${sweptStopped ? `swept the control lane at ${sweptStopped}` : "NO SWEEP"}`);
550
+ must(sweptStopped, "the machine's watchdog did not sweep within 3 minutes of lane stop");
551
+ } finally {
552
+ kill(decoy.pid, "SIGKILL");
553
+ }
554
+ }
555
+
556
+ /** 5. Left alone. */
557
+ async function checkLeftAlone(ctx, say) {
558
+ const { orphanAfterMs } = await settings(ctx);
559
+ const lane = await needStub(ctx, "left-alone", { jobs: ["child", "setsid"] });
560
+ const deadControl = await needStub(ctx, "left-alone-dead", { jobs: [], ending: { afterTicks: 5, code: 0 } });
561
+ const found = await jobsUp(ctx, lane, ["child", "setsid"]);
562
+ must(found, "the left-alone lane's jobs did not start");
563
+ const pause = await ctx.cli(["lane", "pause", lane.key, "--reason", "drill: left alone"]);
564
+ must(pause.ok, `lane pause failed (${pause.error?.code ?? "no such verb"})`);
565
+ const pausedAt = Date.now();
566
+ say(`${lane.key} paused at ${new Date(pausedAt).toISOString()}: ${describe(scanLane(ctx.ps(), lane.key, ctx.root))}; waiting past Dev's orphan limit (${orphanAfterMs / MINUTE} min)`);
567
+ await sleep(orphanAfterMs + 2 * MINUTE);
568
+ const account = await registerStubAccount(ctx, "left-alone");
569
+ must(account.ok, `the left-alone check's stub account could not be registered (${account.code})`);
570
+ const stubAccount = account.profile;
571
+ const tries = [
572
+ ["plain", ["lane", "resume", lane.key]],
573
+ ["ungated", ["lane", "resume", lane.key, "--ungated"]],
574
+ ["named-profile", ["lane", "resume", lane.key, "--profile", stubAccount, "--class", "short"]],
575
+ ["override", ["lane", "resume", lane.key, "--override", "--reason", "drill: override a pause"]],
576
+ ];
577
+ for (const [kind, args] of tries) {
578
+ const result = await ctx.cli(args);
579
+ say(`${kind} resume: ${result.ok ? "ACCEPTED" : `${result.error?.code}: ${String(result.error?.message ?? "").slice(0, 200)}`}`);
580
+ must(!result.ok && result.error?.code === "LANE_PAUSED" && /paused/i.test(result.error?.message ?? ""), `the ${kind} resume was not refused naming the pause`);
581
+ }
582
+ // The machine's own keepalive and watchdog passes, not ones the drill starts: they left the paused lane alone and started the dead one.
583
+ const pass = await until(() => starts(deadControl).length >= 2, 20 * MINUTE, 30 * SECOND);
584
+ say(`${deadControl.key} (dead, unpaused) starts: ${starts(deadControl).length}; ${lane.key} starts: ${starts(lane).length}`);
585
+ must(pass, "no keepalive pass started the unpaused dead stub lane within 20 minutes");
586
+ must(starts(lane).length === 1, "the paused lane was started again");
587
+ const record = await laneRecord(ctx, lane.key);
588
+ must((record?.runs ?? []).filter((run) => run.kind === "lane" && run.status === "running").length === 1 && !(record?.runs ?? []).some((run) => run.livenessState === "orphan" && run.status === "running"),
589
+ "Dev orphaned or replaced the paused lane's run");
590
+ const go = await ctx.cli(["lane", "continue", lane.key]);
591
+ must(go.ok, "lane continue failed");
592
+ await sleep(2 * SECOND);
593
+ const awake = scanLane(ctx.ps(), lane.key, ctx.root);
594
+ say(`after continue: ${describe(awake)}`);
595
+ must(awake.runtime?.pid === found.runtime.pid && !stopped(awake.runtime) && awake.jobs.setsid?.pid === found.jobs.setsid.pid && !stopped(awake.jobs.setsid), "lane continue did not wake the same pids");
596
+ }
597
+
598
+ /** The classifier's answer for one run's final-record facts. */
599
+ async function classify(ctx, facts) {
600
+ return ctx.dev("POST", "/api/v1/run-endings/classify", facts);
601
+ }
602
+
603
+ const finalFacts = (record) => ({
604
+ runtime: record.runtime,
605
+ exitCode: record.exit_code === "" || record.exit_code === null || record.exit_code === undefined ? null : Number(record.exit_code),
606
+ records: [record.last_rate_limit_line ?? record.last_rate_limit_record, record.final_result_line ?? record.final_record, record.codex_final_error_line, ...(record.codex_error_messages ?? [])]
607
+ .filter((line) => typeof line === "string" && line.trim()),
608
+ });
609
+
610
+ /** 6. Named. */
611
+ async function checkNamed(ctx, say) {
612
+ const dir = join(FIXTURES, "o1-final-records");
613
+ must(existsSync(dir), `fixture ${dir} is missing`);
614
+ const wrong = [];
615
+ let total = 0;
616
+ for (const name of readdirSync(dir).filter((file) => file.endsWith(".json")).sort()) {
617
+ const record = JSON.parse(readFileSync(join(dir, name), "utf8"));
618
+ total += 1;
619
+ const answer = await classify(ctx, finalFacts(record));
620
+ if (!answer.ok) { wrong.push(`${record.run_id}: ${answer.code}`); if (wrong.length > 20) break; continue; }
621
+ if (answer.data?.kind !== record.expected_kind) wrong.push(`${record.run_id}: ${answer.data?.kind ?? "none"} != ${record.expected_kind}`);
622
+ }
623
+ say(`final records: ${total - wrong.length} of ${total} given their expected kind${wrong.length ? `; first wrong: ${wrong.slice(0, 5).join("; ")}` : ""}`);
624
+ must(total === 433 && !wrong.length, "Dev's classifier did not give the 433 runs their expected kinds");
625
+ const others = readFileSync(join(FIXTURES, "o1-other-endings.tsv"), "utf8").split("\n").filter(Boolean);
626
+ const head = others.shift().split("\t");
627
+ const named = [];
628
+ for (const line of others) {
629
+ const row = Object.fromEntries(line.split("\t").map((value, index) => [head[index], value]));
630
+ const answer = await classify(ctx, finalFacts(row));
631
+ if (!answer.ok || (answer.data?.kind && answer.data.kind !== "none")) named.push(`${row.run_id}: ${answer.ok ? answer.data.kind : answer.code}`);
632
+ }
633
+ say(`other endings: ${others.length - named.length} of ${others.length} given no account kind${named.length ? `; ${named.slice(0, 5).join("; ")}` : ""}`);
634
+ must(others.length === 50 && !named.length, "Dev's classifier gave a non-account ending an account kind");
635
+ // Replays on the stub: each reaches its run's row as an account death, from output and exit code.
636
+ for (const scenario of REPLAYS) {
637
+ const replay = join(FIXTURES, "o1-replays", scenario);
638
+ if (!existsSync(join(replay, "expected.json"))) { must(false, `replay fixture ${scenario} is missing`); }
639
+ const expected = JSON.parse(readFileSync(join(replay, "expected.json"), "utf8")).expected_row;
640
+ const lane = await needStub(ctx, `named-${scenario}`, { jobs: [] });
641
+ if (scenario === "limit-while-blocked") {
642
+ const blocked = await ctx.cli(["lane", "heartbeat", lane.key, "--note", "BLOCKED: drill replay of a limit while blocked"]);
643
+ must(blocked.ok, `replay ${scenario}: the BLOCKED heartbeat was refused (${blocked.error?.code})`);
644
+ }
645
+ if (scenario === "limit-after-agent-ended") {
646
+ const ended = await ctx.dev("POST", `/api/v1/runs/${encode(lane.runId)}/end`, { status: "done", evidence: [{ kind: "drill", ref: "the agent ended its own run" }] });
647
+ must(ended.ok, `replay ${scenario}: the agent's own run end was refused (${ended.code})`);
648
+ }
649
+ // The log is not the source: a planted line in it must change nothing.
650
+ must(lane.launched?.logPath, `stub lane ${lane.key} reported no run log to plant a line in`);
651
+ await appendFile(lane.launched.logPath, '{"type":"result","is_error":true,"api_error_status":401,"result":"OAuth token has expired"}\n');
652
+ must(await jobsUp(ctx, lane, []), `replay ${scenario}: the stub's runtime did not start`);
653
+ // Unreported: Dev refuses the first exit report. The lane's own config points at a closed port for
654
+ // the ending, then back at Dev: only a report tried again after the first refusal lands.
655
+ const config = scenario === "unreported" ? await readFile(lane.devConfigPath, "utf8") : null;
656
+ if (config) await writeFile(lane.devConfigPath, JSON.stringify({ ...JSON.parse(config), edgeUrl: "http://127.0.0.1:9" }), { mode: 0o600 });
657
+ await writeEnd(lane, { replay });
658
+ await until(() => !scanLane(ctx.ps(), lane.key, ctx.root).runtime, 2 * MINUTE, 2 * SECOND);
659
+ if (config) {
660
+ await sleep(15 * SECOND);
661
+ // The first report did not land: Dev's row has no ending yet.
662
+ const before = await runRecord(ctx, lane.runId);
663
+ must(!before?.ending?.kind, `replay unreported: Dev's row has an ending before the report was tried again (${JSON.stringify(before?.ending)})`);
664
+ await writeFile(lane.devConfigPath, config, { mode: 0o600 });
665
+ say(`replay unreported: the first exit report went to a closed port and Dev's row had no ending 15 s on; Dev's address restored`);
666
+ }
667
+ const row = await until(async () => {
668
+ const run = await runRecord(ctx, lane.runId);
669
+ return run?.ending?.kind ? run : null;
670
+ }, 5 * MINUTE, 15 * SECOND);
671
+ say(`replay ${scenario}: run ${lane.runId} ending ${JSON.stringify(row?.ending ?? null)}`);
672
+ must(row?.ending?.ending === "account_death" && row.ending.kind === expected.kind && (row.ending.statedReset ?? null) === (expected.stated_reset_utc ? new Date(expected.stated_reset_utc).toISOString() : null),
673
+ `replay ${scenario} did not reach its run's row as ${expected.kind} with its stated reset`);
674
+ }
675
+ }
676
+
677
+ /** 7. Not back. */
678
+ async function checkNotBack(ctx, say) {
679
+ const accounts = [];
680
+ for (const name of ["s1", "s2", "s3"]) {
681
+ const account = await registerStubAccount(ctx, `not-back-${name}`, { windows: { fiveHour: { utilization: 10 }, sevenDay: { utilization: 10 } } });
682
+ say(`stub account ${account.profile}: ${account.ok ? `registered ${account.data?.id}` : account.code}`);
683
+ must(account.ok, `stub account ${name} could not be registered (${account.code})`);
684
+ accounts.push(account);
685
+ }
686
+ const [dead, spare, other] = accounts;
687
+ const reading = (account, utilization) => ctx.dev("POST", `/api/v1/runners/${encode(account.data.id)}/usage`, {
688
+ ceiling: "subscription", state: utilization >= 100 ? "exhausted" : "ok", counters: { fiveHour: { utilization }, sevenDay: { utilization } }, observedAt: new Date().toISOString(),
689
+ });
690
+ for (const account of accounts) must((await reading(account, 10)).ok, `a reading for ${account.profile} was refused`);
691
+ const lanesOnDead = [];
692
+ const runsOnDead = async () => {
693
+ let total = 0;
694
+ for (const lane of lanesOnDead) total += ((await laneRecord(ctx, lane.key))?.runs ?? []).filter((run) => run.kind === "lane" && runProfile(run) === dead.profile).length;
695
+ return total;
696
+ };
697
+ const die = async (lane, replay) => {
698
+ await writeEnd(lane, { replay: join(FIXTURES, "o1-replays", replay) });
699
+ must(await until(() => !scanLane(ctx.ps(), lane.key, ctx.root).runtime, 2 * MINUTE, 2 * SECOND), `${lane.key}'s runtime did not end on its replay`);
700
+ };
701
+ // A plain resume leaves the dead account.
702
+ // Long work: only an ok account (check 7's own) admits it, never another check's.
703
+ const plainLane = await needStub(ctx, "not-back-plain", { jobs: [] }, { profile: dead.profile, workClass: "long" });
704
+ lanesOnDead.push(plainLane);
705
+ await die(plainLane, "weekly-limit");
706
+ const diedAt = Date.now();
707
+ await sleep(30 * SECOND);
708
+ const plain = await ctx.cli(["lane", "resume", plainLane.key]);
709
+ const afterPlain = await laneRecord(ctx, plainLane.key);
710
+ say(`plain resume after the death on ${dead.profile}: ${plain.ok ? `started on ${afterPlain?.launch?.profile}` : `${plain.error?.code}: ${String(plain.error?.message).slice(0, 200)}`}`);
711
+ must(plain.ok && [spare.profile, other.profile].includes(afterPlain?.launch?.profile), "a plain resume did not start on another stub account with headroom");
712
+ // A keepalive resume (the machine's own pass) leaves it too.
713
+ const keepLane = await needStub(ctx, "not-back-keepalive", { jobs: [] }, { profile: dead.profile, workClass: "long" });
714
+ lanesOnDead.push(keepLane);
715
+ await die(keepLane, "weekly-limit");
716
+ const kept = await until(async () => {
717
+ const record = await laneRecord(ctx, keepLane.key);
718
+ const started = (record?.runs ?? []).filter((run) => run.kind === "lane" && run.status === "running");
719
+ return started.length ? record : null;
720
+ }, 20 * MINUTE, 30 * SECOND);
721
+ say(`keepalive resume of ${keepLane.key}: ${kept ? `started on ${kept.launch?.profile}` : "no keepalive pass started it within 20 minutes"}`);
722
+ must(kept && [spare.profile, other.profile].includes(kept.launch?.profile), "the machine's keepalive did not resume the lane onto another of check 7's stub accounts");
723
+ // A resume naming the dead account is refused with its next try and stated reset.
724
+ const named = await ctx.cli(["lane", "resume", plainLane.key, "--profile", dead.profile, "--class", "short"]);
725
+ say(`resume naming the dead account: ${named.ok ? "ACCEPTED" : `${named.error?.code}: ${String(named.error?.message).slice(0, 200)}`}`);
726
+ must(!named.ok && /next try/i.test(named.error?.message ?? "") && /reset/i.test(named.error?.message ?? ""), "a resume naming the dead account was not refused naming its next try and stated reset");
727
+ const marked = (await machineAccounts(ctx)).find((account) => account.profile === dead.profile);
728
+ say(`${dead.profile}: ${JSON.stringify(marked?.stop ?? null)}`);
729
+ must(marked?.stop?.kind === "weekly_limit" && marked.stop.statedReset && marked.stop.nextTryAt, "Dev holds no stop mark with its stated reset and next try for the dead account");
730
+ must(Math.abs(Date.parse(marked.stop.nextTryAt) - (diedAt + 60 * MINUTE)) < 2 * MINUTE, "the next try is not an hour after the death (the stated reset is never the wake time)");
731
+ // Headroom clears a usage-limit mark only, within 5 minutes; a 403 mark stays.
732
+ const forbiddenLane = await needStub(ctx, "not-back-403", { jobs: [] }, { profile: other.profile, workClass: "long" });
733
+ await die(forbiddenLane, "subscription-403");
734
+ const limitLane = await needStub(ctx, "not-back-headroom", { jobs: [] }, { profile: spare.profile, workClass: "long" });
735
+ await die(limitLane, "weekly-limit");
736
+ await sleep(30 * SECOND);
737
+ must((await reading(spare, 5)).ok && (await reading(other, 5)).ok, "a reading with headroom was refused");
738
+ const cleared = await until(async () => !(await machineAccounts(ctx)).find((account) => account.profile === spare.profile)?.stop, 5 * MINUTE, 20 * SECOND);
739
+ const forbidden = (await machineAccounts(ctx)).find((account) => account.profile === other.profile);
740
+ say(`headroom: usage-limit mark on ${spare.profile} ${cleared ? "cleared" : "kept"}; 403 mark on ${other.profile} ${JSON.stringify(forbidden?.stop ?? null)}`);
741
+ must(cleared, "a reading with headroom did not clear the usage-limit mark within 5 minutes");
742
+ must(forbidden?.stop?.kind === "subscription_403", "a reading with headroom cleared a 403 mark");
743
+ // The dead account gets nothing for 59 minutes, exactly one try at 60; a working turn clears it.
744
+ const before = await runsOnDead();
745
+ await until(() => Date.now() - diedAt > 59 * MINUTE, 60 * MINUTE, MINUTE);
746
+ const early = (await runsOnDead()) - before;
747
+ await until(() => Date.now() - diedAt > 63 * MINUTE, 5 * MINUTE, 20 * SECOND);
748
+ const tries = (await runsOnDead()) - before - early;
749
+ say(`runs on ${dead.profile} in the 59 minutes after its death: ${early}; tries from 59 to 63 minutes: ${tries}`);
750
+ must(early === 0, "the dead account was given a run within 59 minutes");
751
+ must(tries === 1, `the dead account was not tried exactly once at 60 minutes (${tries})`);
752
+ const clearedByTurn = await until(async () => !(await machineAccounts(ctx)).find((account) => account.profile === dead.profile)?.stop, 3 * MINUTE, 20 * SECOND);
753
+ must(clearedByTurn, "a working turn on the retried account did not clear its stop");
754
+ }
755
+
756
+ /** 8. Headroom. */
757
+ async function checkHeadroom(ctx, say) {
758
+ const probed = await registerStubAccount(ctx, "headroom-s4");
759
+ const lapsed = await registerStubAccount(ctx, "headroom-s5");
760
+ must(probed.ok && lapsed.ok, `a stub account could not be registered (${probed.code ?? lapsed.code})`);
761
+ const account = async (profile) => (await machineAccounts(ctx)).find((row) => row.profile === profile);
762
+ // Only the stub account named is probed: no real account is read.
763
+ const probe = async (profile) => {
764
+ const result = await ctx.cli(["machine", "usage", "report", "--profile", profile, "--probe"]);
765
+ say(`probe ${profile}: ${result.ok ? "ok" : `${result.error?.code}`}`);
766
+ return result;
767
+ };
768
+ await probe(probed.profile);
769
+ const first = await account(probed.profile);
770
+ say(`${probed.profile}: reading ${JSON.stringify(first?.reading ?? null)}`);
771
+ must(first?.reading?.observedAt, "the stub account has no reading after a probe");
772
+ await writeFile(join(probed.profile, "usage.json"), JSON.stringify({ status: 429 }));
773
+ await sleep(2 * SECOND);
774
+ await probe(probed.profile);
775
+ const kept = await account(probed.profile);
776
+ say(`under a 429: reading ${JSON.stringify(kept?.reading ?? null)}, last probe ${JSON.stringify(kept?.lastProbe ?? null)}`);
777
+ must(kept?.reading?.observedAt === first.reading.observedAt && Number.isFinite(kept?.reading?.ageSeconds) && kept?.lastProbe?.status === 429, "under a 429 the account did not keep its last reading with its age");
778
+ await writeFile(join(probed.profile, "usage.json"), JSON.stringify({ windows: { fiveHour: { utilization: 86 }, sevenDay: { utilization: 86 } } }));
779
+ const retry = await probe(probed.profile);
780
+ const fresh = await account(probed.profile);
781
+ must(retry.ok && fresh?.reading?.observedAt && fresh.reading.observedAt !== first.reading.observedAt, "a retry after the 429 did not refresh the reading");
782
+ await writeFile(join(lapsed.profile, "usage.json"), JSON.stringify({ status: "expired" }));
783
+ await probe(lapsed.profile);
784
+ await probe(lapsed.profile);
785
+ const inbox = await ctx.cli(["inbox", "list"]);
786
+ must(inbox.ok, `inbox list failed (${inbox.error?.code})`);
787
+ const items = (inbox.json?.data ?? []).filter((item) => /sign-in needed/i.test(JSON.stringify(item)) && JSON.stringify(item).includes(lapsed.profile));
788
+ const row = await account(lapsed.profile);
789
+ say(`expired sign-in: ${items.length} "sign-in needed" item(s) for ${lapsed.profile}; account ${JSON.stringify({ tries: row?.tries ?? null, signIn: row?.signIn ?? null })}`);
790
+ must(items.length === 1, "an expired sign-in did not make exactly one 'sign-in needed' item in inbox list");
791
+ must(row?.tries === "ended", "an expired sign-in did not end the account's tries");
792
+ // Every Claude account on this machine: a reading under 15 minutes old, that item, or a 429 in ten minutes. Read only.
793
+ const all = (await machineAccounts(ctx)).filter((candidate) => candidate.runtime === "claude");
794
+ const bad = all.filter((candidate) => !((candidate.reading?.ageSeconds ?? Infinity) < 15 * 60 || candidate.signIn === "needed" || (candidate.lastProbe?.status === 429 && Date.now() - Date.parse(candidate.lastProbe.at) < 10 * MINUTE)));
795
+ say(`Claude accounts here: ${all.map((candidate) => `${candidate.profile} age ${candidate.reading?.ageSeconds ?? "none"}s signIn ${candidate.signIn ?? "-"} probe ${candidate.lastProbe?.status ?? "-"}`).join("; ")}`);
796
+ must(all.length && !bad.length, `these Claude accounts have no fresh reading, sign-in item or recent 429: ${bad.map((candidate) => candidate.profile).join(", ")}`);
797
+ }
798
+
799
+ /** 9. Waits. Its own lanes, so no other check races it. */
800
+ async function checkWaits(ctx, say) {
801
+ const names = ["waits-stopped", "waits-replaced", "waits-moved-on", "waits-live"];
802
+ const lanes = [];
803
+ for (const name of names) {
804
+ const lane = await needStub(ctx, name, { jobs: [] });
805
+ const wait = await ctx.cli(["lane", "heartbeat", lane.key, "--note", `WAITING: drill wait of ${name}`, "--waiting-on", `drill-wait-${ctx.runId}-${name}`]);
806
+ must(wait.ok, `${lane.key} could not record its wait (${wait.error?.code})`);
807
+ lanes.push(lane);
808
+ }
809
+ // An escalation each: an unplanned exit orphans the run (lane_escalations).
810
+ for (const lane of lanes.slice(0, 3)) await writeEnd(lane, { code: 3 });
811
+ must(await until(() => lanes.slice(0, 3).every((lane) => !scanLane(ctx.ps(), lane.key, ctx.root).runtime), 2 * MINUTE, 3 * SECOND), "the three lanes' runtimes did not end");
812
+ const escalated = await until(async () => {
813
+ const items = await ctx.cli(["coordinator", "items"]);
814
+ const text = JSON.stringify(items.json ?? "");
815
+ return lanes.slice(0, 3).every((lane) => text.includes(lane.key)) ? items : null;
816
+ }, 3 * MINUTE, 20 * SECOND);
817
+ say(`before: coordinator items ${escalated ? "show" : "do NOT show"} the three lanes' waits and escalations`);
818
+ must(escalated, "the three lanes' waits and escalations never showed, so their expiry cannot be read");
819
+ const replacement = await needStub(ctx, "waits-replacement", { jobs: [] });
820
+ const results = [
821
+ await ctx.cli(["lane", "stop", lanes[0].key, "--reason", "drill: the wait's lane stops", "--no-closeout"]),
822
+ await ctx.cli(["lane", "stop", lanes[1].key, "--launched-in-error", "--replaced-by", replacement.key, "--reason", "drill: replaced", "--no-closeout"]),
823
+ await ctx.cli(["lane", "heartbeat", lanes[2].key, "--note", "drill: moved on, no longer waiting"]),
824
+ ];
825
+ say(`stopped ${results[0].ok ? "ok" : results[0].error?.code}; replaced ${results[1].ok ? "ok" : results[1].error?.code}; newer note ${results[2].ok ? "ok" : results[2].error?.code}`);
826
+ must(results.every((result) => result.ok), "a wait's lane could not be stopped, replaced or moved on");
827
+ await sleep(30 * SECOND);
828
+ const items = await ctx.cli(["coordinator", "items"]);
829
+ const inbox = await ctx.cli(["inbox", "list"]);
830
+ must(items.ok && inbox.ok, "coordinator items or inbox list failed");
831
+ const text = `${JSON.stringify(items.json)}\n${JSON.stringify(inbox.json)}`;
832
+ const stale = lanes.slice(0, 3).filter((lane) => text.includes(lane.key));
833
+ say(`after: stale notices of ${stale.map((lane) => lane.key).join(", ") || "none"}; live wait of ${lanes[3].key} ${text.includes(lanes[3].key) ? "shown" : "MISSING"}`);
834
+ must(!stale.length, "an old notice of an ended, replaced or moved-on lane still shows");
835
+ must(text.includes(lanes[3].key), "the live lane's wait does not show");
836
+ }
837
+
838
+ /** Check 10's two codes, as the red run recorded them: "check 10 codes: SHORT_CODE EXTRA_CODE". */
839
+ export function redRunCodes(text) {
840
+ const match = /check 10 codes: ([A-Z][A-Z0-9_]+) ([A-Z][A-Z0-9_]+)\s*$/m.exec(String(text ?? ""));
841
+ return match ? { short: match[1], extra: match[2] } : null;
842
+ }
843
+
844
+ /** 10. By rule. Its own lane. */
845
+ async function checkByRule(ctx, say) {
846
+ const redPath = join(FIXTURES, "o1-red-run.txt");
847
+ must(existsSync(redPath), `fixture ${redPath} is missing: check 10's two codes come from the red run`);
848
+ const codes = redRunCodes(readFileSync(redPath, "utf8"));
849
+ must(codes, "o1-red-run.txt names no 'check 10 codes: SHORT_CODE EXTRA_CODE' line");
850
+ say(`check 10's codes from the red run: short resume ${codes.short}, extra time ${codes.extra}`);
851
+ const lane = await needStub(ctx, "by-rule", { jobs: [] });
852
+ const record = await laneRecord(ctx, lane.key);
853
+ const fact = await ctx.cli(["lane", "amend", lane.key, "--rules", `fact: lane ${lane.key} is ${record?.status ?? "building"}`, "--reason", "drill: a fact Dev holds"]);
854
+ const factState = JSON.stringify(fact.json?.data?.state ?? fact.json?.data?.status ?? null);
855
+ say(`fact amendment: ${fact.ok ? `applied (${factState})` : fact.error?.code}`);
856
+ must(fact.ok && !/pending/i.test(factState), "a fact amendment matching Dev's record did not arrive without approval or step-up");
857
+ await writeEnd(lane, { code: 4 });
858
+ must(await until(() => !scanLane(ctx.ps(), lane.key, ctx.root).runtime, 2 * MINUTE, 3 * SECOND), "the by-rule lane's runtime did not end");
859
+ await sleep(20 * SECOND);
860
+ const short = await ctx.cli(["lane", "resume", lane.key, "--class", "short"]);
861
+ say(`short resume: ${short.ok ? `accepted (refused ${codes.short} before the fix)` : `refused ${short.error?.code}`}`);
862
+ must(short.ok, `a short-class resume was refused (${short.error?.code}); refused ${codes.short} today, it is accepted after the fix`);
863
+ const extra = await ctx.cli(["lane", "leeway", lane.key, "--reason", "extra time: 30 minutes"]);
864
+ const extraState = JSON.stringify(extra.json?.data?.state ?? null);
865
+ say(`extra time: ${extra.ok ? `accepted ${extraState} (refused ${codes.extra} before the fix)` : `refused ${extra.error?.code}`}`);
866
+ must(extra.ok && /granted/i.test(extraState), `an ask for extra time was not granted by rule (${extra.error?.code ?? extraState}); refused ${codes.extra} today`);
867
+ const scope = await ctx.cli(["lane", "amend", lane.key, "--scope", "drill: a scope change waits for a person", "--reason", "drill control"]);
868
+ const scopeState = JSON.stringify(scope.json?.data?.state ?? scope.json?.data?.status ?? null);
869
+ say(`scope amendment (control): ${scope.ok ? scopeState : scope.error?.code}`);
870
+ must(scope.ok && /pending/i.test(scopeState), "a scope amendment did not wait for a person");
871
+ }
872
+
873
+ /** 11. Codes. Its own lane and its own pending amendment. */
874
+ async function checkCodes(ctx, say) {
875
+ // The edge is Dev's on dev: refused up front in drillContext otherwise.
876
+ say(`edge ${ctx.edgeUrl}; Dev's edge is ${DEV_EDGE}`);
877
+ const spec = await ctx.dev("GET", "/api/v1/openapi.json");
878
+ must(spec.ok && spec.data?.paths, `Dev's routes could not be read (${spec.code})`);
879
+ const needing = [];
880
+ for (const [path, methods] of Object.entries(spec.data.paths))
881
+ for (const [method, operation] of Object.entries(methods ?? {}))
882
+ if (operation?.["x-operator-code"] || /step-up|operator code|TOTP/i.test(`${operation?.summary ?? ""} ${operation?.description ?? ""}`)) needing.push(`${method.toUpperCase()} ${path}`);
883
+ const list = await ctx.dev("GET", "/api/v1/operator/code-acts");
884
+ must(list.ok && Array.isArray(list.data), `Dev's keep-or-drop list could not be read (${list.code})`);
885
+ const listed = new Set(list.data.map((row) => `${String(row.method).toUpperCase()} ${row.path}`));
886
+ const missing = needing.filter((act) => !listed.has(act));
887
+ say(`acts asking for a code in Dev's routes: ${needing.length}; on the keep-or-drop list: ${listed.size}; missing: ${missing.slice(0, 10).join(", ") || "none"}`);
888
+ must(needing.length > 0 && !missing.length, "the keep-or-drop list does not hold every act that asks for a code");
889
+ const lane = await needStub(ctx, "codes", { jobs: [] });
890
+ const scope = await ctx.cli(["lane", "amend", lane.key, "--scope", "drill: an amendment only the operator approves", "--reason", "drill: check 11"]);
891
+ const requestId = scope.json?.data?.requestId ?? scope.json?.data?.id ?? null;
892
+ must(scope.ok && requestId, `check 11 could not make its own pending amendment (${scope.error?.code})`);
893
+ const approve = await ctx.cli(["lane", "amendments", "approve", requestId]);
894
+ say(`approving amendment ${requestId} on ${lane.key} with no code: ${approve.ok ? "ACCEPTED" : approve.error?.code}`);
895
+ must(!approve.ok && approve.error?.code === "AMENDMENT_OPERATOR_REQUIRED", `an operator-only act on a stub lane was not refused AMENDMENT_OPERATOR_REQUIRED (${approve.error?.code ?? "accepted"})`);
896
+ // "No Prod route is called" is read once every check and the cleanup are done (routesCalled).
897
+ }
898
+
899
+ /**
900
+ * Check 11's last part, read after every check and the cleanup: every route
901
+ * the drill called, and every route any process it started called (the CLI
902
+ * commands, the supervisor, the stub and its jobs record through the
903
+ * preloaded recorder), went to Dev's edge or auth, and none is a Prod or
904
+ * release route.
905
+ */
906
+ export function routesCalled(ctx, say) {
907
+ const edgeHost = new URL(DEV_EDGE).host;
908
+ const authHost = ctx.authUrl ? new URL(ctx.authUrl).host : null;
909
+ const recorded = recordedRoutes(ctx);
910
+ const routes = [...ctx.calls.filter((call) => /^[A-Z]+ \//.test(call)).map((call) => call.replace(" /", ` ${edgeHost}/`)), ...recorded];
911
+ const foreign = routes.filter((route) => { const host = route.split(" ")[1]?.split("/")[0]; return host !== edgeHost && host !== authHost; });
912
+ const prod = routes.filter((route) => PROD_ROUTE.test(route));
913
+ say(`routes called over the whole run (the drill's ${routes.length - recorded.length} and its processes' ${recorded.length}): other hosts: ${[...new Set(foreign)].slice(0, 5).join(", ") || "none"}; Prod or release routes: ${prod.join(", ") || "none"}`);
914
+ must(recorded.length > 0, "no route of a process the drill started was recorded, so none could be inspected");
915
+ must(!foreign.length && !prod.length, "the drill called a host other than Dev's edge, or a Prod or release route");
916
+ }
917
+
918
+ /** 12. Publish, headless. */
919
+ async function checkPublish(ctx, say) {
920
+ const fixture = join(ctx.fixtures ?? FIXTURES, "o1-figma-fixture.txt");
921
+ must(existsSync(fixture), `fixture ${fixture} is missing`);
922
+ const lines = readFileSync(fixture, "utf8").split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
923
+ const fileKey = /^key:\s*(\S+)/i.exec(lines.find((line) => /^key:/i.test(line)) ?? "")?.[1];
924
+ const unpublished = lines.filter((line) => /^unpublished:/i.test(line)).map((line) => line.replace(/^unpublished:\s*/i, "").split(/\s+/)[0]);
925
+ must(fileKey && unpublished.length, "the Figma fixture names no file key or no unpublished component");
926
+ // The fixture is a scratch library: never the design system or any file Dev tracks (a lane may hold it).
927
+ // Only Dev's own answer that it does not know the file passes; any other answer (an error included) refuses.
928
+ const tracked = await ctx.dev("GET", `/api/v1/design/files/${encode(fileKey)}`);
929
+ must(!tracked.ok, `the Figma fixture ${fileKey} is a file Dev tracks; the dry run touches only a scratch library`);
930
+ must(tracked.code === "DESIGN_FILE_NOT_FOUND", `the Figma fixture ${fileKey} is not confirmed untracked: Dev answered ${tracked.code ?? "nothing"}, not DESIGN_FILE_NOT_FOUND`);
931
+ // The shared Chrome seat is the one the check is about (headless, shared).
932
+ // It is held for the dry run: the coordinator's own publish-watch job is
933
+ // paused by its hold file, so no publish runs in that seat meanwhile.
934
+ const hold = join(ctx.coordinatorHome ?? coordinatorHome(), "hold-publish-watch");
935
+ // A hold already there means someone else has the seat: refuse, and leave their hold alone.
936
+ must(!existsSync(hold), `publish-watch is already held (${hold}); the shared Chrome seat may be in use, so the dry run does not start`);
937
+ await writeFile(hold, `drill ${ctx.runId}: check 12's dry run holds the shared Chrome seat\n`, { flag: "wx" });
938
+ const before = recordedRoutes(ctx).length;
939
+ let result;
940
+ try {
941
+ result = await ctx.cli(["figma", "publish", fileKey, "--dry-run"], { timeoutMs: 10 * MINUTE });
942
+ } finally {
943
+ await rm(hold, { force: true });
944
+ }
945
+ const rows = (result.json?.data?.rows ?? result.json?.data?.ticked ?? []).map((row) => (typeof row === "string" ? row : row.key ?? row.id ?? row.name));
946
+ say(`figma publish --dry-run ${fileKey}: exit ${result.code}; listed ${rows.join(", ") || "nothing"}`);
947
+ must(result.code === 0, `figma publish --dry-run exited ${result.code} (${result.error?.code ?? result.text.slice(0, 200)})`);
948
+ must(rows.length === unpublished.length && unpublished.every((key) => rows.includes(key)), "the dry run did not list exactly the fixture's unpublished components");
949
+ const published = recordedRoutes(ctx).slice(before).filter((route) => /\/published\b|\/publish\b|api\.figma\.com\/v1\/files\/[^/]+\/(?:versions|publish)/.test(route) && /^(POST|PUT|PATCH)/.test(route));
950
+ say(`write routes during the dry run: ${published.join(", ") || "none"}`);
951
+ must(!published.length && result.json?.data?.published === false, "the dry run published or recorded a publish");
952
+ const chrome = ctx.ps().filter((row) => /Google Chrome|Chromium/.test(row.command) && row.command.includes(join(".config", "nodii-dev", "chrome")) && !/--type=/.test(row.command));
953
+ say(`shared Chrome: ${chrome.map((row) => `${row.pid}${/--headless/.test(row.command) ? " headless" : " WITH A WINDOW"}`).join(", ") || "not running"}`);
954
+ must(chrome.length && chrome.every((row) => /--headless/.test(row.command)), "the dry run did not run in the headless shared Chrome");
955
+ }
956
+
957
+ export { checkPublish };
958
+
959
+ export const CHECKS = [
960
+ [1, "Bounds", checkBounds],
961
+ [2, "Dead", checkDead],
962
+ [3, "Stopped", checkStopped],
963
+ [4, "Paused, then stopped", checkPaused],
964
+ [5, "Left alone", checkLeftAlone],
965
+ [6, "Named", checkNamed],
966
+ [7, "Not back", checkNotBack],
967
+ [8, "Headroom", checkHeadroom],
968
+ [9, "Waits", checkWaits],
969
+ [10, "By rule", checkByRule],
970
+ [11, "Codes", checkCodes],
971
+ [12, "Publish", checkPublish],
972
+ ];
973
+
974
+ /**
975
+ * The processes this drill run left, by its run id alone: a stub runtime (its
976
+ * script sits in the run's folder), a supervisor or job naming one of its lane
977
+ * keys (drill-<run>-...), and check 4's decoy. Never the drill itself.
978
+ */
979
+ export function runProcesses(rows, ctx, self = process.pid) {
980
+ const keyPrefix = `drill-${ctx.runId}-`;
981
+ return rows.filter((row) => row.pid !== self && (
982
+ row.command.includes(keyPrefix) || row.command.includes(`${ctx.root}/`) || row.command.includes(`nodii-drill-decoy ${ctx.runId}`)));
983
+ }
984
+
985
+ /**
986
+ * Stop every stub lane the drill started, end every process of the run, take
987
+ * the coordinator-config copies out of agents/ and set the stub accounts
988
+ * offline. It runs on every exit: a pass, a failure, a crash, the budget
989
+ * running out, and SIGINT or SIGTERM. Each step goes on when one fails.
990
+ */
991
+ async function cleanup(ctx, say) {
992
+ for (const lane of ctx.lanes) {
993
+ try {
994
+ if (lane.registered?.ok) {
995
+ const record = await laneRecord(ctx, lane.key);
996
+ if (record?.paused) await ctx.cli(["lane", "continue", lane.key]);
997
+ if (record && !["stopped", "on_dev", "non_issue"].includes(record.status))
998
+ await ctx.cli(["lane", "stop", lane.key, "--reason", "drill: cleanup", "--no-closeout"]);
999
+ }
1000
+ } catch (error) {
1001
+ say(`cleanup: lane ${lane.key} could not be stopped in Dev (${error?.message ?? error})`);
1002
+ }
1003
+ await rm(lane.devConfigPath, { force: true }).catch(() => {});
1004
+ }
1005
+ // Last, whatever of the run still runs, stopped ones woken first so SIGKILL lands.
1006
+ const left = runProcesses(ctx.ps(), ctx);
1007
+ for (const row of left) { kill(row.pid, "SIGCONT"); kill(row.pid, "SIGKILL"); }
1008
+ if (left.length) say(`cleanup: ended ${left.length} process(es) of the run: ${left.map((row) => row.pid).join(", ")}`);
1009
+ // The drill's stub accounts go offline, so no later placement reads them.
1010
+ let offline = 0;
1011
+ for (const profile of ctx.accounts ?? []) {
1012
+ const result = await ctx.dev("POST", "/api/v1/runners", { kind: "account", machineId: ctx.machineId, runtime: "stub", profile, status: "offline" });
1013
+ if (result.ok) offline += 1;
1014
+ else say(`cleanup: stub account ${profile} could not be set offline (${result.code})`);
1015
+ }
1016
+ say(`cleanup: ${ctx.lanes.length} stub lane(s) stopped and their processes ended; ${offline} of ${(ctx.accounts ?? []).length} stub account(s) offline; files kept in ${ctx.root}`);
1017
+ }
1018
+
1019
+ /**
1020
+ * Run every check at once (each on its own stub lanes), print what each read,
1021
+ * and fail unless all hold. Checks that wait on Dev's orphan limit run beside
1022
+ * the rest, so the drill takes about as long as its slowest check.
1023
+ */
1024
+ export async function drillLanesCommand({ context = drillContext, checks = CHECKS, out = (line) => process.stdout.write(`${line}\n`), budgetMs = DRILL_BUDGET_MS, signals = process, exit = (code) => process.exit(code) } = {}) {
1025
+ const ctx = await context();
1026
+ out(`nodii-dev harness drill lanes: run ${ctx.runId} as coordinator ${ctx.agentId} on ${ctx.machineName ?? ctx.machineId}, edge ${ctx.edgeUrl}; files in ${ctx.root}; fixtures ${FIXTURES}`);
1027
+ const controllers = checks.map(() => new AbortController());
1028
+ let cleaned = null;
1029
+ const cleanOnce = () => (cleaned ??= cleanup(ctx, (line) => out(line)).catch((error) => out(`cleanup failed: ${error?.message ?? error}`)));
1030
+ // Interrupted: stop every check, clean up, and exit as the signal asks.
1031
+ const interrupted = (signal) => {
1032
+ out(`drill interrupted by ${signal}: stopping every check and cleaning up`);
1033
+ for (const controller of controllers) controller.abort();
1034
+ cleanOnce().finally(() => exit(signal === "SIGINT" ? 130 : 143));
1035
+ };
1036
+ const onInt = () => interrupted("SIGINT");
1037
+ const onTerm = () => interrupted("SIGTERM");
1038
+ signals.once?.("SIGINT", onInt);
1039
+ signals.once?.("SIGTERM", onTerm);
1040
+ let results;
1041
+ try {
1042
+ results = await Promise.all(checks.map(async ([id, name, run], index) => {
1043
+ const lines = [];
1044
+ const say = (line) => { lines.push(line); out(`[${id} ${name}] ${line}`); };
1045
+ const controller = controllers[index];
1046
+ let timer;
1047
+ // Its time up, the check is stopped, not left running past the cleanup.
1048
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => { controller.abort(); resolve(new Failed(`did not finish within ${budgetMs / MINUTE} minutes`)); }, budgetMs); });
1049
+ const outcome = await Promise.race([running.run({ signal: controller.signal }, () => run(ctx, say)).then(() => null, (error) => error), timeout]);
1050
+ clearTimeout(timer);
1051
+ const pass = outcome === null;
1052
+ const reason = pass ? null : outcome instanceof Failed || outcome instanceof Aborted ? outcome.message : `${outcome?.code ?? "ERROR"}: ${outcome?.message ?? outcome}`;
1053
+ out(`[${id} ${name}] ${pass ? "PASS" : `FAIL: ${reason}`}`);
1054
+ return { id, name, pass, reason, lines };
1055
+ }));
1056
+ } finally {
1057
+ for (const controller of controllers) controller.abort();
1058
+ await cleanOnce();
1059
+ signals.removeListener?.("SIGINT", onInt);
1060
+ signals.removeListener?.("SIGTERM", onTerm);
1061
+ }
1062
+ // Check 11's route scan covers the whole run, so it is read last.
1063
+ const codes = results.find((result) => result.id === 11);
1064
+ if (codes) {
1065
+ const say = (line) => { codes.lines.push(line); out(`[11 ${codes.name}] ${line}`); };
1066
+ try { routesCalled(ctx, say); }
1067
+ catch (error) {
1068
+ const reason = error instanceof Failed ? error.message : `${error?.code ?? "ERROR"}: ${error?.message ?? error}`;
1069
+ codes.pass = false;
1070
+ codes.reason = codes.reason ? `${codes.reason}; ${reason}` : reason;
1071
+ }
1072
+ out(`[11 ${codes.name}] over the whole run: ${codes.pass ? "PASS" : `FAIL: ${codes.reason}`}`);
1073
+ }
1074
+ const failed = results.filter((result) => !result.pass);
1075
+ out(`${results.length - failed.length} of ${results.length} checks hold.${failed.length ? ` Failing: ${failed.map((result) => result.id).join(", ")}.` : ""}`);
1076
+ return {
1077
+ payload: { data: { runId: ctx.runId, root: ctx.root, checks: results, calls: ctx.calls } },
1078
+ human: "",
1079
+ exitCode: failed.length ? 1 : 0,
1080
+ };
1081
+ }