@nodii/dev 0.6.76 → 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 CHANGED
@@ -95,6 +95,7 @@ import {
95
95
  builtCommand,
96
96
  deltaGatherFlags,
97
97
  laneCommand,
98
+ laneCapCommand,
98
99
  machineCommand,
99
100
  nextCommand,
100
101
  peopleCommand,
@@ -312,6 +313,9 @@ Usage: nodii-dev <command> [options] [--json]
312
313
  # one Dev refuses for good, with a note on its lane
313
314
  lane done-check <key> --evidence TEXT|URL # the done check is met; a launched run that exits after it ends finished
314
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)
315
319
  lane heartbeat|resume|land|verify|prioritize|deprioritize|stop <key>
316
320
  lane heartbeat <key> --note "BLOCKED: ..."|"WAITING: ..."
317
321
  # a note starting BLOCKED or WAITING: (capitals) marks the lane blocked:
@@ -868,6 +872,7 @@ export async function main(argv = process.argv.slice(2)) {
868
872
  if (command === "coordinator") return emitCommand(await coordinatorCommand(action, f, { installWatchdog }));
869
873
  if (command === "steward") return emitCommand(await stewardCommand(action, rest, f));
870
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));
871
876
  if (command === "lane" && action === "close") {
872
877
  const result = await laneClose(rest[0], f);
873
878
  return emit({ data: result.data }, json, result.text);
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.76";
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,6 +35,7 @@ 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"],
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";
@@ -1094,6 +1094,62 @@ export async function builtCommand(action, args, flags, { request = devRequest,
1094
1094
  throw new CliError("USAGE", `Unknown built action: ${action}`, 2);
1095
1095
  }
1096
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
+
1097
1153
  export async function machineCommand(action, args, flags, { request = devRequest } = {}) {
1098
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." };
1099
1155
  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"]);
@@ -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
- return { allowed: true, nudges: commandNudges(command, context) };
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
@@ -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/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
- const report = { ...facts, orphanedRuns, unwatchedRuns, accounts };
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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.76",
3
+ "version": "0.6.77",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {