@nodii/dev 0.6.175 → 0.6.177

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
 
@@ -71,6 +75,133 @@ async function readTail(path, bytes = LOG_TAIL_BYTES) {
71
75
  }
72
76
  }
73
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
+
74
205
  const describeWorktree = ({ state, dirty, unreadable }) => [
75
206
  ...dirty.slice(0, 50),
76
207
  ...(dirty.length > 50 ? [`... ${dirty.length - 50} more`] : []),
@@ -143,11 +274,66 @@ export function laneBlockedReason(lane) {
143
274
  return /^\s*blocked\b/i.test(note) || /^\s*WAITING\s*:/.test(note) ? `Lane heartbeat: ${note.slice(0, 500)}` : null;
144
275
  }
145
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
+
146
329
  /** The step a lane that stopped early goes back to (hub-58, NODII-DEV-CLI-8/9). */
147
- export function continueTaskMessage(laneKey, lane) {
330
+ export function continueTaskMessage(laneKey, lane, env = process.env) {
148
331
  const next = (lane?.next ?? []).map((step) => `${step.side}/${step.step}`);
149
332
  const current = [lane?.currentBackendStep && `backend/${lane.currentBackendStep}`, lane?.currentFrontendStep && `frontend/${lane.currentFrontendStep}`].filter(Boolean);
150
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}.`;
151
337
  const leeway = laneLeewayStep(lane);
152
338
  const issue = leeway?.blockerIssueKey ?? "its blocker";
153
339
  if (leeway?.kind === "ask")
@@ -205,11 +391,13 @@ async function finishLane(request, laneKey, reason, evidence) {
205
391
  * every exit, exit 0 included, is a process exit: Dev orphans the run and
206
392
  * routes it for recovery (`lane resume`).
207
393
  */
208
- 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 }, {
209
395
  request = devRequest,
210
396
  inspect = worktreeState,
211
397
  tail = readTail,
212
398
  markTerminal = markWatchedTerminal,
399
+ now = () => new Date(),
400
+ markExhausted = recordExhaustedAccount,
213
401
  } = {}) {
214
402
  const worktree = await inspect(worktrees);
215
403
  const { status, finished, blocked, finishEvidence } = await laneProgress(request, laneKey);
@@ -223,6 +411,7 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
223
411
  ];
224
412
  let outcome;
225
413
  let body;
414
+ let accountFailure = null;
226
415
  if (finished && clean) {
227
416
  outcome = worktree.state === "clean" ? "done" : "handed_off";
228
417
  body = outcome === "done"
@@ -240,9 +429,20 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
240
429
  } else {
241
430
  outcome = "process_exit";
242
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
+ }
243
443
  body = {
244
- 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).` : ""}`,
245
- 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}`,
246
446
  exitCode: Number.isInteger(exitCode) && exitCode >= 0 && exitCode <= 255 ? exitCode : -1,
247
447
  ...(logTail ? { logTail: logTail.slice(-50_000) } : {}),
248
448
  };
@@ -272,7 +472,7 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
272
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)
273
473
  : null;
274
474
  await markTerminal(runId).catch(() => {});
275
- return { outcome, exitCode: exitCode ?? null, signal: signal ?? null, worktree: worktree.state, laneStatus: status, ...(laneFinish ? { laneFinish } : {}) };
475
+ return { outcome, exitCode: exitCode ?? null, signal: signal ?? null, worktree: worktree.state, laneStatus: status, ...(laneFinish ? { laneFinish } : {}), ...(accountFailure ? { accountFailure } : {}) };
276
476
  }
277
477
 
278
478
  /** The sweep skips a run whose exit was reported (it would otherwise report process_dead). */
@@ -336,6 +536,49 @@ const logSize = (logPath) => {
336
536
  try { return statSync(logPath).size; } catch { return null; }
337
537
  };
338
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
+
339
582
  const continuationLimit = (env) => {
340
583
  const value = Number(env.NODII_DEV_LANE_CONTINUATIONS ?? 3);
341
584
  return Number.isInteger(value) && value >= 0 ? value : 3;
@@ -351,6 +594,7 @@ export async function superviseLane({
351
594
  request = devRequest,
352
595
  rewatch = rewatchRun,
353
596
  env = process.env,
597
+ inbox = inboxForContinuation,
354
598
  } = {}) {
355
599
  if (typeof channel.send !== "function")
356
600
  throw new CliError("USAGE", "__lane-supervisor is started by lane launch and lane resume only.", 2);
@@ -369,18 +613,30 @@ export async function superviseLane({
369
613
  return exit(1);
370
614
  }
371
615
  let state = "spawning";
372
- // The run's heartbeat (30 Oct, hub-58 P0): the heartbeat hook fires only on a
373
- // tool use or at the end of a turn, so the supervisor heartbeats a launched
374
- // 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
375
618
  // heartbeat (MW1-36): a tick counts only when the runtime has written to its
376
- // log since the last one, so a hung runtime goes Quiet and then Orphan.
377
- 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 });
378
628
  const heartbeat = setInterval(() => {
379
629
  if (state !== "running") return;
380
- const size = logSize(logPath);
381
- if (size === null || size === lastLogSize) return;
382
- lastLogSize = size;
383
- 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; }, () => {});
384
640
  }, heartbeatInterval(env));
385
641
  const closed = new Promise((resolve) => child.once("close", (exitCode, signal) => resolve({ exitCode, signal })));
386
642
  child.once("error", (error) => {
@@ -426,8 +682,13 @@ export async function superviseLane({
426
682
  if (!sessionId) break;
427
683
  let lane;
428
684
  try { lane = (await request("GET", `/api/v1/lanes/${encode(laneKey)}`)).data; } catch { break; }
429
- if (doneCheckRecorded(lane) || laneBlocked(lane)) break;
430
- 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);
431
692
  continued += 1;
432
693
  await request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, {
433
694
  note: `continuation ${continued}/${limit} of session ${sessionId} after exit ${exitCode}: ${message}`.slice(0, 500),
@@ -448,14 +709,18 @@ export async function superviseLane({
448
709
  });
449
710
  // A runtime that exits before reading its prompt must not end the supervisor (EPIPE).
450
711
  child.stdin?.on("error", () => {});
451
- child.stdin?.end(`${message}\n`);
712
+ child.stdin?.end(`${mail ? `${mail}\n\n` : ""}${message}\n`);
452
713
  process.stderr.write(`nodii-dev: ${message} (same-session continuation ${continued}/${limit})\n`);
453
714
  ({ exitCode, signal } = await ended);
454
715
  }
455
716
  clearInterval(heartbeat);
456
717
  try {
457
- 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 });
458
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`);
459
724
  if (result.laneFinish?.startsWith("failed"))
460
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`);
461
726
  else if (result.laneFinish)
@@ -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
+ }
package/dist/lanes.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { readPolicy } from "./repo-policy.js";
2
2
  import { execFile } from "node:child_process";
3
3
  import { readFile, realpath, writeFile } from "node:fs/promises";
4
- import { isAbsolute } from "node:path";
4
+ import { isAbsolute, join } from "node:path";
5
5
  import { promisify } from "node:util";
6
- import { coordinatorMachineId, listAccounts, profilePath, reportUsage } from "./accounts.js";
6
+ import { coordinatorMachineId, listAccounts, liveExhaustedAccounts, pickHeadroomAccount, profilePath, reportUsage } from "./accounts.js";
7
7
  import { CliError, encode, devRequest, query, readConfig, requireFlag, LANE_CAP_RAISE_PROMPT } from "./core.js";
8
- import { launchRecovery } from "./runtime-launcher.js";
8
+ import { launchRecovery, recoveryStateRoot } from "./runtime-launcher.js";
9
+ import { defaultReaders, fingerprintStore, resumeGate } from "./resume-gate.js";
9
10
  import { assertGovernorOpen, readGovernor } from "./governor.js";
10
11
  import { recordReviewReceipt, reviewCommitContext } from "./safety.js";
11
12
  import { GATHER_TIMEOUT_MS, PICKER_FIRST_PICK_TIMEOUT_MS, agentFallbackReason, gatherDeadline, gatherText, pickDocuments, pickerModelName, pickTimingLine, pickTimingStats, readPickTimings, recordPickTiming, warmPicker, withPickLock } from "./gather.js";
12
13
  import { storeGatherFreeze } from "./freeze.js";
13
- import { doneCheckRecorded, fixableBlocker } from "./lane-supervisor.js";
14
+ import { doneCheckRecorded, fixableBlocker, subagentBudgetLine } from "./lane-supervisor.js";
15
+ import { assertLaneSwitchOn } from "./lane-switches.js";
14
16
  import { STEWARD_DONE_CHECK, stewardObjective } from "./session-kind.js";
15
17
  import { availableMemoryBytes } from "./host.js";
16
18
  import { assertNothingPending, devDown, queuePending, receiptEvidenceBody, signedBuiltAck } from "./receipt.js";
@@ -211,8 +213,10 @@ async function laneContract(id, request, options) {
211
213
  // Gather never ends on a bare "finished" (hub-58): the next step is the task.
212
214
  // Dev has moved the lane past gather by now (NODII-DEV-CLI-3); recording the
213
215
  // done check is what lets a launched run end finished (NODII-DEV-CLI-4).
214
- const nextStepText = (ref, doneCheck) =>
215
- `Gather is finished. Next: Task. Work the objective until ${doneCheck} is met, record it with \`nodii-dev lane done-check ${ref} --evidence TEXT|URL\`, then run \`nodii-dev lane land ${ref}\` (or the lane's finish command). Don't stop before that.`;
216
+ const nextStepText = (ref, doneCheck, subagents) => [
217
+ `Gather is finished. Next: Task. Work the objective until ${doneCheck} is met, record it with \`nodii-dev lane done-check ${ref} --evidence TEXT|URL\`, then run \`nodii-dev lane land ${ref}\` (or the lane's finish command). Don't stop before that.`,
218
+ subagentBudgetLine(subagents),
219
+ ].filter(Boolean).join("\n");
216
220
  const agentShortlistText = (ref, data, flags) => [
217
221
  ...contractLines(data),
218
222
  `Trigger shortlist ${data.shortlistId} · ${JSON.stringify(data.objective)}`,
@@ -507,7 +511,7 @@ async function resumeHostLost(flags, deps, { request, config }) {
507
511
  }
508
512
 
509
513
  export async function laneCommand(action, args, flags, deps = {}) {
510
- const { request = devRequest, config = readConfig, refreshAccounts = refreshMoveAccounts, gitContext = inferGitContext, commitsOf = branchCommits, read = (path) => readFile(path, "utf8"), reviewContext = reviewCommitContext, reviewReceipt = recordReviewReceipt, picker = pickDocuments, warm = warmPicker, firstPickTimeoutMs = PICKER_FIRST_PICK_TIMEOUT_MS, timings = { record: recordPickTiming, read: readPickTimings }, changedPaths = laneChangedPaths, gatherTimeoutMs = GATHER_TIMEOUT_MS, deadline: outerDeadline, storeFreeze = storeGatherFreeze, launch = launchRecovery, rebind = rebindLaneConfig, catalog = loadDsCatalog, pickLock = withPickLock, check: checkDeps = {}, signReceipt = null } = deps;
514
+ const { request = devRequest, config = readConfig, refreshAccounts = refreshMoveAccounts, exhaustedAccounts = liveExhaustedAccounts, pickAccount = pickHeadroomAccount, gitContext = inferGitContext, commitsOf = branchCommits, read = (path) => readFile(path, "utf8"), reviewContext = reviewCommitContext, reviewReceipt = recordReviewReceipt, picker = pickDocuments, warm = warmPicker, firstPickTimeoutMs = PICKER_FIRST_PICK_TIMEOUT_MS, timings = { record: recordPickTiming, read: readPickTimings }, changedPaths = laneChangedPaths, gatherTimeoutMs = GATHER_TIMEOUT_MS, deadline: outerDeadline, storeFreeze = storeGatherFreeze, launch = launchRecovery, rebind = rebindLaneConfig, catalog = loadDsCatalog, pickLock = withPickLock, check: checkDeps = {}, signReceipt = null } = deps;
511
515
  if (action === "resume" && flags["host-lost"]) {
512
516
  if (args[0]) throw new CliError("USAGE", "lane resume --host-lost takes no <key>: it resumes every host_lost lane on this machine.", 2);
513
517
  return resumeHostLost(flags, deps, { request, config });
@@ -741,6 +745,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
741
745
  ask: contract.objective.ask,
742
746
  boundaries: contract.boundaries,
743
747
  issue: contract.objective.issue,
748
+ issueSet: contract.objective.issueSet,
744
749
  laneNotes: contract.objective.laneNotes,
745
750
  doneCheck: contract.objective.doneCheck ?? doneCheck,
746
751
  lookups: lookup ? [lookup] : [],
@@ -764,7 +769,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
764
769
  const result = { ...payload, picker: { model: picked.model ?? null, latency: picked.latency ?? null, ...(picked.timing ? { timing: picked.timing, stats: picked.stats } : {}) } };
765
770
  const timingLine = picked.timing ? `\n${pickTimingLine(picked.timing, picked.stats)}` : "";
766
771
  const doneText = contract?.objective?.doneCheck ?? doneCheck;
767
- return { payload: result, human: (p) => `${gatherText(p, objective, reasons)}${scopeNotice}${timingLine}\n\n${nextStepText(ref, doneText)}` };
772
+ return { payload: result, human: (p) => `${gatherText(p, objective, reasons)}${scopeNotice}${timingLine}\n\n${nextStepText(ref, doneText, lane?.subagentQuota)}` };
768
773
  } catch (error) {
769
774
  if (signal.aborted) throw new CliError("GATHER_TIMEOUT", `Gather's Dev requests exceeded their ${Math.round(deadline.ms / 1000)}-second deadline (the local pick runs on its own budget); nothing was retried.`, 1);
770
775
  throw error;
@@ -1106,13 +1111,35 @@ export async function laneCommand(action, args, flags, deps = {}) {
1106
1111
  // account. Dev keeps no class for a lane, so it is named here, as at launch.
1107
1112
  if ((flags.profile === undefined) !== (flags.class === undefined))
1108
1113
  throw new CliError("USAGE", "lane resume --profile PATH and --class long|short|no-build go together.", 2);
1114
+ const named = flags.profile !== undefined
1115
+ ? { profile: typeof flags.profile === "string" ? profilePath(flags.profile.trim()) : "", workClass: { long: "long", short: "short", "no-build": "no_build" }[flags.class] }
1116
+ : null;
1117
+ if (named && !isAbsolute(named.profile)) throw new CliError("USAGE", "--profile must be an absolute runtime profile path.", 2);
1118
+ if (named && !named.workClass) throw new CliError("USAGE", "--class must be long, short or no-build (a one-file fix, a publish or verify relaunch, or an evidence-only step).", 2);
1119
+ // NODII-DEV-CLI-191: never relaunch onto an account the supervisor
1120
+ // recorded exhausted (a usage limit, auth or the network) before its reset.
1121
+ const exhausted = await exhaustedAccounts().catch(() => ({}));
1122
+ const refusal = (profile, entry, why) => new CliError("ACCOUNT_EXHAUSTED", `${ref}: ${profile} is recorded exhausted (${entry.kind}) until ${entry.until}${why}. Resume it after that, or move it with lane resume ${ref} --profile PATH --class long|short|no-build to another account.`, 1);
1123
+ if (named && exhausted[named.profile]) throw refusal(named.profile, exhausted[named.profile], "");
1124
+ let target = named;
1125
+ let picked = null;
1126
+ if (!named && Object.keys(exhausted).length) {
1127
+ const launch = (await request("GET", `/api/v1/lanes/${encode(id)}`)).data?.launch;
1128
+ const current = launch?.profile ? profilePath(launch.profile) : null;
1129
+ const entry = current ? exhausted[current] : null;
1130
+ if (entry) {
1131
+ const workClass = ["long", "short", "no_build"].includes(launch.workClass) ? launch.workClass : "long";
1132
+ picked = await pickAccount({ runtime: launch.runtime, from: current, exclude: Object.keys(exhausted), workClass }, { request, config });
1133
+ if (!picked) throw refusal(current, entry, `, and no other registered ${launch.runtime} account on this machine has headroom for ${workClass.replace("_", "-")} work`);
1134
+ target = { profile: profilePath(picked.profile), workClass };
1135
+ picked.note = `${ref}: ${current} is recorded exhausted (${entry.kind}) until ${entry.until}, so the lane moves to ${target.profile} (band ${picked.band}).`;
1136
+ }
1137
+ }
1109
1138
  let move = {};
1110
- if (flags.profile !== undefined) {
1111
- const profile = typeof flags.profile === "string" ? profilePath(flags.profile.trim()) : "";
1112
- if (!isAbsolute(profile)) throw new CliError("USAGE", "--profile must be an absolute runtime profile path.", 2);
1113
- const workClass = { long: "long", short: "short", "no-build": "no_build" }[flags.class];
1114
- if (!workClass) throw new CliError("USAGE", "--class must be long, short or no-build (a one-file fix, a publish or verify relaunch, or an evidence-only step).", 2);
1115
- await refreshAccounts(profile, { request, config });
1139
+ if (target) {
1140
+ const { profile, workClass } = target;
1141
+ // A picked account was read just now.
1142
+ if (!picked) await refreshAccounts(profile, { request, config });
1116
1143
  move = { profile, workClass };
1117
1144
  // hub-232: a long resume is a launch for the governor; a short
1118
1145
  // or no-build resume (a close-out) is never refused. Dev refuses the same.
@@ -1125,12 +1152,33 @@ export async function laneCommand(action, args, flags, deps = {}) {
1125
1152
  if (governor) assertGovernorOpen(governor);
1126
1153
  }
1127
1154
  }
1155
+ // NODII-DEV-CLI-191: --if-changed resumes only when a blocker's real state
1156
+ // changed since the last resume. A superseded lane is refused with the
1157
+ // evidence and stopped by nothing here: MW1-28 names a lane's exits, and
1158
+ // the coordinator ends it by one of them. A landed lane goes on to deploy.
1159
+ let gate = null;
1160
+ if (flags["if-changed"] !== undefined) {
1161
+ assertLaneSwitchOn("resumeIfChanged", "RESUME_IF_CHANGED_OFF", "lane resume --if-changed", "Resume the lane without it, as before.", deps.env ?? process.env);
1162
+ const lane = (await request("GET", `/api/v1/lanes/${encode(id)}`)).data;
1163
+ gate = await resumeGate(lane, {
1164
+ ...defaultReaders({ request }),
1165
+ store: deps.resumeStore ?? fingerprintStore(join(recoveryStateRoot(), "resume-fingerprints.json")),
1166
+ ...(deps.resumeReaders ?? {}),
1167
+ });
1168
+ if (!gate.resume) {
1169
+ const data = { resumed: false, code: gate.code, reason: gate.reason, parts: gate.parts ?? [], dead: gate.dead ?? null };
1170
+ // MW1-28: a lane keeps its slot until on_dev or non_issue, or until a staff person stops it.
1171
+ const next = gate.code === "LANE_DEAD" ? ` MW1-28 is its only way out: a staff person may stop it citing this evidence (\`nodii-dev lane stop ${ref} --reason TEXT\`), or its investigation records non_issue (MW1-28.1).` : "";
1172
+ return { payload: { data }, human: () => `${ref}: not resumed (${gate.code}): ${gate.reason}.${next}` };
1173
+ }
1174
+ }
1128
1175
  const payload = await request(
1129
1176
  "POST",
1130
1177
  `/api/v1/lanes/${encode(id)}/resume`,
1131
1178
  { ...(flags.override ? { override: true, reason: overrideReason } : {}), ...move, ...via },
1132
1179
  );
1133
1180
  const launched = await launchReserved(payload);
1181
+ await gate?.record?.().catch(() => {});
1134
1182
  return {
1135
1183
  payload,
1136
1184
  human: (response) => {
@@ -1142,7 +1190,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
1142
1190
  : "the lane's next unfinished step";
1143
1191
  const override = response.data.run.resumeOverrideReason;
1144
1192
  const moved = response.data.accountMove;
1145
- return `${ref}: ${moved ? `moved from the account at ${moved.fromProfile ?? "an unrecorded profile"} to ${moved.toProfile}; ` : ""}resumed fresh run ${runId} as PID ${launched.pid}; continuing ${continuation} from ${checkpoint}.${override ? ` Override past the two-deaths stop recorded ("${override}"); the death count restarts.` : ""}`;
1193
+ return `${picked ? `${picked.note} ` : ""}${ref}: ${moved ? `moved from the account at ${moved.fromProfile ?? "an unrecorded profile"} to ${moved.toProfile}; ` : ""}resumed ${launched.args?.includes?.("--resume") || launched.args?.[1] === "resume" ? "the same session as" : "fresh"} run ${runId} as PID ${launched.pid}; continuing ${continuation} from ${checkpoint}.${override ? ` Override past the two-deaths stop recorded ("${override}"); the death count restarts.` : ""}`;
1146
1194
  },
1147
1195
  };
1148
1196
  }
@@ -330,6 +330,25 @@ function runHandler(args, input, { spawnImpl = spawn, env = process.env } = {})
330
330
  });
331
331
  }
332
332
 
333
+ // NODII-DEV-CLI-191: the dispatcher is already a nodii-dev process, so
334
+ // these handlers run inside it (hook-handlers.js, the same code `hook ACTION`
335
+ // runs) instead of one process each. A Bash call in a lane was two dispatchers
336
+ // plus five handler processes (safety-pre, nudge-pre, tooling-docs, safety-post
337
+ // and lane-heartbeat); it is now the two dispatchers. Any other handler
338
+ // still gets its own process, and one that cannot run here falls back to it.
339
+ export const IN_PROCESS_HOOKS = new Set(["safety-pre", "nudge-pre", "tooling-docs", "safety-post"]);
340
+
341
+ async function runManagedHandler(args, input, deps = {}) {
342
+ if (args.length === 2 && args[0] === "hook" && IN_PROCESS_HOOKS.has(args[1])) {
343
+ try {
344
+ const inProcess = deps.inProcess ?? (await import("./hook-handlers.js")).runHookInProcess;
345
+ const answer = await inProcess(args[1], input);
346
+ if (answer) return answer;
347
+ } catch {}
348
+ }
349
+ return runHandler(args, input, deps);
350
+ }
351
+
333
352
  const matchTarget = (event, payload) => {
334
353
  if (["PreToolUse", "PermissionRequest", "PostToolUse"].includes(event)) return payload.tool_name ?? "";
335
354
  if (event === "SessionStart") return payload.source ?? "";
@@ -367,7 +386,7 @@ export async function dispatchManagedHook(event, payloadText, deps = {}) {
367
386
  validateManagedHooks(config.hooks ?? {});
368
387
  const payload = JSON.parse(payloadText);
369
388
  const handlers = matchingHandlers(config, event, payload).filter((handler) => lane || sessionScoped(event, handler));
370
- const results = await Promise.all(handlers.map((handler) => (deps.run ?? runHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
389
+ const results = await Promise.all(handlers.map((handler) => (deps.run ?? runManagedHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
371
390
  // A failed handler is unavailable policy, not a denial. Ignore both its
372
391
  // output and stderr; doctor is where hook health remains visible.
373
392
  const successful = results.filter((result) => result.status === 0);
@@ -435,7 +454,7 @@ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
435
454
  // Every matching handler runs: no user settings file can switch managed
436
455
  // policy off. Where a repository also carries the same direct hook, both run.
437
456
  const handlers = claudeHandlers(config, event, payload).filter((handler) => lane || sessionScoped(event, handler));
438
- const results = await Promise.all(handlers.map((handler) => (deps.run ?? runHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
457
+ const results = await Promise.all(handlers.map((handler) => (deps.run ?? runManagedHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
439
458
  const blocked = results.find((result) => result.status === 2 && result.stderr.trim());
440
459
  const successful = results.filter((result) => result.status === 0);
441
460
  const messages = successful.map((result) => responseOf(result.stdout)).filter(Boolean);