@nodii/dev 0.6.208 → 0.6.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lane-asks.js CHANGED
@@ -1,33 +1,26 @@
1
- import { CliError, devRequest, encode, query, requireFlag } from "./core.js";
1
+ import { CliError, devRequest, encode, requireFlag } from "./core.js";
2
2
 
3
3
  /**
4
- * hub-525 (MW1-12.9, MW1-37.2): a lane's questions to its machine
5
- * coordinator. The answer is delivered as an amendment the lane acknowledges
6
- * with a Delta gather; an issue comment alone is not delivery.
4
+ * hub-525 (MW1-37.2): the coordinator puts a leeway off.
7
5
  *
8
- * lane ask <key> --question TEXT [--options a,b]
9
- * lane ask withdraw <ask id>
10
- * lane answer <ask id> --text TEXT
11
- * lane defer <ask or leeway id> --reason TEXT [--minutes N] [--leeway]
12
- * lane asks [--machine M] [--state S] [--lane KEY] [--cursor C] [--limit N]
6
+ * lane defer <leeway id> --reason TEXT [--minutes N]
7
+ *
8
+ * DEV-PROCESS-5, row 29b (one in, one out): the lane-ask family (`lane ask`,
9
+ * `lane ask withdraw`, `lane answer`, `lane asks`, the NODII_DEV_LANE_ASKS
10
+ * switch) is retired. It shipped off by default since 18 Nov (MW1-37.2) and is
11
+ * replaced by role waits. Typing one is refused USAGE with what replaced it.
13
12
  */
14
13
 
15
- /**
16
- * MW1-37.2 (DEC-0503): lane asks ship off by default; NODII_DEV_LANE_ASKS=1
17
- * turns them on. Dev's rulebook holds no clause yet for a lane's question and
18
- * its answer. Off, no command here calls Dev's lane-ask routes (Dev's answer
19
- * route, which delivers the amendment, is then unreachable from the CLI), and
20
- * the coordinator's count, list and gate leave questions out: a question
21
- * cannot be cleared without the answer route.
22
- */
23
- export const laneAsksOn = (env = process.env) => env?.NODII_DEV_LANE_ASKS === "1";
24
- const assertAsksOn = (name, env) => {
25
- if (!laneAsksOn(env))
26
- throw new CliError("LANE_ASKS_OFF", `${name} is off: lane asks ship off by default (MW1-37.2). A lane writes its question as an issue comment or a heartbeat note, as before; NODII_DEV_LANE_ASKS=1 turns the commands on.`, 1);
27
- };
14
+ export const RETIRED_LANE_ASK_ACTIONS = new Set(["ask", "asks", "answer"]);
15
+ export const LANE_ASKS_RETIRED =
16
+ "lane ask, lane asks and lane answer were retired in 0.6.209 (DEV-PROCESS-5, row 29b). A lane waiting on a person records `nodii-dev lane heartbeat <key> --waiting-on person:ROLE`; the role reads them with `nodii-dev lane waits --person ROLE`.";
17
+
18
+ /** `nodii-dev lane ask|asks|answer ...`: refused before anything runs or reaches Dev. */
19
+ export function refuseRetiredLaneAsk(argv) {
20
+ if (argv[0] === "lane" && RETIRED_LANE_ASK_ACTIONS.has(argv[1])) throw new CliError("USAGE", LANE_ASKS_RETIRED, 2);
21
+ }
28
22
 
29
23
  const via = { via: "nodii-dev" };
30
- const ASK_USAGE = "lane ask <key> --question TEXT [--options a,b] | lane ask withdraw <ask id>";
31
24
  const DEFER_MAX_MINUTES = 240;
32
25
 
33
26
  function onlyFlags(name, flags, allowed) {
@@ -36,44 +29,12 @@ function onlyFlags(name, flags, allowed) {
36
29
  throw new CliError("USAGE", `${name} does not take ${extra.map((flag) => `--${flag}`).join(", ")}; its flags: ${allowed.length ? allowed.map((flag) => `--${flag}`).join(", ") : "none"} (and --json).`, 2);
37
30
  }
38
31
 
39
- export async function laneAskCommand(args, flags, { request = devRequest, env = process.env } = {}) {
40
- assertAsksOn("lane ask", env);
41
- const [first, second, ...more] = args;
42
- if (first === "withdraw") {
43
- if (!second || more.length) throw new CliError("USAGE", "lane ask withdraw needs the ask id.", 2);
44
- onlyFlags("lane ask withdraw", flags, []);
45
- const payload = await request("POST", `/api/v1/lane-asks/${encode(second)}/withdraw`, { ...via });
46
- return { payload, human: `Withdrawn (${payload.data?.id ?? second}): ${payload.data?.laneKey ?? "the lane"} no longer asks.` };
47
- }
48
- if (!first || args.length > 1) throw new CliError("USAGE", ASK_USAGE, 2);
49
- onlyFlags("lane ask", flags, ["question", "options"]);
50
- const question = String(requireFlag(flags, "question"));
51
- const options = flags.options === undefined ? undefined : String(requireFlag(flags, "options")).split(",").map((option) => option.trim()).filter(Boolean);
52
- const payload = await request("POST", `/api/v1/lanes/${encode(first)}/asks`, { question, ...(options?.length ? { options } : {}), ...via });
53
- const key = payload.data?.laneKey ?? first;
54
- return { payload, human: `Asked (${payload.data?.id}): the coordinator's answer reaches ${key} as an amendment; acknowledge it with nodii-dev lane gather ${key} --delta. Keep working what is not blocked.` };
55
- }
56
-
57
- export async function laneAnswerCommand(args, flags, { request = devRequest, env = process.env } = {}) {
58
- assertAsksOn("lane answer", env);
59
- if (!args[0] || args.length > 1) throw new CliError("USAGE", "lane answer <ask id> --text TEXT", 2);
60
- onlyFlags("lane answer", flags, ["text"]);
61
- const text = String(requireFlag(flags, "text"));
62
- const payload = await request("POST", `/api/v1/lane-asks/${encode(args[0])}/answer`, { text, ...via });
63
- const { ask, amendment } = payload.data ?? {};
64
- const key = ask?.laneKey ?? "the lane";
65
- return { payload, human: `Answered (${ask?.id ?? args[0]}): ${key} gets it as amendment ${amendment?.version ?? "?"} and acknowledges it with nodii-dev lane gather ${key} --delta.` };
66
- }
67
-
68
- // Dev has no such ask: the id may be a leeway's.
69
- const notFound = (error) => error instanceof CliError && (/NOT_FOUND$/.test(error.code ?? "") || error.code === "HTTP_404");
70
-
71
32
  /**
72
- * `lane defer <id>`: the id is tried as an ask; when Dev has no such ask it
73
- * is tried as a leeway. `--leeway` goes straight to the leeway.
33
+ * `lane defer <leeway id>`: the id is a leeway's. `--leeway` is still accepted
34
+ * (it once skipped the ask) and changes nothing.
74
35
  */
75
- export async function laneDeferCommand(args, flags, { request = devRequest, env = process.env } = {}) {
76
- if (!args[0] || args.length > 1) throw new CliError("USAGE", "lane defer <ask or leeway id> --reason TEXT [--minutes N] [--leeway]", 2);
36
+ export async function laneDeferCommand(args, flags, { request = devRequest } = {}) {
37
+ if (!args[0] || args.length > 1) throw new CliError("USAGE", "lane defer <leeway id> --reason TEXT [--minutes N]", 2);
77
38
  onlyFlags("lane defer", flags, ["reason", "minutes", "leeway"]);
78
39
  const reason = String(requireFlag(flags, "reason"));
79
40
  let minutes;
@@ -83,33 +44,7 @@ export async function laneDeferCommand(args, flags, { request = devRequest, env
83
44
  throw new CliError("USAGE", `--minutes is a whole number from 1 to ${DEFER_MAX_MINUTES} (default 60).`, 2);
84
45
  }
85
46
  const body = { reason, ...(minutes === undefined ? {} : { minutes }), ...via };
86
- const id = encode(args[0]);
87
- let payload;
88
- // With questions off the id can only be a leeway's.
89
- let kind = flags.leeway || !laneAsksOn(env) ? "leeway" : "ask";
90
- if (kind === "ask") {
91
- try {
92
- payload = await request("POST", `/api/v1/lane-asks/${id}/defer`, body);
93
- } catch (error) {
94
- if (!notFound(error)) throw error;
95
- kind = "leeway";
96
- }
97
- }
98
- if (kind === "leeway") payload = await request("POST", `/api/v1/lane-leeway/${id}/defer`, body);
47
+ const payload = await request("POST", `/api/v1/lane-leeway/${encode(args[0])}/defer`, body);
99
48
  const item = payload.data ?? {};
100
- const what = kind === "ask" ? `${item.laneKey ?? "the lane"}'s question` : `${item.laneKey ?? "the lane"}'s leeway for ${item.blockerIssueKey ?? "its blocker"}`;
101
- return { payload, human: `Deferred (${item.id ?? args[0]}) until ${item.deferUntil ?? "?"}: ${reason}. ${what} counts again after that.` };
102
- }
103
-
104
- const askLine = (ask) => [ask.id, ask.laneKey, ask.state === "deferred" && ask.deferUntil ? `deferred until ${ask.deferUntil}` : ask.state, ask.createdAt, String(ask.question ?? "").replace(/\s+/g, " ").trim().slice(0, 100)].join("\t");
105
-
106
- export async function laneAsksCommand(args, flags, { request = devRequest, env = process.env } = {}) {
107
- assertAsksOn("lane asks", env);
108
- const filters = ["machine", "state", "lane", "cursor", "limit"];
109
- if (args.length) throw new CliError("USAGE", `lane asks ${filters.map((flag) => `[--${flag} X]`).join(" ")}`, 2);
110
- onlyFlags("lane asks", flags, filters);
111
- const payload = await request("GET", `/api/v1/lane-asks${query(Object.fromEntries(filters.filter((flag) => flags[flag] !== undefined).map((flag) => [flag, String(requireFlag(flags, flag))])))}`);
112
- const rows = payload.data ?? [];
113
- const more = payload.nextCursor ? `\nMore: nodii-dev lane asks --cursor ${payload.nextCursor}` : "";
114
- return { payload, human: rows.length ? `${rows.map(askLine).join("\n")}${more}` : "No lane asks." };
49
+ return { payload, human: `Deferred (${item.id ?? args[0]}) until ${item.deferUntil ?? "?"}: ${reason}. ${item.laneKey ?? "the lane"}'s leeway for ${item.blockerIssueKey ?? "its blocker"} counts again after that.` };
115
50
  }
@@ -1,4 +1,4 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { createHash, randomBytes } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
3
  import { appendFile, mkdir, open, readFile, rename, stat, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, join } from "node:path";
@@ -168,6 +168,54 @@ export async function inboxStopGate(payload, context, { dir, env = process.env }
168
168
  return takeInboxDelivery(key, { dir: dir ?? envInboxDir(process.env) });
169
169
  }
170
170
 
171
+ /**
172
+ * O3 item 8 (DEC-0569, MW1-36.5): the role a steward answers for, the person
173
+ * in `person:ROLE`. Dev delivers a role's waits to a steward keyed ROLE or
174
+ * steward-ROLE, so the key without its `steward-` prefix. Null when that is
175
+ * no role Dev accepts.
176
+ */
177
+ export function stewardRole(key) {
178
+ const role = String(key ?? "").replace(/^steward-/, "");
179
+ return /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(role) && role.length <= 48 ? role : null;
180
+ }
181
+
182
+ const deliveryId = (ref) => createHash("sha256").update(ref).digest("hex").slice(0, 8);
183
+
184
+ /**
185
+ * O3 item 8: a role's waits and READYs (Dev's `GET /lanes/waits?person=ROLE`
186
+ * board) as inbox entries for its steward, in the shape `lane message` writes,
187
+ * leaving out what `delivered` already holds. A scratch steward has no issue,
188
+ * so Dev's lane message never reaches it; the watchdog sweep writes these to
189
+ * its local inbox file instead. `delivered` comes back holding only refs still
190
+ * on the board, so a wait recorded again later is delivered again.
191
+ */
192
+ export function roleWaitDeliveries(key, board, delivered = [], { now = () => new Date() } = {}) {
193
+ const role = stewardRole(key);
194
+ const seen = new Set(Array.isArray(delivered) ? delivered : []);
195
+ const current = [];
196
+ const entries = [];
197
+ const persons = Array.isArray(board?.persons) ? board.persons : [];
198
+ for (const person of persons.filter((item) => item?.targetKind === "person" && item.targetRef === role)) {
199
+ const ready = new Map((Array.isArray(person.ready) ? person.ready : []).filter((item) => item?.lane && item.readyAt).map((item) => [item.lane, new Date(item.readyAt).toISOString()]));
200
+ for (const lane of Array.isArray(person.laneKeys) ? person.laneKeys : []) {
201
+ const waitRef = `wait:${role}:${lane}`;
202
+ current.push(waitRef);
203
+ if (!seen.has(waitRef))
204
+ entries.push({ id: deliveryId(waitRef), from: lane, to: key, at: now().toISOString(), body: `Lane ${lane} waits on person:${role} (MW1-36.5). It clears the wait itself once it has what it needs.`, issueKey: null, commentRef: null });
205
+ const readyAt = ready.get(lane);
206
+ if (!readyAt) continue;
207
+ const readyRef = `ready:${role}:${lane}:${readyAt}`;
208
+ current.push(readyRef);
209
+ if (!seen.has(readyRef))
210
+ entries.push({ id: deliveryId(readyRef), from: lane, to: key, at: readyAt, body: `Lane ${lane}, waiting on person:${role}, posted READY at ${readyAt} (MW1-36.5).`, issueKey: null, commentRef: null });
211
+ }
212
+ }
213
+ return { role, entries, delivered: current };
214
+ }
215
+
216
+ /** Append entries to a key's local inbox file (0600, dir 0700). */
217
+ export const appendInbox = (key, entries, { dir = inboxDir() } = {}) => append(key, dir, entries);
218
+
171
219
  /** nudge-pre: the lane's unread messages as hook context, from the inbox file alone (no Dev call). Null on any failure. */
172
220
  export async function inboxHookContext({ env = process.env, dir } = {}) {
173
221
  if (!laneSwitchOn("laneMessages", env)) return null;
@@ -178,6 +226,20 @@ export async function inboxHookContext({ env = process.env, dir } = {}) {
178
226
  }
179
227
  }
180
228
 
229
+ /**
230
+ * O3 item 8: a steward session's unread messages (its inbox key is its
231
+ * steward lane key), for the prompt hook's next turn. The local inbox file
232
+ * alone, no Dev call; null on any failure.
233
+ */
234
+ export async function stewardInboxContext(key, { env = process.env, dir } = {}) {
235
+ if (!key || !laneSwitchOn("laneMessages", env)) return null;
236
+ try {
237
+ return await takeInboxDelivery(key, { dir: dir ?? envInboxDir(env) });
238
+ } catch {
239
+ return null;
240
+ }
241
+ }
242
+
181
243
  /** The supervisor's continuation: the lane's unread messages, read from its runtime's config dir. */
182
244
  export const inboxForContinuation = async (laneKey, invocation, { env = process.env } = {}) =>
183
245
  !laneSwitchOn("laneMessages", env) ? null : takeInboxDelivery(laneKey, { dir: inboxDir(invocation?.env?.NODII_DEV_CONFIG_PATH ?? configPath()) });
@@ -104,6 +104,8 @@ const FAILURE_SCAN_LINES = 40;
104
104
  const NO_FAILURE = Object.freeze({ kind: null, resetAt: null, line: null });
105
105
 
106
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";
107
109
 
108
110
  /**
109
111
  * The text of a log line the runtime itself wrote about its failure; null for
@@ -444,7 +446,8 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
444
446
  const readAccountFailure = async (logTail) => {
445
447
  const failure = signal ? NO_FAILURE : classifyRuntimeFailure(logTail, { now: now() });
446
448
  if (!failure.kind) return { failure, note: "" };
447
- const account = profilePath(profile) || join(home ?? homedir(), runtime === "codex" ? ".codex" : ".claude");
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");
448
451
  const until = failure.resetAt ?? new Date(now().getTime() + ACCOUNT_WAIT_MS[failure.kind]).toISOString();
449
452
  accountFailure = { kind: failure.kind, resetAt: failure.resetAt, until, profile: account };
450
453
  await markExhausted(account, { kind: failure.kind, resetAt: failure.resetAt, until, laneKey, runId, line: failure.line, recordedAt: now().toISOString() }).catch(() => {});
@@ -531,7 +534,11 @@ export async function markWatchedTerminal(runId, { home } = {}) {
531
534
  await saveWatchedRun({ ...record, terminalSeenAt: new Date().toISOString(), registryPath });
532
535
  }
533
536
 
534
- const SESSION_ID = { claude: /"session_id":"([0-9a-f-]{36})"/g, codex: /"thread_id":"([0-9a-f-]{36})"/g };
537
+ // The drill's stub runtime writes Claude's records (DEV-PROCESS-1).
538
+ 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
+
540
+ /** The runtime an invocation runs: its own name, or its command for one built before the stub (claude, codex). */
541
+ export const runtimeOf = (invocation) => invocation?.runtime ?? invocation?.command;
535
542
  const LOG_SCAN_BYTES = 256 * 1024;
536
543
 
537
544
  /** The runtime's session id, from the stream-json / --json lines it wrote to the run log. */
@@ -557,7 +564,7 @@ export async function sessionIdFromLog(logPath, runtime) {
557
564
 
558
565
  /** The same session, resumed headless with the same model and permission mode. */
559
566
  export function continuationInvocation(invocation, sessionId) {
560
- if (invocation.command === "claude") return { ...invocation, args: [...invocation.args, "--resume", sessionId] };
567
+ if (["claude", "stub"].includes(runtimeOf(invocation))) return { ...invocation, args: [...invocation.args, "--resume", sessionId] };
561
568
  const model = invocation.args[invocation.args.indexOf("--model") + 1];
562
569
  return { ...invocation, args: ["exec", "resume", "--json", "--dangerously-bypass-approvals-and-sandbox", "--model", model, sessionId, "-"] };
563
570
  }
@@ -758,7 +765,7 @@ export async function superviseLane({
758
765
  // child it stays unbeaten, so a hung run still goes Quiet and then Orphan.
759
766
  // Codex's transcript is its --json stream, the run log itself.
760
767
  let sessionId = null;
761
- const transcripts = () => (invocation.command === "claude" && sessionId ? claudeTranscripts(invocation, sessionId) : []);
768
+ const transcripts = () => (runtimeOf(invocation) === "claude" && sessionId ? claudeTranscripts(invocation, sessionId) : []);
762
769
  const activity = runActivity({ logPath, transcripts });
763
770
  // The lane's beat goes with each run beat. At NODII_DEV_STOP_ONLY_HEARTBEAT=0 the harness's tool-call hook beats the lane instead.
764
771
  const beatLane = () => {
@@ -770,7 +777,7 @@ export async function superviseLane({
770
777
  const at = activity();
771
778
  const tool = at === null ? runningToolCall(child.pid, env) : null;
772
779
  // A tool call still running writes nothing; it beats for at most OPEN_CALL_MAX_MS of silence.
773
- const open = at === null && !tool ? openCallSince({ logPath, transcripts, runtime: invocation.command }) : null;
780
+ const open = at === null && !tool ? openCallSince({ logPath, transcripts, runtime: runtimeOf(invocation) }) : null;
774
781
  if (at !== null || tool || open !== null) {
775
782
  const note = at !== null ? `last activity ${new Date(at).toISOString()}`
776
783
  : tool ? `tool call running: ${redactRunText(tool.names)}, started ${new Date(Date.now() - tool.elapsedMs).toISOString().replace(/\.\d{3}Z$/, "Z")}`
@@ -779,8 +786,8 @@ export async function superviseLane({
779
786
  beatLane();
780
787
  }
781
788
  // The session's transcript is found once its id is in the log.
782
- if (!sessionId && invocation.command === "claude")
783
- sessionIdFromLog(logPath, invocation.command).then((id) => { sessionId ??= id; }, () => {});
789
+ if (!sessionId && runtimeOf(invocation) === "claude")
790
+ sessionIdFromLog(logPath, runtimeOf(invocation)).then((id) => { sessionId ??= id; }, () => {});
784
791
  }, heartbeatInterval(env));
785
792
  const closed = new Promise((resolve) => child.once("close", (exitCode, signal) => resolve({ exitCode, signal })));
786
793
  child.once("error", (error) => {
@@ -824,7 +831,7 @@ export async function superviseLane({
824
831
  let continued = 0;
825
832
  // NODII-DEV-CLI-9: an early stop continues the same session before it is reported.
826
833
  while (!stopping && !signal && continued < limit) {
827
- const sessionId = await sessionIdFromLog(logPath, invocation.command).catch(() => null);
834
+ const sessionId = await sessionIdFromLog(logPath, runtimeOf(invocation)).catch(() => null);
828
835
  if (!sessionId) break;
829
836
  let lane;
830
837
  try { lane = (await request("GET", `/api/v1/lanes/${encode(laneKey)}`)).data; } catch { break; }
@@ -863,8 +870,8 @@ export async function superviseLane({
863
870
  }
864
871
  clearInterval(heartbeat);
865
872
  try {
866
- const runtime = invocation.command;
867
- const profile = invocation.env?.[runtime === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"] ?? null;
873
+ const runtime = runtimeOf(invocation);
874
+ const profile = runtime === "stub" ? invocation.stubAccount ?? null : invocation.env?.[runtime === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"] ?? null;
868
875
  const result = await report({ runId, laneKey, exitCode, signal, worktrees, logPath, continuations: continued, runtime, profile });
869
876
  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`);
870
877
  if (result.accountFailure)
@@ -10,7 +10,7 @@ import { CliError } from "./core.js";
10
10
  *
11
11
  * A switch outside RATIFIED_LANE_SWITCHES (none today) is off by default, on
12
12
  * only when its variable is exactly "1" (the coordinator's instruction of 18 Nov
13
- * 01:55Z, done as NODII_DEV_LANE_ASKS was).
13
+ * 01:55Z).
14
14
  */
15
15
  export const LANE_SWITCHES = Object.freeze({
16
16
  // "BLOCKED is not an exit": only a typed human gate ends a run early.
package/dist/lanes.js CHANGED
@@ -111,8 +111,20 @@ export function heartbeatText(ref, payload, sentWaits = false) {
111
111
  }
112
112
 
113
113
  /** The wait board (GET /lanes/waits) as text: blockers first, then what holds lanes outside the graph. */
114
- export function waitBoardText(board) {
114
+ export function waitBoardText(board, { person } = {}) {
115
115
  const lines = [];
116
+ const people = Array.isArray(board?.persons) ? board.persons : [];
117
+ const peopleLines = () => {
118
+ if (!people.length) return;
119
+ lines.push("Waiting on people:");
120
+ for (const row of people) lines.push(` ${row.targetRef}\tholds ${row.lanes} lane${row.lanes === 1 ? "" : "s"}: ${(row.laneKeys ?? []).join(", ")}`);
121
+ };
122
+ // O3 item 8: `--person ROLE` reads only that role's waits; Dev leaves every other group empty.
123
+ if (person !== undefined) {
124
+ peopleLines();
125
+ if (!lines.length) lines.push(`No lane waits on person:${person}.`);
126
+ return lines.join("\n");
127
+ }
116
128
  const blockers = board?.blockers ?? [];
117
129
  if (blockers.length) {
118
130
  lines.push("Lanes others wait on (highest effective priority first):");
@@ -128,6 +140,7 @@ export function waitBoardText(board) {
128
140
  targets("Launch day:", board?.launchDay?.lanes ? [board.launchDay] : []);
129
141
  targets("Decisions:", board?.decisions);
130
142
  targets("PRs and releases with no lane found:", board?.untraced);
143
+ peopleLines();
131
144
  return lines.join("\n");
132
145
  }
133
146
  // GATHER-NA: a step the coordinator ruled not applicable is never shown as done.
@@ -525,9 +538,12 @@ export async function laneCommand(action, args, flags, deps = {}) {
525
538
  }
526
539
  // hub-246: the wait graph, for the coordinator and the operator.
527
540
  if (action === "waits") {
528
- if (args[0]) throw new CliError("USAGE", "lane waits takes no <key>; pass --machine ID to narrow it to one machine.", 2);
529
- const payload = await request("GET", `/api/v1/lanes/waits${query({ machine: flags.machine })}`);
530
- return { payload, human: (p) => waitBoardText(p.data) };
541
+ if (args[0]) throw new CliError("USAGE", "lane waits takes no <key>; pass --machine ID to narrow it to one machine, or --person ROLE to one role.", 2);
542
+ if (flags.person !== undefined && (typeof flags.person !== "string" || !flags.person.trim()))
543
+ throw new CliError("USAGE", "lane waits --person needs a role, as in --person steward", 2);
544
+ const person = flags.person?.trim().replace(/^person:/i, "");
545
+ const payload = await request("GET", `/api/v1/lanes/waits${query({ machine: flags.machine, person })}`);
546
+ return { payload, human: (p) => waitBoardText(p.data, { person }) };
531
547
  }
532
548
  if (action === "start") {
533
549
  // `--key` names the lane; the positional is then the issue (NODII-DEV-CLI-13).
@@ -724,9 +740,14 @@ export async function laneCommand(action, args, flags, deps = {}) {
724
740
  picker: byAgent ? "agent" : picked.model ?? pickerModelName(),
725
741
  doneCheck,
726
742
  }, { signal });
743
+ // The stored boundary keeps every grant it had: creates (DS-254) and
744
+ // granted section and page ids (hub-643), not only the sets.
727
745
  const figma = figmaScope.map((file) => ({
728
746
  fileKey: file.fileKey,
729
747
  ...(file.componentSets.length ? { componentSetKeys: file.componentSets } : {}),
748
+ ...(file.creates?.length ? { creates: file.creates } : {}),
749
+ ...(file.sections?.length ? { sectionIds: file.sections } : {}),
750
+ ...(file.pages?.length ? { pageIds: file.pages } : {}),
730
751
  }));
731
752
  const lookup = guidelineLookup(scoped.components);
732
753
  const issue = lane.issue ? { key: lane.issue.key, title: lane.issue.title } : null;
@@ -1037,7 +1058,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
1037
1058
  // hub-246: --waiting-on is repeatable; it replaces the lane's waits.
1038
1059
  const waitingOn = flags["waiting-on"] === undefined ? [] : [flags["waiting-on"]].flat();
1039
1060
  if (waitingOn.some((value) => typeof value !== "string" || !value.trim()))
1040
- throw new CliError("USAGE", "lane heartbeat --waiting-on needs a lane key, owner/repo#n, Q-nnn, DEC-nnnn, release:<pkg> or launch-day", 2);
1061
+ throw new CliError("USAGE", "lane heartbeat --waiting-on needs a lane key, owner/repo#n, Q-nnn, DEC-nnnn, release:<pkg>, person:<role> or launch-day", 2);
1041
1062
  const payload = await request("POST", `/api/v1/lanes/${encode(id)}/heartbeat`, { ...(flags.note !== undefined ? { note: flags.note } : {}), ...(waitingOn.length ? { waitingOn } : {}), ...via });
1042
1063
  return { payload, human: (p) => heartbeatText(ref, p, waitingOn.length > 0) };
1043
1064
  }
@@ -4,7 +4,7 @@
4
4
  // when that copy is behind, `doctor` reports it, and `harness update` installs
5
5
  // the latest release over it. A failed lookup says nothing and blocks nothing.
6
6
  import { execFile } from "node:child_process";
7
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
7
+ import { access, constants, mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
8
  import { homedir } from "node:os";
9
9
  import { dirname, isAbsolute, join } from "node:path";
10
10
  import { promisify } from "node:util";
@@ -20,6 +20,21 @@ const runNpm = promisify(execFile);
20
20
  const defaultHome = () => process.env.NODII_DEV_MANAGED_HOME || homedir();
21
21
  const metadataPaths = (home) => [managedClaudeHooksDir(home), managedHooksDir(home)].map((dir) => join(dir, "metadata.json"));
22
22
  const readJson = async (read, path) => { try { return JSON.parse(await read(path, "utf8")); } catch { return null; } };
23
+ // npm writes under <prefix>/lib/node_modules and <prefix>/bin, creating what
24
+ // is missing: the deepest of those, or of the prefix's parents, that exists decides.
25
+ const canWrite = async (prefix) => {
26
+ for (let dir = join(prefix, "lib/node_modules"); ; dir = dirname(dir)) {
27
+ try { await access(dir, constants.F_OK); } catch { if (dir === dirname(dir)) return false; continue; }
28
+ try { await access(dir, constants.W_OK); return true; } catch { return false; }
29
+ }
30
+ };
31
+ /**
32
+ * Where a root-free install goes when the global prefix is root's (system node
33
+ * on Linux, or a root-owned file under a Homebrew prefix): ~/.local. Its bin
34
+ * is not on PATH by default on macOS, and not always on Linux, so a move tells
35
+ * the person to put it first on PATH (harness.js).
36
+ */
37
+ export const userPrefix = (home) => join(home, ".local");
23
38
 
24
39
  const triple = (version) => {
25
40
  const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(version ?? ""));
@@ -87,24 +102,88 @@ export const managedBehindText = ({ version, latest }) =>
87
102
  * after an install or `{ cliPath, version, current: true }` with nothing to do.
88
103
  * Throws when it could not install; the caller reports that and carries on.
89
104
  */
90
- export async function installManagedLatest({ system = false, runningCli = null, home = defaultHome(), exec = runNpm, read = readFile, write = writeFile, now = Date.now } = {}) {
105
+ export async function installManagedLatest({ system = false, runningCli = null, home = defaultHome(), exec = runNpm, read = readFile, write = writeFile, now = Date.now, writable = canWrite } = {}) {
91
106
  const copy = await managedCopy({ home, read });
92
107
  if (!copy && !system) return null;
93
108
  const latest = await latestRelease({ home, exec, read, now, fresh: true });
94
109
  if (!latest) throw new Error(`could not read the latest ${PACKAGE} release from npm`);
95
- const prefix = await installPrefix({ copy, system, runningCli, exec });
110
+ const wanted = await installPrefix({ copy, system, runningCli, exec });
111
+ const installedAt = (prefix) => readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
112
+ const isCurrent = (found) => Boolean(found?.version) && !isBehind(found.version, latest);
113
+ // Install never asks for root (O3 item 1, CLI-15): a prefix this user cannot
114
+ // write moves the managed copy to ~/.local, and every hook follows it. A copy
115
+ // already current where it is stays there: nothing to install, nothing to move.
116
+ const local = userPrefix(home);
117
+ let prefix = wanted;
118
+ let installed = await installedAt(wanted);
119
+ if (!isCurrent(installed) && wanted !== local && !(await writable(wanted))) {
120
+ prefix = local;
121
+ installed = await installedAt(local);
122
+ }
123
+ const current = isCurrent(installed);
124
+ if (!current) {
125
+ const install = (at) => exec("npm", ["install", "-g", `${PACKAGE}@${latest}`, "--prefix", at], { timeout: INSTALL_TIMEOUT_MS });
126
+ try {
127
+ await install(prefix);
128
+ } catch (error) {
129
+ if (!isPermissionError(error)) throw error;
130
+ // The prefix looked writable but npm was refused (a root-owned @nodii/dev
131
+ // or bin/nodii-dev under it): try ~/.local once before calling it a root need.
132
+ if (prefix === local) { await recordNeedsRoot(home, true, now); throw error; }
133
+ prefix = local;
134
+ installed = await installedAt(local);
135
+ try { await install(local); } catch (retry) {
136
+ if (isPermissionError(retry)) await recordNeedsRoot(home, true, now);
137
+ throw retry;
138
+ }
139
+ }
140
+ const after = await installedAt(prefix);
141
+ if (after?.version !== latest) throw new Error(`npm finished but ${prefix}/lib/node_modules/@nodii/dev/bin/nodii-dev is at ${after?.version ?? "no version"}, not ${latest}`);
142
+ }
96
143
  const cliPath = `${prefix}/lib/node_modules/@nodii/dev/bin/nodii-dev`;
97
- const installed = await readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
98
- if (installed?.version && !isBehind(installed.version, latest)) return { cliPath, version: installed.version, current: true };
99
- await exec("npm", ["install", "-g", `${PACKAGE}@${latest}`, "--prefix", prefix], { timeout: INSTALL_TIMEOUT_MS });
100
- const after = await readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
101
- if (after?.version !== latest) throw new Error(`npm finished but ${cliPath} is at ${after?.version ?? "no version"}, not ${latest}`);
102
- // The dispatcher's version check reads this (MW5-6), so it follows the copy.
144
+ const movedFrom = copy && copy.cliPath !== cliPath ? copy.cliPath : null;
145
+ const version = current ? installed.version : latest;
146
+ await recordNeedsRoot(home, false, now);
147
+ // The dispatcher's version check reads this (MW5-6), so it follows the copy;
148
+ // a moved copy rewrites cliPath too, and the dispatcher refresh follows it.
103
149
  for (const path of metadataPaths(home)) {
104
150
  const metadata = await readJson(read, path);
105
- if (metadata?.cliPath === cliPath) await write(path, `${JSON.stringify({ ...metadata, cliVersion: latest }, null, 2)}\n`, { mode: 0o600 });
151
+ if (metadata?.cliPath === cliPath || (movedFrom && metadata?.cliPath === movedFrom))
152
+ await write(path, `${JSON.stringify({ ...metadata, cliPath, cliVersion: version }, null, 2)}\n`, { mode: 0o600 });
106
153
  }
107
- return { cliPath, version: latest, previous: installed?.version ?? null };
154
+ const moved = movedFrom ? { movedFrom } : {};
155
+ return current ? { cliPath, version, current: true, ...moved } : { cliPath, version, previous: installed?.version ?? null, ...moved };
156
+ }
157
+
158
+ // MW5-8.1 (O3 item 4): whether this machine's managed install needs root. A
159
+ // permission refusal at ~/.local (the fallback, tried once after a refusal
160
+ // anywhere else) records true; any install that lands, or finds the copy current,
161
+ // records false. The watchdog sweep reports it as host_facts.needsRoot.
162
+ export const needsRootPath = (home = defaultHome()) => join(home, ".config/nodii-dev/needs-root.json");
163
+ const PERMISSION = /\bEACCES\b|\bEPERM\b|permission denied|operation not permitted/i;
164
+ export const isPermissionError = (error) =>
165
+ PERMISSION.test(`${error?.code ?? ""} ${error?.message ?? ""} ${error?.stderr ?? ""}`);
166
+ async function recordNeedsRoot(home, needsRoot, now) {
167
+ try {
168
+ const path = needsRootPath(home);
169
+ await mkdir(dirname(path), { recursive: true });
170
+ const temporary = `${path}.${process.pid}`;
171
+ await writeFile(temporary, `${JSON.stringify({ needsRoot, at: new Date(now()).toISOString() })}\n`);
172
+ await rename(temporary, path);
173
+ } catch { /* best effort */ }
174
+ }
175
+ /** What the last managed install found: true, false, or null with no record. */
176
+ export async function readNeedsRoot({ home = defaultHome(), read = readFile } = {}) {
177
+ const saved = await readJson(read, needsRootPath(home));
178
+ return typeof saved?.needsRoot === "boolean" ? saved.needsRoot : null;
179
+ }
180
+
181
+ /** The script a machine job (watchdog, coordinator watch) runs: the managed copy's, so `harness update` moves the job with it. */
182
+ export async function managedEntry({ home = defaultHome(), read = readFile } = {}) {
183
+ const copy = await managedCopy({ home, read });
184
+ if (!copy) return null;
185
+ const entry = join(dirname(dirname(copy.cliPath)), "dist/nodii-dev.js");
186
+ try { await access(entry, constants.R_OK); return entry; } catch { return null; }
108
187
  }
109
188
 
110
189
  async function installPrefix({ copy, system, runningCli, exec }) {
package/dist/nodii-dev.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { fail, main } from "./cli.js";
3
+ import { callSourceFor, setCallSource } from "./core.js";
3
4
  import { regroundCurrentLane, shouldReground } from "./freeze.js";
4
5
  import { isHookDenial } from "./hooks.js";
5
6
  import { laneReadCache } from "./read-cache.js";
@@ -23,6 +24,7 @@ async function run() {
23
24
  // AGENT-HARNESS-19: this is the executable boundary, so every ordinary CLI
24
25
  // invocation re-grounds without adding hidden requests to library callers.
25
26
  // cli-134: through the lane read cache, at most once per 15 seconds.
27
+ setCallSource(callSourceFor(argv));
26
28
  if (shouldReground(argv)) await regroundCurrentLane({}, { cache: laneReadCache() });
27
29
  await main(argv);
28
30
  }
@@ -141,3 +141,21 @@ export function toolCallChild(table, runtimePid, { helperWindowMs = HELPER_WINDO
141
141
  const names = (named.length ? named : all).filter((name, index, list) => name !== list[index - 1]);
142
142
  return { pid: call.pid, names: `${names.slice(0, MAX_NAMES).join(" › ")}${names.length > MAX_NAMES ? " › …" : ""}`, elapsedMs: call.elapsedMs };
143
143
  }
144
+
145
+ // O3 item 6 (DEC-0569, MW1-36.5): a steward session is its Claude or Codex runtime.
146
+ const RUNTIME_NAME = /^(?:claude|codex)(?:$|[-_.])/i;
147
+ const RUNTIME_SCRIPT = /[/\\](?:@anthropic-ai[/\\]claude-code|@openai[/\\]codex)[/\\]/i;
148
+ export const isRuntimeCommand = (argv) =>
149
+ RUNTIME_NAME.test(baseName(argv?.[0])) || (RUNNERS.has(baseName(argv?.[0])) && RUNTIME_SCRIPT.test(String(argv?.[1] ?? "")));
150
+
151
+ /** The first ancestor of `pid` (not itself) whose command is the Claude or Codex runtime; null when none is. */
152
+ export function runtimeAncestor(table, pid) {
153
+ const byPid = new Map((table ?? []).map((entry) => [entry.pid, entry]));
154
+ let entry = byPid.get(byPid.get(pid)?.ppid);
155
+ for (let depth = 0; entry && depth < 32; depth += 1) {
156
+ if (!entry.zombie && isRuntimeCommand(entry.argv)) return entry;
157
+ if (entry.ppid === entry.pid) break;
158
+ entry = byPid.get(entry.ppid);
159
+ }
160
+ return null;
161
+ }