@nodii/dev 0.6.75 → 0.6.76

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/cli.js CHANGED
@@ -30,6 +30,7 @@ import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop,
30
30
  import { activeSteward, firstPromptText, isLaneConfig, sessionStartText, stewardCommand } from "./session-kind.js";
31
31
  import { doctorCommand } from "./doctor.js";
32
32
  import { dispatchManagedClaudeHook, dispatchManagedHook } from "./managed-hooks.js";
33
+ import { governorCommand, laneClose } from "./governor.js";
33
34
  import { freezeCommand } from "./freeze.js";
34
35
  import {
35
36
  figmaChangeSetShow,
@@ -353,6 +354,24 @@ Usage: nodii-dev <command> [options] [--json]
353
354
  lane freeze drop <key> --section SECTION --item ID --reason TEXT
354
355
  lane freeze swap <key> --section SECTION [--item ID] --file VALUE.json --reason TEXT
355
356
  lane freeze show|history <key> # durable compact-safe contract and all versions
357
+ lane close <key> [--delivered-by <PR URL|lane key|issue key>] --reason TEXT
358
+ # hub-232. The machine's coordinator closes a lane that marked itself
359
+ # finished with a reason and evidence (MW1-28.2); LANE_NOT_FINISHED
360
+ # otherwise. --delivered-by adds proof on dev (a merged PR verified on
361
+ # dev, a lane at on_dev, or a done issue), checked and recorded;
362
+ # merged-only or on-main proof is refused. Staff may stop on that
363
+ # proof alone (MW1-28). No steward or other agent closes a lane. Its
364
+ # steps stay as they were (nothing is faked done). A finished lane that
365
+ # is orphan, host-lost or worktree-lost closes the same way; a live process is refused
366
+ # (LANE_PROCESS_LIVE); a terminal lane only gains the proof
367
+ governor [show] [--machine-id ID] # the machine's emergency governor: stuck lanes against the threshold, READY
368
+ # on unmerged PRs (MW1-38.14), runs that ended with an open PR and no READY
369
+ # (GOVERNOR_NO_READY) and the merge queue. While it refuses, lane launch and
370
+ # lane resume --class long exit 1 (GOVERNOR_STUCK, READY_BACKLOG)
371
+ governor override --quote TEXT --said-at ISO --reason TEXT [--minutes N] [--machine-id ID]
372
+ # the operator only, signed in: let exactly one launch through, recorded with
373
+ # their words and when they said them; lapses unused (default 60 min)
374
+ governor overrides [--machine-id ID] # the machine's overrides and the launch each let through
356
375
  lane non-issue <key> --reason TEXT --evidence TEXT --reroute KEY[,KEY]|none
357
376
  --branch carried:KEY|dropped[:REASON] [--commits SHA[,SHA]]
358
377
  # DEC-0011: terminal non_issue; issue -> wont_do; slot frees
@@ -849,6 +868,14 @@ export async function main(argv = process.argv.slice(2)) {
849
868
  if (command === "coordinator") return emitCommand(await coordinatorCommand(action, f, { installWatchdog }));
850
869
  if (command === "steward") return emitCommand(await stewardCommand(action, rest, f));
851
870
  if (command === "lane" && action === "launch") return emitCommand(await launchLaneCommand(rest[0], f));
871
+ if (command === "lane" && action === "close") {
872
+ const result = await laneClose(rest[0], f);
873
+ return emit({ data: result.data }, json, result.text);
874
+ }
875
+ if (command === "governor") {
876
+ const result = await governorCommand(action, f);
877
+ return emit({ data: result.data }, json, result.text);
878
+ }
852
879
  if (command === "lane" && action === "amend") return emitCommand(await amendLaneCommand(rest[0], f));
853
880
  if (command === "lane" && action === "gather") {
854
881
  const result = await gatherLaneCommand(rest[0], f);
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.75";
7
+ export const VERSION = "0.6.76";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/flags.js CHANGED
@@ -39,6 +39,11 @@ export const COMMAND_FLAGS = {
39
39
  "lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class"],
40
40
  "lane transfer": ["reason", "to-agent"],
41
41
  "lane stop": ["reason"],
42
+ // hub-232: the honest close-out and the governor.
43
+ "lane close": ["delivered-by", "reason"],
44
+ "governor show": ["machine-id"],
45
+ "governor override": ["machine-id", "quote", "said-at", "reason", "minutes"],
46
+ "governor overrides": ["machine-id"],
42
47
  "lane land": [],
43
48
  "repo policy": ["root"],
44
49
  "repo lint": ["root"],
@@ -0,0 +1,187 @@
1
+ // hub-232: the emergency governor, on the CLI side. Dev holds the
2
+ // rules (GET /machines/:id/governor) and refuses launches itself; the CLI
3
+ // prints the governor to coordinator and steward sessions, refuses a launch
4
+ // before it reaches Dev, gives the honest close-out and records the operator's
5
+ // override. The managed hooks call the two hook entry points at the bottom.
6
+ import { CliError, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
7
+
8
+ export const GOVERNOR_REFUSALS = ["GOVERNOR_STUCK", "READY_BACKLOG"];
9
+
10
+ /**
11
+ * The session kinds the governor binds (hub-232): `coordinator` (the
12
+ * agent is its machine's coordinator) or `steward` (it holds an active steward
13
+ * lane, hub-230). Anything else is null. Steward-harness's own
14
+ * session-kind detection replaces this once it ships in the CLI.
15
+ */
16
+ export async function governorSessionKind({ request = devRequest, config = readConfig } = {}) {
17
+ const c = await config(false);
18
+ if (!c?.agentId) return { kind: null, agent: null };
19
+ const agent = (await request("GET", `/api/v1/agents/${encode(c.agentId)}`)).data;
20
+ if (agent?.role === "coordinator") return { kind: "coordinator", agent };
21
+ try {
22
+ const page = await request("GET", `/api/v1/lanes${query({ agent: c.agentId, kind: "steward", status: "queued,building,built,review,on_main", limit: 1 })}`);
23
+ if ((page.data ?? []).length) return { kind: "steward", agent };
24
+ } catch {
25
+ // Dev before hub-230 has no steward kind and refuses the filter.
26
+ }
27
+ return { kind: null, agent };
28
+ }
29
+
30
+ /** The machine a session's agent belongs to, or the one named with --machine-id. */
31
+ export async function governorMachineId(flags = {}, { request = devRequest, config = readConfig } = {}) {
32
+ if (flags["machine-id"]) return flags["machine-id"];
33
+ const c = await config();
34
+ const agent = (await request("GET", `/api/v1/agents/${encode(c.agentId)}`)).data;
35
+ if (!agent?.machineId) throw new CliError("MACHINE_REQUIRED", "The current agent is not assigned to a machine; pass --machine-id.", 1);
36
+ return agent.machineId;
37
+ }
38
+
39
+ export async function readGovernor(machineId, { request = devRequest } = {}) {
40
+ return (await request("GET", `/api/v1/machines/${encode(machineId)}/governor`)).data;
41
+ }
42
+
43
+ const minutes = (n) => (n >= 120 ? `${Math.round(n / 60)} h` : `${n} min`);
44
+ const iso = (value) => {
45
+ const time = Date.parse(value);
46
+ return Number.isNaN(time) ? "unknown time" : new Date(time).toISOString();
47
+ };
48
+
49
+ /** The governor as the lines a session reads. */
50
+ export function governorLines(g) {
51
+ const state = { open: "open", refused: "REFUSING launches", override: "REFUSING, one operator override live" }[g.state] ?? g.state;
52
+ const lines = [
53
+ `Governor (${g.machineName}): ${state}. Stuck ${g.stuck.count}/${g.stuck.threshold}${g.stuck.waitingOnPublish ? ` (and ${g.stuck.waitingOnPublish} waiting on Publish all, not stuck)` : ""}; READY unmerged ${g.ready.count}/${g.ready.limit}, ${g.ready.overdue} over ${minutes(g.ready.maxWaitMinutes)}.`,
54
+ ];
55
+ for (const refusal of g.refusals) lines.push(` ${refusal.code}: ${refusal.message}`);
56
+ if (g.override)
57
+ lines.push(` Override: "${g.override.quote}" (${g.override.reason}), said ${iso(g.override.saidAt)}, lapses ${iso(g.override.expiresAt)}.`);
58
+ if (g.mergeQueue.length) {
59
+ lines.push(` Merge queue (READY, unmerged over 1 h): ${g.mergeQueue.length}`);
60
+ for (const lane of g.mergeQueue.slice(0, 10)) lines.push(` ${lane.key} ${lane.prs.join(" ")} (${minutes(lane.waitingMinutes)})`);
61
+ }
62
+ if (g.noReady.length) {
63
+ lines.push(` GOVERNOR_NO_READY: ${g.noReady.length} lane run(s) ended with an open PR and no READY (no done check):`);
64
+ for (const lane of g.noReady.slice(0, 10)) lines.push(` ${lane.key} ${lane.prs.join(" ")}`);
65
+ }
66
+ if (g.state !== "open")
67
+ lines.push(" Close out a lane that marked itself finished, as its machine coordinator (MW1-28.2): nodii-dev lane close <key> --reason TEXT [--delivered-by <verified PR URL|on_dev lane key|done issue key>]. Every other lane needs on_dev or a staff stop (MW1-28).");
68
+ return lines;
69
+ }
70
+
71
+ /** Throw the governor's refusal, as Dev would, before a launch reaches Dev. */
72
+ export function assertGovernorOpen(g) {
73
+ if (g.state !== "refused") return;
74
+ const code = g.refusals?.[0]?.code ?? "GOVERNOR_REFUSED";
75
+ throw new CliError(code, governorLines({ ...g, refusals: g.refusals ?? [] }).join("\n"), 1, { governor: g });
76
+ }
77
+
78
+ // --- the Bash commands the hook governs --------------------------------------
79
+
80
+ /**
81
+ * Whether a Bash command launches work the governor governs: `nodii-dev lane
82
+ * launch`, or `nodii-dev lane resume ... --class long`. A short or no-build
83
+ * resume (a close-out), a read and a close are never governed.
84
+ */
85
+ export function governedLaunch(command) {
86
+ const text = String(command ?? "");
87
+ // Any path or wrapper before it (npx, an absolute path, quotes) and global
88
+ // flags between the binary and `lane` still count.
89
+ for (const match of text.matchAll(/nodii-dev(?:\.js)?["']?(?:\s+--?[\w-]+)*\s+lane\s+(launch|resume)\b([^;&|\n]*)/g)) {
90
+ if (match[1] === "launch") return "launch";
91
+ if (/--class(?:\s+|=)["']?long\b/.test(match[2])) return "resume --class long";
92
+ }
93
+ return null;
94
+ }
95
+
96
+ // --- hook entry points ---------------------------------------------------------
97
+
98
+ /** SessionStart: a coordinator or steward session sees its machine's governor. */
99
+ export async function governorSessionStart(deps = {}) {
100
+ const { kind, agent } = await governorSessionKind(deps);
101
+ if (!kind || !agent?.machineId) return "";
102
+ const g = await readGovernor(agent.machineId, deps);
103
+ return [`Session kind: ${kind}.`, ...governorLines(g)].join("\n");
104
+ }
105
+
106
+ /**
107
+ * PreToolUse on Bash: block a governed launch while the governor refuses it.
108
+ * Fails closed: when Dev can't be read, the launch is blocked too. Every other
109
+ * command passes untouched.
110
+ */
111
+ export async function governorPreToolUse(payload, deps = {}) {
112
+ if (payload?.tool_name !== "Bash") return null;
113
+ const what = governedLaunch(payload?.tool_input?.command);
114
+ if (!what) return null;
115
+ let g;
116
+ try {
117
+ // The launch's own target when the command names it, else this agent's machine.
118
+ const named = String(payload.tool_input.command).match(/--machine-id(?:\s+|=)["']?([0-9a-f-]{36})/i)?.[1];
119
+ const machineId = named ?? (await governorMachineId({}, deps));
120
+ g = await readGovernor(machineId, deps);
121
+ } catch (error) {
122
+ return { deny: `nodii-dev governor: the governor could not be read (${error?.message ?? String(error)}), so this ${what} is blocked. Launches fail closed (hub-232); reads and close-outs still run.` };
123
+ }
124
+ if (g.state === "refused")
125
+ return { deny: `nodii-dev governor: ${what} refused.\n${governorLines(g).join("\n")}` };
126
+ return { context: governorLines(g).join("\n") };
127
+ }
128
+
129
+ // --- commands --------------------------------------------------------------------
130
+
131
+ /** `nodii-dev governor [show] [--machine-id ID]` and `nodii-dev governor override ...`. */
132
+ export async function governorCommand(action, flags, { request = devRequest, config = readConfig } = {}) {
133
+ const machineId = await governorMachineId(flags, { request, config });
134
+ if (!action || action === "show") {
135
+ const g = await readGovernor(machineId, { request });
136
+ return { data: g, text: governorLines(g).join("\n") };
137
+ }
138
+ if (action === "override") {
139
+ const quote = requireFlag(flags, "quote");
140
+ const reason = requireFlag(flags, "reason");
141
+ const saidAt = requireFlag(flags, "said-at");
142
+ if (!/(?:Z|[+-]\d\d:?\d\d)$/i.test(saidAt) || Number.isNaN(Date.parse(saidAt))) throw new CliError("USAGE", "--said-at must be an ISO time with an offset, e.g. 2026-11-02T14:50:00Z.", 2);
143
+ const body = { quote, reason, saidAt: new Date(saidAt).toISOString(), via: "nodii-dev" };
144
+ if (flags.minutes !== undefined) {
145
+ const n = Number(flags.minutes);
146
+ if (!Number.isInteger(n) || n < 1) throw new CliError("USAGE", "--minutes must be a whole number of minutes.", 2);
147
+ body.minutes = n;
148
+ }
149
+ const row = (await request("POST", `/api/v1/machines/${encode(machineId)}/governor/override`, body)).data;
150
+ return { data: row, text: `Override recorded: one launch may pass until ${row.expiresAt}. Quote: "${row.quote}".` };
151
+ }
152
+ if (action === "overrides") {
153
+ const rows = (await request("GET", `/api/v1/machines/${encode(machineId)}/governor/overrides`)).data ?? [];
154
+ return {
155
+ data: rows,
156
+ text: rows.length
157
+ ? rows.map((r) => `${r.createdAt} "${r.quote}" (${r.reason}) ${r.consumedLaneKey ? `let ${r.consumedLaneKey} through` : `unused, lapses ${r.expiresAt}`}`).join("\n")
158
+ : "No governor overrides on this machine.",
159
+ };
160
+ }
161
+ throw new CliError("USAGE", "governor [show|override|overrides] [--machine-id ID]", 2);
162
+ }
163
+
164
+ /**
165
+ * `nodii-dev lane close <key> [--delivered-by REF] --reason TEXT`. Dev closes a
166
+ * lane that marked itself finished, for its machine's coordinator (MW1-28.2);
167
+ * REF adds proof the work is on dev, checked and recorded. Staff may stop on
168
+ * that proof alone (MW1-28).
169
+ */
170
+ export async function laneClose(key, flags, { request = devRequest } = {}) {
171
+ if (!key) throw new CliError("USAGE", "lane close needs <key>.", 2);
172
+ const reason = requireFlag(flags, "reason");
173
+ if (flags["delivered-by"] !== undefined && !String(flags["delivered-by"]).trim())
174
+ throw new CliError("USAGE", "--delivered-by needs a verified PR URL, an on_dev lane key or a done issue key; leave it out to close a finished lane (MW1-28.2).", 2);
175
+ const deliveredBy = flags["delivered-by"] === undefined ? undefined : String(flags["delivered-by"]).trim();
176
+ const body = deliveredBy === undefined ? { reason, via: "nodii-dev" } : { deliveredBy, reason, via: "nodii-dev" };
177
+ const result = (await request("POST", `/api/v1/lanes/${encode(key)}/close`, body)).data;
178
+ const kind = result.deliveredBy?.kind ?? "unknown";
179
+ const proof = kind === "finished" ? "its own finished record (MW1-28.2)" : `${kind} ${result.deliveredBy?.ref ?? ""}`.trim();
180
+ const unmerged = result.unmergedOwnPrs?.length ? ` Its own unmerged PRs (close or merge them): ${result.unmergedOwnPrs.join(", ")}.` : "";
181
+ return {
182
+ data: result,
183
+ text: result.closed
184
+ ? `${key} closed out, delivered by ${proof}. Its steps are left as they were.${unmerged}`
185
+ : `${key} was already ${result.lane.status}; recorded that ${proof} delivered it.${unmerged}`,
186
+ };
187
+ }
package/dist/lanes.js CHANGED
@@ -5,6 +5,7 @@ import { promisify } from "node:util";
5
5
  import { coordinatorMachineId, listAccounts, profilePath, reportUsage } from "./accounts.js";
6
6
  import { CliError, encode, devRequest, query, readConfig, requireFlag } from "./core.js";
7
7
  import { launchRecovery } from "./runtime-launcher.js";
8
+ import { assertGovernorOpen, readGovernor } from "./governor.js";
8
9
  import { recordReviewReceipt, reviewCommitContext } from "./safety.js";
9
10
  import { GATHER_TIMEOUT_MS, PICKER_FIRST_PICK_TIMEOUT_MS, agentFallbackReason, gatherDeadline, gatherText, pickDocuments, pickerModelName, pickTimingLine, pickTimingStats, readPickTimings, recordPickTiming, warmPicker, withPickLock } from "./gather.js";
10
11
  import { storeGatherFreeze } from "./freeze.js";
@@ -937,6 +938,16 @@ export async function laneCommand(action, args, flags, deps = {}) {
937
938
  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);
938
939
  await refreshAccounts(profile, { request, config });
939
940
  move = { profile, workClass };
941
+ // hub-232: a long resume is a launch for the governor; a short
942
+ // or no-build resume (a close-out) is never refused. Dev refuses the same.
943
+ if (workClass === "long") {
944
+ let governor = null;
945
+ try {
946
+ const lane = (await request("GET", `/api/v1/lanes/${encode(id)}`)).data;
947
+ if (lane?.machineId) governor = await readGovernor(lane.machineId, { request });
948
+ } catch {}
949
+ if (governor) assertGovernorOpen(governor);
950
+ }
940
951
  }
941
952
  const payload = await request(
942
953
  "POST",
@@ -103,22 +103,90 @@ export function managedHookBundle(hooksText, { home, cliPath, cliVersion = VERSI
103
103
  }
104
104
 
105
105
  // The stable shell entry point both runtimes call. A lane config gets every
106
- // event; any other session only the session-scoped ones (SessionStart,
107
- // UserPromptSubmit, and a PreToolUse that could be a steering act), plus the
108
- // MW8-17 Surface-generation nudge: an edit whose payload names a product page
109
- // goes to `hook surface-gen-pre`, which reads only the edit. Every failure
110
- // ends in the runtime's empty answer (fail open).
111
- const SURFACE_GEN = `case "$managed_input" in *product-pages/*) case "$managed_input" in *'"Edit"'*|*'"Write"'*|*'"MultiEdit"'*|*'"apply_patch"'*) if [ -x "$managed_cli" ]; then managed_output=$(printf '%s' "$managed_input" | "$managed_cli" hook surface-gen-pre 2>/dev/null) && [ -n "$managed_output" ] && { printf '%s\\n' "$managed_output"; exit 0; }; fi ;; esac ;; esac; `;
112
-
106
+ // event; any other session only the session-scoped ones: SessionStart,
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
109
+ // Surface-generation nudge: an edit whose payload names a product page goes to
110
+ // `hook surface-gen-pre`, which reads only the edit. Every failure ends in the
111
+ // runtime's empty answer (fail open), except a governed launch, which the
112
+ // governor answers with a deny when it cannot clear it (fail closed).
113
+ const SURFACE_GEN = `case "$managed_payload" in *product-pages/*) case "$managed_payload" in *'"Edit"'*|*'"Write"'*|*'"MultiEdit"'*|*'"apply_patch"'*) if [ -x "$managed_cli" ]; then managed_output=$(printf '%s' "$managed_payload" | "$managed_cli" hook surface-gen-pre 2>/dev/null) && [ -n "$managed_output" ] && { printf '%s\\n' "$managed_output"; exit 0; }; fi ;; esac ;; esac; `;
114
+ const GOVERNOR_UNCHECKED_DENY = JSON.stringify({
115
+ hookSpecificOutput: {
116
+ hookEventName: "PreToolUse",
117
+ permissionDecision: "deny",
118
+ permissionDecisionReason: "nodii-dev governor: the managed nodii-dev could not run, so this launch is blocked (launches fail closed, hub-232). Fix the CLI (nodii-dev doctor) and retry.",
119
+ },
120
+ });
113
121
  export function dispatchScript(cliPath, action, stopJson) {
114
122
  const command = shellString(cliPath);
115
123
  const empty = stopJson ? ` case "$1" in Stop|SubagentStop) printf '{}\\n' ;; esac\n` : " :\n";
116
- // Only a non-lane PreToolUse reads its payload in the shell, to screen it;
117
- // every other call passes stdin straight through, as before.
118
- const session = ` SessionStart|UserPromptSubmit) ;;\n PreToolUse) managed_input=$(cat); managed_screened=1; ${SURFACE_GEN}case "$managed_input" in ${STEER_MARKERS.join("|")}) ;; *) empty_response "$1"; exit 0 ;; esac ;;\n *) empty_response "$1"; exit 0 ;;\n`;
119
- return `#!/bin/sh\nmanaged_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nmanaged_cli=${command}\nempty_response() {\n${empty}}\nmanaged_screened=\ncase "\${NODII_DEV_CONFIG_PATH##*/}" in\n lane-*.json) ;;\n *) case "$1" in\n${session} esac ;;\nesac\nif [ ! -x "$managed_cli" ]; then empty_response "$1"; exit 0; fi\nexport NODII_DEV_MANAGED_HOOKS_DIR="$managed_dir"\nexport NODII_DEV_MANAGED_CLI_PATH="$managed_cli"\nif [ -n "$managed_screened" ]; then managed_output=$(printf '%s' "$managed_input" | "$managed_cli" hook ${action} "$1" 2>/dev/null); else managed_output=$("$managed_cli" hook ${action} "$1" 2>/dev/null); fi\nmanaged_status=$?\nif [ "$managed_status" -ne 0 ]; then empty_response "$1"; exit 0; fi\nif [ -n "$managed_output" ]; then printf '%s\\n' "$managed_output"; else empty_response "$1"; fi\n`;
124
+ return [
125
+ "#!/bin/sh",
126
+ 'managed_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
127
+ `managed_cli=${command}`,
128
+ `empty_response() {\n${empty}}`,
129
+ // A launch the governor never got to see is refused, not waved through. The
130
+ // match is wider than governedLaunch(): any path, quote or flag between
131
+ // nodii-dev and `lane` (P-8: deny when the check cannot run).
132
+ "governor_unchecked() {",
133
+ ` if printf '%s' "$managed_payload" | grep -Eq 'nodii-dev[^;&|]*lane([[:space:]]|\\\\[nrt])+launch|--class([[:space:]=]|\\\\[nrt])+(\\\\?\"|'\"'\"')?long'; then printf '%s\\n' '${GOVERNOR_UNCHECKED_DENY}'; else empty_response "$1"; fi`,
134
+ "}",
135
+ "managed_buffered=",
136
+ "managed_governed=",
137
+ 'case "${NODII_DEV_CONFIG_PATH##*/}" in',
138
+ " lane-*.json) ;;",
139
+ ' *) case "$1" in',
140
+ " SessionStart|UserPromptSubmit) ;;",
141
+ " PreToolUse)",
142
+ " managed_payload=$(cat)",
143
+ " managed_buffered=1",
144
+ ` 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 ;;`,
146
+ ' *) empty_response "$1"; exit 0 ;;',
147
+ " esac ;;",
148
+ "esac",
149
+ 'if [ ! -x "$managed_cli" ]; then if [ -n "$managed_governed" ]; then governor_unchecked "$1"; else empty_response "$1"; fi; exit 0; fi',
150
+ 'export NODII_DEV_MANAGED_HOOKS_DIR="$managed_dir"',
151
+ 'export NODII_DEV_MANAGED_CLI_PATH="$managed_cli"',
152
+ 'if [ -n "$managed_buffered" ]; then',
153
+ ` managed_output=$(printf '%s' "$managed_payload" | "$managed_cli" hook ${action} "$1" 2>/dev/null)`,
154
+ "else",
155
+ ` managed_output=$("$managed_cli" hook ${action} "$1" 2>/dev/null)`,
156
+ "fi",
157
+ "managed_status=$?",
158
+ 'if [ "$managed_status" -ne 0 ]; then if [ -n "$managed_governed" ]; then governor_unchecked "$1"; else empty_response "$1"; fi; exit 0; fi',
159
+ `if [ -n "$managed_output" ]; then printf '%s\\n' "$managed_output"; else empty_response "$1"; fi`,
160
+ "",
161
+ ].join("\n");
162
+ }
163
+
164
+ /**
165
+ * hub-232: the governor's verdict for a session outside a lane: on SessionStart
166
+ * the machine's governor text for a coordinator or steward, on PreToolUse a
167
+ * deny for a lane launch or long resume it refuses. Null when it has nothing.
168
+ */
169
+ async function governorVerdict(event, payloadText, deps) {
170
+ if (!["SessionStart", "PreToolUse"].includes(event)) return null;
171
+ const governor = deps.governor ?? (await import("./governor.js"));
172
+ if (event === "SessionStart") {
173
+ let text = "";
174
+ try { text = await governor.governorSessionStart(deps); } catch { return null; }
175
+ return text ? { context: text } : null;
176
+ }
177
+ let payload;
178
+ try { payload = JSON.parse(payloadText); } catch { return null; }
179
+ try { return (await governor.governorPreToolUse(payload, deps)) || null; }
180
+ catch (error) {
181
+ // Once a governed launch is matched, any failure denies it (fail closed).
182
+ if (!governor.governedLaunch?.(payload?.tool_input?.command)) return null;
183
+ return { deny: `nodii-dev governor: the governor check failed (${error?.message ?? String(error)}), so this launch is blocked.` };
184
+ }
120
185
  }
121
186
 
187
+ const governorDeny = (event, verdict) => `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, permissionDecision: "deny", permissionDecisionReason: verdict.deny } })}\n`;
188
+ const governorContext = (event, verdict) => (verdict?.context ? `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: verdict.context } })}\n` : "");
189
+
122
190
  /** Claude's managed settings: every event goes to the stable dispatcher; later hook changes live in hooks.json. */
123
191
  export function managedClaudeSettings(dir) {
124
192
  return `${JSON.stringify({ hooks: Object.fromEntries(CLAUDE_HOOK_EVENTS.map((event) => [event, [{ hooks: [{ type: "command", command: managedClaudeCommand(dir, event), timeout: 30 }] }]])) }, null, 2)}\n`;
@@ -256,11 +324,15 @@ function responseOf(stdout) {
256
324
 
257
325
  /** Execute the current generated hook set behind the stable managed dispatcher. */
258
326
  export async function dispatchManagedHook(event, payloadText, deps = {}) {
327
+ let governor = null;
259
328
  try {
260
329
  if (!CODEX_HOOK_EVENTS.includes(event)) return emptyResponse(event);
261
330
  const env = deps.env ?? process.env;
262
331
  const lane = laneConfig(env);
263
332
  if (!lane && !SESSION_SCOPED_EVENTS.includes(event)) return emptyResponse(event);
333
+ // hub-232: the governor answers first; its deny needs no hooks.json.
334
+ governor = lane ? null : await governorVerdict(event, payloadText, deps);
335
+ if (governor?.deny) return governorDeny(event, governor);
264
336
  const dir = deps.dir ?? env.NODII_DEV_MANAGED_HOOKS_DIR ?? managedHooksDir();
265
337
  const config = JSON.parse(await (deps.read ?? readFile)(join(dir, "hooks.json"), "utf8"));
266
338
  validateManagedHooks(config.hooks ?? {});
@@ -274,10 +346,10 @@ export async function dispatchManagedHook(event, payloadText, deps = {}) {
274
346
  if (["PreToolUse", "PermissionRequest"].includes(event)) {
275
347
  const denied = messages.find((message) => message.hookSpecificOutput?.permissionDecision === "deny");
276
348
  if (denied) return `${JSON.stringify(denied)}\n`;
277
- const contexts = messages.map((message) => message.hookSpecificOutput?.additionalContext).filter(Boolean);
349
+ const contexts = [governor?.context, ...messages.map((message) => message.hookSpecificOutput?.additionalContext)].filter(Boolean);
278
350
  return contexts.length ? `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: contexts.join("\n") } })}\n` : "";
279
351
  }
280
- const structured = messages.map((message) => message.hookSpecificOutput?.additionalContext).filter(Boolean);
352
+ const structured = [governor?.context, ...messages.map((message) => message.hookSpecificOutput?.additionalContext)].filter(Boolean);
281
353
  const plain = successful.map((result) => responseOf(result.stdout) ? "" : result.stdout.trim()).filter(Boolean);
282
354
  // A Stop nudge asks the session to continue once; any other Stop output is dropped.
283
355
  if (event === "Stop") {
@@ -287,7 +359,9 @@ export async function dispatchManagedHook(event, payloadText, deps = {}) {
287
359
  if (event === "SubagentStop") return "{}\n";
288
360
  return [...structured, ...plain].join("\n") + ([...structured, ...plain].length ? "\n" : "");
289
361
  } catch {
290
- return emptyResponse(event);
362
+ // The governor's own answer survives a broken hooks.json.
363
+ if (!governor?.context) return emptyResponse(event);
364
+ return event === "PreToolUse" ? governorContext(event, governor) : `${governor.context}\n`;
291
365
  }
292
366
  }
293
367
 
@@ -310,11 +384,15 @@ const claudeHandlers = (config, event, payload) => {
310
384
  * the shell entry point can keep failing open on every other status.
311
385
  */
312
386
  export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
387
+ let governor = null;
313
388
  try {
314
389
  if (!CLAUDE_HOOK_EVENTS.includes(event)) return "";
315
390
  const env = deps.env ?? process.env;
316
391
  const lane = laneConfig(env);
317
392
  if (!lane && !SESSION_SCOPED_EVENTS.includes(event)) return "";
393
+ // hub-232: the governor answers first; its deny needs no hooks.json.
394
+ governor = lane ? null : await governorVerdict(event, payloadText, deps);
395
+ if (governor?.deny) return governorDeny(event, governor);
318
396
  const read = deps.read ?? readFile;
319
397
  const dir = deps.dir ?? env.NODII_DEV_MANAGED_HOOKS_DIR ?? managedClaudeHooksDir();
320
398
  const config = JSON.parse(await read(join(dir, "hooks.json"), "utf8"));
@@ -328,7 +406,7 @@ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
328
406
  const blocked = results.find((result) => result.status === 2 && result.stderr.trim());
329
407
  const successful = results.filter((result) => result.status === 0);
330
408
  const messages = successful.map((result) => responseOf(result.stdout)).filter(Boolean);
331
- const contexts = messages.map((message) => message.hookSpecificOutput?.additionalContext).filter(Boolean);
409
+ const contexts = [governor?.context, ...messages.map((message) => message.hookSpecificOutput?.additionalContext)].filter(Boolean);
332
410
  const context = (extra = []) => [...contexts, ...extra].join("\n");
333
411
  if (event === "PreToolUse") {
334
412
  const denied = messages.find((message) => message.hookSpecificOutput?.permissionDecision === "deny");
@@ -353,7 +431,8 @@ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
353
431
  if (!["SessionStart", "UserPromptSubmit", "PostToolUse", "PostCompact", "SubagentStart"].includes(event)) return "";
354
432
  return contexts.length || plain.length ? `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context(plain) } })}\n` : "";
355
433
  } catch {
356
- return "";
434
+ // The governor's own answer survives a broken hooks.json.
435
+ return governorContext(event, governor);
357
436
  }
358
437
  }
359
438
 
package/dist/review.js CHANGED
@@ -446,35 +446,110 @@ export async function laneChangeSetNodes(request, agentId, fileKeys) {
446
446
  const held = rows.filter((row) => row.holder?.agent?.id === agentId && row.fileKey === fileKey && row.state !== "abandoned");
447
447
  const nodes = new Set();
448
448
  const changeSets = [];
449
+ const items = [];
449
450
  for (const row of held) {
450
451
  const set = (await request("GET", `/api/v1/design/change-sets/${encodeURIComponent(row.id)}`)).data;
451
452
  const live = (set?.items ?? []).filter((item) => item.decision !== "withdrawn" && item.change !== "removed" && item.figmaNodeId);
452
453
  if (!live.length) continue;
453
454
  changeSets.push(row.id);
454
- for (const item of live) nodes.add(item.figmaNodeId);
455
+ for (const item of live) {
456
+ if (!nodes.has(item.figmaNodeId)) items.push({ nodeId: item.figmaNodeId, changeSet: row.id });
457
+ nodes.add(item.figmaNodeId);
458
+ }
455
459
  }
456
- if (nodes.size) scoped[fileKey] = { changeSets, nodes: [...nodes] };
460
+ if (nodes.size) scoped[fileKey] = { changeSets, nodes: [...nodes], items };
457
461
  }
458
462
  return scoped;
459
463
  }
460
464
 
465
+ /**
466
+ * MW8-5: the Swaps in Dev, each as { ref, from, to, text }. A Swap is a Dev
467
+ * Swap record, or an issue titled "Swap" that carries one in its From and To
468
+ * sections (FRONTEND-107, written before Dev had the record type).
469
+ */
470
+ export async function removalSwaps(request) {
471
+ const records = ((await request("GET", "/api/v1/swaps")).data ?? []).map((swap) => ({
472
+ ref: swap.id, from: swap.fromPattern ?? "", to: swap.toPattern ?? "",
473
+ text: [swap.fromPattern, swap.toPattern, swap.whyDecisionLink, swap.guideLink, swap.examplePrLink].filter(Boolean).join("\n"),
474
+ }));
475
+ const titled = [];
476
+ let cursor;
477
+ do {
478
+ const page = await request("GET", `/api/v1/issues?kind=chore&limit=200${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
479
+ titled.push(...(page.data ?? []).filter((issue) => /^swap\b/i.test(issue.title ?? "")));
480
+ cursor = page.nextCursor;
481
+ } while (cursor);
482
+ const section = (body, heading) => body.match(new RegExp(`^#{2,4}\\s+${heading}\\b[^\\n]*\\n([\\s\\S]*?)(?=^#{2,4}\\s|(?![\\s\\S]))`, "mi"))?.[1]?.trim() ?? "";
483
+ const issues = await inBatches(titled, 8, async (issue) => {
484
+ const body = (await request("GET", `/api/v1/issues/${encodeURIComponent(issue.key)}`)).data?.bodyMd ?? "";
485
+ return { ref: issue.key, from: section(body, "From"), to: section(body, "To"), text: `${issue.title}\n${body}` };
486
+ });
487
+ return [...records, ...issues];
488
+ }
489
+
490
+ /**
491
+ * The Swap that removes a change-set node, read from MW2-38.3 with MW8-5 and
492
+ * MW8-20: MW8-5 makes a removal a Swap in Dev, and a removed node has no frame
493
+ * left to check. The Swap names from and to and a change set (`CS-2852`), and Dev's record of that
494
+ * change set, in the node's file, has the node as one of its items. Both are
495
+ * looked up in Dev, never declared by the PR, and no node id is matched across
496
+ * the hop (MW8-20). A Swap naming another set, or a set whose items don't
497
+ * include the node, excuses nothing. readSet(id) gives Dev's change-set record.
498
+ */
499
+ export async function swapFor(swaps, { fileKey, nodeId }, readSet) {
500
+ for (const swap of swaps) {
501
+ if (!swap.from || !swap.to) continue;
502
+ for (const id of new Set(swap.text.match(/\bCS-\d+\b/g) ?? [])) {
503
+ const set = await readSet(id);
504
+ if (!set || (set.fileKey && set.fileKey !== fileKey)) continue;
505
+ if ((set.items ?? []).some((item) => item.decision !== "withdrawn" && item.figmaNodeId === nodeId)) return { ...swap, changeSet: id };
506
+ }
507
+ }
508
+ return null;
509
+ }
510
+
461
511
  /**
462
512
  * DEV-REV-9, design-check part: designCheck on every boundary frame; per-state
463
513
  * frame comparison is Q-162. A boundary file with held change-set nodes
464
514
  * (MW2-38.3, from laneChangeSetNodes) is checked on those nodes only, never
465
- * as the whole file.
515
+ * as the whole file. A change-set node Figma no longer has, which a Swap in
516
+ * Dev removes (MW8-5), is not a frame: like an item recorded as removed
517
+ * (laneChangeSetNodes), there is nothing in Figma to check. It is left out of
518
+ * the frames and listed in inputs.removed with its Swap (NODII-DEV-CLI-67).
519
+ * Without a Swap in Dev whose change set holds the node (swapFor), or when
520
+ * Dev's Swaps or change sets can't be read, the missing node stays a finding.
466
521
  */
467
- export async function figmaFindings(figma, { catalog, check, changeSets = {} }) {
468
- const scopedFrames = Object.entries(changeSets).flatMap(([fileKey, scoped]) => scoped.nodes.map((nodeId) => ({ fileKey, nodeId, state: "default" })));
522
+ export async function figmaFindings(figma, { catalog, check, changeSets = {}, swaps, readSet }) {
523
+ const scopedFrames = Object.entries(changeSets).flatMap(([fileKey, scoped]) => scoped.nodes.map((nodeId) => {
524
+ const item = scoped.items?.find((x) => x.nodeId === nodeId);
525
+ return { fileKey, nodeId, state: "default", ...(item ? { changeSet: item.changeSet } : {}) };
526
+ }));
469
527
  const rest = figma.filter((file) => !changeSets[file.fileKey]);
470
528
  const frames = [...scopedFrames, ...boundaryFrames(rest, rest.some((file) => file.componentSetKeys?.length) ? await catalog() : [])];
471
529
  const findings = [];
530
+ const removed = [];
472
531
  const versions = new Set();
532
+ let known;
533
+ const sets = new Map();
534
+ const cachedSet = (id) => {
535
+ if (!sets.has(id)) sets.set(id, readSet(id).catch(() => null));
536
+ return sets.get(id);
537
+ };
538
+ const removedBySwap = async (frame, data) => {
539
+ if (!swaps || !readSet || !frame.changeSet || !(data.findings ?? []).some((x) => x.check === "FIGMA_NODE_MISSING" && x.nodeId === frame.nodeId)) return null;
540
+ known ??= await swaps().catch(() => []);
541
+ return swapFor(known, frame, cachedSet);
542
+ };
473
543
  for (const frame of frames) {
474
544
  const result = await check(frame.fileKey, frame.nodeId ? { nodes: frame.nodeId } : {});
475
545
  const data = result.payload.data;
476
546
  if (data.libraryVersion) versions.add(data.libraryVersion);
477
- for (const finding of data.findings ?? [])
547
+ const swap = await removedBySwap(frame, data);
548
+ if (swap) {
549
+ removed.push({ frame, nodeId: frame.nodeId, changeSet: swap.changeSet, swap: swap.ref, url: frameUrl(frame.fileKey, frame.nodeId) });
550
+ continue;
551
+ }
552
+ for (const finding of data.findings ?? []) {
478
553
  findings.push({
479
554
  perspective: "figma",
480
555
  severity: "major",
@@ -483,6 +558,7 @@ export async function figmaFindings(figma, { catalog, check, changeSets = {} })
483
558
  frameUrl: frameUrl(frame.fileKey, frame.nodeId ?? finding.nodeId),
484
559
  state: frame.state,
485
560
  });
561
+ }
486
562
  // A component key Figma can't resolve is a finding, never a frame without
487
563
  // its url (NODII-DEV-CLI-66). Minor: nothing was checked against a main.
488
564
  for (const warning of data.warnings ?? [])
@@ -499,9 +575,10 @@ export async function figmaFindings(figma, { catalog, check, changeSets = {} })
499
575
  findings,
500
576
  inputs: {
501
577
  // Dev's check contract names a frame by url and state.
502
- frames: frames.map((frame) => ({ fileKey: frame.fileKey, nodeId: frame.nodeId, state: frame.state, url: frame.nodeId ? frameUrl(frame.fileKey, frame.nodeId) : `https://www.figma.com/design/${frame.fileKey}` })),
578
+ frames: frames.filter((frame) => !removed.some((x) => x.frame === frame)).map((frame) => ({ fileKey: frame.fileKey, nodeId: frame.nodeId, state: frame.state, url: frame.nodeId ? frameUrl(frame.fileKey, frame.nodeId) : `https://www.figma.com/design/${frame.fileKey}` })),
503
579
  libraryVersions: [...versions],
504
580
  frameComparison: "not_built",
581
+ ...(removed.length ? { removed: removed.map(({ frame: _frame, ...entry }) => entry) } : {}),
505
582
  ...(scopedFrames.length ? { changeSets: Object.entries(changeSets).map(([fileKey, scoped]) => ({ fileKey, ids: scoped.changeSets, nodes: scoped.nodes.length })), rule: "MW2-38.3" } : {}),
506
583
  },
507
584
  };
@@ -611,7 +688,7 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
611
688
  throw new ReviewerError(UNAVAILABLE, `the lane's change sets could not be read from Dev (${error?.code ?? "ERROR"}: ${error?.message ?? error}), so the Figma check cannot be scoped to their nodes (MW2-38.3) and did not fall back to the whole file`);
612
689
  }
613
690
  let checked;
614
- try { checked = await figmaFindings(boundary, { catalog, check: designCheck, changeSets }); }
691
+ try { checked = await figmaFindings(boundary, { catalog, check: designCheck, changeSets, swaps: () => removalSwaps(request), readSet: async (id) => (await request("GET", `/api/v1/design/change-sets/${encodeURIComponent(id)}`)).data }); }
615
692
  catch (error) {
616
693
  if (error instanceof ReviewerError) throw error;
617
694
  // A Figma outage (a read past its clock, no answer, rate limited) means
package/dist/starting.js CHANGED
@@ -7,6 +7,7 @@ import { CliError, configPath, devRequest, encode, query, readConfig, requireFla
7
7
  import { assertKnownSets, checkComponentSetKey, checkFileKey, loadDsCatalog, mergeScopes, scopesFromRoutes } from "./figma-scope.js";
8
8
  import { GATHER_TIMEOUT_MS, gatherDeadline } from "./gather.js";
9
9
  import { laneCommand, nextCommand } from "./lanes.js";
10
+ import { assertGovernorOpen, readGovernor } from "./governor.js";
10
11
  import { laneConfigName } from "./lane-env.js";
11
12
  import { hostBootedAt } from "./host.js";
12
13
  import { accountFlags, listAccounts, profilePath, registerAccount, reportUsage, usageLine } from "./accounts.js";
@@ -559,6 +560,7 @@ async function refreshAccountUsage(machineId, runtime, profile, { request }) {
559
560
 
560
561
  export async function launchLaneCommand(key, flags, {
561
562
  request = devRequest,
563
+ readGovernorFor = readGovernor,
562
564
  capacity = refreshAccountUsage,
563
565
  config = readConfig,
564
566
  state = loadJson,
@@ -645,6 +647,12 @@ export async function launchLaneCommand(key, flags, {
645
647
  // not fatal here; Dev's preflight refuses a missing or stale reading and
646
648
  // names the command that fixes it.
647
649
  try { await capacity(coordinator.machineId, runtime, profile, { request }); } catch {}
650
+ // hub-232: the governor refuses here with its full listing, before
651
+ // any worktree is made. Dev's preflight refuses the same; an unread governor
652
+ // leaves the decision to Dev.
653
+ let governor = null;
654
+ try { governor = await readGovernorFor(coordinator.machineId, { request }); } catch {}
655
+ if (governor) assertGovernorOpen(governor);
648
656
  await request("POST", "/api/v1/lanes/launch", { phase: "preflight", ...body });
649
657
  await worktrees(repositories);
650
658
  const lastPushedCommit = await head(repositories);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.75",
3
+ "version": "0.6.76",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {