@nodii/dev 0.6.191 → 0.6.192

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/README.md CHANGED
@@ -79,6 +79,44 @@ refuses those flags. The first command you run after upgrading deletes the old
79
79
  config and its stored secret (Keychain item or file) without printing it, then
80
80
  asks you to run `nodii-dev login`.
81
81
 
82
+ ### Operator step-up: one TOTP code per window (hub-451)
83
+
84
+ ```sh
85
+ nodii-dev operator step-up # ask for the TOTP code now and open the window
86
+ nodii-dev operator step-up --revoke # end it, here and on Dev
87
+ ```
88
+
89
+ An operator-only command (governor override, lane stop, lane amendments
90
+ approve, docs ratify, Figma publish approvals and the rest) is refused to the
91
+ CLI's sign-in until the operator steps up: at a terminal the CLI asks for a
92
+ TOTP code and Dev returns a grant that lives 10 minutes, bound to the person,
93
+ the agent and the OAuth installation. The CLI keeps that grant for the
94
+ operator's own sign-in, so every command in those 10 minutes reuses it and
95
+ asks for no code. It sits in `operator-step-up.<agentId>.json` beside the
96
+ config (`~/.config/nodii-dev/` by default), mode 0600, written through a
97
+ temporary file and a rename, and is used only while it is this user's 0600
98
+ file, bound to this config's agent, person, installation and edge, and has
99
+ more than 5 seconds left. A lapsed one is deleted.
100
+
101
+ It is never read or written by a lane's, coordinator's or steward's config
102
+ (any config under `agents/`, or named `lane-*`, `coordinator-*` or
103
+ `steward-*`), under `NODII_DEV_LANE_KEY` or a launched run's
104
+ `NODII_DEV_RUN_ID`, or by a process with no terminal (an agent running on the
105
+ operator's own config). Dev refuses any other agent's use of a grant anyway.
106
+ The CLI drops it when Dev refuses it: `OPERATOR_STEP_UP_INVALID` (lapsed,
107
+ revoked or not this sign-in's; the CLI asks for a new code),
108
+ `OPERATOR_STEP_UP_NOT_OPERATOR`, `OPERATOR_STEP_UP_LANE_AGENT` or
109
+ `OPERATOR_STEP_UP_COORDINATOR`. `operator step-up --revoke` deletes the file
110
+ and calls `DELETE /api/v1/operator/step-up` with the grant; Dev answers
111
+ `revoked: false` when it held no live grant, and says so. A Dev without that
112
+ route (404 or 405) is reported as "revoked locally": the grant lapses on Dev
113
+ at its expiry and nothing on this machine sends it again. Under a lane's
114
+ config `--revoke` says there is nothing to revoke and calls nothing. Each
115
+ call made in the window carries the grant in `x-operator-step-up`, so Dev
116
+ audits it with the grant's id. The file keeps that id beside the grant, and
117
+ `operator step-up` and `--revoke` show the id, never the grant. The grant is never printed, logged or put in
118
+ argv, and the TOTP code is never stored.
119
+
82
120
  `nodii-dev` is only the Dev control CLI. The local-stack CLI is `./nodii-stack`,
83
121
  run from the `nodii-local-stack` checkout (renamed per operator ruling G3-6,
84
122
  with no alias under the old name). Typing one of its verbs here, such as
@@ -1895,8 +1933,25 @@ Task: STEP.` on stdin. It does this up to `NODII_DEV_LANE_CONTINUATIONS` times
1895
1933
  (a signal) is never continued. While the runtime writes to its log,
1896
1934
  continuations included, the supervisor heartbeats its run every
1897
1935
  `NODII_DEV_RUN_HEARTBEAT_SECONDS` (60) as the lane identity that owns it. A
1898
- runtime that is alive but writes nothing gets no heartbeat from the supervisor,
1899
- so it goes Quiet at 15 minutes and Orphan at 45 (MW1-36). A write to the
1936
+ run beats as the lane from its first second: when the runtime starts, a fresh
1937
+ launch, a `lane resume` (fresh or same-session) and each same-session
1938
+ continuation send a run heartbeat (`lane run started: runtime pid PID
1939
+ (supervisor PID)`, or the continuation's note) and the lane's harness beat,
1940
+ before the runtime writes anything (hub-598). A runtime that is alive but
1941
+ writes nothing, and has no tool call running as a process under it, gets no
1942
+ further heartbeat from the supervisor, so it goes Quiet at 15 minutes and
1943
+ Orphan at 45 (MW1-36). A tool call that is still running as a child process of
1944
+ the runtime counts (hub-598): a long Bash call, a heavy-slot wait or a
1945
+ background task writes nothing until it ends, so on a silent tick the
1946
+ supervisor reads the process tree (`/proc` on Linux, `ps` elsewhere) and beats
1947
+ while the runtime has such a child, with the note `tool call running: NAMES,
1948
+ started TIME`. NAMES are the short command names under the call (a script's
1949
+ file name, or a runner and its subcommand, such as `heavy-slot.sh › bun
1950
+ test`); no other argument is ever sent. The runtime's own helpers do not
1951
+ count: a child started within `NODII_DEV_TOOL_CALL_HELPER_SECONDS` (10) of the
1952
+ runtime's launch (MCP servers, session hooks) or named as an MCP server, and
1953
+ zombies. A call running longer than 2 hours stops counting, so a hung command
1954
+ still goes Quiet and then Orphan. A write to the
1900
1955
  session's Claude transcript (`<profile>/projects/<worktree>/<session>.jsonl`,
1901
1956
  and its subagents' transcripts) counts as one too. So does a tool call that is
1902
1957
  still running: a long command writes nothing until it ends, so while the
@@ -1947,9 +2002,9 @@ Objective, scope and rule changes are durable `lane amend` records, never chat
1947
2002
  messages. A coordinator's or steward's `lane amend` waits for the operator's
1948
2003
  approval (`lane amendments approve`, with their TOTP code). One code covers
1949
2004
  several requests when one command names them (`lane amendments approve ID ID
1950
- ...`) or takes every pending one (`--all-pending`): Dev's step-up lasts 10
1951
- minutes and the CLI holds it for one process, so a shell loop over ids asks
1952
- for a code each time. A leeway grant is
2005
+ ...`) or takes every pending one (`--all-pending`), and since hub-451 the
2006
+ operator's own sign-in at a terminal keeps Dev's 10-minute step-up across
2007
+ commands, so a shell loop over ids asks for one code (see Operator step-up). A leeway grant is
1953
2008
  also delivered as an amendment, and it never waits: the coordinator's grant is
1954
2009
  enough (MW1-12.7, DEC-0486). Every CLI call from a launched worktree checks the current watched
1955
2010
  run's acknowledgement version. A pending change is printed and blocks the
package/dist/cli.js CHANGED
@@ -151,6 +151,7 @@ import { coordinatorGate, coordinatorItemsCommand, observeLaneItems, resetLaneIt
151
151
  import { awsCli, superviseRemoteRun } from "./remote.js";
152
152
  import { issueGroupText, proposeIssueSet } from "./issue-group.js";
153
153
  import { assertLaneSwitchOn } from "./lane-switches.js";
154
+ import { operatorCommand } from "./operator.js";
154
155
 
155
156
  const NOTICE_KINDS = ["lane_wait", "lane_escalation", "credential_expiry"];
156
157
  const LANE_RUN_HOOKS = new Set(["nudge-pre", "nudge-stop", "lane-heartbeat", "session-start", "session-kind", "workflow-post"]);
@@ -712,6 +713,12 @@ Usage: nodii-dev <command> [options] [--json]
712
713
  # the operator only, signed in: let exactly one launch through, recorded with
713
714
  # their words and when they said them; lapses unused (default 60 min)
714
715
  governor overrides [--machine-id ID] # the machine's overrides and the launch each let through
716
+ operator step-up [--revoke] # hub-451: one TOTP code opens Dev's 10-minute step-up for the operator's
717
+ # own sign-in at a terminal; every operator-only command in the window
718
+ # reuses it (kept 0600 beside the config, never printed). A lane's or
719
+ # coordinator's config, a launched run and an agent never read or write it.
720
+ # With no flag it asks for the code now; --revoke deletes it and revokes it
721
+ # on Dev (an older Dev without the route: revoked locally, lapses there)
715
722
  lane non-issue <key> --reason TEXT --evidence TEXT --reroute KEY[,KEY]|none
716
723
  --branch carried:KEY|dropped[:REASON] [--commits SHA[,SHA]]
717
724
  # DEC-0011: terminal non_issue; issue -> wont_do; slot frees
@@ -1363,6 +1370,7 @@ export async function main(argv = process.argv.slice(2)) {
1363
1370
  const result = await laneClose(rest[0], f);
1364
1371
  return emit({ data: result.data }, json, result.text);
1365
1372
  }
1373
+ if (command === "operator") return emitCommand(await operatorCommand(action, rest, f));
1366
1374
  if (command === "governor") {
1367
1375
  const result = await governorCommand(action, f);
1368
1376
  return emit({ data: result.data }, json, result.text);
package/dist/core.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
- import { dirname, join } from "node:path";
5
+ import { basename, dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.191";
7
+ export const VERSION = "0.6.192";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -228,22 +228,128 @@ async function devFetchSend(method, path, bodyText, contentType, accept, extra =
228
228
  // OAuth agent) with 403 OPERATOR_REQUIRED. When a person is at the terminal,
229
229
  // the CLI asks for their TOTP code, Dev verifies it against the signed-in
230
230
  // person, and the call is sent again with the ten-minute grant Dev returns.
231
- // The code is never stored, logged or passed on; the grant lives only in this
232
- // process's memory. Without a TTY (an agent) the refusal is surfaced as it is.
231
+ // The code is never stored, logged or passed on. Without a TTY (an agent) the
232
+ // refusal is surfaced as it is.
233
+ //
234
+ // hub-451: the grant outlives the process for the operator's own sign-in at a
235
+ // terminal: it is kept in a 0600 file beside the config, keyed by the config's
236
+ // agent and bound to its person, installation and edge, until it lapses. So
237
+ // one code covers every command in Dev's window. A lane's or coordinator's
238
+ // config (under agents/), a launched run (NODII_DEV_LANE_KEY,
239
+ // NODII_DEV_RUN_ID) and a process with no terminal never read or write it:
240
+ // Dev refuses any other agent's use anyway, and the CLI never offers it.
241
+ // `operator step-up --revoke` deletes it and asks Dev to revoke the grant.
233
242
  export const OPERATOR_STEP_UP_PATH = "/api/v1/operator/step-up";
234
243
  export const OPERATOR_STEP_UP_HEADER = "x-operator-step-up";
235
244
  // hub-268: a staff-or-operator route (lane stop, Built acknowledge) refuses the
236
245
  // CLI with STAFF_OPERATOR_REQUIRED and accepts the same grant.
237
246
  const STEP_UP_REFUSALS = new Set(["OPERATOR_REQUIRED", "STAFF_OPERATOR_REQUIRED"]);
238
- let stepUpGrant = null; // { grant, expiresAt } for this process only
247
+ // Dev's refusals of a grant the call carried (src/lib/middleware/principal.ts):
248
+ // lapsed, revoked or not this sign-in's (401 OPERATOR_STEP_UP_INVALID), or this
249
+ // agent may no longer step up at all (403). Each drops the stored grant.
250
+ const GRANT_REFUSALS = new Set(["OPERATOR_STEP_UP_INVALID", "OPERATOR_STEP_UP_NOT_OPERATOR", "OPERATOR_STEP_UP_LANE_AGENT", "OPERATOR_STEP_UP_COORDINATOR"]);
251
+ // A grant is reused only while it has more than this left.
252
+ const GRANT_MARGIN_MS = 5_000;
253
+ let stepUpGrant = null; // { grant, expiresAt, id } held by this process (id: Dev's grant id, hub #718)
239
254
  let pendingStepUp = null; // the step-up in flight, shared by concurrent refusals
255
+ let windowLoaded = false; // the stored window was read once by this process
240
256
  let totpPrompt = defaultTotpPrompt;
257
+ const defaultTerminal = () => Boolean(process.stdin.isTTY && process.stderr.isTTY);
258
+ let stepUpTerminal = defaultTerminal;
241
259
 
242
- /** Tests replace the TTY prompt; `null` restores the default. Also forgets the grant. */
260
+ /** Tests replace the TTY prompt; `null` restores the default. Also forgets the grant this process holds. */
243
261
  export function setTotpPrompt(fn) {
244
262
  totpPrompt = fn ?? defaultTotpPrompt;
245
263
  stepUpGrant = null;
246
264
  pendingStepUp = null;
265
+ windowLoaded = false;
266
+ }
267
+
268
+ /** Tests say whether a person is at a terminal; `null` restores the TTY check. */
269
+ export function setStepUpTerminal(fn) {
270
+ stepUpTerminal = fn ?? defaultTerminal;
271
+ }
272
+
273
+ /**
274
+ * The step-up window file for this config, or null when this is not the
275
+ * operator's own sign-in: a launched lane or run, a config under agents/ (a
276
+ * lane's, a coordinator's or a steward's), or a config with no agent.
277
+ */
278
+ export function operatorStepUpFile(config, env = process.env) {
279
+ if (env.NODII_DEV_LANE_KEY || env.NODII_DEV_RUN_ID) return null;
280
+ const file = configPath();
281
+ const dir = dirname(file);
282
+ if (basename(dir) === "agents" || /^(lane|coordinator|steward)-/i.test(basename(file))) return null;
283
+ if (!isOAuthConfig(config) || typeof config.agentId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(config.agentId)) return null;
284
+ return join(dir, `operator-step-up.${config.agentId}.json`);
285
+ }
286
+
287
+ const binding = (config) => ({ agentId: config.agentId, installationId: config.installationId ?? null, person: config.person ?? null, edgeUrl: config.edgeUrl });
288
+ const live = (held) => Boolean(held && Date.parse(held.expiresAt) - Date.now() > GRANT_MARGIN_MS);
289
+
290
+ /** The stored window for this sign-in, when it is this user's 0600 file, bound to this config and live; else null (a stale one is removed). */
291
+ async function readStoredGrant(file, config) {
292
+ let info;
293
+ try {
294
+ info = await lstat(file);
295
+ } catch {
296
+ return null;
297
+ }
298
+ const own = info.isFile() && (info.mode & 0o077) === 0 && (typeof process.getuid !== "function" || info.uid === process.getuid());
299
+ let stored = null;
300
+ if (own) {
301
+ try {
302
+ stored = JSON.parse(await readFile(file, "utf8"));
303
+ } catch {}
304
+ }
305
+ const want = binding(config);
306
+ const bound = stored && Object.entries(want).every(([key, value]) => stored[key] === value) && typeof stored.grant === "string" && stored.grant !== "";
307
+ if (bound && live(stored)) return { grant: stored.grant, expiresAt: stored.expiresAt, id: typeof stored.id === "string" ? stored.id : null };
308
+ await rm(file, { force: true }).catch(() => {});
309
+ return null;
310
+ }
311
+
312
+ /** Write the window atomically: a 0600 temporary file renamed over the old one. */
313
+ async function writeStoredGrant(file, config, held) {
314
+ const tmp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
315
+ try {
316
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
317
+ await writeFile(tmp, `${JSON.stringify({ ...binding(config), id: held.id ?? null, grant: held.grant, expiresAt: held.expiresAt })}\n`, { mode: 0o600, flag: "wx" });
318
+ await chmod(tmp, 0o600);
319
+ await rename(tmp, file);
320
+ } catch {
321
+ // The window is a convenience: this process still holds the grant.
322
+ await rm(tmp, { force: true }).catch(() => {});
323
+ }
324
+ }
325
+
326
+ /** The window file for this process when it may use one: the operator's own sign-in, at a terminal. */
327
+ async function windowFile() {
328
+ if (!stepUpTerminal()) return null;
329
+ const config = await readConfig(false).catch(() => null);
330
+ const file = config ? operatorStepUpFile(config) : null;
331
+ return file ? { file, config } : null;
332
+ }
333
+
334
+ /** Once per process, before the first call: take a live stored grant. */
335
+ async function loadStoredGrant() {
336
+ if (windowLoaded || live(stepUpGrant)) return;
337
+ windowLoaded = true;
338
+ const target = await windowFile();
339
+ if (!target) return;
340
+ const stored = await readStoredGrant(target.file, target.config);
341
+ if (stored && !live(stepUpGrant)) stepUpGrant = stored;
342
+ }
343
+
344
+ /** Forget a grant Dev refused or that lapsed: in memory and, when it is the stored one, on disk. */
345
+ async function dropGrant(grant) {
346
+ if (stepUpGrant?.grant === grant) stepUpGrant = null;
347
+ const target = await windowFile();
348
+ if (!target) return;
349
+ try {
350
+ const stored = JSON.parse(await readFile(target.file, "utf8"));
351
+ if (stored?.grant === grant || !live(stored)) await rm(target.file, { force: true });
352
+ } catch {}
247
353
  }
248
354
 
249
355
  /** Reads one code from the terminal without echoing it, or null when there is no TTY. */
@@ -285,7 +391,7 @@ const refusalCode = (raw) => {
285
391
  }
286
392
  };
287
393
 
288
- const liveGrant = () => (stepUpGrant && Date.parse(stepUpGrant.expiresAt) - Date.now() > 5_000 ? stepUpGrant.grant : null);
394
+ const liveGrant = () => (live(stepUpGrant) ? stepUpGrant.grant : null);
289
395
 
290
396
  /** Ask for the code once and trade it for a grant; null when there is no TTY and the refusal stands. */
291
397
  async function stepUpOnce(refusal, signal) {
@@ -310,7 +416,11 @@ async function stepUpOnce(refusal, signal) {
310
416
  const expiresAt = payload?.data?.expiresAt;
311
417
  if (typeof grant !== "string" || typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)))
312
418
  throw new CliError("OPERATOR_STEP_UP_UNAVAILABLE", "Dev's step-up answer carried no usable grant.", 1);
313
- stepUpGrant = { grant, expiresAt };
419
+ // Dev names the grant by an id that every audit row under it carries (hub #718); an older Dev sends none.
420
+ const id = typeof payload.data.id === "string" ? payload.data.id : null;
421
+ stepUpGrant = { grant, expiresAt, id };
422
+ const target = await windowFile();
423
+ if (target) await writeStoredGrant(target.file, target.config, stepUpGrant);
314
424
  return grant;
315
425
  }
316
426
 
@@ -318,9 +428,11 @@ async function devFetch(method, path, bodyText, contentType, accept, extra = {},
318
428
  const send = (grant) =>
319
429
  devFetchOnce(method, path, bodyText, contentType, accept, grant ? { ...extra, [OPERATOR_STEP_UP_HEADER]: grant } : extra, signal);
320
430
  if (path === OPERATOR_STEP_UP_PATH) return devFetchOnce(method, path, bodyText, contentType, accept, extra, signal);
431
+ await loadStoredGrant();
321
432
  const held = liveGrant();
322
433
  const first = await send(held);
323
434
  const code = refusalCode(first.raw);
435
+ if (held && GRANT_REFUSALS.has(code)) await dropGrant(held);
324
436
  const refused =
325
437
  (first.response.status === 403 && STEP_UP_REFUSALS.has(code)) ||
326
438
  (first.response.status === 401 && code === "OPERATOR_STEP_UP_INVALID");
@@ -339,6 +451,55 @@ async function devFetch(method, path, bodyText, contentType, accept, extra = {},
339
451
  return send(grant);
340
452
  }
341
453
 
454
+ /**
455
+ * hub-451: `operator step-up`: ask for the code now and open the window, so
456
+ * the commands that follow need none. Returns when the window lapses; the
457
+ * grant itself is never returned or printed.
458
+ */
459
+ export async function openOperatorStepUp() {
460
+ const config = await readConfig();
461
+ if (!operatorStepUpFile(config)) return { opened: false, reason: "not-operator" };
462
+ await loadStoredGrant();
463
+ if (!live(stepUpGrant)) {
464
+ const grant = await stepUpOnce("OPERATOR_REQUIRED");
465
+ if (grant === null) return { opened: false, reason: "no-terminal" };
466
+ }
467
+ return { opened: true, id: stepUpGrant.id ?? null, expiresAt: stepUpGrant.expiresAt, stored: Boolean(await windowFile()) };
468
+ }
469
+
470
+ /**
471
+ * hub-451: `operator step-up --revoke`: delete the stored window and ask Dev
472
+ * to revoke the grant (DELETE /api/v1/operator/step-up, hub #718: 200 with
473
+ * data.revoked, false when Dev held no live grant). An older Dev without
474
+ * that route (404, 405) leaves the grant to lapse there: revoked locally.
475
+ * Revoking only removes authority, so it reads the file without a terminal;
476
+ * under a lane's config there is nothing to revoke and Dev is not called.
477
+ */
478
+ export async function revokeOperatorStepUp() {
479
+ const config = await readConfig();
480
+ const file = operatorStepUpFile(config);
481
+ if (!file) return { lane: true, local: false, dev: "skipped" };
482
+ const stored = await readStoredGrant(file, config);
483
+ const held = live(stepUpGrant) ? stepUpGrant : stored;
484
+ await rm(file, { force: true });
485
+ const local = Boolean(stored);
486
+ stepUpGrant = null;
487
+ windowLoaded = true;
488
+ const { response, raw } = await devFetchOnce("DELETE", OPERATOR_STEP_UP_PATH, undefined, undefined, "application/json", held ? { [OPERATOR_STEP_UP_HEADER]: held.grant } : {});
489
+ const known = { lane: false, local, id: held?.id ?? null, expiresAt: held?.expiresAt ?? null };
490
+ if (response.ok) {
491
+ let revoked = true;
492
+ try { revoked = JSON.parse(raw)?.data?.revoked !== false; } catch {}
493
+ return { ...known, dev: revoked ? "revoked" : "none" };
494
+ }
495
+ if (response.status === 404 || response.status === 405) return { ...known, dev: "unsupported" };
496
+ const code = refusalCode(raw);
497
+ if (code === "OPERATOR_STEP_UP_INVALID") return { ...known, dev: "none" };
498
+ let message = null;
499
+ try { message = JSON.parse(raw)?.message ?? null; } catch {}
500
+ throw new CliError(code ?? `HTTP_${response.status}`, `Revoked on this machine, but Dev's revoke failed: ${message ?? `HTTP ${response.status}`}`, 1);
501
+ }
502
+
342
503
  // MW1-37.2: Dev names the lane items waiting on a machine's coordinator in a
343
504
  // response header. The CLI's entry point registers who reads it; it never
344
505
  // fails a request.
@@ -405,7 +566,7 @@ export async function checkLogin() {
405
566
  export const encode = (value) => encodeURIComponent(value);
406
567
  // Switches never take the next token as their value, so
407
568
  // `docs upload --wait rulebook/` keeps rulebook/ as a path.
408
- const SWITCHES = new Set(["all-pending", "confirm-raise", "actionable", "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", "if-changed"]);
569
+ const SWITCHES = new Set(["revoke", "all-pending", "confirm-raise", "actionable", "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", "if-changed"]);
409
570
  export function parseArgs(argv) {
410
571
  const flags = {};
411
572
  const args = [];
package/dist/flags.js CHANGED
@@ -65,6 +65,8 @@ export const COMMAND_FLAGS = {
65
65
  "governor show": ["machine-id"],
66
66
  "governor override": ["machine-id", "quote", "said-at", "reason", "minutes"],
67
67
  "governor overrides": ["machine-id"],
68
+ // hub-451: open the operator's step-up window now, or end it.
69
+ "operator step-up": ["revoke"],
68
70
  "lane land": [],
69
71
  "lane verify": ["dev-check", "checks"],
70
72
  "repo policy": ["root"],
@@ -8,6 +8,7 @@ import { profilePath, recordExhaustedAccount } from "./accounts.js";
8
8
  import { CliError, devRequest, encode } from "./core.js";
9
9
  import { inboxForContinuation, laneMessageCommand } from "./lane-messages.js";
10
10
  import { laneSwitchOn } from "./lane-switches.js";
11
+ import { HELPER_WINDOW_MS, processTable, toolCallChild } from "./process-tree.js";
11
12
  import { redactRunText } from "./runs.js";
12
13
  import { processStartedAt, saveWatchedRun, watchdogRunDir } from "./watchdog.js";
13
14
 
@@ -575,6 +576,26 @@ const heartbeatInterval = (env) => {
575
576
  return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 60_000;
576
577
  };
577
578
 
579
+ // hub-598: a child the runtime starts within this many seconds of its launch is its own helper (an MCP server, a session hook), never a tool call.
580
+ const helperWindow = (env) => {
581
+ const seconds = Number(env.NODII_DEV_TOOL_CALL_HELPER_SECONDS ?? HELPER_WINDOW_MS / 1000);
582
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : HELPER_WINDOW_MS;
583
+ };
584
+
585
+ /**
586
+ * hub-598: the runtime's tool call still running as a process under it (a
587
+ * heavy-slot wait, a build, a background task), for at most OPEN_CALL_MAX_MS;
588
+ * else null. Read only when the runtime is silent.
589
+ */
590
+ export function runningToolCall(pid, env = process.env, { table = processTable } = {}) {
591
+ try {
592
+ const processes = table();
593
+ return processes ? toolCallChild(processes, pid, { helperWindowMs: helperWindow(env), maxMs: OPEN_CALL_MAX_MS }) : null;
594
+ } catch {
595
+ return null;
596
+ }
597
+ }
598
+
578
599
  /** The run log's size, or null when it cannot be read. */
579
600
  const logSize = (logPath) => {
580
601
  try { return statSync(logPath).size; } catch { return null; }
@@ -732,21 +753,30 @@ export async function superviseLane({
732
753
  // harness beat (source "hook", as the per-tool-call hook process sent it),
733
754
  // which keeps Dev's `stuck` meaningful, and the run beat says when the
734
755
  // runtime last wrote.
756
+ // hub-598: a silent runtime with a tool call still running as its child
757
+ // process is beaten too, its note naming the call; with no write and no such
758
+ // child it stays unbeaten, so a hung run still goes Quiet and then Orphan.
735
759
  // Codex's transcript is its --json stream, the run log itself.
736
760
  let sessionId = null;
737
761
  const transcripts = () => (invocation.command === "claude" && sessionId ? claudeTranscripts(invocation, sessionId) : []);
738
762
  const activity = runActivity({ logPath, transcripts });
763
+ // The lane's beat goes with each run beat. At NODII_DEV_STOP_ONLY_HEARTBEAT=0 the harness's tool-call hook beats the lane instead.
764
+ const beatLane = () => {
765
+ if (laneKey && laneSwitchOn("stopOnlyHeartbeat", env)) request("POST", `/api/v1/lanes/${encode(laneKey)}/heartbeat`, { via: "nodii-dev", source: "hook" }).catch(() => {});
766
+ };
739
767
  const heartbeat = setInterval(() => {
740
768
  if (state !== "running") return;
741
769
  // Both beats leave inside the tick, so none follows the exit report.
742
770
  const at = activity();
771
+ const tool = at === null ? runningToolCall(child.pid, env) : null;
743
772
  // A tool call still running writes nothing; it beats for at most OPEN_CALL_MAX_MS of silence.
744
- const open = at === null ? openCallSince({ logPath, transcripts, runtime: invocation.command }) : null;
745
- if (at !== null || open !== null) {
746
- const note = at !== null ? `last activity ${new Date(at).toISOString()}` : `a tool call is still running; last write ${new Date(open).toISOString()}`;
773
+ const open = at === null && !tool ? openCallSince({ logPath, transcripts, runtime: invocation.command }) : null;
774
+ if (at !== null || tool || open !== null) {
775
+ const note = at !== null ? `last activity ${new Date(at).toISOString()}`
776
+ : tool ? `tool call running: ${redactRunText(tool.names)}, started ${new Date(Date.now() - tool.elapsedMs).toISOString().replace(/\.\d{3}Z$/, "Z")}`
777
+ : `a tool call is still running; last write ${new Date(open).toISOString()}`;
747
778
  request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, { note: `lane runtime pid ${child.pid} alive (supervisor ${process.pid}); ${note}` }).catch(() => {});
748
- // At NODII_DEV_STOP_ONLY_HEARTBEAT=0 the harness's tool-call hook beats the lane instead.
749
- if (laneKey && laneSwitchOn("stopOnlyHeartbeat", env)) request("POST", `/api/v1/lanes/${encode(laneKey)}/heartbeat`, { via: "nodii-dev", source: "hook" }).catch(() => {});
779
+ beatLane();
750
780
  }
751
781
  // The session's transcript is found once its id is in the log.
752
782
  if (!sessionId && invocation.command === "claude")
@@ -768,6 +798,8 @@ export async function superviseLane({
768
798
  state = "running";
769
799
  child.stdin.end(message.prompt);
770
800
  tell({ type: "started" });
801
+ // hub-598: a fresh or resumed run beats as the lane from its first second, before it writes.
802
+ request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, { note: `lane run started: runtime pid ${child.pid} (supervisor ${process.pid})` }).catch(() => {}).then(beatLane);
771
803
  } else if (message?.type === "abort" && state !== "running") {
772
804
  state = "aborted";
773
805
  child.kill("SIGTERM");
@@ -807,6 +839,8 @@ export async function superviseLane({
807
839
  await request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, {
808
840
  note: `continuation ${continued}/${limit} of session ${sessionId} after exit ${exitCode}: ${message}`.slice(0, 500),
809
841
  }).catch(() => {});
842
+ // hub-598: the continued session beats as the lane too, before it writes.
843
+ beatLane();
810
844
  const next = continuationInvocation(invocation, sessionId);
811
845
  try {
812
846
  child = spawn(next.command, next.args, { cwd: next.cwd, env: next.env, shell: false, stdio: ["pipe", "inherit", "inherit"] });
@@ -0,0 +1,43 @@
1
+ // hub-451: one TOTP step-up opens Dev's window for the operator's own sign-in
2
+ // at a terminal (core.js keeps it in a 0600 file beside the config). These
3
+ // commands open it ahead of time and end it. The grant is never printed.
4
+ import { CliError, openOperatorStepUp, revokeOperatorStepUp } from "./core.js";
5
+
6
+ export const OPERATOR_USAGE = "operator step-up [--revoke]";
7
+
8
+ export async function operatorCommand(action, rest, flags, deps = {}) {
9
+ if (action !== "step-up" || rest.length) throw new CliError("USAGE", OPERATOR_USAGE, 2);
10
+ return flags.revoke ? revoke(deps.revoke ?? revokeOperatorStepUp) : open(deps.open ?? openOperatorStepUp);
11
+ }
12
+
13
+ async function open(openWindow) {
14
+ const result = await openWindow();
15
+ if (!result.opened)
16
+ throw new CliError(
17
+ "OPERATOR_STEP_UP_LANE_CONFIG",
18
+ "A lane's config, a coordinator's, a launched run or a config with no agent cannot step up. Run it from the machine's own sign-in, in a terminal.",
19
+ 1,
20
+ );
21
+ return {
22
+ payload: { data: { open: true, id: result.id, expiresAt: result.expiresAt, stored: result.stored } },
23
+ human: `Step-up ${result.id ? `${result.id} ` : ""}open until ${result.expiresAt}. Operator-only commands from this sign-in, at a terminal on this machine, need no TOTP code until then. \`nodii-dev operator step-up --revoke\` ends it.`,
24
+ };
25
+ }
26
+
27
+ async function revoke(revokeWindow) {
28
+ const result = await revokeWindow();
29
+ if (result.lane)
30
+ return {
31
+ payload: { data: { revoked: false, local: false, dev: "skipped" } },
32
+ human: "A lane's config, a coordinator's or a launched run never holds an operator step-up: nothing to revoke, and Dev was not called.",
33
+ };
34
+ const named = result.id ? ` ${result.id}` : "";
35
+ const here = result.local ? "Removed from this machine" : "Nothing was stored on this machine";
36
+ const lapses = result.expiresAt ? `lapses on Dev at ${result.expiresAt}` : "lapses on Dev within 10 minutes of its code";
37
+ const human = {
38
+ revoked: `Step-up${named} revoked on Dev. ${here}. The next operator-only command asks for a TOTP code.`,
39
+ none: `Dev holds no live step-up for this sign-in. ${here}. The next operator-only command asks for a TOTP code.`,
40
+ unsupported: `Step-up${named} revoked locally. ${here}. This Dev has no revoke route yet (HTTP 404 or 405), so the grant ${lapses}; no command from this machine sends it again.`,
41
+ }[result.dev];
42
+ return { payload: { data: { revoked: true, local: result.local, dev: result.dev, id: result.id, expiresAt: result.expiresAt } }, human };
43
+ }
@@ -0,0 +1,143 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * hub-598: a runtime blocked in a tool call (a heavy-slot wait, a long build,
7
+ * a background task) writes nothing, yet it is working: a process it started
8
+ * is still running. The lane supervisor reads the process tree to tell that
9
+ * runtime from a hung one, which has no such child.
10
+ *
11
+ * A child counts as a tool call unless it is one of the runtime's own
12
+ * helpers: started within the launch window (MCP servers, session hooks), or
13
+ * named as an MCP server. A call running longer than the cap stops counting,
14
+ * so a command that hangs still lets its run go Quiet and then Orphan
15
+ * (MW1-36).
16
+ */
17
+
18
+ export const TOOL_CALL_MAX_MS = 2 * 60 * 60_000;
19
+ export const HELPER_WINDOW_MS = 10_000;
20
+
21
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "fish", "ksh"]);
22
+ const RUNNERS = new Set([...SHELLS, "node", "bun", "deno", "tsx", "python", "python3", "ruby", "perl", "npx", "bunx", "npm", "pnpm", "yarn", "uv", "uvx"]);
23
+ const SCRIPT_NAME = /^[\w.+@-]{1,40}$/;
24
+ const SUBCOMMAND = /^[a-z][a-z0-9-]{0,19}$/;
25
+ const MAX_NAMES = 4;
26
+
27
+ const baseName = (value) => String(value ?? "").split("/").pop().replace(/^-/, "");
28
+
29
+ /** `[[dd-]hh:]mm:ss`, ps's elapsed time, in ms; null when unreadable. */
30
+ const etimeMs = (value) => {
31
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(value);
32
+ if (!match) return null;
33
+ const [, days = 0, hours = 0, minutes, seconds] = match;
34
+ return (((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1000;
35
+ };
36
+
37
+ /** Rows of `ps -A -o pid=,ppid=,etime=,stat=,command=`. Argv is the command split on spaces. */
38
+ export function parsePs(text) {
39
+ const table = [];
40
+ for (const line of String(text ?? "").split("\n")) {
41
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(.*)$/.exec(line);
42
+ if (!match) continue;
43
+ const elapsedMs = etimeMs(match[3]);
44
+ if (elapsedMs === null) continue;
45
+ const command = match[5].trim();
46
+ table.push({ pid: Number(match[1]), ppid: Number(match[2]), elapsedMs, zombie: match[4].startsWith("Z") || command === "<defunct>", argv: command.split(/\s+/) });
47
+ }
48
+ return table;
49
+ }
50
+
51
+ /** Linux's process table from /proc; null when it cannot be read. Start times are in USER_HZ (100) ticks since boot. */
52
+ export function procTable(proc = "/proc") {
53
+ let uptimeMs;
54
+ let names;
55
+ try {
56
+ uptimeMs = Number(readFileSync(join(proc, "uptime"), "utf8").split(/\s+/)[0]) * 1000;
57
+ names = readdirSync(proc).filter((name) => /^\d+$/.test(name));
58
+ } catch {
59
+ return null;
60
+ }
61
+ if (!Number.isFinite(uptimeMs)) return null;
62
+ const table = [];
63
+ for (const name of names) {
64
+ try {
65
+ const stat = readFileSync(join(proc, name, "stat"), "utf8");
66
+ // The name is in parentheses and may hold either; the fields follow the last ")".
67
+ const close = stat.lastIndexOf(")");
68
+ const fields = stat.slice(close + 2).split(" ");
69
+ const argv = readFileSync(join(proc, name, "cmdline"), "utf8").split("\0").filter(Boolean);
70
+ table.push({
71
+ pid: Number(name),
72
+ ppid: Number(fields[1]),
73
+ elapsedMs: Math.max(0, Math.round(uptimeMs - Number(fields[19]) * 10)),
74
+ zombie: fields[0] === "Z",
75
+ argv: argv.length ? argv : [stat.slice(stat.indexOf("(") + 1, close)],
76
+ });
77
+ } catch {
78
+ // The process ended while the table was read.
79
+ }
80
+ }
81
+ return table;
82
+ }
83
+
84
+ const readPs = () => execFileSync("ps", ["-A", "-o", "pid=,ppid=,etime=,stat=,command="], {
85
+ encoding: "utf8", timeout: 5000, maxBuffer: 32 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"],
86
+ });
87
+
88
+ /** This machine's processes: /proc on Linux, ps elsewhere; null when neither can be read. */
89
+ export function processTable({ platform = process.platform, proc = "/proc", ps = readPs } = {}) {
90
+ if (platform === "linux") {
91
+ const table = procTable(proc);
92
+ if (table) return table;
93
+ }
94
+ try { return parsePs(ps()); } catch { return null; }
95
+ }
96
+
97
+ /** A process's short name: its command, its script's name, or `runner subcommand`; never its other arguments. */
98
+ export function shortCommand(argv) {
99
+ const name = baseName(argv?.[0]);
100
+ const next = argv?.[1];
101
+ if (!RUNNERS.has(name) || !next || next.startsWith("-")) return name;
102
+ if (next.includes("/") || next.includes(".")) {
103
+ const script = baseName(next);
104
+ return SCRIPT_NAME.test(script) ? script : name;
105
+ }
106
+ return SUBCOMMAND.test(next) ? `${name} ${next}` : name;
107
+ }
108
+
109
+ /** A helper by its command: an MCP server or a sleep guard. A shell's `-c` command line is a tool call, whatever it mentions. */
110
+ const helperCommand = (argv) => {
111
+ if (/^-\w*c$/.test(argv[1] ?? "")) return false;
112
+ return baseName(argv[0]) === "caffeinate" || argv.slice(0, 4).some((part) => /mcp|modelcontextprotocol/i.test(part));
113
+ };
114
+
115
+ /**
116
+ * The runtime's running tool call: the longest-running child that is not a
117
+ * helper, a zombie or past maxMs, with the short names of the processes under
118
+ * it ("heavy-slot.sh › bun test"; shells that only wrap are left out). Null
119
+ * when there is none.
120
+ */
121
+ export function toolCallChild(table, runtimePid, { helperWindowMs = HELPER_WINDOW_MS, maxMs = TOOL_CALL_MAX_MS } = {}) {
122
+ const runtime = table.find((entry) => entry.pid === runtimePid);
123
+ if (!runtime) return null;
124
+ const children = new Map();
125
+ for (const entry of table) {
126
+ if (entry.zombie) continue;
127
+ if (!children.has(entry.ppid)) children.set(entry.ppid, []);
128
+ children.get(entry.ppid).push(entry);
129
+ }
130
+ const calls = (children.get(runtimePid) ?? []).filter((child) =>
131
+ child.elapsedMs <= maxMs && runtime.elapsedMs - child.elapsedMs >= helperWindowMs && !helperCommand(child.argv));
132
+ if (!calls.length) return null;
133
+ const call = calls.reduce((oldest, child) => (child.elapsedMs > oldest.elapsedMs ? child : oldest));
134
+ const all = [];
135
+ const walk = (entry, depth) => {
136
+ all.push(shortCommand(entry.argv));
137
+ if (depth < 16) for (const child of children.get(entry.pid) ?? []) walk(child, depth + 1);
138
+ };
139
+ walk(call, 0);
140
+ const named = all.filter((name) => name && !SHELLS.has(name));
141
+ const names = (named.length ? named : all).filter((name, index, list) => name !== list[index - 1]);
142
+ return { pid: call.pid, names: `${names.slice(0, MAX_NAMES).join(" › ")}${names.length > MAX_NAMES ? " › …" : ""}`, elapsedMs: call.elapsedMs };
143
+ }
package/dist/starting.js CHANGED
@@ -849,8 +849,9 @@ const requestLine = (r) => `${r.id}\t${r.laneKey}\t${r.state}\t${r.changedPercen
849
849
  * `lane amendments approve|reject <request> [<request> ...]|--all-pending [--note TEXT]`.
850
850
  * Approve and reject are the operator's: the CLI asks for their TOTP code
851
851
  * (STAFF_OPERATOR_REQUIRED), and an agent's call is refused as it stands.
852
- * hub-525: Dev's step-up grant lasts 10 minutes and this CLI holds it for one
853
- * process, so one command answers several requests under one code.
852
+ * hub-525: Dev's step-up grant lasts 10 minutes, so one command answers
853
+ * several requests under one code (hub-451: and the operator's next commands
854
+ * in the window reuse it).
854
855
  */
855
856
  export async function laneAmendmentsCommand(args, flags, { request = devRequest } = {}) {
856
857
  const [first, ...named] = args;
package/dist/surface.js CHANGED
@@ -752,6 +752,11 @@ function freeIdentifiers(code) {
752
752
  for (const m of masked.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.[A-Za-z][A-Za-z0-9]*)?\}/g)) add(m.index + m[1].length + 2, m[2]);
753
753
  for (const m of masked.matchAll(/(^|>)(\s*)\{([a-z][A-Za-z0-9]*)\}/gm)) add(m.index + m[1].length + m[2].length + 1, m[3]);
754
754
  for (const m of masked.matchAll(/\b[A-Za-z_]\w*:\s*([a-z][A-Za-z0-9]*)(?=\s*[,}\]])/g)) add(m.index + m[0].length - m[1].length, m[1]);
755
+ // NODII-DEV-CLI-241: each element of an array prop (`controls={[control1, control2]}`).
756
+ for (const m of masked.matchAll(/[A-Za-z][\w-]*=\{\[([^\]\[{}]*)\]\}/g)) {
757
+ const start = m.index + m[0].indexOf("[") + 1;
758
+ for (const e of m[1].matchAll(/([a-z][A-Za-z0-9]*)\s*(?=,|$)/g)) add(start + e.index, e[1]);
759
+ }
755
760
  return [...found.entries()].map(([at, name]) => ({ at, name })).sort((a, b) => a.at - b.at);
756
761
  }
757
762
 
@@ -2096,6 +2101,18 @@ function dataProps(views, propsType) {
2096
2101
  entry(m[2]).child = true;
2097
2102
  view.uses.add(m[2]);
2098
2103
  }
2104
+ // NODII-DEV-CLI-241: an identifier in an array prop is one element of that prop.
2105
+ for (const m of body.matchAll(/([A-Za-z][\w-]*)=\{\[([^\]\[{}]*)\]\}/g)) {
2106
+ const start = openingTag(body, m.index);
2107
+ const tag = start === null ? null : /^<([A-Za-z][\w.]*)/.exec(body.slice(start))?.[1];
2108
+ if (!tag) continue;
2109
+ for (const e of m[2].matchAll(/([a-z][A-Za-z0-9]*)\s*(?=,|$)/g)) {
2110
+ if (JS_LITERALS.has(e[1])) continue;
2111
+ const d = entry(e[1]);
2112
+ d.raw ??= `NonNullable<ComponentProps<typeof ${tag}>[${JSON.stringify(m[1])}]>[number]`;
2113
+ view.uses.add(e[1]);
2114
+ }
2115
+ }
2099
2116
  // An overridable table heading retains the drawing's copy when omitted.
2100
2117
  for (const m of body.matchAll(/\{([a-z][A-Za-z0-9]*Heading) \?\? "(?:[^"\\\n]|\\.)*"\}/g)) {
2101
2118
  entry(m[1]).child = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.191",
3
+ "version": "0.6.192",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {