@nodii/dev 0.6.75 → 0.6.77
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 +32 -0
- package/dist/core.js +5 -2
- package/dist/flags.js +6 -0
- package/dist/governor.js +187 -0
- package/dist/lanes.js +68 -1
- package/dist/managed-hooks.js +95 -16
- package/dist/review.js +85 -8
- package/dist/safety.js +7 -2
- package/dist/starting.js +19 -1
- package/dist/watchdog.js +39 -1
- package/package.json +1 -1
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,
|
|
@@ -94,6 +95,7 @@ import {
|
|
|
94
95
|
builtCommand,
|
|
95
96
|
deltaGatherFlags,
|
|
96
97
|
laneCommand,
|
|
98
|
+
laneCapCommand,
|
|
97
99
|
machineCommand,
|
|
98
100
|
nextCommand,
|
|
99
101
|
peopleCommand,
|
|
@@ -311,6 +313,9 @@ Usage: nodii-dev <command> [options] [--json]
|
|
|
311
313
|
# one Dev refuses for good, with a note on its lane
|
|
312
314
|
lane done-check <key> --evidence TEXT|URL # the done check is met; a launched run that exits after it ends finished
|
|
313
315
|
lane subagent-quota <key> <n> # coordinator assigns 0-100 subagent slots
|
|
316
|
+
lane cap <machine> <n> [--confirm-raise --reason TEXT]
|
|
317
|
+
# coordinator declares the machine's lane cap, at least every 60 minutes;
|
|
318
|
+
# a raise needs a yes and a reason (MW1-38.10, MW1-38.13)
|
|
314
319
|
lane heartbeat|resume|land|verify|prioritize|deprioritize|stop <key>
|
|
315
320
|
lane heartbeat <key> --note "BLOCKED: ..."|"WAITING: ..."
|
|
316
321
|
# a note starting BLOCKED or WAITING: (capitals) marks the lane blocked:
|
|
@@ -353,6 +358,24 @@ Usage: nodii-dev <command> [options] [--json]
|
|
|
353
358
|
lane freeze drop <key> --section SECTION --item ID --reason TEXT
|
|
354
359
|
lane freeze swap <key> --section SECTION [--item ID] --file VALUE.json --reason TEXT
|
|
355
360
|
lane freeze show|history <key> # durable compact-safe contract and all versions
|
|
361
|
+
lane close <key> [--delivered-by <PR URL|lane key|issue key>] --reason TEXT
|
|
362
|
+
# hub-232. The machine's coordinator closes a lane that marked itself
|
|
363
|
+
# finished with a reason and evidence (MW1-28.2); LANE_NOT_FINISHED
|
|
364
|
+
# otherwise. --delivered-by adds proof on dev (a merged PR verified on
|
|
365
|
+
# dev, a lane at on_dev, or a done issue), checked and recorded;
|
|
366
|
+
# merged-only or on-main proof is refused. Staff may stop on that
|
|
367
|
+
# proof alone (MW1-28). No steward or other agent closes a lane. Its
|
|
368
|
+
# steps stay as they were (nothing is faked done). A finished lane that
|
|
369
|
+
# is orphan, host-lost or worktree-lost closes the same way; a live process is refused
|
|
370
|
+
# (LANE_PROCESS_LIVE); a terminal lane only gains the proof
|
|
371
|
+
governor [show] [--machine-id ID] # the machine's emergency governor: stuck lanes against the threshold, READY
|
|
372
|
+
# on unmerged PRs (MW1-38.14), runs that ended with an open PR and no READY
|
|
373
|
+
# (GOVERNOR_NO_READY) and the merge queue. While it refuses, lane launch and
|
|
374
|
+
# lane resume --class long exit 1 (GOVERNOR_STUCK, READY_BACKLOG)
|
|
375
|
+
governor override --quote TEXT --said-at ISO --reason TEXT [--minutes N] [--machine-id ID]
|
|
376
|
+
# the operator only, signed in: let exactly one launch through, recorded with
|
|
377
|
+
# their words and when they said them; lapses unused (default 60 min)
|
|
378
|
+
governor overrides [--machine-id ID] # the machine's overrides and the launch each let through
|
|
356
379
|
lane non-issue <key> --reason TEXT --evidence TEXT --reroute KEY[,KEY]|none
|
|
357
380
|
--branch carried:KEY|dropped[:REASON] [--commits SHA[,SHA]]
|
|
358
381
|
# DEC-0011: terminal non_issue; issue -> wont_do; slot frees
|
|
@@ -849,6 +872,15 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
849
872
|
if (command === "coordinator") return emitCommand(await coordinatorCommand(action, f, { installWatchdog }));
|
|
850
873
|
if (command === "steward") return emitCommand(await stewardCommand(action, rest, f));
|
|
851
874
|
if (command === "lane" && action === "launch") return emitCommand(await launchLaneCommand(rest[0], f));
|
|
875
|
+
if (command === "lane" && action === "cap") return emitCommand(await laneCapCommand(rest, f));
|
|
876
|
+
if (command === "lane" && action === "close") {
|
|
877
|
+
const result = await laneClose(rest[0], f);
|
|
878
|
+
return emit({ data: result.data }, json, result.text);
|
|
879
|
+
}
|
|
880
|
+
if (command === "governor") {
|
|
881
|
+
const result = await governorCommand(action, f);
|
|
882
|
+
return emit({ data: result.data }, json, result.text);
|
|
883
|
+
}
|
|
852
884
|
if (command === "lane" && action === "amend") return emitCommand(await amendLaneCommand(rest[0], f));
|
|
853
885
|
if (command === "lane" && action === "gather") {
|
|
854
886
|
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.
|
|
7
|
+
export const VERSION = "0.6.77";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
|
@@ -82,6 +82,9 @@ export async function deleteCredentials() {
|
|
|
82
82
|
await Promise.all([deleteLegacySecret(), rm(configPath(), { force: true })]);
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
+
/** MW1-38.13's words, shown by lane cap and by the safety hook. */
|
|
86
|
+
export const LANE_CAP_RAISE_PROMPT = "You cannot increase the cap to get around the lane on_dev requirement - are you sure? y/n";
|
|
87
|
+
|
|
85
88
|
export class CliError extends Error {
|
|
86
89
|
constructor(code, message, exitCode, details) {
|
|
87
90
|
super(message);
|
|
@@ -222,7 +225,7 @@ export async function checkLogin() {
|
|
|
222
225
|
export const encode = (value) => encodeURIComponent(value);
|
|
223
226
|
// Switches never take the next token as their value, so
|
|
224
227
|
// `docs upload --wait rulebook/` keeps rulebook/ as a path.
|
|
225
|
-
const SWITCHES = new Set(["json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical", "no-embed", "behind", "write", "fetch"]);
|
|
228
|
+
const SWITCHES = new Set(["confirm-raise", "json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical", "no-embed", "behind", "write", "fetch"]);
|
|
226
229
|
export function parseArgs(argv) {
|
|
227
230
|
const flags = {};
|
|
228
231
|
const args = [];
|
package/dist/flags.js
CHANGED
|
@@ -35,10 +35,16 @@ export const COMMAND_FLAGS = {
|
|
|
35
35
|
"receipt verify": ["commit"],
|
|
36
36
|
"sync pending": ["discard", "reason"],
|
|
37
37
|
"lane done-check": ["evidence"],
|
|
38
|
+
"lane cap": ["confirm-raise", "reason"],
|
|
38
39
|
"lane heartbeat": ["note"],
|
|
39
40
|
"lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class"],
|
|
40
41
|
"lane transfer": ["reason", "to-agent"],
|
|
41
42
|
"lane stop": ["reason"],
|
|
43
|
+
// hub-232: the honest close-out and the governor.
|
|
44
|
+
"lane close": ["delivered-by", "reason"],
|
|
45
|
+
"governor show": ["machine-id"],
|
|
46
|
+
"governor override": ["machine-id", "quote", "said-at", "reason", "minutes"],
|
|
47
|
+
"governor overrides": ["machine-id"],
|
|
42
48
|
"lane land": [],
|
|
43
49
|
"repo policy": ["root"],
|
|
44
50
|
"repo lint": ["root"],
|
package/dist/governor.js
ADDED
|
@@ -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
|
@@ -3,8 +3,9 @@ import { readFile, realpath, writeFile } from "node:fs/promises";
|
|
|
3
3
|
import { isAbsolute } from "node:path";
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
5
|
import { coordinatorMachineId, listAccounts, profilePath, reportUsage } from "./accounts.js";
|
|
6
|
-
import { CliError, encode, devRequest, query, readConfig, requireFlag } from "./core.js";
|
|
6
|
+
import { CliError, encode, devRequest, query, readConfig, requireFlag, LANE_CAP_RAISE_PROMPT } 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",
|
|
@@ -1083,6 +1094,62 @@ export async function builtCommand(action, args, flags, { request = devRequest,
|
|
|
1083
1094
|
throw new CliError("USAGE", `Unknown built action: ${action}`, 2);
|
|
1084
1095
|
}
|
|
1085
1096
|
|
|
1097
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1098
|
+
|
|
1099
|
+
async function askOnTerminal(question) {
|
|
1100
|
+
const { createInterface } = await import("node:readline/promises");
|
|
1101
|
+
const terminal = createInterface({ input: process.stdin, output: process.stdout });
|
|
1102
|
+
try { return (await terminal.question(`${question} `)).trim(); }
|
|
1103
|
+
finally { terminal.close(); }
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* `lane cap <machine> <n>` declares or re-declares a machine's lane cap
|
|
1108
|
+
* (MW1-38.10). Dev decides what a raise is, so a stale local view can't skip the
|
|
1109
|
+
* confirmation. A person answers y and gives a reason; an agent passes
|
|
1110
|
+
* --confirm-raise --reason TEXT, so a raise is never silent (MW1-38.13).
|
|
1111
|
+
*/
|
|
1112
|
+
export async function laneCapCommand(args, flags, {
|
|
1113
|
+
request = devRequest,
|
|
1114
|
+
ask = askOnTerminal,
|
|
1115
|
+
interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
1116
|
+
} = {}) {
|
|
1117
|
+
const machine = need(args[0], "lane cap needs <machine> <n>");
|
|
1118
|
+
const raw = need(args[1], "lane cap needs <machine> <n>");
|
|
1119
|
+
const cap = Number(raw);
|
|
1120
|
+
if (!Number.isInteger(cap) || cap < 0 || cap > 500)
|
|
1121
|
+
throw new CliError("USAGE", "The lane cap must be a whole number from 0 to 500.", 2);
|
|
1122
|
+
if (flags["confirm-raise"] && !flags.reason)
|
|
1123
|
+
throw new CliError("USAGE", "--confirm-raise needs --reason TEXT.", 2);
|
|
1124
|
+
let id = machine;
|
|
1125
|
+
if (!UUID.test(machine)) {
|
|
1126
|
+
const found = (await request("GET", "/api/v1/machines")).data.find((x) => x.name === machine);
|
|
1127
|
+
if (!found) throw new CliError("MACHINE_NOT_FOUND", `No machine is named ${machine}.`, 1);
|
|
1128
|
+
id = found.id;
|
|
1129
|
+
}
|
|
1130
|
+
const declare = (body) => request("PUT", `/api/v1/machines/${encode(id)}/lane-cap`, body);
|
|
1131
|
+
const human = (p) => {
|
|
1132
|
+
const { raised, previousCap, laneCap } = p.data;
|
|
1133
|
+
const change = raised ? `raised from ${previousCap} to ${laneCap.cap}` : `declared at ${laneCap.cap}`;
|
|
1134
|
+
return `${machine}: lane cap ${change}, ${laneCap.count} lanes counted. It lapses at ${laneCap.lapsesAt}; re-declare before then.`;
|
|
1135
|
+
};
|
|
1136
|
+
const body = { cap, ...(flags["confirm-raise"] ? { confirmRaise: true, reason: flags.reason } : {}) };
|
|
1137
|
+
try {
|
|
1138
|
+
return { payload: await declare(body), human };
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
if (error?.code !== "LANE_CAP_RAISE_NOT_CONFIRMED") throw error;
|
|
1141
|
+
if (!interactive)
|
|
1142
|
+
throw new CliError(error.code, `${LANE_CAP_RAISE_PROMPT} To go ahead, run it again with --confirm-raise --reason TEXT.`, 1, error.details);
|
|
1143
|
+
const { previousCap, requestedCap } = error.details ?? {};
|
|
1144
|
+
console.error(`Raising the lane cap on ${machine} from ${previousCap} to ${requestedCap}.`);
|
|
1145
|
+
if ((await ask(LANE_CAP_RAISE_PROMPT)).toLowerCase() !== "y")
|
|
1146
|
+
throw new CliError("LANE_CAP_RAISE_DECLINED", "The cap was not raised.", 1);
|
|
1147
|
+
const reason = flags.reason ?? (await ask("Reason for the raise:"));
|
|
1148
|
+
if (!reason) throw new CliError("USAGE", "A raise needs a reason.", 2);
|
|
1149
|
+
return { payload: await declare({ cap, confirmRaise: true, reason }), human };
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1086
1153
|
export async function machineCommand(action, args, flags, { request = devRequest } = {}) {
|
|
1087
1154
|
if (action === "list") return { payload: await request("GET", "/api/v1/machines"), human: (p) => p.data.map((x) => `${x.id}\t${x.name}\tcoordinator=${x.coordinatorAgentId}`).join("\n") || "No machines." };
|
|
1088
1155
|
const id = need(args[0], `machine ${action} needs <machine>`);
|
package/dist/managed-hooks.js
CHANGED
|
@@ -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
|
|
107
|
-
// UserPromptSubmit, and a PreToolUse that
|
|
108
|
-
//
|
|
109
|
-
//
|
|
110
|
-
//
|
|
111
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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)
|
|
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) =>
|
|
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
|
-
|
|
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/safety.js
CHANGED
|
@@ -3,7 +3,8 @@ import { appendFile, mkdir, readFile, realpath, writeFile } from "node:fs/promis
|
|
|
3
3
|
import { homedir, tmpdir } from "node:os";
|
|
4
4
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
|
-
import { CliError, configPath, devRequest, encode, readConfig } from "./core.js";
|
|
6
|
+
import { CliError, LANE_CAP_RAISE_PROMPT, configPath, devRequest, encode, readConfig } from "./core.js";
|
|
7
|
+
import { laneCapReminder } from "./watchdog.js";
|
|
7
8
|
|
|
8
9
|
const execFileAsync = promisify(execFile);
|
|
9
10
|
const ACTIVE = new Set(["queued", "building", "built", "review", "on_main"]);
|
|
@@ -258,6 +259,9 @@ export function commandNudges(command, context) {
|
|
|
258
259
|
if (!provenLane(context)) nudges.push("nodii-dev safety: can't verify review: this is not a proven current-lane context.");
|
|
259
260
|
else if (!context.reviewFlowKnown) nudges.push(`nodii-dev safety: can't verify review for ${context.lane?.key ?? context.branch}: Dev's lane review receipt flow is unavailable.`);
|
|
260
261
|
}
|
|
262
|
+
// MW1-38.13: a raise reaches the agent's context, not only the terminal.
|
|
263
|
+
if (/\bnodii-dev\b.*\blane\s+cap\b.*--confirm-raise\b/s.test(command))
|
|
264
|
+
nudges.push(`nodii-dev: ${LANE_CAP_RAISE_PROMPT} This command confirms a raise; run it only if the machine's resources changed (MW1-38.11).`);
|
|
261
265
|
if (!provenLane(context)) nudges.push(...commandViolations(command, context).map(nudgeViolation));
|
|
262
266
|
return nudges;
|
|
263
267
|
}
|
|
@@ -515,7 +519,8 @@ export async function safetyPreHook(payload, contextOrResolver = safetyContext)
|
|
|
515
519
|
if (violation && provenLane(context)) blocked(violation);
|
|
516
520
|
if (usesNoVerify(command) && context.role === "coordinator" && context.noVerifyReason)
|
|
517
521
|
await recordNoVerifyReason(cwd, context.noVerifyReason);
|
|
518
|
-
|
|
522
|
+
const reminder = context.role === "coordinator" ? await laneCapReminder() : null;
|
|
523
|
+
return { allowed: true, nudges: [...commandNudges(command, context), ...(reminder ? [reminder] : [])] };
|
|
519
524
|
}
|
|
520
525
|
const paths = editPaths(payload);
|
|
521
526
|
if (!paths.length) {
|
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";
|
|
@@ -557,8 +558,17 @@ async function refreshAccountUsage(machineId, runtime, profile, { request }) {
|
|
|
557
558
|
return reportUsage(accounts, { request, probe: true });
|
|
558
559
|
}
|
|
559
560
|
|
|
561
|
+
/** MW1-38.12: name the lanes Dev counted, so the coordinator can see which one to close. */
|
|
562
|
+
function laneCapRefusal(error) {
|
|
563
|
+
if (!["LANE_CAP_REACHED", "LANE_CAP_LAPSED"].includes(error?.code)) return error;
|
|
564
|
+
const lanes = error.details?.lanes ?? [];
|
|
565
|
+
const listed = lanes.map((lane) => `\n ${lane.key}\t${lane.status}\tlast heartbeat ${lane.lastHeartbeatAt}`).join("");
|
|
566
|
+
return new CliError(error.code, `${error.message}\nLanes counted (${lanes.length}):${listed || " none"}`, error.exitCode ?? 1);
|
|
567
|
+
}
|
|
568
|
+
|
|
560
569
|
export async function launchLaneCommand(key, flags, {
|
|
561
570
|
request = devRequest,
|
|
571
|
+
readGovernorFor = readGovernor,
|
|
562
572
|
capacity = refreshAccountUsage,
|
|
563
573
|
config = readConfig,
|
|
564
574
|
state = loadJson,
|
|
@@ -645,13 +655,21 @@ export async function launchLaneCommand(key, flags, {
|
|
|
645
655
|
// not fatal here; Dev's preflight refuses a missing or stale reading and
|
|
646
656
|
// names the command that fixes it.
|
|
647
657
|
try { await capacity(coordinator.machineId, runtime, profile, { request }); } catch {}
|
|
648
|
-
|
|
658
|
+
// hub-232: the governor refuses here with its full listing, before
|
|
659
|
+
// any worktree is made. Dev's preflight refuses the same; an unread governor
|
|
660
|
+
// leaves the decision to Dev.
|
|
661
|
+
let governor = null;
|
|
662
|
+
try { governor = await readGovernorFor(coordinator.machineId, { request }); } catch {}
|
|
663
|
+
if (governor) assertGovernorOpen(governor);
|
|
664
|
+
try { await request("POST", "/api/v1/lanes/launch", { phase: "preflight", ...body }); }
|
|
665
|
+
catch (error) { throw laneCapRefusal(error); }
|
|
649
666
|
await worktrees(repositories);
|
|
650
667
|
const lastPushedCommit = await head(repositories);
|
|
651
668
|
let payload;
|
|
652
669
|
try {
|
|
653
670
|
payload = await request("POST", "/api/v1/lanes/launch", { phase: "register", ...body, lastPushedCommit });
|
|
654
671
|
} catch (error) {
|
|
672
|
+
error = laneCapRefusal(error);
|
|
655
673
|
throw new CliError(error?.code ?? "LANE_REGISTER_FAILED", `${error?.message ?? error}. Worktrees were created and were not removed; reconcile them before retrying.`, 1);
|
|
656
674
|
}
|
|
657
675
|
// An agent is dispatched only onto a lane whose start Dev recorded: building,
|
package/dist/watchdog.js
CHANGED
|
@@ -205,6 +205,36 @@ export async function refreshMachineUsage(machineId, {
|
|
|
205
205
|
return results;
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
+
const LANE_CAP_REMIND_MS = 10 * 60_000;
|
|
209
|
+
const laneCapReminderPath = (home = homedir()) => join(watchdogHome(home), "lane-cap-reminder.txt");
|
|
210
|
+
|
|
211
|
+
/** MW1-38.10: what the coordinator must hear, or null while the cap has time left. */
|
|
212
|
+
export function laneCapReminderText(state, now = new Date()) {
|
|
213
|
+
if (!state) return null;
|
|
214
|
+
if (state.cap === null || !state.lapsesAt)
|
|
215
|
+
return "nodii-dev watchdog: this machine has no declared lane cap, so Dev refuses new launches. Declare it with nodii-dev lane cap (MW1-38.10).";
|
|
216
|
+
const left = new Date(state.lapsesAt).getTime() - now.getTime();
|
|
217
|
+
if (left <= 0)
|
|
218
|
+
return `nodii-dev watchdog: this machine's lane cap lapsed at ${state.lapsesAt}, so Dev refuses new launches. Re-declare it with nodii-dev lane cap (MW1-38.10).`;
|
|
219
|
+
if (left <= LANE_CAP_REMIND_MS)
|
|
220
|
+
return `nodii-dev watchdog: this machine's lane cap lapses at ${state.lapsesAt}. Re-declare it with nodii-dev lane cap (MW1-38.10).`;
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Held in a file because the sweep runs under launchd, outside the coordinator's session. */
|
|
225
|
+
export async function saveLaneCapReminder(text, { home = homedir() } = {}) {
|
|
226
|
+
const path = laneCapReminderPath(home);
|
|
227
|
+
if (!text) return rm(path, { force: true });
|
|
228
|
+
await mkdir(dirname(path), { recursive: true });
|
|
229
|
+
await writeFile(path, text);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** The safety hook shows this on the coordinator's next shell command. It fails open. */
|
|
233
|
+
export async function laneCapReminder({ home = homedir() } = {}) {
|
|
234
|
+
try { return (await readFile(laneCapReminderPath(home), "utf8")).trim() || null; }
|
|
235
|
+
catch { return null; }
|
|
236
|
+
}
|
|
237
|
+
|
|
208
238
|
/** One launchd sweep. The machine coordinator reports every observation through Dev's run watchdog contract. */
|
|
209
239
|
export async function sweepWatchdog({
|
|
210
240
|
records,
|
|
@@ -215,6 +245,7 @@ export async function sweepWatchdog({
|
|
|
215
245
|
machineId,
|
|
216
246
|
now = () => new Date(),
|
|
217
247
|
refreshUsage = refreshMachineUsage,
|
|
248
|
+
saveReminder = saveLaneCapReminder,
|
|
218
249
|
} = {}) {
|
|
219
250
|
const loaded = records ? { records, errors: [] } : await loadRecords();
|
|
220
251
|
const facts = await collect(loaded.records, { errors: [...loaded.errors] });
|
|
@@ -315,7 +346,14 @@ export async function sweepWatchdog({
|
|
|
315
346
|
} catch (error) {
|
|
316
347
|
facts.errors.push({ kind: "usage", code: error?.code ?? "ACCOUNT_USAGE_REPORT_FAILED" });
|
|
317
348
|
}
|
|
318
|
-
|
|
349
|
+
let laneCap = null;
|
|
350
|
+
try {
|
|
351
|
+
laneCap = (await request("GET", `/api/v1/machines/${encode(effectiveMachineId)}`)).data?.laneCapState ?? null;
|
|
352
|
+
await saveReminder(laneCapReminderText(laneCap, now()));
|
|
353
|
+
} catch (error) {
|
|
354
|
+
facts.errors.push({ kind: "lane_cap", code: error?.code ?? "LANE_CAP_READ_FAILED" });
|
|
355
|
+
}
|
|
356
|
+
const report = { ...facts, orphanedRuns, unwatchedRuns, accounts, laneCap };
|
|
319
357
|
return report;
|
|
320
358
|
}
|
|
321
359
|
|