@nodii/dev 0.6.218 → 0.6.220

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,11 +1,11 @@
1
1
  import { execFile as execFileCallback, spawn as nodeSpawn } from "node:child_process";
2
- import { closeSync, fstatSync, openSync, readSync, readdirSync, statSync } from "node:fs";
2
+ import { closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { open, readFile, writeFile } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
- import { dirname, join } from "node:path";
5
+ import { basename, dirname, join } from "node:path";
6
6
  import { promisify } from "node:util";
7
- import { profilePath, recordExhaustedAccount } from "./accounts.js";
8
- import { CliError, devRequest, encode } from "./core.js";
7
+ import { profilePath } from "./accounts.js";
8
+ import { CliError, configPath, devRequest, encode } from "./core.js";
9
9
  import { inboxForContinuation, laneMessageCommand } from "./lane-messages.js";
10
10
  import { laneSwitchOn } from "./lane-switches.js";
11
11
  import { HELPER_WINDOW_MS, processTable, toolCallChild } from "./process-tree.js";
@@ -62,6 +62,23 @@ export async function worktreeState(worktrees, { execute = execFile } = {}) {
62
62
  return { state: unreadable.length ? "unknown" : dirty.length ? "dirty" : "clean", dirty, unreadable };
63
63
  }
64
64
 
65
+ /**
66
+ * O3 item 2: a worktree's git state at a run's exit: its commit, branch,
67
+ * whether it holds uncommitted work, and how many commits it is ahead of
68
+ * origin/main (a fact, never the landed test of MW1-30.1). Null fields where
69
+ * git cannot say.
70
+ */
71
+ export async function gitAtExit(worktree, { execute = execFile } = {}) {
72
+ const git = async (...args) => {
73
+ try { return (await execute("git", ["-C", worktree, ...args], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 })).stdout.trim(); } catch { return null; }
74
+ };
75
+ const head = await git("rev-parse", "HEAD");
76
+ const branch = await git("symbolic-ref", "--quiet", "--short", "HEAD");
77
+ const status = await git("status", "--porcelain");
78
+ const ahead = await git("rev-list", "--count", "origin/main..HEAD");
79
+ return { head, branch, dirty: status === null ? null : status.length > 0, aheadOfBase: ahead === null || !/^\d+$/.test(ahead) ? null : Number(ahead) };
80
+ }
81
+
65
82
  async function readTail(path, bytes = LOG_TAIL_BYTES) {
66
83
  if (!path) return "";
67
84
  const handle = await open(path, "r");
@@ -76,153 +93,114 @@ async function readTail(path, bytes = LOG_TAIL_BYTES) {
76
93
  }
77
94
  }
78
95
 
79
- // NODII-DEV-CLI-191: 144 lane runs (7%) died on a spend, weekly or model
80
- // limit (49), the network (46) or auth (45), and a resume put them back on the
81
- // same account. The runtime's own lines name the failure.
82
- const USAGE_LIMIT = [
83
- /Claude AI usage limit reached/i,
84
- // "usage", "weekly", "session", "Opus": Claude and Codex name the limit
85
- // differently and add names, so any one or two words may stand before it.
86
- /\byou(?:'|’)ve hit your (?:[\w-]+ ){0,2}limit\b/i,
87
- // Claude's result record carries the error's own code whatever its words say.
88
- /"api_error"\s*:\s*"usage_limit_reached"/,
89
- /\b(?:5-hour|five-hour|session|weekly|opus|sonnet)\b[^\n]{0,40}\blimit reached\b/i,
90
- /\busage limit (?:reached|exceeded)\b/i,
91
- ];
92
- const AUTH = [
93
- /OAuth token (?:has )?expired/i, /\bauthentication_error\b/, /\bInvalid API key\b/i, /Please run \/login/i,
94
- /\bAPI Error:? 401\b|\b401 Unauthorized\b|"status":\s*401\b/i, /\btoken_expired\b|refresh token (?:was )?(?:already used|expired|invalid)/i,
95
- ];
96
- const NETWORK = [
97
- /\bcf-ray\b/i, /\bCloudflare\b/i, /\bECONNRESET\b/, /\bETIMEDOUT\b/, /\bECONNREFUSED\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,
98
- /\bfetch failed\b/i, /\b529\b[^\n]*\bOverloaded\b|\boverloaded_error\b/i, /stream disconnected before completion/i,
99
- ];
100
- const FAILURE_KINDS = [["usage_limit", USAGE_LIMIT], ["auth", AUTH], ["network", NETWORK]];
101
- /** How long an account waits when its failure names no reset time. */
102
- export const ACCOUNT_WAIT_MS = { usage_limit: 5 * 3_600_000, auth: 3_600_000, network: 3_600_000 };
103
- const FAILURE_SCAN_LINES = 40;
104
- const NO_FAILURE = Object.freeze({ kind: null, resetAt: null, line: null });
105
-
106
- const SUCCEEDED = Symbol("succeeded");
107
- /** The account a stub run's failure is recorded against (DEV-PROCESS-1): never a real profile. */
108
- export const STUB_ACCOUNT = "stub:drill";
109
96
 
110
97
  /**
111
- * The text of a log line the runtime itself wrote about its failure; null for
112
- * a tool's output, the model's own words and other events (a test run that
113
- * printed ECONNRESET is not a network failure); SUCCEEDED for a turn that
114
- * ended well, after which nothing older counts. The tail's first line may be
115
- * cut mid-record: a fragment of JSON is skipped.
98
+ * DEV-PROCESS-1 item 6: the run's final-record facts, read from the runtime's
99
+ * own output as it streams (never from the run log, which the lane can
100
+ * write): the last result record, the last rate-limit event, the last
101
+ * synthetic assistant message, and Codex's last turn.failed, turn.completed
102
+ * and error events. Dev classifies them (one classifier, in Dev); the CLI
103
+ * only carries the raw lines, redacted, with the exit code or signal.
116
104
  */
117
- function runtimeLine(line, first) {
118
- const text = line.trim();
119
- if (!text) return null;
120
- if (!text.startsWith("{")) return first && /^[^{"]*"\s*[,:}\]]/.test(text) ? null : text;
121
- let record;
122
- try { record = JSON.parse(text); } catch { return null; }
123
- if (record?.type === "result") return record.is_error ? text : SUCCEEDED;
124
- if (record?.type === "turn.completed") return SUCCEEDED;
125
- if (record?.type === "error" || record?.type === "turn.failed") return text;
126
- return record?.type === "assistant" && record?.message?.model === "<synthetic>" ? text : null;
127
- }
128
-
129
- const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
130
- const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
131
-
132
- function zonedParts(ms, timeZone) {
133
- const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", {
134
- timeZone, hourCycle: "h23", weekday: "short", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit",
135
- }).formatToParts(new Date(ms)).map((part) => [part.type, part.value]));
136
- 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()) };
137
- }
138
-
139
- /** The UTC time of a wall-clock time in a time zone. */
140
- function zonedToUtc(year, month, day, hour, minute, timeZone) {
141
- const wall = Date.UTC(year, month, day, hour, minute);
142
- const offset = (ms) => {
143
- const p = zonedParts(ms, timeZone);
144
- return Date.UTC(p.year, p.month, p.day, p.hour, p.minute, p.second) - Math.floor(ms / 1000) * 1000;
145
- };
146
- return wall - offset(wall - offset(wall));
147
- }
105
+ const RECORD_MAX = 8000;
106
+ const CODEX_ERRORS_KEPT = 5;
107
+ export class FinalRecordTap {
108
+ /**
109
+ * `tokens` carries the run's totals into a same-session continuation's tap
110
+ * (O3 item 2: the run's tokens, summed from its stream's usage records).
111
+ */
112
+ constructor({ tokens } = {}) {
113
+ this.partial = "";
114
+ this.kept = { result: null, rateLimit: null, synthetic: null, turnFailed: null, turnCompleted: null, errors: [] };
115
+ this.tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, ...(tokens ?? {}) };
116
+ this.messages = new Set();
117
+ }
148
118
 
149
- /** "3pm", "Mon 9am", "11:30pm (Asia/Kolkata)", "Nov 20th, 2026 3:05 PM": the next such time after now. */
150
- function parseWallClock(text, now, defaultZone) {
151
- const time = /\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\b/i.exec(text);
152
- if (!time) return null;
153
- const hour = (Number(time[1]) % 12) + (time[3].toLowerCase() === "p" ? 12 : 0);
154
- const minute = Number(time[2] ?? 0);
155
- let timeZone = defaultZone;
156
- const zone = /\(([A-Za-z_]+(?:\/[A-Za-z_+-]+)*)\)/.exec(text)?.[1];
157
- if (zone) {
158
- try { new Intl.DateTimeFormat("en-US", { timeZone: zone }); timeZone = zone; } catch {}
119
+ /** One usage record's tokens, added once: Claude repeats a message's usage on each of its content records. */
120
+ count(usage, id) {
121
+ if (!usage || typeof usage !== "object") return;
122
+ if (id) { if (this.messages.has(id)) return; this.messages.add(id); }
123
+ const n = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
124
+ this.tokens.input += n(usage.input_tokens);
125
+ this.tokens.output += n(usage.output_tokens);
126
+ this.tokens.cacheRead += n(usage.cache_read_input_tokens) + n(usage.cached_input_tokens);
127
+ this.tokens.cacheWrite += n(usage.cache_creation_input_tokens);
159
128
  }
160
- const today = zonedParts(now.getTime(), timeZone);
161
- const at = (year, month, day) => zonedToUtc(year, month, day, hour, minute, timeZone);
162
- 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);
163
- let ms;
164
- if (date) {
165
- const month = MONTHS.indexOf(date[1].toLowerCase());
166
- ms = at(date[3] ? Number(date[3]) : today.year, month, Number(date[2]));
167
- if (!date[3] && ms <= now.getTime()) ms = at(today.year + 1, month, Number(date[2]));
168
- } else {
169
- const weekday = /\b(sun|mon|tue|wed|thu|fri|sat)[a-z]*\b/i.exec(text);
170
- const ahead = weekday ? (WEEKDAYS.indexOf(weekday[1].toLowerCase()) - today.weekday + 7) % 7 : 0;
171
- ms = at(today.year, today.month, today.day + ahead);
172
- if (ms <= now.getTime()) ms = at(today.year, today.month, today.day + ahead + (weekday ? 7 : 1));
129
+
130
+ feed(chunk) {
131
+ const text = this.partial + String(chunk);
132
+ const lines = text.split("\n");
133
+ this.partial = lines.pop() ?? "";
134
+ // A line longer than any record kept is not one: drop what is buffered of it.
135
+ if (this.partial.length > 4 * 1024 * 1024) this.partial = "";
136
+ for (const line of lines) this.line(line);
173
137
  }
174
- return new Date(ms).toISOString();
175
- }
176
138
 
177
- const DURATION_MS = { d: 86_400_000, h: 3_600_000, m: 60_000, s: 1000 };
139
+ line(raw) {
140
+ const text = raw.trim();
141
+ if (!text.startsWith("{")) return;
142
+ let record;
143
+ try { record = JSON.parse(text); } catch { return; }
144
+ const keep = () => redactRunText(text).slice(0, RECORD_MAX);
145
+ // Claude's (and the stub's) assistant records and Codex's completed turns carry the usage.
146
+ if (record?.type === "assistant") this.count(record?.message?.usage, record?.message?.id);
147
+ else if (record?.type === "turn.completed") this.count(record?.usage);
148
+ if (record?.type === "result") this.kept.result = keep();
149
+ else if (record?.type === "rate_limit_event") this.kept.rateLimit = keep();
150
+ else if (record?.type === "assistant" && record?.message?.model === "<synthetic>") this.kept.synthetic = keep();
151
+ else if (record?.type === "turn.failed") this.kept.turnFailed = keep();
152
+ else if (record?.type === "turn.completed") this.kept.turnCompleted = keep();
153
+ else if (record?.type === "error") this.kept.errors = [...this.kept.errors, keep()].slice(-CODEX_ERRORS_KEPT);
154
+ }
178
155
 
179
- /** The reset time a usage-limit line gives, or null. */
180
- function limitResetAt(line, now, timeZone) {
181
- const epoch = /usage limit reached\|(\d{10,13})\b/i.exec(line)?.[1];
182
- if (epoch) return new Date(epoch.length > 10 ? Number(epoch) : Number(epoch) * 1000).toISOString();
183
- const after = /try again in\s+([^."\n]+)/i.exec(line)?.[1];
184
- if (after) {
185
- 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);
186
- if (total) return new Date(now.getTime() + total).toISOString();
156
+ /** The facts sent to Dev: the runtime, how it ended, and its final records in order. */
157
+ facts({ runtime, exitCode, signal }) {
158
+ if (this.partial) { this.line(this.partial); this.partial = ""; }
159
+ const { rateLimit, synthetic, result, errors, turnFailed, turnCompleted } = this.kept;
160
+ return {
161
+ runtime,
162
+ exitCode: Number.isInteger(exitCode) ? exitCode : null,
163
+ signal: signal ?? null,
164
+ source: "runtime_output",
165
+ records: [rateLimit, synthetic, result, ...errors, turnCompleted, turnFailed].filter(Boolean),
166
+ tokens: { ...this.tokens },
167
+ };
187
168
  }
188
- const at = /(?:try again at|resets?(?:\s+at)?)\s+(.+)$/i.exec(line)?.[1];
189
- return at ? parseWallClock(at, now, timeZone) : null;
190
169
  }
191
-
192
- /**
193
- * NODII-DEV-CLI-191: the account failure a run's log tail ends on: a
194
- * usage limit (with its reset time when the runtime gives one), auth, or the
195
- * network (Cloudflare, a reset connection, an overloaded API). The newest
196
- * line the runtime wrote decides; `{ kind: null }` when it names none.
197
- */
198
- export function classifyRuntimeFailure(logTail, { now = new Date(), timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone } = {}) {
199
- const lines = String(logTail ?? "").split("\n");
200
- for (let index = lines.length - 1; index >= Math.max(0, lines.length - FAILURE_SCAN_LINES); index -= 1) {
201
- const line = runtimeLine(lines[index], index === 0);
202
- if (line === SUCCEEDED) break;
203
- if (!line) continue;
204
- const found = FAILURE_KINDS.find(([, patterns]) => patterns.some((pattern) => pattern.test(line)));
205
- if (!found) continue;
206
- const kind = found[0];
207
- return { kind, resetAt: kind === "usage_limit" ? limitResetAt(line, now, timeZone) : null, line: line.slice(0, 1000) };
170
+ /** Whether Dev classes a turn's final-record facts as an account death (DEV-PROCESS-1 item 6). False when Dev does not answer. */
171
+ export async function accountDeath(request, facts) {
172
+ try {
173
+ return (await request("POST", "/api/v1/run-endings/classify", facts))?.data?.ending === "account_death";
174
+ } catch {
175
+ return false;
208
176
  }
209
- return NO_FAILURE;
210
177
  }
211
178
 
179
+ /** The account a stub run's failure is recorded against (DEV-PROCESS-1): never a real profile. */
180
+ export const STUB_ACCOUNT = "stub:drill";
181
+
212
182
  const describeWorktree = ({ state, dirty, unreadable }) => [
213
183
  ...dirty.slice(0, 50),
214
184
  ...(dirty.length > 50 ? [`... ${dirty.length - 50} more`] : []),
215
185
  ...unreadable.map((worktree) => `${worktree}: git status failed`),
216
186
  ].join("\n") || state;
217
187
 
218
- async function send(request, path, body, attempts = 3) {
188
+ // DEV-PROCESS-1 item 6: an exit report Dev did not take (it was unreachable, or
189
+ // answered 5xx with no code) is tried again for about ten minutes, so a run's
190
+ // ending reaches its row even when the first report is refused.
191
+ export const REPORT_ATTEMPTS = 15;
192
+ const reportDelay = (attempt) => Math.min(60_000, 500 * 2 ** (attempt - 1));
193
+ const UNANSWERED = /^(DEV_TIMEOUT|DEV_UNREACHABLE|HTTP_5\d\d)$/;
194
+
195
+ async function send(request, path, body, attempts = REPORT_ATTEMPTS, { delay = reportDelay, wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) } = {}) {
219
196
  for (let attempt = 1; ; attempt++) {
220
197
  try {
221
198
  return await request("POST", path, body);
222
199
  } catch (error) {
223
- // Dev's answer is final; only a transport failure is retried.
224
- if (error instanceof CliError || attempt >= attempts) throw error;
225
- await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
200
+ // Dev's answer is final; only a transport failure or a gateway error with no Dev code is retried.
201
+ const unanswered = !(error instanceof CliError) || UNANSWERED.test(error.code ?? "");
202
+ if (!unanswered || attempt >= attempts) throw error;
203
+ await wait(delay(attempt));
226
204
  }
227
205
  }
228
206
  }
@@ -418,13 +396,12 @@ async function finishLane(request, laneKey, reason, evidence) {
418
396
  * every exit, exit 0 included, is a process exit: Dev orphans the run and
419
397
  * routes it for recovery (`lane resume`).
420
398
  */
421
- export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations = 0, runtime, profile, home }, {
399
+ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations = 0, runtime, profile, home, finalRecord = null, harnessEnd = null }, {
422
400
  request = devRequest,
423
401
  inspect = worktreeState,
424
402
  tail = readTail,
425
403
  markTerminal = markWatchedTerminal,
426
404
  now = () => new Date(),
427
- markExhausted = recordExhaustedAccount,
428
405
  tellCoordinator = messageCoordinator,
429
406
  recordBaseline = blockerBaselineAtExit,
430
407
  } = {}) {
@@ -440,19 +417,11 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
440
417
  ];
441
418
  let outcome;
442
419
  let body;
420
+ // DEV-PROCESS-1 item 6: how the run ended is Dev's to say, from the final
421
+ // record's facts (the runtime's own output and exit code), never from the
422
+ // log the lane can write. Dev sets the account's stop mark and names the
423
+ // death's fingerprint; the CLI only reads its answer back.
443
424
  let accountFailure = null;
444
- // NODII-DEV-CLI-191: a run that died on its account says so, and the
445
- // account is recorded exhausted so lane resume does not relaunch onto it.
446
- const readAccountFailure = async (logTail) => {
447
- const failure = signal ? NO_FAILURE : classifyRuntimeFailure(logTail, { now: now() });
448
- if (!failure.kind) return { failure, note: "" };
449
- // The drill's stub has no account: its planted failures are recorded under a name no real profile has.
450
- const account = runtime === "stub" ? profilePath(profile) || STUB_ACCOUNT : profilePath(profile) || join(home ?? homedir(), runtime === "codex" ? ".codex" : ".claude");
451
- const until = failure.resetAt ?? new Date(now().getTime() + ACCOUNT_WAIT_MS[failure.kind]).toISOString();
452
- accountFailure = { kind: failure.kind, resetAt: failure.resetAt, until, profile: account };
453
- await markExhausted(account, { kind: failure.kind, resetAt: failure.resetAt, until, laneKey, runId, line: failure.line, recordedAt: now().toISOString() }).catch(() => {});
454
- return { failure, note: ` 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.` };
455
- };
456
425
  if (finished && clean) {
457
426
  outcome = worktree.state === "clean" ? "done" : "handed_off";
458
427
  body = outcome === "done"
@@ -461,10 +430,7 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
461
430
  } else if (finished) {
462
431
  // A finished lane has nothing to resume, so a failed exit is not a death.
463
432
  outcome = "failed";
464
- // A lane whose done check is recorded but which is not terminal (READY,
465
- // waiting to land) can still be resumed: its account death is recorded.
466
- const { note } = FINISHED_LANE.has(status) ? { note: "" } : await readAccountFailure(redactRunText(await tail(logPath).catch(() => "")).trim());
467
- body = { status: "failed", reason: `The lane process ${exited} after lane ${laneKey} reached ${status}.${note}`, evidence };
433
+ body = { status: "failed", reason: `The lane process ${exited} after lane ${laneKey} reached ${status}.`, evidence };
468
434
  } else if (blocked) {
469
435
  // hub-58 (30 Oct): a lane that recorded BLOCKED stopped on purpose. Its
470
436
  // run ends blocked: never an orphan, never a death to resume.
@@ -475,27 +441,35 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
475
441
  await recordBaseline(laneKey, lane, { request }).catch(() => {});
476
442
  } else {
477
443
  outcome = "process_exit";
444
+ // The tail is evidence for a person reading the run; nothing classifies it.
478
445
  const logTail = redactRunText(await tail(logPath).catch(() => "")).trim();
479
- const { failure, note: accountNote } = await readAccountFailure(logTail);
480
446
  body = {
481
- 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}`,
482
- deathFingerprint: failure.kind ? `lane-account-${failure.kind}` : signal ? `lane-signal-${signal}` : clean ? "lane-unfinished-exit-0" : `lane-exit-${exitCode ?? -1}`,
447
+ 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).` : ""}`,
448
+ deathFingerprint: signal ? `lane-signal-${signal}` : clean ? "lane-unfinished-exit-0" : `lane-exit-${exitCode ?? -1}`,
483
449
  exitCode: Number.isInteger(exitCode) && exitCode >= 0 && exitCode <= 255 ? exitCode : -1,
484
450
  ...(logTail ? { logTail: logTail.slice(-50_000) } : {}),
485
451
  };
486
452
  }
453
+ // DEV-PROCESS-1 item 6: every exit path carries the final-record facts,
454
+ // with the lane's worktree as git reads it at exit (O3 item 2).
455
+ if (finalRecord) body.finalRecord = { ...finalRecord, ...(worktrees?.[0] ? { git: await gitAtExit(worktrees[0]).catch(() => null) } : {}) };
456
+ // DEV-PROCESS-1 item 3: the harness ended this run on purpose; Dev records who and why and counts no death.
457
+ if (harnessEnd) body.harnessEnd = harnessEnd;
487
458
  // NODII-DEV-CLI-191 (19 Nov after-measurement): a run that chose to end
488
459
  // (exit 0, no account death) while its lane waits on something of its own
489
460
  // leaves the same baseline as a blocked one, so a plain resume finds
490
461
  // nothing changed. gen-90-dev, READY and waiting on the operator, was
491
462
  // resumed three times in ten minutes without one. A kill mid-work records nothing.
492
- if (outcome !== "blocked" && clean && !accountFailure && (lane?.waits?.length ?? 0) > 0)
493
- await recordBaseline(laneKey, lane, { request }).catch(() => {});
463
+ let answer = null;
494
464
  try {
495
- await send(request, `/api/v1/runs/${encode(runId)}/${outcome === "process_exit" ? "process-exit" : "end"}`, body);
465
+ answer = await send(request, `/api/v1/runs/${encode(runId)}/${outcome === "process_exit" ? "process-exit" : "end"}`, body);
496
466
  } catch (error) {
497
467
  // The agent may have ended its own run already; that is not a failure.
498
- if (error?.code === "RUN_ALREADY_TERMINAL") outcome = "already_terminal";
468
+ if (error?.code === "RUN_ALREADY_TERMINAL") {
469
+ outcome = "already_terminal";
470
+ // DEV-PROCESS-1 item 6: a run the agent ended itself still died as it died: its facts reach the row.
471
+ if (finalRecord) await send(request, `/api/v1/runs/${encode(runId)}/final-record`, { finalRecord }).catch(() => {});
472
+ }
499
473
  // A Dev without the blocked status refuses it: report the exit, which a
500
474
  // current Dev also ends blocked from the lane's own record.
501
475
  else if (outcome === "blocked" && error instanceof CliError) {
@@ -504,9 +478,16 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
504
478
  reason: body.reason,
505
479
  deathFingerprint: signal ? `lane-signal-${signal}` : clean ? "lane-unfinished-exit-0" : `lane-exit-${exitCode ?? -1}`,
506
480
  exitCode: Number.isInteger(exitCode) && exitCode >= 0 && exitCode <= 255 ? exitCode : -1,
481
+ ...(finalRecord ? { finalRecord } : {}),
482
+ ...(harnessEnd ? { harnessEnd } : {}),
507
483
  });
508
484
  } else throw error;
509
485
  }
486
+ const ending = answer?.data?.run?.ending ?? null;
487
+ if (ending?.ending === "account_death")
488
+ accountFailure = { kind: ending.kind, statedReset: ending.statedReset ?? null, profile: profilePath(profile) || (runtime === "stub" ? STUB_ACCOUNT : null) };
489
+ if (outcome !== "blocked" && clean && !accountFailure && (lane?.waits?.length ?? 0) > 0)
490
+ await recordBaseline(laneKey, lane, { request }).catch(() => {});
510
491
  // hub-525: only a clean exit after a recorded done check, with
511
492
  // nothing left uncommitted, finishes the lane; a failed, blocked, unfinished
512
493
  // or handed-off exit never does. READY is a recorded done check too, so a
@@ -534,6 +515,38 @@ export async function markWatchedTerminal(runId, { home } = {}) {
534
515
  await saveWatchedRun({ ...record, terminalSeenAt: new Date().toISOString(), registryPath });
535
516
  }
536
517
 
518
+ /**
519
+ * DEV-PROCESS-1 item 3: before a harness verb (lane stop, a coordinator's end)
520
+ * signals a lane's supervisor, it leaves a note naming itself and why, so the
521
+ * run's end reaches Dev as the harness's, with who and why, never as a death.
522
+ * The note is per lane and read once, within its 10-minute life.
523
+ */
524
+ // Beside the run folders: the same place for a lane's config (agents/lane-*.json) and the caller's (config.json).
525
+ const runsRoot = () => {
526
+ const configDir = dirname(configPath());
527
+ return join(basename(configDir) === "agents" ? dirname(configDir) : configDir, "runs");
528
+ };
529
+ export const endNotePath = (laneKey, root = runsRoot()) => join(root, "end-notes", `${String(laneKey).replace(/[^A-Za-z0-9_.-]/g, "_")}.json`);
530
+ const END_NOTE_MS = 10 * 60_000;
531
+
532
+ export function writeEndNote(laneKey, { by, reason }, { root = runsRoot(), now = () => new Date() } = {}) {
533
+ const path = endNotePath(laneKey, root);
534
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
535
+ writeFileSync(path, JSON.stringify({ by: String(by).slice(0, 200), reason: String(reason).slice(0, 1000), writtenAt: now().toISOString() }), { mode: 0o600 });
536
+ }
537
+
538
+ export function readEndNote(laneKey, { root = runsRoot(), now = () => new Date() } = {}) {
539
+ const path = endNotePath(laneKey, root);
540
+ try {
541
+ const note = JSON.parse(readFileSync(path, "utf8"));
542
+ rmSync(path, { force: true });
543
+ if (now().getTime() - Date.parse(note.writtenAt) > END_NOTE_MS) return null;
544
+ return { by: note.by, reason: note.reason };
545
+ } catch {
546
+ return null;
547
+ }
548
+ }
549
+
537
550
  // The drill's stub runtime writes Claude's records (DEV-PROCESS-1).
538
551
  const SESSION_ID = { claude: /"session_id":"([0-9a-f-]{36})"/g, codex: /"thread_id":"([0-9a-f-]{36})"/g, stub: /"session_id":"([0-9a-f-]{36})"/g };
539
552
 
@@ -746,11 +759,18 @@ export async function superviseLane({
746
759
  };
747
760
  let child;
748
761
  try {
749
- child = spawn(invocation.command, invocation.args, { cwd: invocation.cwd, env: invocation.env, shell: false, stdio: ["pipe", "inherit", "inherit"] });
762
+ child = spawn(invocation.command, invocation.args, { cwd: invocation.cwd, env: invocation.env, shell: false, stdio: ["pipe", "pipe", "inherit"] });
750
763
  } catch (error) {
751
764
  tell({ type: "error", message: error.message });
752
765
  return exit(1);
753
766
  }
767
+ // DEV-PROCESS-1 item 6: the runtime's output passes through here to the run log, and its final records are kept.
768
+ let tap = new FinalRecordTap();
769
+ const relay = (proc, into) => proc.stdout?.on("data", (chunk) => {
770
+ try { process.stdout.write(chunk); } catch {}
771
+ into.feed(chunk);
772
+ });
773
+ relay(child, tap);
754
774
  let state = "spawning";
755
775
  // The run's heartbeat (30 Oct, hub-58 P0): the supervisor heartbeats a
756
776
  // launched lane's run, as the lane identity that owns it. A live PID is not a
@@ -821,7 +841,13 @@ export async function superviseLane({
821
841
  });
822
842
  // A signal sent to the supervisor ends the runtime too, and is reported.
823
843
  let stopping = false;
824
- for (const name of SIGNALS) process.on(name, () => { stopping = true; child.kill(name); });
844
+ // DEV-PROCESS-1 item 3: a supervisor told to stop is a harness end, not a death. The verb that sent the signal leaves a note naming itself.
845
+ let harnessEnd = null;
846
+ for (const name of SIGNALS) process.on(name, () => {
847
+ stopping = true;
848
+ harnessEnd ??= { ...(readEndNote(laneKey) ?? { by: "unnamed", reason: `the lane supervisor was sent ${name} with no note from the harness` }), signal: name, at: new Date().toISOString() };
849
+ child.kill(name);
850
+ });
825
851
  let { exitCode, signal } = await closed;
826
852
  if (state !== "running") {
827
853
  clearInterval(heartbeat);
@@ -835,13 +861,18 @@ export async function superviseLane({
835
861
  if (!sessionId) break;
836
862
  let lane;
837
863
  try { lane = (await request("GET", `/api/v1/lanes/${encode(laneKey)}`)).data; } catch { break; }
838
- // NODII-DEV-CLI-191: a fixable blocker is continued; only a human gate ends the run.
839
- if (doneCheckRecorded(lane) || laneRunEnds(lane, env)) break;
864
+ if (doneCheckRecorded(lane)) break;
840
865
  // NODII-DEV-CLI-191: the same session on a used-up account only fails again.
841
- if (classifyRuntimeFailure(redactRunText(await readTail(logPath).catch(() => ""))).kind) break;
842
- const message = continueTaskMessage(laneKey, lane, env);
866
+ // DEV-PROCESS-1 item 6: Dev says whether this turn's facts are an account
867
+ // death; an unanswered ask continues, as a turn with no death would.
868
+ if (await accountDeath(request, tap.facts({ runtime: runtimeOf(invocation), exitCode, signal }))) break;
843
869
  // NODII-DEV-CLI-191: unread lane messages lead the next turn (Claude and Codex alike), delivered once.
844
870
  const mail = await inbox(laneKey, invocation, { env }).catch(() => null);
871
+ // NODII-DEV-CLI-191: a fixable blocker is continued; only a human gate ends the run.
872
+ // DEV-PROCESS-1 (the planner's live examples, 25 Nov): a message waiting for a
873
+ // lane at its gate is often the answer to it, so the run reads it first.
874
+ if (laneRunEnds(lane, env) && !mail) break;
875
+ const message = continueTaskMessage(laneKey, lane, env);
845
876
  continued += 1;
846
877
  await request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, {
847
878
  note: `continuation ${continued}/${limit} of session ${sessionId} after exit ${exitCode}: ${message}`.slice(0, 500),
@@ -850,7 +881,9 @@ export async function superviseLane({
850
881
  beatLane();
851
882
  const next = continuationInvocation(invocation, sessionId);
852
883
  try {
853
- child = spawn(next.command, next.args, { cwd: next.cwd, env: next.env, shell: false, stdio: ["pipe", "inherit", "inherit"] });
884
+ child = spawn(next.command, next.args, { cwd: next.cwd, env: next.env, shell: false, stdio: ["pipe", "pipe", "inherit"] });
885
+ tap = new FinalRecordTap({ tokens: tap.facts({}).tokens });
886
+ relay(child, tap);
854
887
  } catch {
855
888
  break;
856
889
  }
@@ -872,10 +905,11 @@ export async function superviseLane({
872
905
  try {
873
906
  const runtime = runtimeOf(invocation);
874
907
  const profile = runtime === "stub" ? invocation.stubAccount ?? null : invocation.env?.[runtime === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"] ?? null;
875
- const result = await report({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations: continued, runtime, profile });
908
+ const finalRecord = tap.facts({ runtime, exitCode, signal });
909
+ const result = await report({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations: continued, runtime, profile, finalRecord, harnessEnd });
876
910
  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`);
877
911
  if (result.accountFailure)
878
- 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`);
912
+ process.stderr.write(`nodii-dev: Dev classed this run an account death (${result.accountFailure.kind}${result.accountFailure.statedReset ? `, stated reset ${result.accountFailure.statedReset}` : ""}); ${result.accountFailure.profile ?? "its account"} is stopped in Dev and tried again in an hour.\n`);
879
913
  if (result.laneFinish?.startsWith("failed"))
880
914
  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`);
881
915
  else if (result.laneFinish)