@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/setup.js CHANGED
@@ -2,6 +2,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
2
  import { dirname, join, resolve } from "node:path";
3
3
  import { CliError, checkLogin } from "./core.js";
4
4
  import { codexHooksFromClaude } from "./harness.js";
5
+ import { heartbeatSettingsSnippet } from "./hooks.js";
5
6
  import { regroundingHooksSnippet, safetySettingsSnippet } from "./safety.js";
6
7
  import { EMBED_MODEL, pickerPin, setupOllama } from "./gather.js";
7
8
 
@@ -18,11 +19,12 @@ description: Drive every Nodii build lane through nodii-dev from start to verifi
18
19
 
19
20
  Use \`nodii-dev\` as the control plane. It talks only to Dev, through the platform edge, signed in with \`nodii-dev login\` as the platform tenant's OAuth app. The canonical policy is the build-workflow rulebook in Dev (\`nodii-dev rulebook list\`), §§1–8 (operator rulings A-020/A-021). Never change lane state in Dev by another route.
20
21
 
21
- 1. The machine coordinator runs \`nodii-dev coordinator start --machine NAME [--account RUNTIME:PROFILE ...]\` (each model account a lane may run on is registered once; its usage is reported then, before each launch and by the watchdog), then \`nodii-dev lane launch KEY\` with the issue (whose title is the objective), done check, build kind/side, repeated repository/branch pairs, runtime profile/model, subagent quota and the lane's class (\`--class long|short|no-build\`, weighed against the account's usage band). A launched agent begins with \`nodii-dev lane gather\` from its worktree.
22
- 2. Re-run \`nodii-dev lane gather\` for the current steps and rules; start, complete, or block the reported API step with \`nodii-dev lane step\`. After an authoritative \`lane amend\`, every run is blocked until its own \`lane gather --delta\` acknowledgement.
22
+ 1. The machine coordinator runs \`nodii-dev coordinator start --machine NAME [--account RUNTIME:PROFILE ...]\` (each model account a lane may run on is registered once; its usage is reported then, before each launch and by the watchdog), then \`nodii-dev lane launch KEY\` with the issue (whose title is the objective), done check, build kind/side, repeated repository/branch pairs, runtime profile/model, and the lane's class (\`--class long|short|no-build\`, weighed against the account's usage band). \`--subagents N\` is optional and defaults to 4 (\`nodii-dev rules show MW1-38.15\`). A launched agent begins with \`nodii-dev lane gather\` from its worktree. Before its next action the coordinator clears what lanes wait on it for: \`nodii-dev coordinator items\` lists each item with its command (\`lane leeway grant|refuse ID\`, \`lane answer ID --text TEXT\`, \`lane defer ID --reason TEXT\`). \`lane leeway grant\` asks for no TOTP code (\`nodii-dev rules show MW1-12.7\`).
23
+ 2. Re-run \`nodii-dev lane gather\` for the current steps and rules; start, complete, or block the reported API step with \`nodii-dev lane step\`. After an authoritative \`lane amend\`, every run is blocked until its own \`lane gather --delta\` acknowledgement. For a lane blocked on an open issue that no live lane holds, the command is \`nodii-dev lane leeway KEY --blocker ISSUE --reason TEXT\`; Dev refuses a second lane with \`LEEWAY_BLOCKER_HELD\` and names the holder, and \`lane gather --delta\` acknowledges the grant. The rules are in Dev: \`nodii-dev rules show MW1-12.6\` and \`MW1-12.8\`.
23
24
  3. Record durable evidence with \`nodii-dev lane evidence KEY --pr|--commit|--figma|--deploy|--dev-check REF\` and heartbeat long-running work with \`nodii-dev lane heartbeat KEY --note "..."\` (notes are at most 500 characters).
24
- 4. Record the review gate with \`nodii-dev lane review KEY\`. After merge, run \`nodii-dev lane land KEY\`. Done still means deployed and checked live on dev as the right user: \`nodii-dev lane verify KEY --dev-check REF\`.
25
- 5. Use \`nodii-dev lane prioritize|deprioritize KEY --reason "..."\` when priority changes; the reason is required. The lane stays on Built until a staff login runs \`nodii-dev built ack KEY\`. Never treat acknowledgement as testing.
25
+ 4. Before a push or a pull request that changes a command, route, refusal code or hook, run \`nodii-dev repo docs-check\`: it reads the \`toolingDocs\` block of \`nodii.repo.yaml\`, and \`hook tooling-docs\` refuses \`git push\` and \`gh pr create|ready\` with \`TOOLING_DOCS_STALE\` on the same finding. The rule is in Dev: \`nodii-dev rules show MW1-46.3\`.
26
+ 5. Record the review gate with \`nodii-dev lane review KEY\`. After merge, run \`nodii-dev lane land KEY\`. Done still means deployed and checked live on dev as the right user: \`nodii-dev lane verify KEY --dev-check REF\`.
27
+ 6. Use \`nodii-dev lane prioritize|deprioritize KEY --reason "..."\` when priority changes; the reason is required. The lane stays on Built until a staff login runs \`nodii-dev built ack KEY\`. Never treat acknowledgement as testing.
26
28
 
27
29
  ## Steps
28
30
 
@@ -53,7 +55,8 @@ export const workflowHooks = () => {
53
55
  { hooks: [{ type: "command", command: "nodii-dev lane list --mine --json" }] },
54
56
  ...regroundingHooksSnippet().hooks.SessionStart,
55
57
  ],
56
- Stop: [{ hooks: [{ type: "command", command: "nodii-dev hook lane-heartbeat" }] }],
58
+ // One Stop beat, the harness's own entry, so a repository set up and harnessed has one (NODII-DEV-CLI-191).
59
+ Stop: heartbeatSettingsSnippet().hooks.Stop,
57
60
  PreToolUse: safety.PreToolUse,
58
61
  PostToolUse: [
59
62
  ...safety.PostToolUse,
package/dist/starting.js CHANGED
@@ -11,8 +11,10 @@ import { laneCommand, nextCommand } from "./lanes.js";
11
11
  import { assertGovernorOpen, readGovernor } from "./governor.js";
12
12
  import { laneConfigName } from "./lane-env.js";
13
13
  import { hostBootedAt } from "./host.js";
14
- import { cachedGet } from "./read-cache.js";
14
+ import { cachedGet, laneReadCache } from "./read-cache.js";
15
+ import { clearCoordinatorMarker, coordinatorMarkerPath } from "./coordinator-items.js";
15
16
  import { accountFlags, listAccounts, profilePath, registerAccount, reportUsage, usageLine } from "./accounts.js";
17
+ import { subagentBudgetLine } from "./lane-supervisor.js";
16
18
 
17
19
  const execFile = promisify(execFileCallback);
18
20
  const via = { via: "nodii-dev" };
@@ -189,6 +191,15 @@ export async function findCoordinatorRun(machine, {
189
191
  return newest;
190
192
  }
191
193
 
194
+ /**
195
+ * MW1-37.2: coordinator.json beside the config marks this identity's sessions
196
+ * as a coordinator's, so the managed dispatcher runs the coordinator gate for
197
+ * them and for no other session. Best effort: the gate is off without it.
198
+ */
199
+ async function markCoordinatorSession(save, state) {
200
+ try { await save(coordinatorMarkerPath({ NODII_DEV_CONFIG_PATH: configPath() }), state); } catch {}
201
+ }
202
+
192
203
  const coordinatorState = (machine, run, agentId) => ({
193
204
  machine,
194
205
  machineId: run.metadata.machineId,
@@ -202,6 +213,7 @@ const coordinatorState = (machine, run, agentId) => ({
202
213
  * state file and restart the heartbeater. Dev's run is unchanged.
203
214
  */
204
215
  async function adoptCoordinatorRun(machine, run, c, { save, heartbeater, existingHeartbeater, installWatchdog }) {
216
+ await markCoordinatorSession(save, coordinatorState(machine, run, c.agentId));
205
217
  await save(stateFile(machine), coordinatorState(machine, run, c.agentId));
206
218
  const expected = run.expectedHeartbeatSeconds ?? 60;
207
219
  // A heartbeater still beating this run keeps it; a second is never started.
@@ -276,6 +288,7 @@ export async function coordinatorHeartbeatLoop({ machine, runId, pid, processSta
276
288
  catch (error) { if (error?.code !== "EEXIST") throw error; }
277
289
  },
278
290
  sleep = (ms) => delay(ms),
291
+ clearMarker = clearCoordinatorMarker,
279
292
  } = {}) {
280
293
  for (;;) {
281
294
  const current = await currentRunId();
@@ -296,6 +309,8 @@ export async function coordinatorHeartbeatLoop({ machine, runId, pid, processSta
296
309
  } catch (error) {
297
310
  if (error?.code !== "RUN_ALREADY_TERMINAL") throw error;
298
311
  }
312
+ // The session is gone: its coordinator marker goes with it (MW1-37.2).
313
+ await clearMarker(runId).catch(() => {});
299
314
  return { stopped: "session_exited" };
300
315
  }
301
316
  try {
@@ -424,13 +439,15 @@ export async function coordinatorCommand(action, flags, {
424
439
  } catch {}
425
440
  throw new CliError("COORDINATOR_WATCH_FAILED", `Coordinator run ${payload.data.run.id} was registered, but its session could not be watched: ${error.message}`, 1);
426
441
  }
427
- await save(stateFile(machine), {
442
+ const started = {
428
443
  machine,
429
444
  machineId: payload.data.machine.id,
430
445
  runId: payload.data.run.id,
431
446
  agentId: c.agentId,
432
447
  startedAt: payload.data.run.startedAt,
433
- });
448
+ };
449
+ await markCoordinatorSession(save, started);
450
+ await save(stateFile(machine), started);
434
451
  // The run expects a heartbeat every expectedHeartbeatSeconds; heartbeat at
435
452
  // half that so one late beat never makes it quiet.
436
453
  const expected = payload.data.run.expectedHeartbeatSeconds ?? (flags["heartbeat-seconds"] ? Number(flags["heartbeat-seconds"]) : 60);
@@ -464,7 +481,7 @@ export async function coordinatorCommand(action, flags, {
464
481
  };
465
482
  }
466
483
 
467
- async function createWorktrees(repositories, run = execFile) {
484
+ export async function createWorktrees(repositories, run = execFile) {
468
485
  for (const repository of repositories) {
469
486
  try {
470
487
  const { stdout } = await run("git", ["-C", repository.worktree, "branch", "--show-current"], { encoding: "utf8" });
@@ -484,7 +501,7 @@ async function createWorktrees(repositories, run = execFile) {
484
501
  }
485
502
  }
486
503
 
487
- async function writeLaneMarkers(repositories, marker, run = execFile, save = saveJson) {
504
+ export async function writeLaneMarkers(repositories, marker, run = execFile, save = saveJson) {
488
505
  for (const repository of repositories) {
489
506
  const { stdout } = await run("git", ["-C", repository.worktree, "rev-parse", "--git-dir"], { encoding: "utf8" });
490
507
  const gitDir = isAbsolute(stdout.trim()) ? stdout.trim() : resolve(repository.worktree, stdout.trim());
@@ -530,6 +547,15 @@ async function refreshAccountUsage(machineId, runtime, profile, { request }) {
530
547
  return reportUsage(accounts, { request, probe: true });
531
548
  }
532
549
 
550
+ /** MW1-38.15: a lane launched without --subagents gets this many subagent slots. */
551
+ export const DEFAULT_SUBAGENT_QUOTA = 4;
552
+
553
+ /** Dev clamps a new lane's quota in the two_builds and one_build usage bands; say so when it did. */
554
+ function quotaClampLine(clamp) {
555
+ if (!clamp || clamp.granted === undefined) return null;
556
+ return `Subagent quota: asked ${clamp.asked ?? "?"}, granted ${clamp.granted}${clamp.band ? ` (account usage band ${clamp.band})` : ""}.`;
557
+ }
558
+
533
559
  /** MW1-38.12: name the lanes Dev counted, so the coordinator can see which one to close. */
534
560
  function laneCapRefusal(error) {
535
561
  if (!["LANE_CAP_REACHED", "LANE_CAP_LAPSED"].includes(error?.code)) return error;
@@ -611,7 +637,8 @@ export async function launchLaneCommand(key, flags, {
611
637
  profile,
612
638
  devConfigPath,
613
639
  model: requireFlag(flags, "model"),
614
- subagentQuota: Number(requireFlag(flags, "subagents")),
640
+ // MW1-38.15: 4 subagent slots unless the coordinator says otherwise; 0 stays 0.
641
+ subagentQuota: flags.subagents === undefined ? DEFAULT_SUBAGENT_QUOTA : typeof flags.subagents === "string" ? Number(flags.subagents) : Number.NaN,
615
642
  workClass,
616
643
  ...(flags.notes ? { notes: flags.notes } : {}),
617
644
  ...(flags["narrowing-note"] ? { narrowingNote: flags["narrowing-note"] } : {}),
@@ -667,7 +694,8 @@ export async function launchLaneCommand(key, flags, {
667
694
  profileHome: body.profile,
668
695
  cwd: repositories[0].worktree,
669
696
  addDirs: repositories.slice(1).map(({ worktree }) => worktree),
670
- prompt: payload.data.brief,
697
+ // NODII-DEV-CLI-191: the brief names the subagent budget.
698
+ prompt: [payload.data.brief, subagentBudgetLine(payload.data.lane?.subagentQuota ?? body.subagentQuota)].filter(Boolean).join("\n\n"),
671
699
  runId: payload.data.run.id,
672
700
  });
673
701
  } catch (error) {
@@ -681,10 +709,11 @@ export async function launchLaneCommand(key, flags, {
681
709
  }
682
710
  throw new CliError("LANE_LAUNCH_FAILED", `Lane ${key} is registered but its runtime did not start: ${error.message}. Dev recorded it for lane resume.`, 1);
683
711
  }
712
+ const clampLine = quotaClampLine(payload.data?.subagentQuotaClamp ?? payload.subagentQuotaClamp);
684
713
  const figmaLines = body.figmaScopes.map((scope) => `Figma scope: ${scope.fileKey} ${scope.componentSets.length ? `component sets ${scope.componentSets.join(", ")}` : "(whole file)"}`);
685
714
  return {
686
715
  payload: { ...payload, figmaScopes: body.figmaScopes },
687
- human: [`Launched ${key}: ${payload.data.brief}`, ...(figmaLines.length ? figmaLines : ["Figma scope: none declared"])].join("\n"),
716
+ human: [`Launched ${key}: ${payload.data.brief}`, ...(clampLine ? [clampLine] : []), ...(figmaLines.length ? figmaLines : ["Figma scope: none declared"])].join("\n"),
688
717
  };
689
718
  }
690
719
 
@@ -812,35 +841,63 @@ const requestLine = (r) => `${r.id}\t${r.laneKey}\t${r.state}\t${r.changedPercen
812
841
 
813
842
  /**
814
843
  * hub-400: `lane amendments [<key>] [--all|--state STATE]`,
815
- * `lane amendments show|approve|reject|withdraw <request> [--note TEXT]`.
844
+ * `lane amendments show|withdraw <request>`,
845
+ * `lane amendments approve|reject <request> [<request> ...]|--all-pending [--note TEXT]`.
816
846
  * Approve and reject are the operator's: the CLI asks for their TOTP code
817
847
  * (STAFF_OPERATOR_REQUIRED), and an agent's call is refused as it stands.
848
+ * hub-525: Dev's step-up grant lasts 10 minutes and this CLI holds it for one
849
+ * process, so one command answers several requests under one code.
818
850
  */
819
851
  export async function laneAmendmentsCommand(args, flags, { request = devRequest } = {}) {
820
- const [first, second] = args;
852
+ const [first, ...named] = args;
821
853
  const decisions = ["show", "approve", "reject", "withdraw"];
822
854
  if (decisions.includes(first)) {
823
- if (!REQUEST_ID.test(second ?? "")) throw new CliError("USAGE", `lane amendments ${first} needs the request id (lane amendments lists them).`, 2);
824
- const path = `/api/v1/lane-amendment-requests/${encode(second)}`;
855
+ const many = first === "approve" || first === "reject";
856
+ const allPending = Boolean(flags["all-pending"]);
857
+ if (allPending && (!many || named.length))
858
+ throw new CliError("USAGE", "--all-pending goes with lane amendments approve or reject, and takes no request id.", 2);
859
+ if (!allPending && (named.length < 1 || (!many && named.length > 1) || named.some((id) => !REQUEST_ID.test(id))))
860
+ throw new CliError("USAGE", `lane amendments ${first} needs ${many ? "one or more request ids, or --all-pending" : "the request id"} (lane amendments lists them).`, 2);
861
+ const pathOf = (id) => `/api/v1/lane-amendment-requests/${encode(id)}`;
825
862
  if (first === "show") {
826
- const r = (await request("GET", path)).data;
863
+ const r = (await request("GET", pathOf(named[0]))).data;
827
864
  return {
828
865
  payload: { data: r },
829
866
  human: [`${r.laneKey}: ${r.state}, ${r.changedPercent}% of the brief${r.pivot ? ` (refused: ${r.pivot})` : ""}, asked ${r.createdAt}.`, `Reason: ${r.reason}`, "", r.diff].join("\n"),
830
867
  };
831
868
  }
832
869
  const body = first === "withdraw" ? { via: "nodii-dev" } : { ...(flags.note ? { note: String(flags.note) } : {}), via: "nodii-dev" };
833
- const payload = await request("POST", `${path}/${first}`, body);
834
- const r = payload.data;
835
- const human =
836
- first === "approve"
870
+ const line = (payload) => {
871
+ const r = payload.data;
872
+ return first === "approve"
837
873
  ? `Approved: ${r.laneKey} amendment ${payload.amendment?.version ?? "?"} applied. Its run picks it up with nodii-dev lane gather --delta.`
838
874
  : first === "reject"
839
875
  ? `Rejected: ${r.laneKey} keeps its brief.`
840
876
  : `Withdrawn: ${r.laneKey}'s amendment request ${r.id}.`;
841
- return { payload, human };
877
+ };
878
+ const ids = allPending ? ((await request("GET", "/api/v1/lane-amendment-requests")).data ?? []).map((r) => r.id) : named;
879
+ if (!ids.length) return { payload: { data: [] }, human: `No pending lane amendment requests to ${first}.` };
880
+ if (ids.length === 1 && !allPending) {
881
+ const payload = await request("POST", `${pathOf(ids[0])}/${first}`, body);
882
+ return { payload, human: line(payload) };
883
+ }
884
+ // One after another, in this process: the first asks for the code, the
885
+ // rest reuse its grant. A refusal stops the run and says where it stands.
886
+ const answered = [];
887
+ for (const [index, id] of ids.entries()) {
888
+ try {
889
+ answered.push(await request("POST", `${pathOf(id)}/${first}`, body));
890
+ } catch (error) {
891
+ if (!(error instanceof CliError)) throw error;
892
+ const rest = ids.slice(index + 1);
893
+ const report = [...answered.map(line), `${id}: ${error.message}`, ...(rest.length ? [`Not tried: ${rest.join(", ")}`] : [])];
894
+ throw new CliError(error.code, report.join("\n"), error.exitCode ?? 1, error.details);
895
+ }
896
+ }
897
+ return { payload: { data: answered.map((payload) => ({ ...payload.data, amendment: payload.amendment ?? null })) }, human: answered.map(line).join("\n") };
842
898
  }
843
- if (first !== undefined && args.length > 1) throw new CliError("USAGE", "lane amendments [<key>] [--all|--state STATE] | show|approve|reject|withdraw <request> [--note TEXT]", 2);
899
+ if (first !== undefined && args.length > 1) throw new CliError("USAGE", "lane amendments [<key>] [--all|--state STATE] | show|withdraw <request> | approve|reject <request> [<request> ...]|--all-pending [--note TEXT]", 2);
900
+ if (flags["all-pending"]) throw new CliError("USAGE", "--all-pending goes with lane amendments approve or reject.", 2);
844
901
  if (flags.all && flags.state) throw new CliError("USAGE", "lane amendments takes --all or --state, not both.", 2);
845
902
  const params = new URLSearchParams();
846
903
  if (first) params.set("lane", first);
@@ -881,7 +938,7 @@ export async function laneAuthorityCommand(sub, key, flags, { request = devReque
881
938
  if (extra.length) throw new CliError("USAGE", `lane authority list takes no ${extra.map((flag) => `--${flag}`).join(", ")}.`, 2);
882
939
  const payload = await request("GET", `/api/v1/lanes/${encode(key)}/authority`);
883
940
  const rows = payload.data ?? [];
884
- const line = (row) => `${row.createdAt} ${row.kind}${row.toAgentId ? ` to ${row.toAgentId}` : ""} ${row.personId} at ${row.saidAt}: "${row.quote}"${row.appliedAt ? ` (applied ${row.appliedAt})` : ""}`;
941
+ const line = (row) => `${row.createdAt} ${row.kind}${row.toAgentId ? ` to ${row.toAgentId}` : ""} ${row.personId ?? (row.standingOrderRef ? `standing order ${row.standingOrderRef}` : "no person")}${row.saidAt ? ` at ${row.saidAt}` : ""}${row.quote ? `: "${row.quote}"` : ""}${row.appliedAt ? ` (applied ${row.appliedAt})` : ""}`;
885
942
  return { payload, human: rows.length ? rows.map(line).join("\n") : `${key} has no recorded authority.` };
886
943
  }
887
944
  if (basename(path).startsWith("lane-"))
@@ -923,11 +980,47 @@ export async function currentMarker(run = execFile, load = loadJson, env = proce
923
980
  return { ...marker, runId };
924
981
  }
925
982
 
983
+ // An amendment, a leeway, a question and its answer or deferral, and a lane message change no brief by themselves.
984
+ const GUARD_EXEMPT_LANE_ACTIONS = new Set(["amend", "leeway", "ask", "asks", "answer", "defer", "message", "inbox"]);
985
+
986
+ /**
987
+ * MW1-12.9: what a lane hook tells a long-running session about an amendment
988
+ * it has not acknowledged (an answer, a leeway grant, a rebrief), so it learns
989
+ * of it without running a nodii-dev command itself. The read goes through the
990
+ * 15-second cache under its own key, so the guard below still blocks from
991
+ * Dev's own answer; each newest version is said once a minute at most. Null
992
+ * when there is nothing to say, and on any failure.
993
+ */
994
+ export async function pendingAmendmentContext({ request = devRequest, marker = currentMarker, cache = laneReadCache(), told = laneReadCache({ ttlMs: 60_000 }) } = {}) {
995
+ try {
996
+ const lane = await marker();
997
+ if (!lane) return null;
998
+ const path = `/api/v1/lanes/${encode(lane.laneKey)}/amendments${query({ runId: lane.runId })}`;
999
+ let pending = await cache.get(`${path}#context`);
1000
+ if (pending === undefined) {
1001
+ pending = await request("GET", path);
1002
+ await cache.set(`${path}#context`, pending);
1003
+ }
1004
+ const rows = [...(pending?.data ?? [])].sort((a, b) => a.version - b.version);
1005
+ if (!rows.length) return null;
1006
+ const newest = rows.at(-1).version;
1007
+ if ((await told.get(`${path}#told`)) === newest) return null;
1008
+ await told.set(`${path}#told`, newest);
1009
+ const listed = rows.map((row) => `v${row.version} ${String(row.reason ?? "").replace(/\s+/g, " ").trim().slice(0, 160)}`).join("; ");
1010
+ const many = rows.length > 1;
1011
+ return `nodii-dev: lane ${lane.laneKey} has ${many ? `${rows.length} amendments` : "an amendment"} it has not acknowledged (${listed}). Run \`nodii-dev lane gather ${lane.laneKey} --delta\` now: it shows ${many ? "them" : "it"} and acknowledges ${many ? "them" : "it"}, and every other nodii-dev command is refused until then.`;
1012
+ } catch {
1013
+ return null;
1014
+ }
1015
+ }
1016
+
926
1017
  export async function amendmentGuard(argv, { request = devRequest, marker = currentMarker, cache = null } = {}) {
927
1018
  const lane = await marker();
928
1019
  if (!lane) return null;
929
1020
  const [command, action] = argv.filter((token) => !token.startsWith("--"));
930
- if ((command === "lane" && action === "gather" && argv.includes("--delta")) || (command === "lane" && action === "amend")) return lane;
1021
+ // MW1-12.6: asking for leeway, and a coordinator's grant or refusal, change
1022
+ // no brief by themselves; a grant reaches the lane as its own amendment.
1023
+ if ((command === "lane" && action === "gather" && argv.includes("--delta")) || (command === "lane" && GUARD_EXEMPT_LANE_ACTIONS.has(action)) || (command === "coordinator" && action === "items")) return lane;
931
1024
  // cli-134: only "nothing pending" is cached, so a pending amendment always
932
1025
  // blocks from Dev's own answer and its acknowledgement is seen at once.
933
1026
  const pending = await cachedGet(cache, request, `/api/v1/lanes/${encode(lane.laneKey)}/amendments${query({ runId: lane.runId })}`, (answer) => Array.isArray(answer?.data) && !answer.data.length);
@@ -0,0 +1,127 @@
1
+ // `nodii-dev repo docs-check` and `nodii-dev hook tooling-docs`: docs move with
2
+ // tooling (hub-525; MW1-46.3, DEC-0486; operator, 17 Nov 2026).
3
+ //
4
+ // A repository names, in the `toolingDocs` block of nodii.repo.yaml, the files
5
+ // that hold its commands, routes, refusal codes and hooks (`tooling`) and the
6
+ // files that describe them (`docs`). A range that changes a tooling file and no
7
+ // docs file is stale, unless a commit in the range carries a
8
+ // `Docs-unaffected: <reason>` trailer. The hook refuses `git push` and
9
+ // `gh pr create|ready` on a stale range. A repository without the block is not
10
+ // checked. The check reads git only; it never calls Dev.
11
+ import { execFile } from "node:child_process";
12
+ import { promisify } from "node:util";
13
+ import { CliError } from "./core.js";
14
+ import { POLICY_FILE, readPolicy } from "./repo-policy.js";
15
+ import { withoutHeredocBodies } from "./safety.js";
16
+
17
+ const execFileAsync = promisify(execFile);
18
+ export const TOOLING_DOCS_BASE = "origin/main";
19
+ export const DOCS_UNAFFECTED = "Docs-unaffected";
20
+
21
+ /** Does the glob match the whole path? `*` and `?` stay in one folder; `**` crosses folders. */
22
+ export function globMatches(glob, path) {
23
+ let source = "";
24
+ for (let i = 0; i < glob.length; i++) {
25
+ const c = glob[i];
26
+ if (c === "*" && glob[i + 1] === "*") {
27
+ // `**/` also matches no folder at all, so docs/**/*.md takes docs/a.md.
28
+ if (glob[i + 2] === "/") { source += "(?:.*/)?"; i += 2; } else { source += ".*"; i += 1; }
29
+ } else if (c === "*") source += "[^/]*";
30
+ else if (c === "?") source += "[^/]";
31
+ else source += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
32
+ }
33
+ return new RegExp(`^${source}$`).test(path);
34
+ }
35
+
36
+ async function git(root, args) {
37
+ const { stdout } = await execFileAsync("git", ["-C", root, ...args], { maxBuffer: 64 * 1024 * 1024 });
38
+ return stdout;
39
+ }
40
+
41
+ /**
42
+ * Check the range `<base>...HEAD` of one repository. Returns
43
+ * `{ checked: false, stale: false, reason }` when there is nothing to check
44
+ * against, else `{ checked: true, stale, base, tooling, docs, unaffected }`.
45
+ */
46
+ export async function toolingDocsCheck(root, { base = TOOLING_DOCS_BASE } = {}) {
47
+ const skip = (reason) => ({ checked: false, stale: false, reason });
48
+ let policy;
49
+ try { policy = await readPolicy(root); } catch (error) {
50
+ if (error.code !== "POLICY_MISSING" && error.code !== "POLICY_INVALID") throw error;
51
+ return skip(error.message);
52
+ }
53
+ if (!policy.toolingDocs) return skip(`${POLICY_FILE} has no toolingDocs block`);
54
+ try { await git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]); } catch { return skip(`${base} is not a commit here; fetch it or pass --base`); }
55
+ const changed = (await git(root, ["diff", "--name-only", `${base}...HEAD`])).split("\n").filter(Boolean);
56
+ const matching = (globs) => changed.filter((path) => globs.some((glob) => globMatches(glob, path))).sort();
57
+ const tooling = matching(policy.toolingDocs.tooling);
58
+ const docs = matching(policy.toolingDocs.docs);
59
+ const messages = await git(root, ["log", "--format=%B", `${base}..HEAD`]);
60
+ const unaffected = new RegExp(`^${DOCS_UNAFFECTED}:[ \\t]*(\\S.*)$`, "m").exec(messages)?.[1].trim() ?? null;
61
+ return { checked: true, stale: tooling.length > 0 && docs.length === 0 && !unaffected, base, tooling, docs, unaffected, docsGlobs: policy.toolingDocs.docs };
62
+ }
63
+
64
+ const listed = (paths, max = 8) => `${paths.slice(0, max).join(", ")}${paths.length > max ? ` and ${paths.length - max} more` : ""}`;
65
+
66
+ /** The refusal's text: what changed, where its docs are, and the two ways to clear it. */
67
+ export function toolingDocsStaleText(result) {
68
+ return `TOOLING_DOCS_STALE: this change touches tooling (${listed(result.tooling)}) and no file that describes it, in ${result.base}...HEAD (MW1-46.3). `
69
+ + `Update the docs it makes stale in the same change (${listed(result.docsGlobs)}), `
70
+ + `or declare them unaffected in a commit message with the trailer \`${DOCS_UNAFFECTED}: <reason>\`. Check again: nodii-dev repo docs-check.`;
71
+ }
72
+
73
+ // `git [-C DIR | -c k=v | --flag]... push` and `gh pr create|ready`, at the start of a command in a chain.
74
+ const SEGMENT = /(?:^|&&|\|\||[;|\n(])\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(git((?:\s+(?:-C\s+(?:"[^"]*"|'[^']*'|\S+)|-c\s+\S+|--?[A-Za-z][\w-]*(?:=\S+)?))*)\s+push\b|gh\s+pr\s+(?:create|ready)\b)/g;
75
+
76
+ /** The directories a command pushes or opens a pull request from: `cwd`, or a `git -C` target. */
77
+ export function toolingDocsTargets(command, cwd) {
78
+ const out = [];
79
+ for (const match of withoutHeredocBodies(String(command ?? "")).matchAll(SEGMENT)) {
80
+ const dir = /(?:^|\s)-C\s+("[^"]*"|'[^']*'|\S+)/.exec(match[2] ?? "")?.[1];
81
+ out.push(dir ? dir.replace(/^(["'])(.*)\1$/, "$2") : cwd);
82
+ }
83
+ return [...new Set(out)];
84
+ }
85
+
86
+ /**
87
+ * PreToolUse on Bash. Returns `{ deny }` for a `git push` or `gh pr
88
+ * create|ready` over a stale range, else null. Fails open: outside a
89
+ * repository, or on any git error, the call passes.
90
+ */
91
+ export async function toolingDocsHook(payload) {
92
+ if (payload?.tool_name !== "Bash") return null;
93
+ const cwd = payload.cwd ?? process.cwd();
94
+ for (const dir of toolingDocsTargets(payload.tool_input?.command, cwd)) {
95
+ try {
96
+ const root = (await git(dir, ["rev-parse", "--show-toplevel"])).trim();
97
+ const result = await toolingDocsCheck(root);
98
+ if (result.stale) return { deny: toolingDocsStaleText(result) };
99
+ } catch {}
100
+ }
101
+ return null;
102
+ }
103
+
104
+ export const toolingDocsSettingsSnippet = () => ({
105
+ hooks: { PreToolUse: [{ matcher: "^Bash$", hooks: [{ type: "command", command: "nodii-dev hook tooling-docs" }] }] },
106
+ });
107
+
108
+ const human = (result) => {
109
+ if (!result.checked) return `Not checked: ${result.reason}.`;
110
+ if (result.stale) return toolingDocsStaleText(result);
111
+ if (!result.tooling.length) return `${result.base}...HEAD changes no tooling file.`;
112
+ return result.docs.length
113
+ ? `${result.base}...HEAD changes tooling (${listed(result.tooling)}) and its docs (${listed(result.docs)}).`
114
+ : `${result.base}...HEAD changes tooling (${listed(result.tooling)}); docs declared unaffected: ${result.unaffected}`;
115
+ };
116
+
117
+ /** `repo docs-check [--base REF]`: 0 clean or not checked, 1 TOOLING_DOCS_STALE. */
118
+ export async function repoDocsCheckCommand(rest, flags = {}) {
119
+ if (rest.length) throw new CliError("USAGE", `repo docs-check [--base REF] takes no arguments, got: ${rest.join(" ")}`, 2);
120
+ if (flags.base === true) throw new CliError("USAGE", "repo docs-check --base REF", 2);
121
+ let root;
122
+ try { root = flags.root && flags.root !== true ? String(flags.root) : (await git(process.cwd(), ["rev-parse", "--show-toplevel"])).trim(); } catch { throw new CliError("USAGE", "Run this inside a git repository.", 2); }
123
+ const result = await toolingDocsCheck(root, flags.base ? { base: String(flags.base) } : {});
124
+ const { docsGlobs: _globs, ...rest_ } = result;
125
+ const payload = { root, passed: !result.stale, ...(result.stale ? { code: "TOOLING_DOCS_STALE" } : {}), ...rest_ };
126
+ return { payload, human: () => human(result), exitCode: result.stale ? 1 : 0 };
127
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.174",
3
+ "version": "0.6.176",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {