@nodii/dev 0.6.174 → 0.6.176

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.
@@ -1,9 +1,13 @@
1
1
  import { execFile as execFileCallback, spawn as nodeSpawn } from "node:child_process";
2
- import { statSync } from "node:fs";
2
+ import { readdirSync, statSync } from "node:fs";
3
3
  import { open, readFile, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
4
5
  import { dirname, join } from "node:path";
5
6
  import { promisify } from "node:util";
7
+ import { profilePath, recordExhaustedAccount } from "./accounts.js";
6
8
  import { CliError, devRequest, encode } from "./core.js";
9
+ import { inboxForContinuation } from "./lane-messages.js";
10
+ import { laneSwitchOn } from "./lane-switches.js";
7
11
  import { redactRunText } from "./runs.js";
8
12
  import { processStartedAt, saveWatchedRun, watchdogRunDir } from "./watchdog.js";
9
13
 
@@ -19,6 +23,11 @@ import { processStartedAt, saveWatchedRun, watchdogRunDir } from "./watchdog.js"
19
23
  * watchdog could only see a vanished PID and counted every exit as
20
24
  * process_dead.
21
25
  *
26
+ * hub-525: ending the run does not finish the lane. A clean exit
27
+ * after `lane done-check` also records the lane finished (POST
28
+ * /lanes/:id/finish, as `lane finish` does) with the done check's evidence,
29
+ * so its coordinator's `lane close` is not refused LANE_NOT_FINISHED.
30
+ *
22
31
  * NODII-DEV-CLI-9: an exit before the done check, with the lane not
23
32
  * BLOCKED, first continues the SAME session (`claude --resume`, `codex exec
24
33
  * resume`) with "Lane <key>: done check not recorded. Continue the Task:
@@ -66,6 +75,133 @@ async function readTail(path, bytes = LOG_TAIL_BYTES) {
66
75
  }
67
76
  }
68
77
 
78
+ // NODII-DEV-CLI-191: 144 lane runs (7%) died on a spend, weekly or model
79
+ // limit (49), the network (46) or auth (45), and a resume put them back on the
80
+ // same account. The runtime's own lines name the failure.
81
+ const USAGE_LIMIT = [
82
+ /Claude AI usage limit reached/i,
83
+ /\byou(?:'|’)ve hit your (?:usage )?limit\b/i,
84
+ /\b(?:5-hour|five-hour|session|weekly|opus|sonnet)\b[^\n]{0,40}\blimit reached\b/i,
85
+ /\busage limit (?:reached|exceeded)\b/i,
86
+ ];
87
+ const AUTH = [
88
+ /OAuth token (?:has )?expired/i, /\bauthentication_error\b/, /\bInvalid API key\b/i, /Please run \/login/i,
89
+ /\bAPI Error:? 401\b|\b401 Unauthorized\b|"status":\s*401\b/i, /\btoken_expired\b|refresh token (?:was )?(?:already used|expired|invalid)/i,
90
+ ];
91
+ const NETWORK = [
92
+ /\bcf-ray\b/i, /\bCloudflare\b/i, /\bECONNRESET\b/, /\bETIMEDOUT\b/, /\bECONNREFUSED\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,
93
+ /\bfetch failed\b/i, /\b529\b[^\n]*\bOverloaded\b|\boverloaded_error\b/i, /stream disconnected before completion/i,
94
+ ];
95
+ const FAILURE_KINDS = [["usage_limit", USAGE_LIMIT], ["auth", AUTH], ["network", NETWORK]];
96
+ /** How long an account waits when its failure names no reset time. */
97
+ export const ACCOUNT_WAIT_MS = { usage_limit: 5 * 3_600_000, auth: 3_600_000, network: 3_600_000 };
98
+ const FAILURE_SCAN_LINES = 40;
99
+ const NO_FAILURE = Object.freeze({ kind: null, resetAt: null, line: null });
100
+
101
+ const SUCCEEDED = Symbol("succeeded");
102
+
103
+ /**
104
+ * The text of a log line the runtime itself wrote about its failure; null for
105
+ * a tool's output, the model's own words and other events (a test run that
106
+ * printed ECONNRESET is not a network failure); SUCCEEDED for a turn that
107
+ * ended well, after which nothing older counts. The tail's first line may be
108
+ * cut mid-record: a fragment of JSON is skipped.
109
+ */
110
+ function runtimeLine(line, first) {
111
+ const text = line.trim();
112
+ if (!text) return null;
113
+ if (!text.startsWith("{")) return first && /^[^{"]*"\s*[,:}\]]/.test(text) ? null : text;
114
+ let record;
115
+ try { record = JSON.parse(text); } catch { return null; }
116
+ if (record?.type === "result") return record.is_error ? text : SUCCEEDED;
117
+ if (record?.type === "turn.completed") return SUCCEEDED;
118
+ if (record?.type === "error" || record?.type === "turn.failed") return text;
119
+ return record?.type === "assistant" && record?.message?.model === "<synthetic>" ? text : null;
120
+ }
121
+
122
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
123
+ const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
124
+
125
+ function zonedParts(ms, timeZone) {
126
+ const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", {
127
+ timeZone, hourCycle: "h23", weekday: "short", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit",
128
+ }).formatToParts(new Date(ms)).map((part) => [part.type, part.value]));
129
+ return { year: +parts.year, month: +parts.month - 1, day: +parts.day, hour: +parts.hour % 24, minute: +parts.minute, second: +parts.second, weekday: WEEKDAYS.indexOf(parts.weekday.toLowerCase()) };
130
+ }
131
+
132
+ /** The UTC time of a wall-clock time in a time zone. */
133
+ function zonedToUtc(year, month, day, hour, minute, timeZone) {
134
+ const wall = Date.UTC(year, month, day, hour, minute);
135
+ const offset = (ms) => {
136
+ const p = zonedParts(ms, timeZone);
137
+ return Date.UTC(p.year, p.month, p.day, p.hour, p.minute, p.second) - Math.floor(ms / 1000) * 1000;
138
+ };
139
+ return wall - offset(wall - offset(wall));
140
+ }
141
+
142
+ /** "3pm", "Mon 9am", "11:30pm (Asia/Kolkata)", "Nov 20th, 2026 3:05 PM": the next such time after now. */
143
+ function parseWallClock(text, now, defaultZone) {
144
+ const time = /\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\b/i.exec(text);
145
+ if (!time) return null;
146
+ const hour = (Number(time[1]) % 12) + (time[3].toLowerCase() === "p" ? 12 : 0);
147
+ const minute = Number(time[2] ?? 0);
148
+ let timeZone = defaultZone;
149
+ const zone = /\(([A-Za-z_]+(?:\/[A-Za-z_+-]+)*)\)/.exec(text)?.[1];
150
+ if (zone) {
151
+ try { new Intl.DateTimeFormat("en-US", { timeZone: zone }); timeZone = zone; } catch {}
152
+ }
153
+ const today = zonedParts(now.getTime(), timeZone);
154
+ const at = (year, month, day) => zonedToUtc(year, month, day, hour, minute, timeZone);
155
+ const date = /\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?\b(?:,?\s+(\d{4}))?/i.exec(text);
156
+ let ms;
157
+ if (date) {
158
+ const month = MONTHS.indexOf(date[1].toLowerCase());
159
+ ms = at(date[3] ? Number(date[3]) : today.year, month, Number(date[2]));
160
+ if (!date[3] && ms <= now.getTime()) ms = at(today.year + 1, month, Number(date[2]));
161
+ } else {
162
+ const weekday = /\b(sun|mon|tue|wed|thu|fri|sat)[a-z]*\b/i.exec(text);
163
+ const ahead = weekday ? (WEEKDAYS.indexOf(weekday[1].toLowerCase()) - today.weekday + 7) % 7 : 0;
164
+ ms = at(today.year, today.month, today.day + ahead);
165
+ if (ms <= now.getTime()) ms = at(today.year, today.month, today.day + ahead + (weekday ? 7 : 1));
166
+ }
167
+ return new Date(ms).toISOString();
168
+ }
169
+
170
+ const DURATION_MS = { d: 86_400_000, h: 3_600_000, m: 60_000, s: 1000 };
171
+
172
+ /** The reset time a usage-limit line gives, or null. */
173
+ function limitResetAt(line, now, timeZone) {
174
+ const epoch = /usage limit reached\|(\d{10,13})\b/i.exec(line)?.[1];
175
+ if (epoch) return new Date(epoch.length > 10 ? Number(epoch) : Number(epoch) * 1000).toISOString();
176
+ const after = /try again in\s+([^."\n]+)/i.exec(line)?.[1];
177
+ if (after) {
178
+ const total = [...after.matchAll(/(\d+)\s*(d|h|m|s)[a-z]*/gi)].reduce((sum, [, n, unit]) => sum + Number(n) * DURATION_MS[unit.toLowerCase()], 0);
179
+ if (total) return new Date(now.getTime() + total).toISOString();
180
+ }
181
+ const at = /(?:try again at|resets?(?:\s+at)?)\s+(.+)$/i.exec(line)?.[1];
182
+ return at ? parseWallClock(at, now, timeZone) : null;
183
+ }
184
+
185
+ /**
186
+ * NODII-DEV-CLI-191: the account failure a run's log tail ends on: a
187
+ * usage limit (with its reset time when the runtime gives one), auth, or the
188
+ * network (Cloudflare, a reset connection, an overloaded API). The newest
189
+ * line the runtime wrote decides; `{ kind: null }` when it names none.
190
+ */
191
+ export function classifyRuntimeFailure(logTail, { now = new Date(), timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone } = {}) {
192
+ const lines = String(logTail ?? "").split("\n");
193
+ for (let index = lines.length - 1; index >= Math.max(0, lines.length - FAILURE_SCAN_LINES); index -= 1) {
194
+ const line = runtimeLine(lines[index], index === 0);
195
+ if (line === SUCCEEDED) break;
196
+ if (!line) continue;
197
+ const found = FAILURE_KINDS.find(([, patterns]) => patterns.some((pattern) => pattern.test(line)));
198
+ if (!found) continue;
199
+ const kind = found[0];
200
+ return { kind, resetAt: kind === "usage_limit" ? limitResetAt(line, now, timeZone) : null, line: line.slice(0, 1000) };
201
+ }
202
+ return NO_FAILURE;
203
+ }
204
+
69
205
  const describeWorktree = ({ state, dirty, unreadable }) => [
70
206
  ...dirty.slice(0, 50),
71
207
  ...(dirty.length > 50 ? [`... ${dirty.length - 50} more`] : []),
@@ -93,11 +229,38 @@ export const doneCheckRecorded = (lane) =>
93
229
  || (lane?.steps ?? []).some((step) => step.stepKey === "dev_check" && step.state === "done")
94
230
  || FINISHED_LANE.has(lane?.status);
95
231
 
96
- /** A lane is BLOCKED by a blocked step (`lane step --block`) or a latest heartbeat note that starts "blocked" or "WAITING:" (AGENT-HARNESS-46). */
232
+ const LIVE_LEEWAY = ["granted", "requested"];
233
+
234
+ /**
235
+ * hub-525 (MW1-12.6): the leeway step a lane is on, or null. A
236
+ * granted leeway is the fix to make, a requested one waits on the coordinator
237
+ * while the lane works what is not blocked, and `leewayNext` is Dev naming an
238
+ * open issue no live lane holds, with the `lane leeway` command that asks for
239
+ * it. The lane's `next` (its step array) is never read for this.
240
+ */
241
+ export function laneLeewayStep(lane) {
242
+ for (const state of LIVE_LEEWAY) {
243
+ const leeway = (Array.isArray(lane?.leeways) ? lane.leeways : []).find((candidate) => candidate?.state === state);
244
+ if (leeway) return { kind: state, id: leeway.id, blockerIssueKey: leeway.blockerIssueKey };
245
+ }
246
+ const next = fixableBlocker(lane?.leewayNext);
247
+ return next ? { kind: "ask", ...next } : null;
248
+ }
249
+
250
+ /** Dev's unasked fixable blocker: an object with a command, or null. */
251
+ export function fixableBlocker(next) {
252
+ if (!next || typeof next !== "object" || Array.isArray(next) || typeof next.command !== "string" || !next.command.trim()) return null;
253
+ return { command: next.command.trim(), blockerIssueKey: next.blockerIssueKey, reason: next.reason };
254
+ }
255
+
256
+ /** A lane is BLOCKED by a blocked step (`lane step --block`) or a latest heartbeat note that starts "blocked" or "WAITING:" (AGENT-HARNESS-46), unless leeway covers it (MW1-12.6). */
97
257
  export const laneBlocked = (lane) => Boolean(laneBlockedReason(lane));
98
258
 
99
259
  /** Why a lane is BLOCKED, or null (the same rule Dev applies to a run's exit). */
100
260
  export function laneBlockedReason(lane) {
261
+ // MW1-12.6: a lane with leeway asked or granted, or with a blocker it can
262
+ // ask leeway for, is not BLOCKED: its session is continued, not released.
263
+ if (laneLeewayStep(lane)) return null;
101
264
  const step = (lane?.steps ?? []).find((candidate) => candidate.state === "blocked");
102
265
  if (step) return `Lane step ${step.side}/${step.stepKey} is blocked.`;
103
266
  // hub-283: the open waits first, then the latest heartbeat that says something.
@@ -111,11 +274,74 @@ export function laneBlockedReason(lane) {
111
274
  return /^\s*blocked\b/i.test(note) || /^\s*WAITING\s*:/.test(note) ? `Lane heartbeat: ${note.slice(0, 500)}` : null;
112
275
  }
113
276
 
277
+ // NODII-DEV-CLI-191: only a typed human gate ends a lane's run. A wait on
278
+ // an operator question, a decision, a release (the steward judges it) or launch
279
+ // day, a wait on a steward lane, or a latest heartbeat typed
280
+ // `WAITING: human-gate totp|steward|spend: ...`. Every other blocker (a blocked
281
+ // step, a PR, an issue, another lane, an untyped BLOCKED or WAITING note) is
282
+ // the lane's to claim and fix.
283
+ const HUMAN_GATE_WAITS = new Set(["question", "decision", "release", "launch_day"]);
284
+ const HUMAN_GATE_NOTE = /^\s*(?:BLOCKED|WAITING)\s*:?\s*human[- ]gate\s*\(?\s*(totp|steward|spend)\b/i;
285
+ export const HUMAN_GATE_COMMAND = (laneKey) => `nodii-dev lane heartbeat ${laneKey} --note "WAITING: human-gate totp|steward|spend: <what the person must do>"`;
286
+
287
+ const latestNote = (lane) => String((lane?.events ?? [])
288
+ .filter((event) => event.type === "heartbeat" && event.metadata?.source !== "hook" && String(event.metadata?.note ?? "").trim())
289
+ .at(-1)?.metadata?.note ?? "");
290
+
291
+ /**
292
+ * NODII-DEV-CLI-191: the subagent budget the model is told. Dev's quota
293
+ * only caps registrations; a model uses a budget only when it knows it.
294
+ * Null when the quota is unknown.
295
+ */
296
+ export function subagentBudgetLine(quota, env = process.env) {
297
+ // Off unless NODII_DEV_SUBAGENT_BUDGET=1 until its clause is in force.
298
+ if (!laneSwitchOn("subagentBudget", env)) return null;
299
+ const n = Number(quota);
300
+ if (quota == null || !Number.isInteger(n) || n < 0) return null;
301
+ // P-19: the count is a fact from Dev; how to use them is the rulebook's (MW1-11, MW1-38.15), cited, never restated.
302
+ if (n === 0) return "You have no subagent slots (MW1-38.15).";
303
+ return `You have ${n} subagent slot${n === 1 ? "" : "s"} (the Agent tool; MW1-38.15). Fan independent work out to them as MW1-11 says.`;
304
+ }
305
+
306
+ /** The typed human gate that ends a lane's run, or null (NODII-DEV-CLI-191). */
307
+ export function laneHumanGate(lane) {
308
+ for (const wait of lane?.waits ?? []) {
309
+ if (HUMAN_GATE_WAITS.has(wait?.targetKind)) return `Lane waits on ${wait.targetRef} (a ${wait.targetKind.replace("_", " ")}, a human gate).`;
310
+ const blocker = wait?.blockerLaneKey ?? (wait?.targetKind === "lane" ? wait?.targetRef : null);
311
+ if (typeof blocker === "string" && /^steward-/.test(blocker)) return `Lane waits on ${blocker} (a steward-only step, a human gate).`;
312
+ }
313
+ const note = latestNote(lane);
314
+ return HUMAN_GATE_NOTE.test(note) ? `Lane heartbeat: ${note.slice(0, 500)}` : null;
315
+ }
316
+
317
+ /**
318
+ * NODII-DEV-CLI-191: "BLOCKED is not an exit" is ahead of its clause (the
319
+ * draft on NODII-DEV-CLI-191 waits for its
320
+ * Docs change), so it ships off, as lane questions did (DEC-0503):
321
+ * NODII_DEV_BLOCKED_NOT_EXIT=1 turns it on. Off, a BLOCKED lane ends its run as
322
+ * before, except where leeway covers it (MW1-12.6, DEC-0486).
323
+ */
324
+ export const blockedIsNotExit = (env = process.env) => env?.NODII_DEV_BLOCKED_NOT_EXIT === "1";
325
+
326
+ /** Why a lane's run may end before its done check, or null. */
327
+ export const laneRunEnds = (lane, env = process.env) => (blockedIsNotExit(env) ? laneHumanGate(lane) : laneBlockedReason(lane));
328
+
114
329
  /** The step a lane that stopped early goes back to (hub-58, NODII-DEV-CLI-8/9). */
115
- export function continueTaskMessage(laneKey, lane) {
330
+ export function continueTaskMessage(laneKey, lane, env = process.env) {
116
331
  const next = (lane?.next ?? []).map((step) => `${step.side}/${step.step}`);
117
332
  const current = [lane?.currentBackendStep && `backend/${lane.currentBackendStep}`, lane?.currentFrontendStep && `frontend/${lane.currentFrontendStep}`].filter(Boolean);
118
333
  const step = (next.length ? next : current).join(" and ") || "the lane's objective";
334
+ const blocked = laneLeewayStep(lane) ? null : laneBlockedReason(lane);
335
+ if (blocked && blockedIsNotExit(env) && !laneHumanGate(lane))
336
+ return `Lane ${laneKey}: ${blocked} That does not end the run: claim it with \`nodii-dev lane leeway\` (MW1-12.6), fix it with your subagents, and keep working what is not blocked. Only a typed human gate ends a run: \`${HUMAN_GATE_COMMAND(laneKey)}\`. Done check not recorded. Continue the Task: ${step}.`;
337
+ const leeway = laneLeewayStep(lane);
338
+ const issue = leeway?.blockerIssueKey ?? "its blocker";
339
+ if (leeway?.kind === "ask")
340
+ return `Lane ${laneKey}: blocked on ${issue}, which no live lane holds. Do not stop BLOCKED: ask the coordinator for leeway with \`${leeway.command}\`, then keep working what is not blocked.`;
341
+ if (leeway?.kind === "granted")
342
+ return `Lane ${laneKey}: leeway ${leeway.id} for ${issue} is granted. Run \`nodii-dev lane gather ${laneKey} --delta\` if its amendment is not acknowledged yet, then fix ${issue} as its own PR. Done check not recorded: continue the Task: ${step}.`;
343
+ if (leeway?.kind === "requested")
344
+ return `Lane ${laneKey}: leeway ${leeway.id} for ${issue} waits on the coordinator; do not start that fix yet. Done check not recorded: keep working what is not blocked: ${step}.`;
119
345
  return `Lane ${laneKey}: done check not recorded. Continue the Task: ${step}.`;
120
346
  }
121
347
 
@@ -126,9 +352,35 @@ export function continueTaskMessage(laneKey, lane) {
126
352
  async function laneProgress(request, laneKey) {
127
353
  try {
128
354
  const lane = (await request("GET", `/api/v1/lanes/${encode(laneKey)}`)).data;
129
- return { status: lane?.status ?? null, finished: doneCheckRecorded(lane), blocked: laneBlockedReason(lane) };
355
+ return { status: lane?.status ?? null, finished: doneCheckRecorded(lane), blocked: laneBlockedReason(lane), finishEvidence: laneFinishEvidence(lane) };
130
356
  } catch {
131
- return { status: null, finished: false, blocked: null };
357
+ return { status: null, finished: false, blocked: null, finishEvidence: null };
358
+ }
359
+ }
360
+
361
+ /**
362
+ * The evidence the supervisor finishes a lane with: its recorded done check's
363
+ * (`lane done-check`). Null when there is none, when the lane has ended (Dev
364
+ * refuses LANE_TERMINAL), or when the lane already marked itself finished.
365
+ */
366
+ function laneFinishEvidence(lane) {
367
+ const evidence = lane?.doneCheckRecorded?.evidence;
368
+ if (typeof evidence !== "string" || !evidence.trim()) return null;
369
+ if (FINISHED_LANE.has(lane?.status) || lane?.finishedRecord) return null;
370
+ return evidence.trim().slice(0, 8000);
371
+ }
372
+
373
+ /**
374
+ * Record the lane finished after its run ended. Never throws: a failed call
375
+ * leaves the exit as it was reported, and the lane can still run `lane finish`.
376
+ */
377
+ async function finishLane(request, laneKey, reason, evidence) {
378
+ try {
379
+ await send(request, `/api/v1/lanes/${encode(laneKey)}/finish`, { reason, evidence, via: "nodii-dev" });
380
+ return "recorded";
381
+ } catch (error) {
382
+ if (error?.code === "LANE_ALREADY_FINISHED") return "already_finished";
383
+ return `failed: ${error?.code ?? error?.message ?? error}`;
132
384
  }
133
385
  }
134
386
 
@@ -139,14 +391,16 @@ async function laneProgress(request, laneKey) {
139
391
  * every exit, exit 0 included, is a process exit: Dev orphans the run and
140
392
  * routes it for recovery (`lane resume`).
141
393
  */
142
- export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations = 0 }, {
394
+ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations = 0, runtime, profile, home }, {
143
395
  request = devRequest,
144
396
  inspect = worktreeState,
145
397
  tail = readTail,
146
398
  markTerminal = markWatchedTerminal,
399
+ now = () => new Date(),
400
+ markExhausted = recordExhaustedAccount,
147
401
  } = {}) {
148
402
  const worktree = await inspect(worktrees);
149
- const { status, finished, blocked } = await laneProgress(request, laneKey);
403
+ const { status, finished, blocked, finishEvidence } = await laneProgress(request, laneKey);
150
404
  const clean = exitCode === 0 && !signal;
151
405
  const exitRef = signal ? `signal ${signal}` : String(exitCode ?? -1);
152
406
  const exited = signal ? `was ended by ${signal}` : `exited with code ${exitCode ?? -1}`;
@@ -157,6 +411,7 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
157
411
  ];
158
412
  let outcome;
159
413
  let body;
414
+ let accountFailure = null;
160
415
  if (finished && clean) {
161
416
  outcome = worktree.state === "clean" ? "done" : "handed_off";
162
417
  body = outcome === "done"
@@ -174,9 +429,20 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
174
429
  } else {
175
430
  outcome = "process_exit";
176
431
  const logTail = redactRunText(await tail(logPath).catch(() => "")).trim();
432
+ // NODII-DEV-CLI-191: a run that died on its account says so, and the
433
+ // account is recorded exhausted so lane resume does not relaunch onto it.
434
+ const failure = signal ? NO_FAILURE : classifyRuntimeFailure(logTail, { now: now() });
435
+ let accountNote = "";
436
+ if (failure.kind) {
437
+ const account = profilePath(profile) || join(home ?? homedir(), runtime === "codex" ? ".codex" : ".claude");
438
+ const until = failure.resetAt ?? new Date(now().getTime() + ACCOUNT_WAIT_MS[failure.kind]).toISOString();
439
+ accountFailure = { kind: failure.kind, resetAt: failure.resetAt, until, profile: account };
440
+ await markExhausted(account, { kind: failure.kind, resetAt: failure.resetAt, until, laneKey, runId, line: failure.line, recordedAt: now().toISOString() }).catch(() => {});
441
+ accountNote = ` The runtime's log shows an account failure (${failure.kind}, ${failure.resetAt ? `resets ${failure.resetAt}` : "no reset time given"}): ${JSON.stringify(failure.line.slice(0, 300))}. ${account} is recorded exhausted until ${until}: lane resume moves the lane to another account with headroom, or refuses ACCOUNT_EXHAUSTED until then.`;
442
+ }
177
443
  body = {
178
- reason: `The lane process ${exited} before lane ${laneKey}'s done check was recorded (lane ${status ?? "status unknown"}), so the run is unfinished; its worktree is ${worktree.state}.${continuations ? ` It was continued in the same session ${continuations} time${continuations === 1 ? "" : "s"} first (NODII-DEV-CLI-9).` : ""}`,
179
- deathFingerprint: signal ? `lane-signal-${signal}` : clean ? "lane-unfinished-exit-0" : `lane-exit-${exitCode ?? -1}`,
444
+ reason: `The lane process ${exited} before lane ${laneKey}'s done check was recorded (lane ${status ?? "status unknown"}), so the run is unfinished; its worktree is ${worktree.state}.${continuations ? ` It was continued in the same session ${continuations} time${continuations === 1 ? "" : "s"} first (NODII-DEV-CLI-9).` : ""}${accountNote}`,
445
+ deathFingerprint: failure.kind ? `lane-account-${failure.kind}` : signal ? `lane-signal-${signal}` : clean ? "lane-unfinished-exit-0" : `lane-exit-${exitCode ?? -1}`,
180
446
  exitCode: Number.isInteger(exitCode) && exitCode >= 0 && exitCode <= 255 ? exitCode : -1,
181
447
  ...(logTail ? { logTail: logTail.slice(-50_000) } : {}),
182
448
  };
@@ -197,8 +463,16 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
197
463
  });
198
464
  } else throw error;
199
465
  }
466
+ // hub-525: only a clean exit after a recorded done check, with
467
+ // nothing left uncommitted, finishes the lane; a failed, blocked, unfinished
468
+ // or handed-off exit never does. READY is a recorded done check too, so a
469
+ // lane that still waits (on its steward, say) or has a blocked step is not
470
+ // finished by its exit.
471
+ const laneFinish = finished && clean && !blocked && worktree.state === "clean" && finishEvidence
472
+ ? await finishLane(request, laneKey, `The lane's done check was recorded and its process exited 0 with its worktree ${worktree.state}; recorded by the lane supervisor on exit.`, finishEvidence)
473
+ : null;
200
474
  await markTerminal(runId).catch(() => {});
201
- return { outcome, exitCode: exitCode ?? null, signal: signal ?? null, worktree: worktree.state, laneStatus: status };
475
+ return { outcome, exitCode: exitCode ?? null, signal: signal ?? null, worktree: worktree.state, laneStatus: status, ...(laneFinish ? { laneFinish } : {}), ...(accountFailure ? { accountFailure } : {}) };
202
476
  }
203
477
 
204
478
  /** The sweep skips a run whose exit was reported (it would otherwise report process_dead). */
@@ -262,6 +536,49 @@ const logSize = (logPath) => {
262
536
  try { return statSync(logPath).size; } catch { return null; }
263
537
  };
264
538
 
539
+ const mtimeOf = (path) => {
540
+ try { return statSync(path).mtimeMs; } catch { return null; }
541
+ };
542
+
543
+ /**
544
+ * NODII-DEV-CLI-191: the runtime's activity, for the supervisor's tick.
545
+ * Each call answers the time of the newest write since the last call that
546
+ * answered one: the run log grew, or a session transcript (the session's own,
547
+ * or a subagent's) was written. Null when nothing was written: a quiet tick.
548
+ */
549
+ export function runActivity({ logPath, transcripts = () => [], now = Date.now }) {
550
+ const newestTranscript = () => {
551
+ let newest = null;
552
+ for (const path of transcripts()) {
553
+ const at = mtimeOf(path);
554
+ if (at !== null && (newest === null || at > newest)) newest = at;
555
+ }
556
+ return newest;
557
+ };
558
+ let lastSize = logSize(logPath);
559
+ // A transcript found later (its session id appears in the log) counts only for writes after the watch began.
560
+ let lastTranscript = newestTranscript() ?? now();
561
+ return () => {
562
+ const size = logSize(logPath);
563
+ const transcript = newestTranscript();
564
+ const grew = size !== null && size !== lastSize;
565
+ const wrote = transcript !== null && transcript > lastTranscript;
566
+ if (!grew && !wrote) return null;
567
+ lastSize = size ?? lastSize;
568
+ lastTranscript = transcript ?? lastTranscript;
569
+ return Math.max(grew ? mtimeOf(logPath) ?? now() : 0, wrote ? transcript : 0);
570
+ };
571
+ }
572
+
573
+ /** Claude's transcript of a session in a lane worktree, and its subagents' transcripts. */
574
+ export function claudeTranscripts(invocation, sessionId, { home = homedir() } = {}) {
575
+ const project = join(invocation.env?.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects", String(invocation.cwd).replace(/[^A-Za-z0-9]/g, "-"));
576
+ const subagents = join(project, sessionId, "subagents");
577
+ let names = [];
578
+ try { names = readdirSync(subagents).filter((name) => name.endsWith(".jsonl")); } catch {}
579
+ return [join(project, `${sessionId}.jsonl`), ...names.map((name) => join(subagents, name))];
580
+ }
581
+
265
582
  const continuationLimit = (env) => {
266
583
  const value = Number(env.NODII_DEV_LANE_CONTINUATIONS ?? 3);
267
584
  return Number.isInteger(value) && value >= 0 ? value : 3;
@@ -277,6 +594,7 @@ export async function superviseLane({
277
594
  request = devRequest,
278
595
  rewatch = rewatchRun,
279
596
  env = process.env,
597
+ inbox = inboxForContinuation,
280
598
  } = {}) {
281
599
  if (typeof channel.send !== "function")
282
600
  throw new CliError("USAGE", "__lane-supervisor is started by lane launch and lane resume only.", 2);
@@ -295,18 +613,30 @@ export async function superviseLane({
295
613
  return exit(1);
296
614
  }
297
615
  let state = "spawning";
298
- // The run's heartbeat (30 Oct, hub-58 P0): the heartbeat hook fires only on a
299
- // tool use or at the end of a turn, so the supervisor heartbeats a launched
300
- // lane's run, as the lane identity that owns it. A live PID is not a
616
+ // The run's heartbeat (30 Oct, hub-58 P0): the supervisor heartbeats a
617
+ // launched lane's run, as the lane identity that owns it. A live PID is not a
301
618
  // heartbeat (MW1-36): a tick counts only when the runtime has written to its
302
- // log since the last one, so a hung runtime goes Quiet and then Orphan.
303
- let lastLogSize = logSize(logPath);
619
+ // log or its session transcript since the last one, so a hung runtime goes
620
+ // Quiet and then Orphan. NODII-DEV-CLI-191: the same tick is the lane's
621
+ // harness beat (source "hook", as the per-tool-call hook process sent it),
622
+ // which keeps Dev's `stuck` meaningful, and the run beat says when the
623
+ // runtime last wrote.
624
+ // Codex's transcript is its --json stream, the run log itself.
625
+ let sessionId = null;
626
+ const transcripts = () => (invocation.command === "claude" && sessionId ? claudeTranscripts(invocation, sessionId) : []);
627
+ const activity = runActivity({ logPath, transcripts });
304
628
  const heartbeat = setInterval(() => {
305
629
  if (state !== "running") return;
306
- const size = logSize(logPath);
307
- if (size === null || size === lastLogSize) return;
308
- lastLogSize = size;
309
- request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, { note: `lane runtime pid ${child.pid} alive (supervisor ${process.pid})` }).catch(() => {});
630
+ // Both beats leave inside the tick, so none follows the exit report.
631
+ const at = activity();
632
+ if (at !== null) {
633
+ request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, { note: `lane runtime pid ${child.pid} alive (supervisor ${process.pid}); last activity ${new Date(at).toISOString()}` }).catch(() => {});
634
+ // Off (NODII_DEV_STOP_ONLY_HEARTBEAT unset), the harness's tool-call hook beats the lane instead.
635
+ if (laneKey && laneSwitchOn("stopOnlyHeartbeat", env)) request("POST", `/api/v1/lanes/${encode(laneKey)}/heartbeat`, { via: "nodii-dev", source: "hook" }).catch(() => {});
636
+ }
637
+ // The session's transcript is found once its id is in the log.
638
+ if (!sessionId && invocation.command === "claude")
639
+ sessionIdFromLog(logPath, invocation.command).then((id) => { sessionId ??= id; }, () => {});
310
640
  }, heartbeatInterval(env));
311
641
  const closed = new Promise((resolve) => child.once("close", (exitCode, signal) => resolve({ exitCode, signal })));
312
642
  child.once("error", (error) => {
@@ -352,8 +682,13 @@ export async function superviseLane({
352
682
  if (!sessionId) break;
353
683
  let lane;
354
684
  try { lane = (await request("GET", `/api/v1/lanes/${encode(laneKey)}`)).data; } catch { break; }
355
- if (doneCheckRecorded(lane) || laneBlocked(lane)) break;
356
- const message = continueTaskMessage(laneKey, lane);
685
+ // NODII-DEV-CLI-191: a fixable blocker is continued; only a human gate ends the run.
686
+ if (doneCheckRecorded(lane) || laneRunEnds(lane, env)) break;
687
+ // NODII-DEV-CLI-191: the same session on a used-up account only fails again.
688
+ if (classifyRuntimeFailure(redactRunText(await readTail(logPath).catch(() => ""))).kind) break;
689
+ const message = continueTaskMessage(laneKey, lane, env);
690
+ // NODII-DEV-CLI-191: unread lane messages lead the next turn (Claude and Codex alike), delivered once.
691
+ const mail = await inbox(laneKey, invocation, { env }).catch(() => null);
357
692
  continued += 1;
358
693
  await request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, {
359
694
  note: `continuation ${continued}/${limit} of session ${sessionId} after exit ${exitCode}: ${message}`.slice(0, 500),
@@ -374,14 +709,22 @@ export async function superviseLane({
374
709
  });
375
710
  // A runtime that exits before reading its prompt must not end the supervisor (EPIPE).
376
711
  child.stdin?.on("error", () => {});
377
- child.stdin?.end(`${message}\n`);
712
+ child.stdin?.end(`${mail ? `${mail}\n\n` : ""}${message}\n`);
378
713
  process.stderr.write(`nodii-dev: ${message} (same-session continuation ${continued}/${limit})\n`);
379
714
  ({ exitCode, signal } = await ended);
380
715
  }
381
716
  clearInterval(heartbeat);
382
717
  try {
383
- const result = await report({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations: continued });
718
+ const runtime = invocation.command;
719
+ const profile = invocation.env?.[runtime === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"] ?? null;
720
+ const result = await report({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations: continued, runtime, profile });
384
721
  process.stderr.write(`nodii-dev: lane process exit reported to Dev (${result.outcome}, exit ${signal ?? exitCode}, lane ${result.laneStatus ?? "status unknown"}, worktree ${result.worktree}).\n`);
722
+ if (result.accountFailure)
723
+ process.stderr.write(`nodii-dev: the run died on its account (${result.accountFailure.kind}); ${result.accountFailure.profile} is recorded exhausted until ${result.accountFailure.until}.\n`);
724
+ if (result.laneFinish?.startsWith("failed"))
725
+ process.stderr.write(`nodii-dev: could not record lane ${laneKey} finished (${result.laneFinish.slice("failed: ".length)}); run \`nodii-dev lane finish ${laneKey} --reason TEXT --evidence TEXT|URL\` so its coordinator can close it.\n`);
726
+ else if (result.laneFinish)
727
+ process.stderr.write(`nodii-dev: lane ${laneKey} ${result.laneFinish === "recorded" ? "recorded finished" : "was already recorded finished"}; its coordinator can close it.\n`);
385
728
  return exit(0);
386
729
  } catch (error) {
387
730
  process.stderr.write(`nodii-dev: could not report the lane process exit to Dev (${error?.code ?? error?.message ?? error}); the watchdog reports it as process_dead.\n`);
@@ -0,0 +1,32 @@
1
+ import { CliError } from "./core.js";
2
+
3
+ /**
4
+ * NODII-DEV-CLI-191 (the coordinator's instruction of 18 Nov, done as
5
+ * NODII_DEV_LANE_ASKS and NODII_DEV_BLOCKED_NOT_EXIT were): the lane-orchestration
6
+ * features whose clauses are drafted but not yet in Dev's rulebook ship off by
7
+ * default. Each is on only when its variable is exactly "1"; off, it behaves as
8
+ * before NODII-DEV-CLI-191. When a clause is in force (its version lands), its
9
+ * default flips.
10
+ */
11
+ export const LANE_SWITCHES = Object.freeze({
12
+ // Amended MW1-102: resume only when a blocker changed.
13
+ resumeIfChanged: "NODII_DEV_RESUME_IF_CHANGED",
14
+ // "A resume continues the lane's own session".
15
+ sameSessionResume: "NODII_DEV_SAME_SESSION_RESUME",
16
+ // "The model is told its budget".
17
+ subagentBudget: "NODII_DEV_SUBAGENT_BUDGET",
18
+ // `issues group`: propose a lane's issue set from an objective.
19
+ issuesGroup: "NODII_DEV_ISSUES_GROUP",
20
+ // `lane message`, `lane inbox` and their hook delivery.
21
+ laneMessages: "NODII_DEV_LANE_MESSAGES",
22
+ // The harness beats a lane on Stop only; the supervisor beats it while it acts.
23
+ stopOnlyHeartbeat: "NODII_DEV_STOP_ONLY_HEARTBEAT",
24
+ });
25
+
26
+ export const laneSwitchOn = (name, env = process.env) => env?.[LANE_SWITCHES[name]] === "1";
27
+
28
+ /** Refuse `<CODE>` when the switch is off: `what` is off, `instead` says what to do meanwhile. */
29
+ export function assertLaneSwitchOn(name, code, what, instead, env = process.env) {
30
+ if (laneSwitchOn(name, env)) return;
31
+ throw new CliError(code, `${what} is off: it ships off until its clause is in Dev's rulebook (NODII-DEV-CLI-191). ${instead} ${LANE_SWITCHES[name]}=1 turns it on.`, 1);
32
+ }