@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.
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 } 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";
@@ -70,21 +72,42 @@ const laneWaitsText = (x) => (x.waits?.length ? `\twaits on ${x.waits.map(waitTe
70
72
  const waitText = (w) => `${w.blockerLaneKey && w.blockerLaneKey !== w.targetRef ? `${w.blockerLaneKey} (${w.targetRef})` : w.targetRef}${w.chain ? ` [chain: ${w.chain.why} ${w.chain.headLaneKey}]` : ""}`;
71
73
  const laneLine = (x) => `${x.key}\t${x.status}\t${x.kind}/${x.side}\t${x.title}${x.stuck ? "\tSTUCK" : ""}${laneLiveness(x)}${lanePriority(x)}${laneWaitsText(x)}`;
72
74
 
75
+ /**
76
+ * hub-525 (MW1-12.6): the lane's leeways, and the command Dev
77
+ * gives when a BLOCKED or WAITING note names an open issue no live lane holds:
78
+ * `leewayNext` on the lane detail the heartbeat returns (`next` there is the
79
+ * step list and is never read for this).
80
+ */
81
+ function leewayLines(payload) {
82
+ const data = payload?.data ?? {};
83
+ const lines = [];
84
+ const leeways = (Array.isArray(data.leeways) ? data.leeways : []).filter((leeway) => leeway?.blockerIssueKey && leeway.state);
85
+ if (leeways.length)
86
+ lines.push(` leeway: ${leeways.map((leeway) => `${leeway.blockerIssueKey} ${leeway.state}${leeway.state === "requested" ? " (waits on the coordinator)" : ""}`).join(", ")}`);
87
+ const next = fixableBlocker(data.leewayNext);
88
+ if (next)
89
+ lines.push(
90
+ ` ${next.blockerIssueKey ?? "The blocker"} is open and no live lane holds it${next.reason ? ` (${next.reason})` : ""}. Do not stop BLOCKED: ask the coordinator for leeway. Run:`,
91
+ ` ${next.command}`,
92
+ );
93
+ return lines;
94
+ }
95
+
73
96
  /** What a heartbeat changed in the lane's waits. */
74
97
  export function heartbeatText(ref, payload, sentWaits = false) {
75
98
  const waits = payload?.waits;
76
99
  // A Dev without hub-246 answers with no `waits` key at all and ignores the flag.
77
100
  if (sentWaits && waits === undefined)
78
101
  return `${ref}: heartbeat recorded, but this Dev does not record --waiting-on yet (needs the hub-246 deploy); the wait was not stored.`;
79
- if (!waits) return `${ref}: heartbeat recorded.`;
80
102
  const lines = [`${ref}: heartbeat recorded.`];
103
+ if (!waits) return [...lines, ...leewayLines(payload)].join("\n");
81
104
  for (const change of waits.changes ?? [])
82
105
  lines.push(change.change === "new" ? ` now waits on ${change.targetRef}` : ` no longer waits on ${change.targetRef} (${change.clearReason})`);
83
106
  for (const drop of waits.dropped ?? []) lines.push(` not a wait: ${drop.ref}: ${drop.why}`);
84
107
  if (waits.notices) lines.push(` coordinator notified (${waits.notices} notice${waits.notices === 1 ? "" : "s"})`);
85
108
  const current = payload.data?.waits ?? [];
86
109
  if (current.length) lines.push(` waiting on: ${current.map(waitText).join(", ")}`);
87
- return lines.join("\n");
110
+ return [...lines, ...leewayLines(payload)].join("\n");
88
111
  }
89
112
 
90
113
  /** The wait board (GET /lanes/waits) as text: blockers first, then what holds lanes outside the graph. */
@@ -190,8 +213,10 @@ async function laneContract(id, request, options) {
190
213
  // Gather never ends on a bare "finished" (hub-58): the next step is the task.
191
214
  // Dev has moved the lane past gather by now (NODII-DEV-CLI-3); recording the
192
215
  // done check is what lets a launched run end finished (NODII-DEV-CLI-4).
193
- const nextStepText = (ref, doneCheck) =>
194
- `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");
195
220
  const agentShortlistText = (ref, data, flags) => [
196
221
  ...contractLines(data),
197
222
  `Trigger shortlist ${data.shortlistId} · ${JSON.stringify(data.objective)}`,
@@ -486,7 +511,7 @@ async function resumeHostLost(flags, deps, { request, config }) {
486
511
  }
487
512
 
488
513
  export async function laneCommand(action, args, flags, deps = {}) {
489
- 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;
490
515
  if (action === "resume" && flags["host-lost"]) {
491
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);
492
517
  return resumeHostLost(flags, deps, { request, config });
@@ -720,6 +745,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
720
745
  ask: contract.objective.ask,
721
746
  boundaries: contract.boundaries,
722
747
  issue: contract.objective.issue,
748
+ issueSet: contract.objective.issueSet,
723
749
  laneNotes: contract.objective.laneNotes,
724
750
  doneCheck: contract.objective.doneCheck ?? doneCheck,
725
751
  lookups: lookup ? [lookup] : [],
@@ -743,7 +769,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
743
769
  const result = { ...payload, picker: { model: picked.model ?? null, latency: picked.latency ?? null, ...(picked.timing ? { timing: picked.timing, stats: picked.stats } : {}) } };
744
770
  const timingLine = picked.timing ? `\n${pickTimingLine(picked.timing, picked.stats)}` : "";
745
771
  const doneText = contract?.objective?.doneCheck ?? doneCheck;
746
- 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)}` };
747
773
  } catch (error) {
748
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);
749
775
  throw error;
@@ -988,6 +1014,25 @@ export async function laneCommand(action, args, flags, deps = {}) {
988
1014
  throw new CliError("DONE_CHECK_NOT_RECORDED", `Dev took the evidence but does not show ${ref}'s done check as recorded; it predates NODII-DEV-CLI-4. The run would still end orphaned.`, 1);
989
1015
  return { payload, human: `${ref}: done check recorded. The lane's run ends finished when its process exits.` };
990
1016
  }
1017
+ // hub-525 (MW1-28.2): the lane's own agent marks the lane finished,
1018
+ // which is what its coordinator's `lane close` needs (LANE_NOT_FINISHED).
1019
+ if (action === "finish") {
1020
+ const text = (name, limit, what) => {
1021
+ const value = flags[name];
1022
+ if (Array.isArray(value)) throw new CliError("USAGE", `Give --${name} once.`, 2);
1023
+ const trimmed = typeof value === "string" ? value.trim() : "";
1024
+ if (!trimmed) throw new CliError("USAGE", `lane finish needs --${name} ${what}`, 2);
1025
+ if (trimmed.length > limit) throw new CliError("USAGE", `--${name} is ${trimmed.length} characters; Dev keeps at most ${limit.toLocaleString("en-US")}.`, 2);
1026
+ return trimmed;
1027
+ };
1028
+ const body = {
1029
+ reason: text("reason", 4_000, "TEXT: why the lane is finished."),
1030
+ evidence: text("evidence", 8_000, "TEXT|URL: what the lane delivered and where its branch and commits went."),
1031
+ ...via,
1032
+ };
1033
+ const payload = await request("POST", `/api/v1/lanes/${encode(id)}/finish`, body);
1034
+ return { payload, human: `${ref}: recorded finished. Its coordinator can close it with nodii-dev lane close ${ref} --reason TEXT.` };
1035
+ }
991
1036
  if (action === "heartbeat") {
992
1037
  // hub-246: --waiting-on is repeatable; it replaces the lane's waits.
993
1038
  const waitingOn = flags["waiting-on"] === undefined ? [] : [flags["waiting-on"]].flat();
@@ -1066,13 +1111,35 @@ export async function laneCommand(action, args, flags, deps = {}) {
1066
1111
  // account. Dev keeps no class for a lane, so it is named here, as at launch.
1067
1112
  if ((flags.profile === undefined) !== (flags.class === undefined))
1068
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
+ }
1069
1138
  let move = {};
1070
- if (flags.profile !== undefined) {
1071
- const profile = typeof flags.profile === "string" ? profilePath(flags.profile.trim()) : "";
1072
- if (!isAbsolute(profile)) throw new CliError("USAGE", "--profile must be an absolute runtime profile path.", 2);
1073
- const workClass = { long: "long", short: "short", "no-build": "no_build" }[flags.class];
1074
- 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);
1075
- 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 });
1076
1143
  move = { profile, workClass };
1077
1144
  // hub-232: a long resume is a launch for the governor; a short
1078
1145
  // or no-build resume (a close-out) is never refused. Dev refuses the same.
@@ -1085,12 +1152,33 @@ export async function laneCommand(action, args, flags, deps = {}) {
1085
1152
  if (governor) assertGovernorOpen(governor);
1086
1153
  }
1087
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
+ }
1088
1175
  const payload = await request(
1089
1176
  "POST",
1090
1177
  `/api/v1/lanes/${encode(id)}/resume`,
1091
1178
  { ...(flags.override ? { override: true, reason: overrideReason } : {}), ...move, ...via },
1092
1179
  );
1093
1180
  const launched = await launchReserved(payload);
1181
+ await gate?.record?.().catch(() => {});
1094
1182
  return {
1095
1183
  payload,
1096
1184
  human: (response) => {
@@ -1102,7 +1190,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
1102
1190
  : "the lane's next unfinished step";
1103
1191
  const override = response.data.run.resumeOverrideReason;
1104
1192
  const moved = response.data.accountMove;
1105
- 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.` : ""}`;
1106
1194
  },
1107
1195
  };
1108
1196
  }
package/dist/leeway.js ADDED
@@ -0,0 +1,218 @@
1
+ import { execFile as execFileCallback } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { CliError, devRequest, encode, query, requireFlag } from "./core.js";
6
+ import { createWorktrees, writeLaneMarkers } from "./starting.js";
7
+
8
+ /**
9
+ * hub-525 (MW1-12.6 to MW1-12.8): leeway. A lane blocked on an open
10
+ * issue that no live lane holds asks its machine coordinator for leeway to fix
11
+ * it, instead of ending BLOCKED. Dev claims the issue for the lane (a second
12
+ * asker is refused with the holder's key and waits on it), the coordinator
13
+ * grants or refuses, and a grant reaches the lane as an amendment it
14
+ * acknowledges with a Delta gather before it starts the fix.
15
+ *
16
+ * lane leeway <key> --blocker ISSUE [--repo NAME] --reason TEXT
17
+ * lane leeway grant <id> [--note TEXT] [--source PATH] [--worktree PATH]
18
+ * lane leeway refuse <id> [--note TEXT]
19
+ * lane leeway withdraw <id>
20
+ * lane leeway list [--machine M] [--state S] [--lane KEY] [--cursor C] [--limit N]
21
+ * lane leeway show <id>
22
+ */
23
+
24
+ const execFile = promisify(execFileCallback);
25
+ const via = { via: "nodii-dev" };
26
+ const USAGE = "lane leeway <key> --blocker ISSUE [--repo NAME] --reason TEXT | lane leeway grant <id> [--note TEXT] [--source PATH] [--worktree PATH] | lane leeway refuse <id> [--note TEXT] | lane leeway withdraw <id> | lane leeway list [--machine M] [--state S] [--lane KEY] [--cursor C] [--limit N] | lane leeway show <id>";
27
+ const SUBCOMMANDS = ["grant", "refuse", "withdraw", "list", "show"];
28
+ const FLAGS = {
29
+ ask: ["blocker", "repo", "reason"],
30
+ grant: ["note", "source", "worktree"],
31
+ refuse: ["note"],
32
+ withdraw: [],
33
+ list: ["machine", "state", "lane", "cursor", "limit"],
34
+ show: [],
35
+ };
36
+
37
+ function onlyFlags(sub, flags) {
38
+ const extra = Object.keys(flags).filter((flag) => !["json", "help", ...FLAGS[sub]].includes(flag));
39
+ if (!extra.length) return;
40
+ const name = sub === "ask" ? "lane leeway <key>" : `lane leeway ${sub}`;
41
+ throw new CliError("USAGE", `${name} does not take ${extra.map((flag) => `--${flag}`).join(", ")}; its flags: ${FLAGS[sub].length ? FLAGS[sub].map((flag) => `--${flag}`).join(", ") : "none"} (and --json).`, 2);
42
+ }
43
+
44
+ const issueOf = (leeway) => leeway?.blockerIssueKey ?? leeway?.blockerIssueId ?? "the blocker";
45
+ const titled = (leeway) => `${issueOf(leeway)}${leeway?.blockerIssueTitle ? ` "${leeway.blockerIssueTitle}"` : ""}${leeway?.repo ? ` in ${leeway.repo}` : ""}`;
46
+ const oneLine = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
47
+ const leewayLine = (leeway) => [leeway.id, leeway.laneKey, leeway.state, issueOf(leeway), leeway.repo ?? "-", leeway.createdAt, oneLine(leeway.reason).slice(0, 100)].join("\t");
48
+
49
+ /** The source checkout a worktree belongs to (the parent of its common git dir). */
50
+ async function worktreeSource(worktree) {
51
+ const { stdout } = await execFile("git", ["-C", worktree, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8" });
52
+ return dirname(stdout.trim());
53
+ }
54
+
55
+ async function isGitRepository(path) {
56
+ try {
57
+ await execFile("git", ["-C", path, "rev-parse", "--git-dir"], { encoding: "utf8" });
58
+ return true;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ /** The lane marker launch wrote in a worktree's git dir, or null. */
65
+ async function readLaneMarker(worktree) {
66
+ try {
67
+ const { stdout } = await execFile("git", ["-C", worktree, "rev-parse", "--path-format=absolute", "--git-dir"], { encoding: "utf8" });
68
+ return JSON.parse(await readFile(join(stdout.trim(), "nodii-lane.json"), "utf8"));
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ async function ask(key, flags, { request }) {
75
+ if (!key) throw new CliError("USAGE", USAGE, 2);
76
+ onlyFlags("ask", flags);
77
+ const blocker = String(requireFlag(flags, "blocker"));
78
+ const reason = String(requireFlag(flags, "reason"));
79
+ const repo = flags.repo === undefined ? undefined : String(requireFlag(flags, "repo"));
80
+ let payload;
81
+ try {
82
+ payload = await request("POST", `/api/v1/lanes/${encode(key)}/leeway`, { blocker, ...(repo ? { repo } : {}), reason, ...via });
83
+ } catch (error) {
84
+ // Every other refusal is Dev's own text. This one also says who holds the issue and what the lane does next.
85
+ if (error?.code !== "LEEWAY_BLOCKER_HELD") throw error;
86
+ const holder = error.details?.holderLaneKey ?? "another lane";
87
+ const held = `${blocker} is held by lane ${holder}${error.details?.leewayId ? ` (leeway ${error.details.leewayId})` : ""}.`;
88
+ const wait = error.details?.waitRecorded
89
+ ? `A wait on ${holder} was recorded for ${key}: Dev resumes ${key} when ${holder} lands the fix.`
90
+ : `Dev recorded no wait: record it with nodii-dev lane heartbeat ${key} --waiting-on ${holder}.`;
91
+ throw new CliError(error.code, `${error.message}\n${held} ${wait} Keep working what is not blocked; do not start the fix.`, error.exitCode ?? 1, error.details);
92
+ }
93
+ const leeway = payload.data;
94
+ const coordinator = leeway?.coordinatorName ? `coordinator ${leeway.coordinatorName}` : "the machine coordinator";
95
+ return { payload, human: `Leeway asked (${leeway?.id}): ${leeway?.blockerIssueKey ?? blocker} claimed for ${leeway?.laneKey ?? key}. Waiting for ${coordinator}. Keep working what is not blocked.` };
96
+ }
97
+
98
+ /**
99
+ * Where the fix's worktree goes, for a repository the lane does not have:
100
+ * `<source>/.claude/worktrees/<lane key>`, as `lane launch` places it. The
101
+ * source is --source, else the checkout of that name beside the lane's first
102
+ * repository's.
103
+ */
104
+ async function grantWorktree(leeway, lane, flags, { sourceOf, isRepository }) {
105
+ for (const flag of ["source", "worktree"])
106
+ if (flags[flag] !== undefined && !isAbsolute(String(requireFlag(flags, flag))))
107
+ throw new CliError("USAGE", `--${flag} needs an absolute path.`, 2);
108
+ let source = flags.source ? resolve(String(flags.source)) : null;
109
+ if (!source) {
110
+ const first = (lane.repositories ?? []).find((repository) => repository.worktree)?.worktree ?? lane.worktree;
111
+ let beside = null;
112
+ try { beside = first ? join(dirname(await sourceOf(first)), leeway.repo) : null; } catch {}
113
+ if (!beside || !(await isRepository(beside)))
114
+ throw new CliError("LEEWAY_SOURCE_REQUIRED", `Leeway ${leeway.id} is for ${leeway.repo}, which ${leeway.laneKey} does not work in, and ${beside ? `${beside} is not a git checkout` : "its checkout could not be found beside the lane's worktree"}. Pass --source /absolute/path/to/${leeway.repo} (and --worktree PATH to place the worktree elsewhere). Nothing was granted.`, 2);
115
+ source = beside;
116
+ } else if (!(await isRepository(source)))
117
+ throw new CliError("LEEWAY_SOURCE_REQUIRED", `--source ${source} is not a git checkout of ${leeway.repo}. Nothing was granted.`, 2);
118
+ const worktree = resolve(flags.worktree ? String(flags.worktree) : join(source, ".claude", "worktrees", leeway.laneKey));
119
+ return { source, worktree };
120
+ }
121
+
122
+ async function grant(id, flags, { request, sourceOf, isRepository, worktrees, laneMarker, markers }) {
123
+ onlyFlags("grant", flags);
124
+ const path = `/api/v1/lane-leeway/${encode(id)}`;
125
+ const asked = (await request("GET", path)).data;
126
+ // A repository the lane already works in needs no worktree: the lane's
127
+ // safety hook keeps it on its lane branch, so the fix is its own commit
128
+ // range and PR from the worktree it has.
129
+ let lane = null;
130
+ let placed = null;
131
+ if (asked?.repo) {
132
+ lane = (await request("GET", `/api/v1/lanes/${encode(asked.laneKey ?? asked.laneId)}`)).data ?? {};
133
+ if (!(lane.repositories ?? []).some((repository) => repository.repo === asked.repo))
134
+ placed = await grantWorktree(asked, lane, flags, { sourceOf, isRepository });
135
+ }
136
+ const payload = await request("POST", `${path}/grant`, { ...(flags.note ? { note: String(flags.note) } : {}), ...(placed ? { worktree: placed.worktree } : {}), ...via });
137
+ const { leeway = asked, amendment, repository, warnings = [] } = payload.data ?? {};
138
+ const laneKey = leeway?.laneKey ?? asked?.laneKey;
139
+ const lines = [
140
+ `Leeway granted (${leeway?.id ?? id}): ${laneKey} may fix ${titled({ ...asked, ...leeway })}. Amendment ${amendment?.version ?? "?"} carries it: ${laneKey} acknowledges it with nodii-dev lane gather ${laneKey} --delta and does not start the fix before that.`,
141
+ ];
142
+ if (placed) {
143
+ const created = { repo: repository?.repo ?? asked.repo, source: placed.source, branch: repository?.branch ?? `fix/${laneKey}`, worktree: repository?.worktree ?? placed.worktree, baseRef: "origin/main" };
144
+ try {
145
+ await worktrees([created]);
146
+ } catch (error) {
147
+ throw new CliError("LEEWAY_WORKTREE_FAILED", `Leeway ${leeway?.id ?? id} is granted, but its worktree could not be created (${error?.message ?? error}). Create it, then tell ${laneKey}: git -C ${created.source} worktree add ${created.worktree} -b ${created.branch} ${created.baseRef}`, 1, { leeway, repository: created });
148
+ }
149
+ // The lane's marker, so a command run in the new worktree is the lane's.
150
+ const first = (lane?.repositories ?? []).find((known) => known.worktree)?.worktree ?? lane?.worktree;
151
+ const marker = first ? await laneMarker(first).catch(() => null) : null;
152
+ const marked = marker ? await markers([created], marker).then(() => true, () => false) : false;
153
+ // Without its marker a command run there is not the lane's, so it would
154
+ // skip the lane's amendment check: say so instead of reporting a clean grant.
155
+ if (!marked) lines.push(`Warning: ${created.worktree} has no lane marker (nodii-lane.json in its git directory), so commands run there are not checked as ${laneKey}'s. Before the lane works there, copy it from the git directory of ${first ?? "the lane's first worktree"} (git -C PATH rev-parse --git-dir).`);
156
+ lines.push(`Worktree: ${created.worktree} on ${created.branch} (from ${created.baseRef}).`);
157
+ } else {
158
+ const own = asked?.repo ? (lane?.repositories ?? []).find((known) => known.repo === asked.repo) : null;
159
+ lines.push(`The fix goes in ${laneKey}'s existing worktree${asked?.repo ? ` for ${asked.repo}` : ""}${own?.worktree ? ` (${own.worktree})` : ""} as its own commit range and its own PR; the lane stays on its lane branch.`);
160
+ }
161
+ lines.push(
162
+ `The fix is its own PR, linked to ${issueOf({ ...asked, ...leeway })} and merged by the repository's steward where it has one: leeway covers the fix, not the merge.`,
163
+ `After the fix merges, ${laneKey} rebases its own PR on origin/main.`,
164
+ ...warnings.map((warning) => `Warning ${warning.code}: ${warning.message}`),
165
+ );
166
+ return { payload, human: lines.join("\n") };
167
+ }
168
+
169
+ export async function laneLeewayCommand(args, flags, {
170
+ request = devRequest,
171
+ sourceOf = worktreeSource,
172
+ isRepository = isGitRepository,
173
+ worktrees = createWorktrees,
174
+ laneMarker = readLaneMarker,
175
+ markers = writeLaneMarkers,
176
+ } = {}) {
177
+ const [first, second, ...more] = args;
178
+ if (!SUBCOMMANDS.includes(first)) {
179
+ if (args.length > 1) throw new CliError("USAGE", USAGE, 2);
180
+ return ask(first, flags, { request });
181
+ }
182
+ if (first === "list") {
183
+ if (second !== undefined) throw new CliError("USAGE", USAGE, 2);
184
+ onlyFlags("list", flags);
185
+ const filters = Object.fromEntries(FLAGS.list.filter((flag) => flags[flag] !== undefined).map((flag) => [flag, String(requireFlag(flags, flag))]));
186
+ const payload = await request("GET", `/api/v1/lane-leeway${query(filters)}`);
187
+ const rows = payload.data ?? [];
188
+ // Dev pages this as it pages the lane list.
189
+ const more = payload.nextCursor ? `\nMore: nodii-dev lane leeway list --cursor ${payload.nextCursor}` : "";
190
+ return { payload, human: rows.length ? `${rows.map(leewayLine).join("\n")}${more}` : "No leeway requests." };
191
+ }
192
+ if (!second || more.length) throw new CliError("USAGE", `lane leeway ${first} needs the leeway id (lane leeway list shows them).`, 2);
193
+ if (first === "grant") return grant(second, flags, { request, sourceOf, isRepository, worktrees, laneMarker, markers });
194
+ onlyFlags(first, flags);
195
+ const path = `/api/v1/lane-leeway/${encode(second)}`;
196
+ if (first === "show") {
197
+ const payload = await request("GET", path);
198
+ const leeway = payload.data;
199
+ return {
200
+ payload,
201
+ human: [
202
+ `Leeway ${leeway.id}: ${leeway.state}. ${leeway.laneKey} asked to fix ${titled(leeway)}.`,
203
+ `Reason: ${leeway.reason}`,
204
+ `Asked ${leeway.createdAt}${leeway.decidedAt ? `; decided ${leeway.decidedAt}` : ""}${leeway.closedAt ? `; closed ${leeway.closedAt}` : ""}.${leeway.decisionNote ? ` Note: ${leeway.decisionNote}` : ""}`,
205
+ ...(leeway.depth > 1 || leeway.parentLeewayId ? [`Depth ${leeway.depth ?? "?"}${leeway.parentLeewayId ? `, under leeway ${leeway.parentLeewayId}` : ""}.`] : []),
206
+ ...(leeway.state === "requested" ? [`Waiting for ${leeway.coordinatorName ? `coordinator ${leeway.coordinatorName}` : "the machine coordinator"}: nodii-dev lane leeway grant ${leeway.id} | nodii-dev lane leeway refuse ${leeway.id} --note TEXT`] : []),
207
+ ].join("\n"),
208
+ };
209
+ }
210
+ const payload = await request("POST", `${path}/${first}`, { ...(first === "refuse" && flags.note ? { note: String(flags.note) } : {}), ...via });
211
+ const leeway = payload.data;
212
+ return {
213
+ payload,
214
+ human: first === "refuse"
215
+ ? `Leeway refused (${leeway.id}): ${leeway.laneKey} was not given ${issueOf(leeway)}.${leeway.decisionNote ?? flags.note ? ` Note: ${leeway.decisionNote ?? flags.note}` : ""}`
216
+ : `Leeway withdrawn (${leeway.id}): ${leeway.laneKey} no longer asks for ${issueOf(leeway)}.`,
217
+ };
218
+ }
@@ -59,10 +59,10 @@ const laneConfig = (env) => /^lane-[a-z0-9_-]+\.json$/i.test(basename(env.NODII_
59
59
  // nudged to cite before it steers (MW1-95): these handlers, on these events,
60
60
  // run for every session. Everything else stays lane-only.
61
61
  export const SESSION_SCOPED_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse"];
62
- export const SESSION_SCOPED_COMMANDS = ["nodii-dev hook session-start", "nodii-dev hook session-kind", "nodii-dev hook nudge-pre"];
62
+ export const SESSION_SCOPED_COMMANDS = ["nodii-dev hook session-start", "nodii-dev hook session-kind", "nodii-dev hook nudge-pre", "nodii-dev hook tooling-docs"];
63
63
  // The shell's cheap screen for a non-lane PreToolUse: only a call that could
64
64
  // be a steering act (MW1-95) starts the CLI. The CLI decides exactly.
65
- const STEER_MARKERS = ['*\'"SendMessage"\'*', "*'lane amend'*", "*'gh pr '*", "*'nodii.repo.yaml'*", "*'lefthook.yml'*", "*'.github/workflows/'*"];
65
+ const STEER_MARKERS = ['*\'"SendMessage"\'*', "*'lane amend'*", "*'gh pr '*", "*'git push'*", "*' push'*", "*'nodii.repo.yaml'*", "*'lefthook.yml'*", "*'.github/workflows/'*"];
66
66
  const sessionScoped = (event, handler) => SESSION_SCOPED_EVENTS.includes(event) && SESSION_SCOPED_COMMANDS.includes(String(handler?.command ?? "").trim());
67
67
  const emptyResponse = (event) => ["Stop", "SubagentStop"].includes(event) ? "{}\n" : "";
68
68
 
@@ -105,7 +105,9 @@ export function managedHookBundle(hooksText, { home, cliPath, cliVersion = VERSI
105
105
  // The stable shell entry point both runtimes call. A lane config gets every
106
106
  // event; any other session only the session-scoped ones: SessionStart,
107
107
  // UserPromptSubmit, and a PreToolUse that names a lane launch or resume (the
108
- // governor, hub-232) or could be a steering act (MW1-95), plus the MW8-17
108
+ // governor, hub-232) or could be a steering act (MW1-95), a coordinator
109
+ // session's nodii-dev call or operator question (the coordinator gate,
110
+ // MW1-37.2: only where coordinator.json sits beside the config), plus the MW8-17
109
111
  // Surface-generation nudge: an edit whose payload names a product page goes to
110
112
  // `hook surface-gen-pre`, which reads only the edit. Every failure ends in the
111
113
  // runtime's empty answer (fail open), except a governed launch, which the
@@ -134,6 +136,11 @@ export function dispatchScript(cliPath, action, stopJson) {
134
136
  "}",
135
137
  "managed_buffered=",
136
138
  "managed_governed=",
139
+ // MW1-37.2: `coordinator start` writes coordinator.json beside the config.
140
+ // Only a session with it pays for the coordinator gate, and only on a call
141
+ // that names nodii-dev or asks the operator.
142
+ 'managed_config=${NODII_DEV_CONFIG_PATH:-$HOME/.config/nodii-dev/config.json}',
143
+ 'managed_coordinator="${managed_config%/*}/coordinator.json"',
137
144
  'case "${NODII_DEV_CONFIG_PATH##*/}" in',
138
145
  " lane-*.json) ;;",
139
146
  ' *) case "$1" in',
@@ -142,7 +149,7 @@ export function dispatchScript(cliPath, action, stopJson) {
142
149
  " managed_payload=$(cat)",
143
150
  " managed_buffered=1",
144
151
  ` if printf '%s' "$managed_payload" | grep -Eq 'lane([[:space:]]|\\\\[nrt])+(launch|resume)'; then managed_governed=1;`,
145
- ` else ${SURFACE_GEN}case "$managed_payload" in ${STEER_MARKERS.join("|")}) ;; *) empty_response "$1"; exit 0 ;; esac; fi ;;`,
152
+ ` else ${SURFACE_GEN}case "$managed_payload" in ${STEER_MARKERS.join("|")}) ;; *'"AskUserQuestion"'*|*nodii-dev*|*@nodii/dev*) if [ ! -f "$managed_coordinator" ]; then empty_response "$1"; exit 0; fi ;; *) empty_response "$1"; exit 0 ;; esac; fi ;;`,
146
153
  ' *) empty_response "$1"; exit 0 ;;',
147
154
  " esac ;;",
148
155
  "esac",
@@ -184,6 +191,24 @@ async function governorVerdict(event, payloadText, deps) {
184
191
  }
185
192
  }
186
193
 
194
+ /**
195
+ * MW1-37.2: the coordinator gate's verdict for a session outside a lane, on
196
+ * PreToolUse. It fails open: any failure is no verdict. The governor's launch
197
+ * gate above is separate and stays fail-closed.
198
+ */
199
+ async function coordinatorGateVerdict(event, payloadText, deps) {
200
+ if (event !== "PreToolUse") return null;
201
+ try {
202
+ const gate = deps.coordinatorGate ?? (await import("./coordinator-items.js")).coordinatorGate;
203
+ return (await gate(JSON.parse(payloadText), deps)) || null;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+
209
+ /** The governor's context and the gate's, as one. */
210
+ const withGate = (governor, gate) => (gate?.context ? { context: [governor?.context, gate.context].filter(Boolean).join("\n") } : governor);
211
+
187
212
  const governorDeny = (event, verdict) => `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, permissionDecision: "deny", permissionDecisionReason: verdict.deny } })}\n`;
188
213
  const governorContext = (event, verdict) => (verdict?.context ? `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: verdict.context } })}\n` : "");
189
214
 
@@ -305,6 +330,25 @@ function runHandler(args, input, { spawnImpl = spawn, env = process.env } = {})
305
330
  });
306
331
  }
307
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
+
308
352
  const matchTarget = (event, payload) => {
309
353
  if (["PreToolUse", "PermissionRequest", "PostToolUse"].includes(event)) return payload.tool_name ?? "";
310
354
  if (event === "SessionStart") return payload.source ?? "";
@@ -333,12 +377,16 @@ export async function dispatchManagedHook(event, payloadText, deps = {}) {
333
377
  // hub-232: the governor answers first; its deny needs no hooks.json.
334
378
  governor = lane ? null : await governorVerdict(event, payloadText, deps);
335
379
  if (governor?.deny) return governorDeny(event, governor);
380
+ // MW1-37.2: then the coordinator gate, for a coordinator session.
381
+ const gate = lane ? null : await coordinatorGateVerdict(event, payloadText, deps);
382
+ if (gate?.deny) return governorDeny(event, gate);
383
+ governor = withGate(governor, gate);
336
384
  const dir = deps.dir ?? env.NODII_DEV_MANAGED_HOOKS_DIR ?? managedHooksDir();
337
385
  const config = JSON.parse(await (deps.read ?? readFile)(join(dir, "hooks.json"), "utf8"));
338
386
  validateManagedHooks(config.hooks ?? {});
339
387
  const payload = JSON.parse(payloadText);
340
388
  const handlers = matchingHandlers(config, event, payload).filter((handler) => lane || sessionScoped(event, handler));
341
- 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)));
342
390
  // A failed handler is unavailable policy, not a denial. Ignore both its
343
391
  // output and stderr; doctor is where hook health remains visible.
344
392
  const successful = results.filter((result) => result.status === 0);
@@ -393,6 +441,10 @@ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
393
441
  // hub-232: the governor answers first; its deny needs no hooks.json.
394
442
  governor = lane ? null : await governorVerdict(event, payloadText, deps);
395
443
  if (governor?.deny) return governorDeny(event, governor);
444
+ // MW1-37.2: then the coordinator gate, for a coordinator session.
445
+ const gate = lane ? null : await coordinatorGateVerdict(event, payloadText, deps);
446
+ if (gate?.deny) return governorDeny(event, gate);
447
+ governor = withGate(governor, gate);
396
448
  const read = deps.read ?? readFile;
397
449
  const dir = deps.dir ?? env.NODII_DEV_MANAGED_HOOKS_DIR ?? managedClaudeHooksDir();
398
450
  const config = JSON.parse(await read(join(dir, "hooks.json"), "utf8"));
@@ -402,7 +454,7 @@ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
402
454
  // Every matching handler runs: no user settings file can switch managed
403
455
  // policy off. Where a repository also carries the same direct hook, both run.
404
456
  const handlers = claudeHandlers(config, event, payload).filter((handler) => lane || sessionScoped(event, handler));
405
- 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)));
406
458
  const blocked = results.find((result) => result.status === 2 && result.stderr.trim());
407
459
  const successful = results.filter((result) => result.status === 0);
408
460
  const messages = successful.map((result) => responseOf(result.stdout)).filter(Boolean);