@nodii/dev 0.6.76 → 0.6.78

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/flags.js CHANGED
@@ -35,12 +35,15 @@ export const COMMAND_FLAGS = {
35
35
  "receipt verify": ["commit"],
36
36
  "sync pending": ["discard", "reason"],
37
37
  "lane done-check": ["evidence"],
38
- "lane heartbeat": ["note"],
38
+ "lane cap": ["confirm-raise", "reason"],
39
+ "lane heartbeat": ["note", "waiting-on"],
40
+ "lane waits": ["machine"],
39
41
  "lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class"],
40
42
  "lane transfer": ["reason", "to-agent"],
41
- "lane stop": ["reason"],
43
+ "lane stop": ["reason", "sweeper", "no-closeout"],
44
+ "lane closeout": ["reason"],
42
45
  // hub-232: the honest close-out and the governor.
43
- "lane close": ["delivered-by", "reason"],
46
+ "lane close": ["delivered-by", "reason", "sweeper", "no-closeout"],
44
47
  "governor show": ["machine-id"],
45
48
  "governor override": ["machine-id", "quote", "said-at", "reason", "minutes"],
46
49
  "governor overrides": ["machine-id"],
package/dist/governor.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // before it reaches Dev, gives the honest close-out and records the operator's
5
5
  // override. The managed hooks call the two hook entry points at the bottom.
6
6
  import { CliError, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
7
+ import { holdsLine, laneCloseout } from "./lanes.js";
7
8
 
8
9
  export const GOVERNOR_REFUSALS = ["GOVERNOR_STUCK", "READY_BACKLOG"];
9
10
 
@@ -167,21 +168,29 @@ export async function governorCommand(action, flags, { request = devRequest, con
167
168
  * REF adds proof the work is on dev, checked and recorded. Staff may stop on
168
169
  * that proof alone (MW1-28).
169
170
  */
170
- export async function laneClose(key, flags, { request = devRequest } = {}) {
171
+ export async function laneClose(key, flags, { request = devRequest, closeout = laneCloseout } = {}) {
171
172
  if (!key) throw new CliError("USAGE", "lane close needs <key>.", 2);
172
173
  const reason = requireFlag(flags, "reason");
173
174
  if (flags["delivered-by"] !== undefined && !String(flags["delivered-by"]).trim())
174
175
  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
176
  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 body = {
178
+ ...(deliveredBy === undefined ? {} : { deliveredBy }),
179
+ reason,
180
+ ...(flags.sweeper ? { sweeper: String(flags.sweeper) } : {}),
181
+ via: "nodii-dev",
182
+ };
177
183
  const result = (await request("POST", `/api/v1/lanes/${encode(key)}/close`, body)).data;
184
+ // hub-244: Dev released the holds; the machine half runs here.
185
+ const local = flags["no-closeout"] ? null : await closeout(key, reason, { request });
178
186
  const kind = result.deliveredBy?.kind ?? "unknown";
179
187
  const proof = kind === "finished" ? "its own finished record (MW1-28.2)" : `${kind} ${result.deliveredBy?.ref ?? ""}`.trim();
180
188
  const unmerged = result.unmergedOwnPrs?.length ? ` Its own unmerged PRs (close or merge them): ${result.unmergedOwnPrs.join(", ")}.` : "";
189
+ const head = result.closed
190
+ ? `${key} closed out, delivered by ${proof}. Its steps are left as they were.${unmerged}`
191
+ : `${key} was already ${result.lane.status}; recorded that ${proof} delivered it.${unmerged}`;
181
192
  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}`,
193
+ data: { ...result, ...(local ? { closeout: local.repositories } : {}) },
194
+ text: [head, holdsLine(result.holdsReleased), local?.text].filter(Boolean).join("\n"),
186
195
  };
187
196
  }
package/dist/lanes.js CHANGED
@@ -3,7 +3,7 @@ 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
8
  import { assertGovernorOpen, readGovernor } from "./governor.js";
9
9
  import { recordReviewReceipt, reviewCommitContext } from "./safety.js";
@@ -16,6 +16,7 @@ import { assertNothingPending, devDown, queuePending, receiptEvidenceBody, signe
16
16
  import { SWAP_BOUNDARIES, componentsForScope, guidelineLookup, laneFigmaScope, loadDsCatalog } from "./figma-scope.js";
17
17
  import { designCheck } from "./design.js";
18
18
  import { LANE_ENV_FIX, laneEnvProblem, laneEnvReport } from "./lane-env.js";
19
+ import { closeoutLane } from "./closeout.js";
19
20
  import { GATES_RECEIPT, REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, repoGeneratedPaths, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
20
21
 
21
22
  const execFileAsync = promisify(execFile);
@@ -60,7 +61,49 @@ export async function inferGitContext() {
60
61
 
61
62
  // `building` is the lane's phase, not a process: say when nothing healthy is running (MW1-36).
62
63
  const laneLiveness = (x) => x.liveness && x.liveness !== "active" ? `\t${x.liveness.toUpperCase()}` : "";
63
- const laneLine = (x) => `${x.key}\t${x.status}\t${x.kind}/${x.side}\t${x.title}${x.stuck ? "\tSTUCK" : ""}${laneLiveness(x)}`;
64
+ // hub-246: a lane others wait on shows its effective priority and count.
65
+ const lanePriority = (x) => (x.waitCount ? `\tpriority ${x.effectivePriority} (${x.waitCount} waiting)` : "");
66
+ const laneWaitsText = (x) => (x.waits?.length ? `\twaits on ${x.waits.map(waitText).join(", ")}` : "");
67
+ const waitText = (w) => `${w.blockerLaneKey && w.blockerLaneKey !== w.targetRef ? `${w.blockerLaneKey} (${w.targetRef})` : w.targetRef}${w.chain ? ` [chain: ${w.chain.why} ${w.chain.headLaneKey}]` : ""}`;
68
+ const laneLine = (x) => `${x.key}\t${x.status}\t${x.kind}/${x.side}\t${x.title}${x.stuck ? "\tSTUCK" : ""}${laneLiveness(x)}${lanePriority(x)}${laneWaitsText(x)}`;
69
+
70
+ /** What a heartbeat changed in the lane's waits. */
71
+ export function heartbeatText(ref, payload, sentWaits = false) {
72
+ const waits = payload?.waits;
73
+ // A Dev without hub-246 answers with no `waits` key at all and ignores the flag.
74
+ if (sentWaits && waits === undefined)
75
+ return `${ref}: heartbeat recorded, but this Dev does not record --waiting-on yet (needs the hub-246 deploy); the wait was not stored.`;
76
+ if (!waits) return `${ref}: heartbeat recorded.`;
77
+ const lines = [`${ref}: heartbeat recorded.`];
78
+ for (const change of waits.changes ?? [])
79
+ lines.push(change.change === "new" ? ` now waits on ${change.targetRef}` : ` no longer waits on ${change.targetRef} (${change.clearReason})`);
80
+ for (const drop of waits.dropped ?? []) lines.push(` not a wait: ${drop.ref}: ${drop.why}`);
81
+ if (waits.notices) lines.push(` coordinator notified (${waits.notices} notice${waits.notices === 1 ? "" : "s"})`);
82
+ const current = payload.data?.waits ?? [];
83
+ if (current.length) lines.push(` waiting on: ${current.map(waitText).join(", ")}`);
84
+ return lines.join("\n");
85
+ }
86
+
87
+ /** The wait board (GET /lanes/waits) as text: blockers first, then what holds lanes outside the graph. */
88
+ export function waitBoardText(board) {
89
+ const lines = [];
90
+ const blockers = board?.blockers ?? [];
91
+ if (blockers.length) {
92
+ lines.push("Lanes others wait on (highest effective priority first):");
93
+ for (const b of blockers)
94
+ lines.push(` ${b.key}\tpriority ${b.effectivePriority} (own ${b.ownPriority} + ${b.waitCount} waiting)\t${b.status}${b.stuck ? " STUCK" : ""}${b.liveness === "orphan" ? " ORPHANED" : ""}\twaited on by ${(b.directWaiters ?? []).join(", ")}${b.chain ? `\tCHAIN: fix ${b.chain.headLaneKey} (${b.chain.why}) first` : ""}`);
95
+ } else lines.push("No lane waits on another lane.");
96
+ const targets = (title, rows) => {
97
+ if (!rows?.length) return;
98
+ lines.push(title);
99
+ for (const row of rows) lines.push(` ${row.targetRef}\tholds ${row.lanes} lane${row.lanes === 1 ? "" : "s"}: ${(row.laneKeys ?? []).join(", ")}`);
100
+ };
101
+ targets("Operator questions:", board?.operatorQuestions);
102
+ targets("Launch day:", board?.launchDay?.lanes ? [board.launchDay] : []);
103
+ targets("Decisions:", board?.decisions);
104
+ targets("PRs and releases with no lane found:", board?.untraced);
105
+ return lines.join("\n");
106
+ }
64
107
  // GATHER-NA: a step the coordinator ruled not applicable is never shown as done.
65
108
  const stepState = (s) => s.state === "not_applicable" ? `not applicable: ${s.notApplicableReason ?? "(no reason recorded)"}` : s.state;
66
109
  const detailText = (x) => [laneLine(x), ...(x.steps ?? []).map((s) => ` ${s.side}\t${stepState(s)}\t${s.stepKey}\t${s.label}`)].join("\n");
@@ -407,9 +450,17 @@ export async function laneCommand(action, args, flags, deps = {}) {
407
450
  }
408
451
  if (action === "list") {
409
452
  const c = flags.mine ? await config() : null;
410
- const payload = await request("GET", `/api/v1/lanes${query({ kind: flags.kind, status: flags.status, machine: flags.machine, agent: flags.mine ? c.agentId : flags.agent, "waiting-on": flags["waiting-on"], stuck: flags.stuck, cursor: flags.cursor, limit: flags.limit })}`);
453
+ if (flags.sort !== undefined && !["created", "priority"].includes(flags.sort))
454
+ throw new CliError("USAGE", "lane list --sort takes created or priority", 2);
455
+ const payload = await request("GET", `/api/v1/lanes${query({ kind: flags.kind, status: flags.status, machine: flags.machine, agent: flags.mine ? c.agentId : flags.agent, "waiting-on": flags["waiting-on"], stuck: flags.stuck, sort: flags.sort, cursor: flags.cursor, limit: flags.limit })}`);
411
456
  return { payload, human: (p) => p.data.map(laneLine).join("\n") || "No lanes." };
412
457
  }
458
+ // hub-246: the wait graph, for the coordinator and the operator.
459
+ if (action === "waits") {
460
+ if (args[0]) throw new CliError("USAGE", "lane waits takes no <key>; pass --machine ID to narrow it to one machine.", 2);
461
+ const payload = await request("GET", `/api/v1/lanes/waits${query({ machine: flags.machine })}`);
462
+ return { payload, human: (p) => waitBoardText(p.data) };
463
+ }
413
464
  if (action === "start") {
414
465
  // `--key` names the lane; the positional is then the issue (NODII-DEV-CLI-13).
415
466
  if (flags.key !== undefined && (typeof flags.key !== "string" || !flags.key.trim()))
@@ -858,7 +909,12 @@ export async function laneCommand(action, args, flags, deps = {}) {
858
909
  return { payload, human: `${ref}: done check recorded. The lane's run ends finished when its process exits.` };
859
910
  }
860
911
  if (action === "heartbeat") {
861
- return { payload: await request("POST", `/api/v1/lanes/${encode(id)}/heartbeat`, { ...(flags.note !== undefined ? { note: flags.note } : {}), ...via }), human: `${ref}: heartbeat recorded.` };
912
+ // hub-246: --waiting-on is repeatable; it replaces the lane's waits.
913
+ const waitingOn = flags["waiting-on"] === undefined ? [] : [flags["waiting-on"]].flat();
914
+ if (waitingOn.some((value) => typeof value !== "string" || !value.trim()))
915
+ throw new CliError("USAGE", "lane heartbeat --waiting-on needs a lane key, owner/repo#n, Q-nnn, DEC-nnnn, release:<pkg> or launch-day", 2);
916
+ const payload = await request("POST", `/api/v1/lanes/${encode(id)}/heartbeat`, { ...(flags.note !== undefined ? { note: flags.note } : {}), ...(waitingOn.length ? { waitingOn } : {}), ...via });
917
+ return { payload, human: (p) => heartbeatText(ref, p, waitingOn.length > 0) };
862
918
  }
863
919
  if (action === "subagent-quota") {
864
920
  const raw = need(args[1], "lane subagent-quota needs <key> <n>");
@@ -1006,7 +1062,23 @@ export async function laneCommand(action, args, flags, deps = {}) {
1006
1062
  const payload = await request("POST", `/api/v1/lanes/${encode(id)}/${action}`, { reason: requireFlag(flags, "reason"), ...via });
1007
1063
  return { payload, human: `${ref}: ${action}d.` };
1008
1064
  }
1009
- if (action === "stop") return { payload: await request("POST", `/api/v1/lanes/${encode(id)}/stop`, { reason: requireFlag(flags, "reason"), ...via }), human: `${ref}: stopped.` };
1065
+ if (action === "stop") {
1066
+ const reason = requireFlag(flags, "reason");
1067
+ // Dev first: a stop it refuses changes nothing on this machine (hub-244).
1068
+ const payload = await request("POST", `/api/v1/lanes/${encode(id)}/stop`, { reason, ...(flags.sweeper ? { sweeper: String(flags.sweeper) } : {}), ...via });
1069
+ const closeout = flags["no-closeout"] ? null : await laneCloseout(ref, reason, { request, config, closeout: deps.closeout });
1070
+ return {
1071
+ payload: { ...payload, ...(closeout ? { closeout: closeout.repositories } : {}) },
1072
+ human: [`${ref}: stopped.`, holdsLine(payload?.holdsReleased), closeout?.text].filter(Boolean).join("\n"),
1073
+ };
1074
+ }
1075
+ if (action === "closeout") {
1076
+ const lane = (await request("GET", `/api/v1/lanes/${encode(id)}`)).data;
1077
+ if (!["stopped", "non_issue", "on_dev"].includes(lane.status))
1078
+ throw new CliError("LANE_NOT_ENDED", `${ref} is ${lane.status}; lane closeout runs for an ended lane. Stop it with nodii-dev lane stop ${ref} --reason TEXT.`, 1);
1079
+ const closeout = await laneCloseout(ref, requireFlag(flags, "reason"), { request, config, closeout: deps.closeout, lane });
1080
+ return { payload: { data: closeout.repositories }, human: closeout.text };
1081
+ }
1010
1082
  if (action === "non-issue") {
1011
1083
  const body = await nonIssueBody(flags, async () => commitsOf((await request("GET", `/api/v1/lanes/${encode(id)}`)).data));
1012
1084
  const payload = await request("POST", `/api/v1/lanes/${encode(id)}/non-issue`, body);
@@ -1018,6 +1090,31 @@ export async function laneCommand(action, args, flags, deps = {}) {
1018
1090
  throw new CliError("USAGE", `Unknown lane action: ${action}`, 2);
1019
1091
  }
1020
1092
 
1093
+ /** What Dev released in a lane's end, in one line (hub-244). */
1094
+ export function holdsLine(released) {
1095
+ if (!released) return null;
1096
+ const { abandoned = [], moved = [], kept = [] } = released.changeSets ?? {};
1097
+ const parts = [];
1098
+ if (released.issueClaims?.length) parts.push(`issue claims released: ${released.issueClaims.join(", ")}`);
1099
+ if (abandoned.length) parts.push(`change sets abandoned: ${abandoned.map((x) => x.id).join(", ")}`);
1100
+ if (moved.length) parts.push(`moved: ${moved.map((x) => `${x.id} to ${x.toLane}`).join(", ")}`);
1101
+ if (kept.length) parts.push(`kept with operator decisions (listed on the issue and to the coordinator): ${kept.map((x) => `${x.id} (${x.state})`).join(", ")}`);
1102
+ if (released.agentShared) parts.push("the agent runs another lane, so its change sets stayed");
1103
+ if (released.sweeperRefused) parts.push(`sweeper refused: ${released.sweeperRefused}`);
1104
+ return `Dev released: ${parts.length ? parts.join("; ") : "nothing held"}.`;
1105
+ }
1106
+
1107
+ /**
1108
+ * The machine half of a lane's end (closeout.js): push, Stopped PR, test
1109
+ * stacks, worktree. Runs only after Dev accepted the end.
1110
+ */
1111
+ export async function laneCloseout(ref, reason, { request = devRequest, config = readConfig, closeout = closeoutLane, lane } = {}) {
1112
+ const record = lane ?? (await request("GET", `/api/v1/lanes/${encode(ref)}`)).data;
1113
+ let onBehalfOf;
1114
+ try { onBehalfOf = (await config())?.person; } catch { onBehalfOf = undefined; }
1115
+ return closeout(record, { reason, request, onBehalfOf });
1116
+ }
1117
+
1021
1118
  /**
1022
1119
  * The files a lane touches, for path-tagged rules (M05-32): its branch and
1023
1120
  * working-tree changes against origin/main, plus untracked files, read from
@@ -1094,6 +1191,62 @@ export async function builtCommand(action, args, flags, { request = devRequest,
1094
1191
  throw new CliError("USAGE", `Unknown built action: ${action}`, 2);
1095
1192
  }
1096
1193
 
1194
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1195
+
1196
+ async function askOnTerminal(question) {
1197
+ const { createInterface } = await import("node:readline/promises");
1198
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
1199
+ try { return (await terminal.question(`${question} `)).trim(); }
1200
+ finally { terminal.close(); }
1201
+ }
1202
+
1203
+ /**
1204
+ * `lane cap <machine> <n>` declares or re-declares a machine's lane cap
1205
+ * (MW1-38.10). Dev decides what a raise is, so a stale local view can't skip the
1206
+ * confirmation. A person answers y and gives a reason; an agent passes
1207
+ * --confirm-raise --reason TEXT, so a raise is never silent (MW1-38.13).
1208
+ */
1209
+ export async function laneCapCommand(args, flags, {
1210
+ request = devRequest,
1211
+ ask = askOnTerminal,
1212
+ interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY),
1213
+ } = {}) {
1214
+ const machine = need(args[0], "lane cap needs <machine> <n>");
1215
+ const raw = need(args[1], "lane cap needs <machine> <n>");
1216
+ const cap = Number(raw);
1217
+ if (!Number.isInteger(cap) || cap < 0 || cap > 500)
1218
+ throw new CliError("USAGE", "The lane cap must be a whole number from 0 to 500.", 2);
1219
+ if (flags["confirm-raise"] && !flags.reason)
1220
+ throw new CliError("USAGE", "--confirm-raise needs --reason TEXT.", 2);
1221
+ let id = machine;
1222
+ if (!UUID.test(machine)) {
1223
+ const found = (await request("GET", "/api/v1/machines")).data.find((x) => x.name === machine);
1224
+ if (!found) throw new CliError("MACHINE_NOT_FOUND", `No machine is named ${machine}.`, 1);
1225
+ id = found.id;
1226
+ }
1227
+ const declare = (body) => request("PUT", `/api/v1/machines/${encode(id)}/lane-cap`, body);
1228
+ const human = (p) => {
1229
+ const { raised, previousCap, laneCap } = p.data;
1230
+ const change = raised ? `raised from ${previousCap} to ${laneCap.cap}` : `declared at ${laneCap.cap}`;
1231
+ return `${machine}: lane cap ${change}, ${laneCap.count} lanes counted. It lapses at ${laneCap.lapsesAt}; re-declare before then.`;
1232
+ };
1233
+ const body = { cap, ...(flags["confirm-raise"] ? { confirmRaise: true, reason: flags.reason } : {}) };
1234
+ try {
1235
+ return { payload: await declare(body), human };
1236
+ } catch (error) {
1237
+ if (error?.code !== "LANE_CAP_RAISE_NOT_CONFIRMED") throw error;
1238
+ if (!interactive)
1239
+ throw new CliError(error.code, `${LANE_CAP_RAISE_PROMPT} To go ahead, run it again with --confirm-raise --reason TEXT.`, 1, error.details);
1240
+ const { previousCap, requestedCap } = error.details ?? {};
1241
+ console.error(`Raising the lane cap on ${machine} from ${previousCap} to ${requestedCap}.`);
1242
+ if ((await ask(LANE_CAP_RAISE_PROMPT)).toLowerCase() !== "y")
1243
+ throw new CliError("LANE_CAP_RAISE_DECLINED", "The cap was not raised.", 1);
1244
+ const reason = flags.reason ?? (await ask("Reason for the raise:"));
1245
+ if (!reason) throw new CliError("USAGE", "A raise needs a reason.", 2);
1246
+ return { payload: await declare({ cap, confirmRaise: true, reason }), human };
1247
+ }
1248
+ }
1249
+
1097
1250
  export async function machineCommand(action, args, flags, { request = devRequest } = {}) {
1098
1251
  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." };
1099
1252
  const id = need(args[0], `machine ${action} needs <machine>`);
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"]);
@@ -238,7 +239,34 @@ async function generatedFile(path, context) {
238
239
  const p = cleanPath(path);
239
240
  if (generatedByPath(p) || context.generatedPaths.some((x) => globPattern(x).test(p))) return true;
240
241
  const text = await optional(resolve(context.root, p));
241
- return text !== null && GENERATED_MARK.test(text.slice(0, 4096));
242
+ return text !== null && generatedHeader(text);
243
+ }
244
+
245
+ // A line comment: `//`, `#`, `--` or `;`.
246
+ const LINE_COMMENT = /^\s*(?:\/\/|#|--|;)/;
247
+ // The opening of a block comment: `/*` or `<!--`.
248
+ const BLOCK_OPEN = /^\s*(?:\/\*|<!--)/;
249
+ const BLOCK_CLOSE = /\*\/|-->/;
250
+
251
+ /**
252
+ * Whether a file declares itself generated in its header: the leading comment
253
+ * block (at most its first 12 lines, after a shebang and blank lines). A marker
254
+ * further down, in a string, a regex or later prose, does not count, so a
255
+ * generator that emits a "Do not edit" header is not itself generated
256
+ * (NODII-DEV-CLI-68).
257
+ */
258
+ export function generatedHeader(text) {
259
+ const header = [];
260
+ let inBlock = false;
261
+ for (const [at, line] of String(text).slice(0, 4096).split(/\r?\n/).entries()) {
262
+ if (header.length >= 12) break;
263
+ if (!inBlock && (!line.trim() || (at === 0 && line.startsWith("#!")))) continue;
264
+ if (inBlock) inBlock = !BLOCK_CLOSE.test(line);
265
+ else if (BLOCK_OPEN.test(line)) inBlock = !BLOCK_CLOSE.test(line.replace(BLOCK_OPEN, ""));
266
+ else if (!LINE_COMMENT.test(line)) break;
267
+ header.push(line);
268
+ }
269
+ return GENERATED_MARK.test(header.join("\n"));
242
270
  }
243
271
 
244
272
  function exactDeployGrant(context) {
@@ -258,6 +286,9 @@ export function commandNudges(command, context) {
258
286
  if (!provenLane(context)) nudges.push("nodii-dev safety: can't verify review: this is not a proven current-lane context.");
259
287
  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
288
  }
289
+ // MW1-38.13: a raise reaches the agent's context, not only the terminal.
290
+ if (/\bnodii-dev\b.*\blane\s+cap\b.*--confirm-raise\b/s.test(command))
291
+ 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
292
  if (!provenLane(context)) nudges.push(...commandViolations(command, context).map(nudgeViolation));
262
293
  return nudges;
263
294
  }
@@ -515,7 +546,8 @@ export async function safetyPreHook(payload, contextOrResolver = safetyContext)
515
546
  if (violation && provenLane(context)) blocked(violation);
516
547
  if (usesNoVerify(command) && context.role === "coordinator" && context.noVerifyReason)
517
548
  await recordNoVerifyReason(cwd, context.noVerifyReason);
518
- return { allowed: true, nudges: commandNudges(command, context) };
549
+ const reminder = context.role === "coordinator" ? await laneCapReminder() : null;
550
+ return { allowed: true, nudges: [...commandNudges(command, context), ...(reminder ? [reminder] : [])] };
519
551
  }
520
552
  const paths = editPaths(payload);
521
553
  if (!paths.length) {
package/dist/starting.js CHANGED
@@ -558,6 +558,14 @@ async function refreshAccountUsage(machineId, runtime, profile, { request }) {
558
558
  return reportUsage(accounts, { request, probe: true });
559
559
  }
560
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
+
561
569
  export async function launchLaneCommand(key, flags, {
562
570
  request = devRequest,
563
571
  readGovernorFor = readGovernor,
@@ -653,13 +661,15 @@ export async function launchLaneCommand(key, flags, {
653
661
  let governor = null;
654
662
  try { governor = await readGovernorFor(coordinator.machineId, { request }); } catch {}
655
663
  if (governor) assertGovernorOpen(governor);
656
- await request("POST", "/api/v1/lanes/launch", { phase: "preflight", ...body });
664
+ try { await request("POST", "/api/v1/lanes/launch", { phase: "preflight", ...body }); }
665
+ catch (error) { throw laneCapRefusal(error); }
657
666
  await worktrees(repositories);
658
667
  const lastPushedCommit = await head(repositories);
659
668
  let payload;
660
669
  try {
661
670
  payload = await request("POST", "/api/v1/lanes/launch", { phase: "register", ...body, lastPushedCommit });
662
671
  } catch (error) {
672
+ error = laneCapRefusal(error);
663
673
  throw new CliError(error?.code ?? "LANE_REGISTER_FAILED", `${error?.message ?? error}. Worktrees were created and were not removed; reconcile them before retrying.`, 1);
664
674
  }
665
675
  // An agent is dispatched only onto a lane whose start Dev recorded: building,
package/dist/surface.js CHANGED
@@ -31,7 +31,7 @@ import { CliError } from "./core.js";
31
31
  import { createRenderer } from "./vendor/render-templates.mjs";
32
32
 
33
33
  /** Bumped whenever the emitted code changes shape for the same inputs. */
34
- export const GENERATOR_FORMAT = 4;
34
+ export const GENERATOR_FORMAT = 5;
35
35
  export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
36
36
  export const GENERATED_SUFFIX = ".surface.generated.tsx";
37
37
  const CATALOG_PATH = "packages/blocks/src/product-pages/catalog.ts";
@@ -482,14 +482,31 @@ const propType = (d) => {
482
482
 
483
483
  const indent = (code, depth) => code.split("\n").map((line) => (line ? `${" ".repeat(depth)}${line}` : line)).join("\n");
484
484
 
485
+ // A part this narrow or narrower keeps its Figma width at every page width: an
486
+ // icon, an avatar, a switch, a separator. Anything wider is content that reflows.
487
+ export const INTRINSIC_MAX_PX = 48;
488
+
489
+ /**
490
+ * A node's size as the page's layout classes (never a component prop: a
491
+ * template reads only component properties, U07-19). Width is responsive at
492
+ * page level: the root fills the page (w-full), not the Figma frame's width; a
493
+ * FIXED part wider than INTRINSIC_MAX_PX keeps its Figma width only as an
494
+ * upper bound (max-w-full, and in a row it may shrink: min-w-0 instead of
495
+ * shrink-0), so the page reflows below the Figma width; an intrinsic part keeps
496
+ * its width and does not shrink. FILL, HUG, FIXED heights and min/max widths
497
+ * are as Figma sets them. A child of a frame with no auto layout is never
498
+ * positioned absolutely: that frame is refused (see emitNode); only a child
499
+ * Figma itself marks absolute is.
500
+ */
485
501
  function sizeClasses(node, parent, root) {
486
502
  const out = [];
487
503
  const [h, v] = node.sizing ?? ["FIXED", "FIXED"];
488
504
  const pm = parent?.layout?.mode;
489
505
  if (node.absolute) out.push("absolute", `left-${step(node.x ?? 0)}`, `top-${step(node.y ?? 0)}`);
490
- else if (parent && !pm && node.x !== undefined) out.push("absolute", `left-${step(node.x)}`, `top-${step(node.y)}`);
491
506
  if (node.width === undefined) return out;
492
- if (root || h === "FIXED") out.push(`w-${step(node.width)}`, ...(pm === "HORIZONTAL" ? ["shrink-0"] : []));
507
+ if (root) out.push("w-full");
508
+ else if (h === "FIXED" && node.width <= INTRINSIC_MAX_PX) out.push(`w-${step(node.width)}`, ...(pm === "HORIZONTAL" ? ["shrink-0"] : []));
509
+ else if (h === "FIXED") out.push(`w-${step(node.width)}`, ...(node.maxWidth ? [] : ["max-w-full"]), ...(pm === "HORIZONTAL" && !node.minWidth ? ["min-w-0"] : []));
493
510
  else if (h === "FILL") out.push(...(pm === "HORIZONTAL" ? ["min-w-0", "flex-1"] : pm === "VERTICAL" ? ["self-stretch"] : ["w-full"]));
494
511
  if (!root && v === "FIXED") out.push(`h-${step(node.height)}`, ...(pm === "VERTICAL" ? ["shrink-0"] : []));
495
512
  else if (!root && v === "FILL") out.push(...(pm === "VERTICAL" ? ["min-h-0", "flex-1"] : pm === "HORIZONTAL" ? ["self-stretch"] : ["h-full"]));
@@ -500,8 +517,10 @@ function sizeClasses(node, parent, root) {
500
517
 
501
518
  function layoutClasses(node) {
502
519
  const l = node.layout;
503
- if (!l) return node.children?.length ? ["relative"] : [];
504
- const out = [];
520
+ // A child Figma marks absolute is placed against this frame.
521
+ const anchor = (node.children ?? []).some((c) => c.visible !== false && c.absolute) ? ["relative"] : [];
522
+ if (!l) return anchor;
523
+ const out = [...anchor];
505
524
  if (l.mode === "GRID") {
506
525
  out.push("grid");
507
526
  if (l.columns) out.push(`grid-cols-${l.columns}`);
@@ -568,6 +587,10 @@ function emitNode(node, ctx) {
568
587
  );
569
588
  const slotContent = (prop) => {
570
589
  const slotNode = (node.children ?? []).find((c) => c.type === "SLOT" && c.slot === prop);
590
+ if (slotNode && !slotNode.layout && (slotNode.children ?? []).filter((c) => c.visible !== false && !c.absolute).length > 1) {
591
+ note(`${path} › ${prop}`, "layout", `slot ${prop} has no auto layout`);
592
+ return comment(`unmapped: slot ${JSON.stringify(prop)} has no auto layout`);
593
+ }
571
594
  const inner = (slotNode?.children ?? []).map((c) => emitNode(c, { ...ctx, depth: 0, parent: slotNode, path: `${path} › ${prop}`, root: false })).filter((x) => x !== null);
572
595
  return inner.length === 0 ? "<></>" : inner.length === 1 ? inner[0] : `<>\n${inner.map((x) => indent(x, 1)).join("\n")}\n</>`;
573
596
  };
@@ -613,6 +636,12 @@ function emitNode(node, ctx) {
613
636
  const painted = Boolean(node.fills?.length || node.strokes?.length || node.radius || node.effects);
614
637
  if (painted)
615
638
  note(path, "frame", `${node.instance ? `local component ${describe(node)}` : node.type.toLowerCase()} draws its own ${[node.fills?.length && "fill", node.strokes?.length && "stroke", node.radius && "radius", node.effects && `effect ${node.effects}`].filter(Boolean).join(", ")}`);
639
+ // A frame that holds layers without auto layout has no flex or grid to
640
+ // become: it is refused and reported, never drawn by absolute positions.
641
+ if (!node.layout && (node.children ?? []).some((c) => c.visible !== false && !c.absolute)) {
642
+ note(path, "layout", `${node.instance ? `local component ${describe(node)}` : node.type.toLowerCase()} has no auto layout`);
643
+ return indent(comment(`unmapped: ${node.type.toLowerCase()} ${JSON.stringify(node.name)} has no auto layout`), depth);
644
+ }
616
645
  const classes = cls([...sizeClasses(node, parent, root), ...layoutClasses(node), node.clips ? "overflow-hidden" : null]);
617
646
  const kids = (node.children ?? []).map(child).filter((x) => x !== null);
618
647
  const open = `<div${classes ? ` className="${classes}"` : ""}`;
package/dist/watchdog.js CHANGED
@@ -5,6 +5,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { CliError, configPath, devRequest, encode, readConfig } from "./core.js";
7
7
  import { USAGE_REFRESH_MS, listAccounts, reportUsage } from "./accounts.js";
8
+ import { laneCloseout } from "./lanes.js";
8
9
 
9
10
  const execFile = promisify(execFileCallback);
10
11
  export const WATCHDOG_LABEL = "com.nodii.watchdog";
@@ -205,6 +206,36 @@ export async function refreshMachineUsage(machineId, {
205
206
  return results;
206
207
  }
207
208
 
209
+ const LANE_CAP_REMIND_MS = 10 * 60_000;
210
+ const laneCapReminderPath = (home = homedir()) => join(watchdogHome(home), "lane-cap-reminder.txt");
211
+
212
+ /** MW1-38.10: what the coordinator must hear, or null while the cap has time left. */
213
+ export function laneCapReminderText(state, now = new Date()) {
214
+ if (!state) return null;
215
+ if (state.cap === null || !state.lapsesAt)
216
+ 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).";
217
+ const left = new Date(state.lapsesAt).getTime() - now.getTime();
218
+ if (left <= 0)
219
+ 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).`;
220
+ if (left <= LANE_CAP_REMIND_MS)
221
+ return `nodii-dev watchdog: this machine's lane cap lapses at ${state.lapsesAt}. Re-declare it with nodii-dev lane cap (MW1-38.10).`;
222
+ return null;
223
+ }
224
+
225
+ /** Held in a file because the sweep runs under launchd, outside the coordinator's session. */
226
+ export async function saveLaneCapReminder(text, { home = homedir() } = {}) {
227
+ const path = laneCapReminderPath(home);
228
+ if (!text) return rm(path, { force: true });
229
+ await mkdir(dirname(path), { recursive: true });
230
+ await writeFile(path, text);
231
+ }
232
+
233
+ /** The safety hook shows this on the coordinator's next shell command. It fails open. */
234
+ export async function laneCapReminder({ home = homedir() } = {}) {
235
+ try { return (await readFile(laneCapReminderPath(home), "utf8")).trim() || null; }
236
+ catch { return null; }
237
+ }
238
+
208
239
  /** One launchd sweep. The machine coordinator reports every observation through Dev's run watchdog contract. */
209
240
  export async function sweepWatchdog({
210
241
  records,
@@ -215,12 +246,15 @@ export async function sweepWatchdog({
215
246
  machineId,
216
247
  now = () => new Date(),
217
248
  refreshUsage = refreshMachineUsage,
249
+ closeout = laneCloseout,
250
+ saveReminder = saveLaneCapReminder,
218
251
  } = {}) {
219
252
  const loaded = records ? { records, errors: [] } : await loadRecords();
220
253
  const facts = await collect(loaded.records, { errors: [...loaded.errors] });
221
254
  const byId = new Map(loaded.records.map((record) => [record.runId, record]));
222
255
  const effectiveMachineId = machineId ?? (await coordinatorMachine({ request })).machineId;
223
256
  const orphanedRuns = [];
257
+ const finalOrphanCloseouts = [];
224
258
  // Dev's live runs are the authority, not the local flags (NODII-DEV-CLI-42):
225
259
  // a run Dev still holds as running gets its dead process reported again, and
226
260
  // a run with no local record is one this sweep cannot see. Without Dev's list
@@ -294,6 +328,17 @@ export async function sweepWatchdog({
294
328
  if (response?.data?.run?.livenessState === "orphan") {
295
329
  record.orphanReportedAt = observedAt;
296
330
  orphanedRuns.push({ runId: record.runId, pid: record.pid, reportedAt: record.orphanReportedAt });
331
+ // hub-244: an Orphan that turned final (no automatic relaunch)
332
+ // closes out here; Dev released its holds in the same report.
333
+ const run = response.data.run;
334
+ if (run.kind === "lane" && run.laneId && run.autoRelaunchAllowed === false) {
335
+ try {
336
+ const result = await closeout(run.laneId, run.failureReason ?? "final Orphan: the same death twice", { request });
337
+ finalOrphanCloseouts.push({ runId: record.runId, laneId: run.laneId, repositories: result.repositories });
338
+ } catch (error) {
339
+ facts.errors.push({ kind: "closeout", runId: record.runId, code: error?.code ?? "LANE_CLOSEOUT_FAILED" });
340
+ }
341
+ }
297
342
  } else if (["done", "handed_off", "failed", "blocked"].includes(response?.data?.run?.status)) {
298
343
  record.terminalSeenAt = observedAt;
299
344
  } else {
@@ -315,7 +360,14 @@ export async function sweepWatchdog({
315
360
  } catch (error) {
316
361
  facts.errors.push({ kind: "usage", code: error?.code ?? "ACCOUNT_USAGE_REPORT_FAILED" });
317
362
  }
318
- const report = { ...facts, orphanedRuns, unwatchedRuns, accounts };
363
+ let laneCap = null;
364
+ try {
365
+ laneCap = (await request("GET", `/api/v1/machines/${encode(effectiveMachineId)}`)).data?.laneCapState ?? null;
366
+ await saveReminder(laneCapReminderText(laneCap, now()));
367
+ } catch (error) {
368
+ facts.errors.push({ kind: "lane_cap", code: error?.code ?? "LANE_CAP_READ_FAILED" });
369
+ }
370
+ const report = { ...facts, orphanedRuns, finalOrphanCloseouts, unwatchedRuns, accounts, laneCap };
319
371
  return report;
320
372
  }
321
373
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.76",
3
+ "version": "0.6.78",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {