@nodii/dev 0.6.209 → 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/README.md CHANGED
@@ -945,6 +945,7 @@ nodii-dev docs parked [CODE] [--status pending|acknowledged]
945
945
  nodii-dev harness install [--include-drafts] [--adopt PATH,...] [--dry-run] [--system]
946
946
  nodii-dev harness update [--include-drafts] [--adopt PATH,...] [--dry-run] [--system]
947
947
  nodii-dev harness check [--json] # 0 current, 1 differs from Dev, 2 no harness
948
+ nodii-dev harness drill lanes # DEV-PROCESS-1's done check, Part A: see "The lane drill"
948
949
  nodii-dev repo policy [--json] # print this repository's nodii.repo.yaml facts (STD-11)
949
950
  nodii-dev repo lint [--json] # 0 clean, 1 findings
950
951
  nodii-dev repo docs-check [--base REF] [--json] # 0 clean or not checked, 1 TOOLING_DOCS_STALE (docs move with tooling)
@@ -955,6 +956,61 @@ nodii-dev watchdog install [--interval SECONDS] # macOS: com.nodii.watchdog in ~
955
956
  nodii-dev watchdog sweep # the job's entrypoint; normally not run by hand
956
957
  ```
957
958
 
959
+ ### The lane drill: `harness drill lanes` (DEV-PROCESS-1)
960
+
961
+ `nodii-dev harness drill lanes` is the frozen done check of DEV-PROCESS-1,
962
+ Part A. The machine's coordinator runs it, under its own config, from the
963
+ installed release. It is never run by the lane that built it. It runs for
964
+ about an hour, with no model and no typed code, and exits 1 unless checks
965
+ 1 to 12 all hold. It prints every pid, run id and Dev record it reads.
966
+
967
+ - **Stub lanes.** The drill starts scratch lanes on the `stub` runtime
968
+ (`src/drill-stub.js`). Dev admits them under ruling A: no override, outside
969
+ the lane cap, and no repository, real account, Figma file or change set
970
+ (`STUB_LANE_BOUNDS`). A stub follows a JSON script given with
971
+ `--script PATH`:
972
+ - its jobs (a child, a nohup, a setsid and a heavy-slot job, each naming the
973
+ lane's key);
974
+ - its ticks and the tokens each tick reports;
975
+ - its `steps` (`[{afterTicks, sh}]`), each run once by `/bin/sh -c`;
976
+ - a silence (`silentAfterTicks`);
977
+ - a scripted or replayed ending, written verbatim. The stub classifies
978
+ nothing.
979
+ - **Finding processes.** The drill finds a lane's processes by scanning `ps`
980
+ for the lane's key, never from a list of its own.
981
+ - **Stub accounts** are drill folders registered as `stub` account runners.
982
+ The account reader reads a stub account's `usage.json`: a reading, a 429,
983
+ or an expired sign-in. No real account is read or written. Cleanup sets the
984
+ stub accounts offline.
985
+ - **Recorded routes.** Every process the drill starts preloads a route
986
+ recorder (`NODE_OPTIONS` for Node, `BUN_OPTIONS` for Bun) that logs method,
987
+ host and path only. Check 11 reads the whole run's routes after every check
988
+ and the cleanup.
989
+ - **Fixtures** are the planner's, frozen under
990
+ `~/Projects/_handoff/dev-process-2026-11-23/evidence/o1/`. A missing fixture
991
+ fails the check that needs it. Check 10 reads the red run's line
992
+ `check 10 codes: SHORT_CODE EXTRA_CODE` from `o1-red-run.txt`.
993
+ - **Scratch files** go under `~/.nodii/drill/<run>/` and are kept.
994
+ - **Up front and on every exit.** A config whose edge is not dev Dev's is
995
+ refused before anything starts. Cleanup runs on every exit (a pass, a
996
+ failure, a crash, a check's time running out, SIGINT or SIGTERM). It stops
997
+ the run's stub lanes in Dev, ends every process carrying the run's id,
998
+ removes the coordinator-config copies from `agents/` and sets the stub
999
+ accounts offline. A check whose time is up is stopped: it starts no further
1000
+ lane or command.
1001
+ - **No credentials.** The stub and its steps run with every credential-shaped
1002
+ variable removed (GitHub, AWS, Figma, npm, Claude, Codex, and any token,
1003
+ secret, password or key). A stub account must be a folder under
1004
+ `~/.nodii/drill/`.
1005
+ - **The Publish check** dry-runs only a scratch library: a fixture file that Dev
1006
+ tracks is refused, and it passes only on Dev's own `DESIGN_FILE_NOT_FOUND`
1007
+ answer (any other answer refuses). During its dry run it holds the
1008
+ coordinator's publish-watch job (`hold-publish-watch`), so no publish shares
1009
+ the shared Chrome seat at the same time; a hold already there refuses.
1010
+
1011
+ Changing an assertion, a control, a fixture or the drill's files needs a
1012
+ person's word (DEV-PROCESS-1, Done check).
1013
+
958
1014
  ### Structured dev checks
959
1015
 
960
1016
  `lane verify --checks FILE` sends what you read on dev. FILE is a JSON array, one entry per service and kind. Dev decides each result from the evidence and stores it, failed ones too. `lane show` lists them as `devChecks`.
package/dist/accounts.js CHANGED
@@ -304,7 +304,23 @@ export async function pickHeadroomAccount({ runtime, from, exclude = [], workCla
304
304
  return results.find((result) => !result.error && (ADMITS[workClass] ?? ADMITS.long).includes(result.band)) ?? null;
305
305
  }
306
306
 
307
- const READERS = { claude: readClaudeUsage, codex: readCodexUsage };
307
+ /**
308
+ * DEV-PROCESS-1 item 8: a stub account's reading, from its drill folder's
309
+ * usage.json, which the drill writes: {windows} is a reading, {status: 429}
310
+ * the usage endpoint refusing, {status: "expired"} a lapsed sign-in. No token
311
+ * and no network: a stub account is never a real one.
312
+ */
313
+ export async function readStubUsage(profile, { read = readFile, now = () => new Date() } = {}) {
314
+ let usage;
315
+ try { usage = JSON.parse(await read(join(profile, "usage.json"), "utf8")); }
316
+ catch { throw new CliError("ACCOUNT_USAGE_UNAVAILABLE", `The stub account ${profile} has no readable usage.json.`, 1); }
317
+ if (usage?.status === "expired") throw new CliError("ACCOUNT_TOKEN_EXPIRED", `The stub account ${profile}'s sign-in has expired.`, 1);
318
+ if (Number.isInteger(usage?.status)) throw new CliError("ACCOUNT_USAGE_UNAVAILABLE", `The stub account ${profile}'s usage endpoint answered ${usage.status}.`, 1, { httpStatus: usage.status });
319
+ const window = (value) => (value && typeof value.utilization === "number" ? { utilization: value.utilization, resetsAt: value.resetsAt ?? null } : null);
320
+ return { source: "stub-usage-file", measuredAt: now().toISOString(), windows: { fiveHour: window(usage?.windows?.fiveHour), sevenDay: window(usage?.windows?.sevenDay) } };
321
+ }
322
+
323
+ const READERS = { claude: readClaudeUsage, codex: readCodexUsage, stub: readStubUsage };
308
324
 
309
325
  /** The usage ceiling body Dev stores for one reading. */
310
326
  export function usageReport(reading) {
package/dist/cli.js CHANGED
@@ -344,6 +344,10 @@ Usage: nodii-dev <command> [options] [--json]
344
344
  harness install|update [--include-drafts[=false]] [--adopt PATH,...] [--dry-run] [--system]
345
345
  # --system stages managed hooks and only prints operator-reviewed sudo commands
346
346
  harness check # 0 current, 1 differs from Dev, 2 not installed
347
+ harness drill lanes # DEV-PROCESS-1 done check, Part A: about an hour of scratch lanes on the
348
+ # stub runtime (no model, no account), run by the machine's coordinator;
349
+ # prints every pid, run id and Dev record it read; exit 1 unless checks
350
+ # 1 to 12 all hold. Its fixtures are the planner's (frozen)
347
351
  harness update --check # the same check
348
352
  harness week # the weekly page (O3 item 4, MW5-8.1): run-hours that pushed nothing by
349
353
  # ending class with tokens, unknown and claimed waits, top refusals, hours
@@ -1292,6 +1296,12 @@ export async function main(argv = process.argv.slice(2)) {
1292
1296
  }
1293
1297
  // O3 item 4 (MW5-8.1, DEC-0569): the weekly page, read from Dev and printed for a non-builder.
1294
1298
  if (command === "harness" && action === "week") return emitCommand(await harnessWeekCommand(rest, f));
1299
+ if (command === "harness" && action === "drill") {
1300
+ // DEV-PROCESS-1: the frozen done check's Part A. `lanes` is its one drill.
1301
+ if (rest.length !== 1 || rest[0] !== "lanes") throw new CliError("USAGE", "harness drill lanes takes no other arguments.", 2);
1302
+ const { drillLanesCommand } = await import("./drill.js");
1303
+ return emitCommand(await drillLanesCommand());
1304
+ }
1295
1305
  if (command === "harness" && ["install", "update", "check"].includes(action)) {
1296
1306
  // `--include-drafts` is a switch: `--include-drafts false` would leave `false` here and turn drafts on.
1297
1307
  if (rest.length) throw new CliError("USAGE", `harness ${action} takes no arguments, got: ${rest.join(" ")}. Write a flag value as --include-drafts=false.`, 2);
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/pr
4
4
  import { homedir, platform } from "node:os";
5
5
  import { basename, dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.209";
7
+ export const VERSION = "0.6.210";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -0,0 +1,213 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DEV-PROCESS-1 must-item 1: the drill's stub runtime. A stub lane runs this
4
+ * in place of `claude`, so a drill uses no model and no account, whoever
5
+ * resumes its lane. O3 reuses it.
6
+ *
7
+ * drill-stub.js --script PATH [--resume SESSION_ID]
8
+ *
9
+ * It behaves as a lane runtime does where the harness can see it: it reads
10
+ * its prompt on stdin, prints Claude's stream-json records (a session id, an
11
+ * assistant turn with its token counts every tick, a final result), and starts
12
+ * the processes a real lane starts:
13
+ *
14
+ * child a plain child process
15
+ * nohup a `nohup` job, which ignores SIGHUP
16
+ * setsid a job in its own session and process group (what `setsid` does)
17
+ * heavy a job run through `nodii-dev heavy run --size light`, with the
18
+ * drill's own slot directory and limits file, never the machine's
19
+ *
20
+ * Each job's argv ends `nodii-drill-job <lane key> <role>`, so a scan of `ps`
21
+ * for the lane's key finds it without any list the stub keeps. Each writes its
22
+ * pid to <dir>/<role>.pid and a tick to <dir>/<role>.ticks every second.
23
+ *
24
+ * The script (JSON) says what this run does; every field may be left out:
25
+ *
26
+ * dir where pids, ticks and the end file live (default: the script's
27
+ * folder, then the lane key)
28
+ * jobs the roles to start (default: all four)
29
+ * cli the nodii-dev the heavy job runs (default: nodii-dev on PATH)
30
+ * tokens {"input": N, "output": N}: the usage each assistant tick reports
31
+ * silentAfterTicks N: after N ticks it writes nothing more and stays
32
+ * alive, as a hung runtime does (its jobs keep running)
33
+ * steps [{"afterTicks": N, "sh": "..."}]: at tick N each runs once, in
34
+ * order, as `/bin/sh -c sh` in the stub's cwd with STUB_SCRIPT_DIR
35
+ * set to the script's folder; its stdout and stderr go to the
36
+ * stub's stdout, then a line gives its exit code. The next tick
37
+ * waits for it; it never changes the ending.
38
+ * ending how the turn ends when no end file comes first:
39
+ * {"afterTicks": N, "code": C, "result": {...}}: a result record
40
+ * with these fields (is_error, api_error_status, terminal_reason,
41
+ * rate-limit status and reset), then exit C;
42
+ * {"afterTicks": N, "replay": "DIR"}: a recorded ending, printed as
43
+ * it was: DIR/stdout.jsonl line by line, then exit DIR/exit_code
44
+ * (an exit code of 128 + a signal ends it by that signal).
45
+ *
46
+ * --account PROFILE names the stub account the lane runs on (a drill folder,
47
+ * never a real profile); it appears in the init record and nowhere else.
48
+ *
49
+ * <dir>/end.json, written by the drill, ends the turn at once with the same
50
+ * fields as `ending`.
51
+ *
52
+ * Its jobs are left running when it ends, as a real runtime's background
53
+ * jobs are: stopping them is the harness's job, and the drill checks it.
54
+ */
55
+ import { spawn } from "node:child_process";
56
+ import { randomUUID } from "node:crypto";
57
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
58
+ import { dirname, isAbsolute, join, resolve } from "node:path";
59
+ import { setTimeout as delay } from "node:timers/promises";
60
+ import { fileURLToPath } from "node:url";
61
+
62
+ const TICK_MS = 1000;
63
+
64
+ /**
65
+ * A credential-shaped variable: a token, secret, password, key or PAT, and
66
+ * every GitHub, AWS, Figma, Anthropic, OpenAI, Claude, Codex, npm or Docker
67
+ * variable. The stub and its steps run without them: a step is a script's
68
+ * shell command, and a stub uses no account or service but Dev, which it
69
+ * reaches through its config file (NODII_DEV_CONFIG_PATH).
70
+ */
71
+ const CREDENTIAL = /(?:TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|API_?KEY|PRIVATE_?KEY|_PAT|AUTH)$|^(?:AWS_|GH_|GITHUB_|FIGMA|ANTHROPIC_|OPENAI_|CLAUDE_|CODEX_|NPM_|DOCKER_|GOOGLE_APPLICATION)/i;
72
+ export const stubEnv = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => !CREDENTIAL.test(name)));
73
+ export const ROLES = ["child", "nohup", "setsid", "heavy"];
74
+
75
+ /** The command line that runs one job: a loop that writes its pid and ticks. */
76
+ export function jobScript(dir, role) {
77
+ const pid = JSON.stringify(join(dir, `${role}.pid`));
78
+ const ticks = JSON.stringify(join(dir, `${role}.ticks`));
79
+ return `require("fs").writeFileSync(${pid}, process.pid + "\\n"); setInterval(() => require("fs").appendFileSync(${ticks}, Date.now() + "\\n"), ${TICK_MS});`;
80
+ }
81
+
82
+ /** How each job is started: the command, its arguments and its spawn options. */
83
+ export function jobSpawn(role, dir, { laneKey, cwd, env = process.env, node = process.execPath, cli = "nodii-dev" }) {
84
+ // The lane key and the role stand in the job's own argv, so `ps` names whose job it is.
85
+ const script = ["-e", jobScript(dir, role), "nodii-drill-job", laneKey, role];
86
+ const base = { cwd, env, stdio: "ignore" };
87
+ if (role === "child") return { command: node, args: script, options: base };
88
+ if (role === "nohup") return { command: "nohup", args: [node, ...script], options: base };
89
+ // Node's detached spawn calls setsid(2): the job leads a new session, out of the runtime's process group.
90
+ if (role === "setsid") return { command: node, args: script, options: { ...base, detached: true } };
91
+ if (role === "heavy") return {
92
+ command: cli,
93
+ args: ["heavy", "run", "--size", "light", "--", node, ...script],
94
+ options: { ...base, env: { ...env, HEAVY_SLOT_DIR: join(dir, "heavy-slots"), NODII_RESOURCE_LIMITS: join(dir, "limits.env"), HEAVY_SLOT_POLL_SEC: "1" } },
95
+ };
96
+ throw new Error(`unknown drill job ${role}`);
97
+ }
98
+
99
+ /** The drill's limits file: light slots that admit at once, so the heavy job never waits on this machine's queue. */
100
+ export const DRILL_LIMITS = "HEAVY_SLOTS=4\nHEAVY_MIN_AVAIL_GB=0\nHEAVY_STAGGER_SEC=0\nHEAVY_LANDING_RESERVE=0\nHEAVY_RECLAIM_MIN=0\nLIGHT_SLOTS=4\nLIGHT_MIN_AVAIL_GB=0\n";
101
+
102
+ /** The script's settings, with every default filled in. */
103
+ export function readScript(path, laneKey) {
104
+ if (typeof path !== "string" || !isAbsolute(path)) throw new Error("drill-stub needs --script with an absolute path");
105
+ const script = JSON.parse(readFileSync(path, "utf8"));
106
+ const jobs = Array.isArray(script.jobs) ? script.jobs : ROLES;
107
+ for (const role of jobs) if (!ROLES.includes(role)) throw new Error(`unknown drill job ${role}`);
108
+ return {
109
+ dir: script.dir ? resolve(dirname(path), script.dir) : join(dirname(path), laneKey),
110
+ jobs,
111
+ cli: typeof script.cli === "string" && script.cli ? script.cli : "nodii-dev",
112
+ tokens: { input: Number(script.tokens?.input) || 0, output: Number(script.tokens?.output) || 0 },
113
+ ending: script.ending ?? null,
114
+ silentAfterTicks: Number.isInteger(script.silentAfterTicks) ? script.silentAfterTicks : null,
115
+ steps: Array.isArray(script.steps) ? script.steps.filter((step) => Number.isInteger(step?.afterTicks) && typeof step.sh === "string") : [],
116
+ base: dirname(path),
117
+ };
118
+ }
119
+
120
+ /** The lines and exit code an ending prints: a result record, or a recorded run's own output. */
121
+ export function endingOutput(ending, sessionId, base) {
122
+ if (ending?.replay) {
123
+ const dir = resolve(base, ending.replay);
124
+ const lines = readFileSync(join(dir, "stdout.jsonl"), "utf8").split("\n").filter(Boolean);
125
+ const code = Number(readFileSync(join(dir, "exit_code"), "utf8").trim());
126
+ return { lines, code: Number.isInteger(code) ? code : 1 };
127
+ }
128
+ const code = Number.isInteger(ending?.code) ? ending.code : 0;
129
+ const record = { type: "result", subtype: code ? "error_during_execution" : "success", is_error: Boolean(code), session_id: sessionId, ...(ending?.result ?? {}) };
130
+ return { lines: [JSON.stringify(record)], code };
131
+ }
132
+
133
+ const argument = (argv, name) => {
134
+ const at = argv.indexOf(name);
135
+ return at >= 0 ? argv[at + 1] : undefined;
136
+ };
137
+
138
+ async function readStdin() {
139
+ let text = "";
140
+ process.stdin.setEncoding("utf8");
141
+ for await (const chunk of process.stdin) text += chunk;
142
+ return text;
143
+ }
144
+
145
+ export async function main({ argv = process.argv, env = process.env, cwd = process.cwd() } = {}) {
146
+ const laneKey = env.NODII_DEV_LANE_KEY ?? "drill";
147
+ const script = readScript(argument(argv, "--script"), laneKey);
148
+ const { dir } = script;
149
+ mkdirSync(dir, { recursive: true });
150
+ if (!existsSync(join(dir, "limits.env"))) writeFileSync(join(dir, "limits.env"), DRILL_LIMITS);
151
+ const print = (record) => process.stdout.write(`${typeof record === "string" ? record : JSON.stringify(record)}\n`);
152
+ const prompt = await readStdin();
153
+ const resumed = argument(argv, "--resume");
154
+ const sessionId = resumed ?? randomUUID();
155
+ writeFileSync(join(dir, "runtime.pid"), `${process.pid}\n`);
156
+ appendFileSync(join(dir, "runtime.starts"), `${Date.now()} ${process.pid} ${resumed ? "resume" : "fresh"}\n`);
157
+ print({ type: "system", subtype: "init", session_id: sessionId, model: "drill-stub", cwd, account: argument(argv, "--account") ?? null });
158
+ print({ type: "user", session_id: sessionId, message: { role: "user", content: prompt.slice(0, 2000) } });
159
+ // A resumed session's jobs are the first session's: the drill reads those.
160
+ if (!resumed) {
161
+ for (const role of script.jobs) {
162
+ const { command, args, options } = jobSpawn(role, dir, { laneKey, cwd, env, cli: script.cli });
163
+ const job = spawn(command, args, options);
164
+ job.on("error", (error) => appendFileSync(join(dir, `${role}.error`), `${error.message}\n`));
165
+ job.unref();
166
+ }
167
+ }
168
+ const endPath = join(dir, "end.json");
169
+ const scripted = script.ending && Number.isInteger(script.ending.afterTicks) ? script.ending : null;
170
+ // A step's output shares the stub's stdout, so what the stub printed is flushed first.
171
+ const flush = () => new Promise((done) => process.stdout.write("", done));
172
+ const runStep = async (step, number) => {
173
+ await flush();
174
+ const outcome = await new Promise((done) => {
175
+ const child = spawn("/bin/sh", ["-c", step.sh], { cwd, env: { ...stubEnv(env), STUB_SCRIPT_DIR: script.base }, stdio: ["ignore", 1, 1] });
176
+ child.once("error", (error) => done(`did not run: ${error.message}`));
177
+ child.once("close", (code, signal) => done(signal ? `exit signal ${signal}` : `exit ${code}`));
178
+ });
179
+ print(`drill step ${number} (afterTicks ${step.afterTicks}): ${outcome}`);
180
+ };
181
+ const ran = new Set();
182
+ const started = Date.now();
183
+ let ticks = 0;
184
+ let ending = null;
185
+ while (!ending) {
186
+ // Ticks keep to the clock; one that a step held up comes as soon as it is done.
187
+ await delay(Math.max(0, started + (ticks + 1) * TICK_MS - Date.now()));
188
+ ticks += 1;
189
+ const silent = script.silentAfterTicks !== null && ticks > script.silentAfterTicks;
190
+ if (!silent) print({ type: "assistant", session_id: sessionId, message: { model: "drill-stub", role: "assistant", content: [{ type: "text", text: `drill tick ${ticks}` }], usage: { input_tokens: script.tokens.input, output_tokens: script.tokens.output } } });
191
+ if (!silent) appendFileSync(join(dir, "runtime.ticks"), `${Date.now()}\n`);
192
+ for (const [index, step] of script.steps.entries()) {
193
+ if (ran.has(index) || ticks < step.afterTicks) continue;
194
+ ran.add(index);
195
+ await runStep(step, index + 1);
196
+ }
197
+ if (existsSync(endPath)) {
198
+ try { ending = JSON.parse(readFileSync(endPath, "utf8")); } catch { ending = {}; }
199
+ rmSync(endPath, { force: true });
200
+ } else if (scripted && ticks >= scripted.afterTicks) ending = scripted;
201
+ }
202
+ const { lines, code } = endingOutput(ending, sessionId, script.base);
203
+ for (const line of lines) print(line);
204
+ // A recorded run that a signal ended (exit 143 is SIGTERM) ends the same way here.
205
+ const signal = { 129: "SIGHUP", 130: "SIGINT", 137: "SIGKILL", 143: "SIGTERM" }[code];
206
+ if (signal) {
207
+ await new Promise((resolve) => process.stdout.write("", resolve));
208
+ process.kill(process.pid, signal);
209
+ }
210
+ process.exitCode = code;
211
+ }
212
+
213
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) await main();