@nodii/dev 0.6.208 → 0.6.209

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/lanes.js CHANGED
@@ -111,8 +111,20 @@ export function heartbeatText(ref, payload, sentWaits = false) {
111
111
  }
112
112
 
113
113
  /** The wait board (GET /lanes/waits) as text: blockers first, then what holds lanes outside the graph. */
114
- export function waitBoardText(board) {
114
+ export function waitBoardText(board, { person } = {}) {
115
115
  const lines = [];
116
+ const people = Array.isArray(board?.persons) ? board.persons : [];
117
+ const peopleLines = () => {
118
+ if (!people.length) return;
119
+ lines.push("Waiting on people:");
120
+ for (const row of people) lines.push(` ${row.targetRef}\tholds ${row.lanes} lane${row.lanes === 1 ? "" : "s"}: ${(row.laneKeys ?? []).join(", ")}`);
121
+ };
122
+ // O3 item 8: `--person ROLE` reads only that role's waits; Dev leaves every other group empty.
123
+ if (person !== undefined) {
124
+ peopleLines();
125
+ if (!lines.length) lines.push(`No lane waits on person:${person}.`);
126
+ return lines.join("\n");
127
+ }
116
128
  const blockers = board?.blockers ?? [];
117
129
  if (blockers.length) {
118
130
  lines.push("Lanes others wait on (highest effective priority first):");
@@ -128,6 +140,7 @@ export function waitBoardText(board) {
128
140
  targets("Launch day:", board?.launchDay?.lanes ? [board.launchDay] : []);
129
141
  targets("Decisions:", board?.decisions);
130
142
  targets("PRs and releases with no lane found:", board?.untraced);
143
+ peopleLines();
131
144
  return lines.join("\n");
132
145
  }
133
146
  // GATHER-NA: a step the coordinator ruled not applicable is never shown as done.
@@ -525,9 +538,12 @@ export async function laneCommand(action, args, flags, deps = {}) {
525
538
  }
526
539
  // hub-246: the wait graph, for the coordinator and the operator.
527
540
  if (action === "waits") {
528
- if (args[0]) throw new CliError("USAGE", "lane waits takes no <key>; pass --machine ID to narrow it to one machine.", 2);
529
- const payload = await request("GET", `/api/v1/lanes/waits${query({ machine: flags.machine })}`);
530
- return { payload, human: (p) => waitBoardText(p.data) };
541
+ if (args[0]) throw new CliError("USAGE", "lane waits takes no <key>; pass --machine ID to narrow it to one machine, or --person ROLE to one role.", 2);
542
+ if (flags.person !== undefined && (typeof flags.person !== "string" || !flags.person.trim()))
543
+ throw new CliError("USAGE", "lane waits --person needs a role, as in --person steward", 2);
544
+ const person = flags.person?.trim().replace(/^person:/i, "");
545
+ const payload = await request("GET", `/api/v1/lanes/waits${query({ machine: flags.machine, person })}`);
546
+ return { payload, human: (p) => waitBoardText(p.data, { person }) };
531
547
  }
532
548
  if (action === "start") {
533
549
  // `--key` names the lane; the positional is then the issue (NODII-DEV-CLI-13).
@@ -724,9 +740,14 @@ export async function laneCommand(action, args, flags, deps = {}) {
724
740
  picker: byAgent ? "agent" : picked.model ?? pickerModelName(),
725
741
  doneCheck,
726
742
  }, { signal });
743
+ // The stored boundary keeps every grant it had: creates (DS-254) and
744
+ // granted section and page ids (hub-643), not only the sets.
727
745
  const figma = figmaScope.map((file) => ({
728
746
  fileKey: file.fileKey,
729
747
  ...(file.componentSets.length ? { componentSetKeys: file.componentSets } : {}),
748
+ ...(file.creates?.length ? { creates: file.creates } : {}),
749
+ ...(file.sections?.length ? { sectionIds: file.sections } : {}),
750
+ ...(file.pages?.length ? { pageIds: file.pages } : {}),
730
751
  }));
731
752
  const lookup = guidelineLookup(scoped.components);
732
753
  const issue = lane.issue ? { key: lane.issue.key, title: lane.issue.title } : null;
@@ -1037,7 +1058,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
1037
1058
  // hub-246: --waiting-on is repeatable; it replaces the lane's waits.
1038
1059
  const waitingOn = flags["waiting-on"] === undefined ? [] : [flags["waiting-on"]].flat();
1039
1060
  if (waitingOn.some((value) => typeof value !== "string" || !value.trim()))
1040
- 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);
1061
+ throw new CliError("USAGE", "lane heartbeat --waiting-on needs a lane key, owner/repo#n, Q-nnn, DEC-nnnn, release:<pkg>, person:<role> or launch-day", 2);
1041
1062
  const payload = await request("POST", `/api/v1/lanes/${encode(id)}/heartbeat`, { ...(flags.note !== undefined ? { note: flags.note } : {}), ...(waitingOn.length ? { waitingOn } : {}), ...via });
1042
1063
  return { payload, human: (p) => heartbeatText(ref, p, waitingOn.length > 0) };
1043
1064
  }
@@ -4,7 +4,7 @@
4
4
  // when that copy is behind, `doctor` reports it, and `harness update` installs
5
5
  // the latest release over it. A failed lookup says nothing and blocks nothing.
6
6
  import { execFile } from "node:child_process";
7
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
7
+ import { access, constants, mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
8
  import { homedir } from "node:os";
9
9
  import { dirname, isAbsolute, join } from "node:path";
10
10
  import { promisify } from "node:util";
@@ -20,6 +20,21 @@ const runNpm = promisify(execFile);
20
20
  const defaultHome = () => process.env.NODII_DEV_MANAGED_HOME || homedir();
21
21
  const metadataPaths = (home) => [managedClaudeHooksDir(home), managedHooksDir(home)].map((dir) => join(dir, "metadata.json"));
22
22
  const readJson = async (read, path) => { try { return JSON.parse(await read(path, "utf8")); } catch { return null; } };
23
+ // npm writes under <prefix>/lib/node_modules and <prefix>/bin, creating what
24
+ // is missing: the deepest of those, or of the prefix's parents, that exists decides.
25
+ const canWrite = async (prefix) => {
26
+ for (let dir = join(prefix, "lib/node_modules"); ; dir = dirname(dir)) {
27
+ try { await access(dir, constants.F_OK); } catch { if (dir === dirname(dir)) return false; continue; }
28
+ try { await access(dir, constants.W_OK); return true; } catch { return false; }
29
+ }
30
+ };
31
+ /**
32
+ * Where a root-free install goes when the global prefix is root's (system node
33
+ * on Linux, or a root-owned file under a Homebrew prefix): ~/.local. Its bin
34
+ * is not on PATH by default on macOS, and not always on Linux, so a move tells
35
+ * the person to put it first on PATH (harness.js).
36
+ */
37
+ export const userPrefix = (home) => join(home, ".local");
23
38
 
24
39
  const triple = (version) => {
25
40
  const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(version ?? ""));
@@ -87,24 +102,88 @@ export const managedBehindText = ({ version, latest }) =>
87
102
  * after an install or `{ cliPath, version, current: true }` with nothing to do.
88
103
  * Throws when it could not install; the caller reports that and carries on.
89
104
  */
90
- export async function installManagedLatest({ system = false, runningCli = null, home = defaultHome(), exec = runNpm, read = readFile, write = writeFile, now = Date.now } = {}) {
105
+ export async function installManagedLatest({ system = false, runningCli = null, home = defaultHome(), exec = runNpm, read = readFile, write = writeFile, now = Date.now, writable = canWrite } = {}) {
91
106
  const copy = await managedCopy({ home, read });
92
107
  if (!copy && !system) return null;
93
108
  const latest = await latestRelease({ home, exec, read, now, fresh: true });
94
109
  if (!latest) throw new Error(`could not read the latest ${PACKAGE} release from npm`);
95
- const prefix = await installPrefix({ copy, system, runningCli, exec });
110
+ const wanted = await installPrefix({ copy, system, runningCli, exec });
111
+ const installedAt = (prefix) => readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
112
+ const isCurrent = (found) => Boolean(found?.version) && !isBehind(found.version, latest);
113
+ // Install never asks for root (O3 item 1, CLI-15): a prefix this user cannot
114
+ // write moves the managed copy to ~/.local, and every hook follows it. A copy
115
+ // already current where it is stays there: nothing to install, nothing to move.
116
+ const local = userPrefix(home);
117
+ let prefix = wanted;
118
+ let installed = await installedAt(wanted);
119
+ if (!isCurrent(installed) && wanted !== local && !(await writable(wanted))) {
120
+ prefix = local;
121
+ installed = await installedAt(local);
122
+ }
123
+ const current = isCurrent(installed);
124
+ if (!current) {
125
+ const install = (at) => exec("npm", ["install", "-g", `${PACKAGE}@${latest}`, "--prefix", at], { timeout: INSTALL_TIMEOUT_MS });
126
+ try {
127
+ await install(prefix);
128
+ } catch (error) {
129
+ if (!isPermissionError(error)) throw error;
130
+ // The prefix looked writable but npm was refused (a root-owned @nodii/dev
131
+ // or bin/nodii-dev under it): try ~/.local once before calling it a root need.
132
+ if (prefix === local) { await recordNeedsRoot(home, true, now); throw error; }
133
+ prefix = local;
134
+ installed = await installedAt(local);
135
+ try { await install(local); } catch (retry) {
136
+ if (isPermissionError(retry)) await recordNeedsRoot(home, true, now);
137
+ throw retry;
138
+ }
139
+ }
140
+ const after = await installedAt(prefix);
141
+ if (after?.version !== latest) throw new Error(`npm finished but ${prefix}/lib/node_modules/@nodii/dev/bin/nodii-dev is at ${after?.version ?? "no version"}, not ${latest}`);
142
+ }
96
143
  const cliPath = `${prefix}/lib/node_modules/@nodii/dev/bin/nodii-dev`;
97
- const installed = await readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
98
- if (installed?.version && !isBehind(installed.version, latest)) return { cliPath, version: installed.version, current: true };
99
- await exec("npm", ["install", "-g", `${PACKAGE}@${latest}`, "--prefix", prefix], { timeout: INSTALL_TIMEOUT_MS });
100
- const after = await readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
101
- if (after?.version !== latest) throw new Error(`npm finished but ${cliPath} is at ${after?.version ?? "no version"}, not ${latest}`);
102
- // The dispatcher's version check reads this (MW5-6), so it follows the copy.
144
+ const movedFrom = copy && copy.cliPath !== cliPath ? copy.cliPath : null;
145
+ const version = current ? installed.version : latest;
146
+ await recordNeedsRoot(home, false, now);
147
+ // The dispatcher's version check reads this (MW5-6), so it follows the copy;
148
+ // a moved copy rewrites cliPath too, and the dispatcher refresh follows it.
103
149
  for (const path of metadataPaths(home)) {
104
150
  const metadata = await readJson(read, path);
105
- if (metadata?.cliPath === cliPath) await write(path, `${JSON.stringify({ ...metadata, cliVersion: latest }, null, 2)}\n`, { mode: 0o600 });
151
+ if (metadata?.cliPath === cliPath || (movedFrom && metadata?.cliPath === movedFrom))
152
+ await write(path, `${JSON.stringify({ ...metadata, cliPath, cliVersion: version }, null, 2)}\n`, { mode: 0o600 });
106
153
  }
107
- return { cliPath, version: latest, previous: installed?.version ?? null };
154
+ const moved = movedFrom ? { movedFrom } : {};
155
+ return current ? { cliPath, version, current: true, ...moved } : { cliPath, version, previous: installed?.version ?? null, ...moved };
156
+ }
157
+
158
+ // MW5-8.1 (O3 item 4): whether this machine's managed install needs root. A
159
+ // permission refusal at ~/.local (the fallback, tried once after a refusal
160
+ // anywhere else) records true; any install that lands, or finds the copy current,
161
+ // records false. The watchdog sweep reports it as host_facts.needsRoot.
162
+ export const needsRootPath = (home = defaultHome()) => join(home, ".config/nodii-dev/needs-root.json");
163
+ const PERMISSION = /\bEACCES\b|\bEPERM\b|permission denied|operation not permitted/i;
164
+ export const isPermissionError = (error) =>
165
+ PERMISSION.test(`${error?.code ?? ""} ${error?.message ?? ""} ${error?.stderr ?? ""}`);
166
+ async function recordNeedsRoot(home, needsRoot, now) {
167
+ try {
168
+ const path = needsRootPath(home);
169
+ await mkdir(dirname(path), { recursive: true });
170
+ const temporary = `${path}.${process.pid}`;
171
+ await writeFile(temporary, `${JSON.stringify({ needsRoot, at: new Date(now()).toISOString() })}\n`);
172
+ await rename(temporary, path);
173
+ } catch { /* best effort */ }
174
+ }
175
+ /** What the last managed install found: true, false, or null with no record. */
176
+ export async function readNeedsRoot({ home = defaultHome(), read = readFile } = {}) {
177
+ const saved = await readJson(read, needsRootPath(home));
178
+ return typeof saved?.needsRoot === "boolean" ? saved.needsRoot : null;
179
+ }
180
+
181
+ /** The script a machine job (watchdog, coordinator watch) runs: the managed copy's, so `harness update` moves the job with it. */
182
+ export async function managedEntry({ home = defaultHome(), read = readFile } = {}) {
183
+ const copy = await managedCopy({ home, read });
184
+ if (!copy) return null;
185
+ const entry = join(dirname(dirname(copy.cliPath)), "dist/nodii-dev.js");
186
+ try { await access(entry, constants.R_OK); return entry; } catch { return null; }
108
187
  }
109
188
 
110
189
  async function installPrefix({ copy, system, runningCli, exec }) {
package/dist/nodii-dev.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { fail, main } from "./cli.js";
3
+ import { callSourceFor, setCallSource } from "./core.js";
3
4
  import { regroundCurrentLane, shouldReground } from "./freeze.js";
4
5
  import { isHookDenial } from "./hooks.js";
5
6
  import { laneReadCache } from "./read-cache.js";
@@ -23,6 +24,7 @@ async function run() {
23
24
  // AGENT-HARNESS-19: this is the executable boundary, so every ordinary CLI
24
25
  // invocation re-grounds without adding hidden requests to library callers.
25
26
  // cli-134: through the lane read cache, at most once per 15 seconds.
27
+ setCallSource(callSourceFor(argv));
26
28
  if (shouldReground(argv)) await regroundCurrentLane({}, { cache: laneReadCache() });
27
29
  await main(argv);
28
30
  }
@@ -141,3 +141,21 @@ export function toolCallChild(table, runtimePid, { helperWindowMs = HELPER_WINDO
141
141
  const names = (named.length ? named : all).filter((name, index, list) => name !== list[index - 1]);
142
142
  return { pid: call.pid, names: `${names.slice(0, MAX_NAMES).join(" › ")}${names.length > MAX_NAMES ? " › …" : ""}`, elapsedMs: call.elapsedMs };
143
143
  }
144
+
145
+ // O3 item 6 (DEC-0569, MW1-36.5): a steward session is its Claude or Codex runtime.
146
+ const RUNTIME_NAME = /^(?:claude|codex)(?:$|[-_.])/i;
147
+ const RUNTIME_SCRIPT = /[/\\](?:@anthropic-ai[/\\]claude-code|@openai[/\\]codex)[/\\]/i;
148
+ export const isRuntimeCommand = (argv) =>
149
+ RUNTIME_NAME.test(baseName(argv?.[0])) || (RUNNERS.has(baseName(argv?.[0])) && RUNTIME_SCRIPT.test(String(argv?.[1] ?? "")));
150
+
151
+ /** The first ancestor of `pid` (not itself) whose command is the Claude or Codex runtime; null when none is. */
152
+ export function runtimeAncestor(table, pid) {
153
+ const byPid = new Map((table ?? []).map((entry) => [entry.pid, entry]));
154
+ let entry = byPid.get(byPid.get(pid)?.ppid);
155
+ for (let depth = 0; entry && depth < 32; depth += 1) {
156
+ if (!entry.zombie && isRuntimeCommand(entry.argv)) return entry;
157
+ if (entry.ppid === entry.pid) break;
158
+ entry = byPid.get(entry.ppid);
159
+ }
160
+ return null;
161
+ }
@@ -0,0 +1,77 @@
1
+ // O3 item 9 (MW1-115, DEC-0569): `nodii-dev ruling file --text TEXT`.
2
+ //
3
+ // Any session files a ruling in the turn it was typed. The proof is the
4
+ // prompt hook's own record of the turn (session-kind.js recordTurn), kept on
5
+ // this machine and never sent: the text must be an exact substring of that
6
+ // turn's prompt, else RULING_NOT_TYPED and nothing is sent. Only the ruling's
7
+ // own words leave the machine; it binds nothing until sorted and uploaded.
8
+ import { CliError, devRequest } from "./core.js";
9
+ import { readTurns } from "./session-kind.js";
10
+
11
+ /** A ruling must be filed in the turn it was typed; a turn older than this is not that turn. */
12
+ export const TURN_WINDOW_MS = 30 * 60_000;
13
+ /** A ruling is a sentence, not a fragment: at least this many words and characters, and at most RULING_MAX_CHARS. */
14
+ export const RULING_MIN_WORDS = 3;
15
+ export const RULING_MIN_CHARS = 12;
16
+ export const RULING_MAX_CHARS = 4000;
17
+ const USAGE = "ruling file --text - (the person's exact words on stdin, as typed this turn: --text - <<'EOF' ... EOF), or --text 'WORDS' in single quotes";
18
+
19
+ /** The words as the turn holds them: byte for byte, else with the surrounding whitespace trimmed; null when not typed. */
20
+ export function typedForm(prompt, text) {
21
+ if (prompt.includes(text)) return text;
22
+ const trimmed = text.trim();
23
+ return trimmed && trimmed !== text && prompt.includes(trimmed) ? trimmed : null;
24
+ }
25
+
26
+ /** The session this command runs in, as the runtime names it; null when it does not. */
27
+ export const sessionOf = (env = process.env) => env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || null;
28
+
29
+ /**
30
+ * The turn that typed the text: the session's own (CLAUDE_SESSION_ID or
31
+ * CLAUDE_CODE_SESSION_ID), within the window. No session id, or no turn the
32
+ * hook recorded for it, is no proof: another session's turn never stands in.
33
+ */
34
+ export function typingTurn(turns, text, { env = process.env, now = Date.now() } = {}) {
35
+ const session = sessionOf(env);
36
+ if (!session) return null;
37
+ const own = turns.filter((turn) => {
38
+ const at = Date.parse(turn.at);
39
+ return turn.sessionId === session && Number.isFinite(at) && now - at <= TURN_WINDOW_MS && at - now <= 60_000;
40
+ });
41
+ const holding = own
42
+ .map((turn) => ({ turn, text: typedForm(turn.prompt, text) }))
43
+ .filter((match) => match.text !== null)
44
+ .sort((a, b) => Date.parse(b.turn.at) - Date.parse(a.turn.at));
45
+ return holding[0] ?? null;
46
+ }
47
+
48
+ async function readStdin(stream = process.stdin) {
49
+ const chunks = [];
50
+ for await (const chunk of stream) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
51
+ return Buffer.concat(chunks).toString("utf8");
52
+ }
53
+
54
+ export async function rulingCommand(action, args, flags, { request = devRequest, turns = readTurns, env = process.env, now = Date.now, stdin = readStdin } = {}) {
55
+ if (action !== "file" || args.length) throw new CliError("USAGE", USAGE, 2);
56
+ // `--text -` reads the exact bytes from stdin; a heredoc's own closing newline is not the person's.
57
+ const text = flags.text === "-" ? String(await stdin()).replace(/\r?\n$/, "") : flags.text;
58
+ if (typeof text !== "string" || !text.trim()) throw new CliError("USAGE", USAGE, 2);
59
+ const words = text.trim();
60
+ if (words.length < RULING_MIN_CHARS || words.split(/\s+/).length < RULING_MIN_WORDS || words.length > RULING_MAX_CHARS)
61
+ throw new CliError("USAGE", `A ruling is the person's whole instruction: at least ${RULING_MIN_WORDS} words and ${RULING_MIN_CHARS} characters, at most ${RULING_MAX_CHARS}. ${USAGE}`, 2);
62
+ const match = typingTurn(await turns(), text, { env, now: now() });
63
+ if (!match)
64
+ throw new CliError("RULING_NOT_TYPED", sessionOf(env)
65
+ ? "This session's prompt hook did not see these words typed in its current turn (within 30 minutes), so nothing was sent. File only the person's exact words, in the turn they typed them (MW1-115)."
66
+ : "This command does not know its session (no CLAUDE_SESSION_ID or CLAUDE_CODE_SESSION_ID), so no turn proves these words were typed and nothing was sent (MW1-115).", 2);
67
+ const payload = await request("POST", "/api/v1/rulings", { text: match.text, sessionId: match.turn.sessionId, typedAt: match.turn.at });
68
+ return {
69
+ payload,
70
+ human: (p) => {
71
+ const r = p?.data ?? {};
72
+ return [`Ruling ${r.id ?? "(no id)"} filed verbatim (MW1-115); it binds nothing until sorted and uploaded.`,
73
+ ` person ${r.personId ?? "?"} · session ${r.sessionId ?? match.turn.sessionId} · typed ${r.typedAt ?? match.turn.at} · filed ${r.filedAt ?? "?"}`,
74
+ ` "${r.text ?? match.text}"`].join("\n");
75
+ },
76
+ };
77
+ }
package/dist/safety.js CHANGED
@@ -1185,7 +1185,9 @@ export const codexSafetyHooksSnippet = () => ({
1185
1185
  });
1186
1186
 
1187
1187
  // The compact entry re-grounds the Freeze; the other entry prints the session
1188
- // kind on every other start, and the first prompt confirms it (MW1-92). Two
1188
+ // kind on every other start, and the first prompt confirms it (MW1-92). The
1189
+ // prompt hook runs every prompt: it keeps the turn locally as ruling file's
1190
+ // proof and asks the session to file the person's rules (MW1-115). Two
1189
1191
  // entries, so a repository already carrying the compact one gains only the new.
1190
1192
  export const regroundingHooksSnippet = () => ({
1191
1193
  hooks: {
@@ -8,12 +8,16 @@
8
8
  // with no branch or worktree, so it reuses lane Gather, Freeze and the
9
9
  // post-compaction re-grounding. Every entry point fails open: no Dev, no
10
10
  // sign-in or an unknown payload ends in the operator-assistant reading.
11
+ // Every prompt (O3 items 8 and 9, MW1-115, DEC-0569) also keeps the turn on
12
+ // this machine as `ruling file`'s proof and shows a steward its unread lane
13
+ // messages from its local inbox file.
14
+ import { createHash } from "node:crypto";
11
15
  import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
12
16
  import { basename, dirname, join } from "node:path";
13
17
  import { CliError, configPath, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
14
18
  import { currentLane, regroundLane } from "./freeze.js";
15
19
  import { coordinatorGatherPayload, gatherText } from "./gather.js";
16
- import { laneAsksOn } from "./lane-asks.js";
20
+ import { stewardInboxContext } from "./lane-messages.js";
17
21
  import { managedBehindText } from "./managed-version.js";
18
22
 
19
23
  export const SESSION_KINDS = ["lane", "coordinator", "steward", "operator_assistant"];
@@ -132,7 +136,7 @@ export async function kindContract(resolved, { request = devRequest, env = proce
132
136
  },
133
137
  coordinator: () => [
134
138
  // What lanes wait on this coordinator for comes before its next action (MW1-12.6, MW1-12.7; DEC-0486).
135
- `First, before your next action: \`nodii-dev coordinator items\` lists what lanes wait on you for, each with its command (\`nodii-dev lane leeway grant|refuse ID\`, ${laneAsksOn(env) ? "\`nodii-dev lane answer ID --text TEXT\`, " : ""}\`nodii-dev lane defer ID --reason TEXT\`). \`lane leeway grant\` asks for no TOTP code; the rule is in Dev: \`nodii-dev rules show MW1-12.7\`.`,
139
+ `First, before your next action: \`nodii-dev coordinator items\` lists what lanes wait on you for, each with its command (\`nodii-dev lane leeway grant|refuse ID\`, \`nodii-dev lane defer ID --reason TEXT\`). \`lane leeway grant\` asks for no TOTP code; the rule is in Dev: \`nodii-dev rules show MW1-12.7\`.`,
136
140
  // The rule is MW1-38.15 in Dev's rulebook (`nodii-dev rules show MW1-38.15`); this line only names the command's default.
137
141
  "MW1-38.15: `lane launch` gives a lane 4 subagent slots unless `--subagents N` says otherwise (fewer lanes, subagents fanned out inside each).",
138
142
  "Next: `nodii-dev lane list` for this machine's lanes.",
@@ -162,11 +166,13 @@ async function stewardClauseMap(steward, request) {
162
166
  }
163
167
 
164
168
  /** Plain text for SessionStart: the kind, its contract and, where it has one, its stored contract. */
165
- export async function sessionStartText(payload, { managed = async () => null, request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, state = writeKindState } = {}) {
169
+ export async function sessionStartText(payload, { managed = async () => null, request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, state = writeKindState, runtimePid = sessionRuntimePid } = {}) {
166
170
  const cwd = payload?.cwd ?? process.cwd();
167
171
  const compact = payload?.source === "compact";
168
172
  const resolved = { ...(await dev({ cwd, env }, { request, config })), notes: [] };
169
- await state(payload?.session_id, { kind: resolved.kind, source: resolved.source }).catch(() => {});
173
+ // The runtime's pid lets `steward register` find this session's state when no session id reaches it.
174
+ const pid = await Promise.resolve().then(runtimePid).catch(() => null);
175
+ await state(payload?.session_id, { kind: resolved.kind, source: resolved.source, ...stewardKeyOf(resolved), ...(pid ? { runtimePid: pid } : {}) }).catch(() => {});
170
176
  const parts = [await kindText(resolved, { request })];
171
177
  const copy = await managed().catch(() => null);
172
178
  if (copy?.behind) parts[0] = `${managedBehindText(copy)}\n${parts[0]}`;
@@ -215,7 +221,7 @@ export async function firstPromptText(payload, { request = devRequest, config =
215
221
  if (before?.prompted) return null;
216
222
  const prompt = kindFromPrompt(payload?.prompt);
217
223
  const resolved = resolveKind(await dev({ cwd: payload?.cwd ?? process.cwd(), env }, { request, config }), prompt);
218
- await state(session, { kind: resolved.kind, source: resolved.source, prompted: true }).catch(() => {});
224
+ await state(session, { kind: resolved.kind, source: resolved.source, prompted: true, ...stewardKeyOf(resolved) }).catch(() => {});
219
225
  // SessionStart already printed this kind and nothing disagrees: say so in one line.
220
226
  if (before?.kind === resolved.kind && !resolved.notes.length)
221
227
  return prompt ? `Session kind: ${KIND_LABEL[resolved.kind]} (MW1-92), confirmed by the first prompt.` : null;
@@ -225,8 +231,107 @@ export async function firstPromptText(payload, { request = devRequest, config =
225
231
  return text;
226
232
  }
227
233
 
228
- const stateDir = () => join(dirname(configPath()), STATE_DIR);
229
- const statePath = (session) => join(stateDir(), `${String(session).replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
234
+ // The steward's lane key is its inbox key (NODII-DEV-CLI-191), read on every turn without a Dev call (O3 item 8).
235
+ const stewardKeyOf = (resolved) => (resolved.kind === "steward" && resolved.steward?.key ? { stewardKey: resolved.steward.key } : {});
236
+
237
+ /**
238
+ * O3 item 9 (MW1-115): every prompt, the hook keeps the turn on this machine
239
+ * only, so `ruling file` can prove its words were typed in it. One file per
240
+ * session, overwritten each turn; it is never sent.
241
+ */
242
+ export const RULING_LINE = "nodii-dev: if the person's message gives an instruction or rule about how work is done, file it verbatim this turn, their exact words on stdin: `nodii-dev ruling file --text - <<'EOF'`, the words, then `EOF` on its own line; or `--text '<their exact words>'` in single quotes (MW1-115). File nothing else.";
243
+
244
+ /** A lane session (a lane run or a lane config) files no rulings, so its turns are not kept. */
245
+ const isLaneSession = (env) => Boolean(env.NODII_DEV_RUN_ID) || isLaneConfig(env);
246
+
247
+ /** UserPromptSubmit, every prompt: record the turn, the first prompt's kind, a steward's unread messages, the ruling line. */
248
+ export async function promptTurnText(payload, { env = process.env, turn = recordTurn, readState = readKindState, inbox = stewardInboxContext, first = firstPromptText, runtimePid = sessionRuntimePid, watched = watchedStewards, ...deps } = {}) {
249
+ const session = payload?.session_id;
250
+ // The ruling line asks only for what this turn's record can prove (review of #505).
251
+ const recorded = isLaneSession(env) ? null : await turn(session, payload?.prompt).catch(() => null);
252
+ const kind = await first(payload, { env, readState, ...deps }).catch(() => null);
253
+ // O3 item 8: a steward session sees its deliveries at its next turn, from its local inbox file alone.
254
+ const state = await readState(session).catch(() => null);
255
+ // Only the session the steward run watches reads its inbox: another session of the same agent would consume it (review of #505).
256
+ const mail = state?.kind === "steward" && state.stewardKey && !isLaneConfig(env) && (await isWatchedSteward(state.stewardKey, { runtimePid, watched }))
257
+ ? await inbox(state.stewardKey, { env }).catch(() => null) : null;
258
+ return [kind, mail, recorded ? RULING_LINE : null].filter(Boolean).join("\n\n");
259
+ }
260
+
261
+ /** The pid of the Claude or Codex runtime this process runs under, or null. */
262
+ export async function sessionRuntimePid({ pid = process.pid } = {}) {
263
+ const tree = await import("./process-tree.js");
264
+ return tree.runtimeAncestor(tree.processTable(), pid)?.pid ?? null;
265
+ }
266
+
267
+ /** The watched steward runs on this machine: [{ steward, pid }]. */
268
+ async function watchedStewards() {
269
+ const { readWatchedRuns } = await import("./watchdog.js");
270
+ return (await readWatchedRuns()).records.filter((record) => record.steward).map(({ steward, pid }) => ({ steward, pid }));
271
+ }
272
+
273
+ /** Is this session the one whose runtime the watched run for KEY names? */
274
+ async function isWatchedSteward(key, { runtimePid, watched }) {
275
+ try {
276
+ const records = (await watched()).filter((record) => record.steward === key);
277
+ if (!records.length) return false;
278
+ const pid = await runtimePid();
279
+ return Boolean(pid) && records.some((record) => record.pid === pid);
280
+ } catch { return false; }
281
+ }
282
+
283
+ /**
284
+ * The session `steward register` runs in: CLAUDE_SESSION_ID or
285
+ * CLAUDE_CODE_SESSION_ID, else the session-kinds state whose SessionStart
286
+ * recorded this runtime's pid. Null when neither names one.
287
+ */
288
+ export async function callingSession({ env = process.env, pid = null, dir = stateDir() } = {}) {
289
+ const named = env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID;
290
+ if (named) return String(named);
291
+ if (!pid) return null;
292
+ let found = null;
293
+ for (const name of await readdir(dir).catch(() => [])) {
294
+ if (!name.endsWith(".json") || name.endsWith(TURN_SUFFIX)) continue;
295
+ try {
296
+ const state = JSON.parse(await readFile(join(dir, name), "utf8"));
297
+ if (state?.runtimePid === pid && (!found || Date.parse(state.at) > Date.parse(found.at))) found = { session: name.slice(0, -".json".length), at: state.at };
298
+ } catch {}
299
+ }
300
+ return found?.session ?? null;
301
+ }
302
+
303
+ export const kindStateDir = () => join(dirname(configPath()), STATE_DIR);
304
+ const stateDir = kindStateDir;
305
+ const safeSession = (session) => String(session).replace(/[^A-Za-z0-9_-]/g, "_");
306
+ const statePath = (session) => join(stateDir(), `${safeSession(session)}.json`);
307
+ export const TURN_SUFFIX = ".turn.json";
308
+ export const turnPath = (session, dir = stateDir()) => join(dir, `${safeSession(session)}${TURN_SUFFIX}`);
309
+ export const promptSha256 = (prompt) => createHash("sha256").update(String(prompt), "utf8").digest("hex");
310
+
311
+ /** The session's current turn, {sessionId, promptSha256, prompt, at}, replacing the one before (0600, never sent). */
312
+ export async function recordTurn(session, prompt, { now = Date.now(), dir = stateDir() } = {}) {
313
+ if (!session || typeof prompt !== "string") return null;
314
+ await mkdir(dir, { recursive: true, mode: 0o700 });
315
+ const record = { sessionId: String(session), promptSha256: promptSha256(prompt), prompt, at: new Date(now).toISOString() };
316
+ const path = turnPath(session, dir);
317
+ const temporary = `${path}.${process.pid}.tmp`;
318
+ await writeFile(temporary, `${JSON.stringify(record)}\n`, { mode: 0o600 });
319
+ await rename(temporary, path);
320
+ return record;
321
+ }
322
+
323
+ /** Every session's recorded turn in the state dir; unreadable or altered files are left out. */
324
+ export async function readTurns({ dir = stateDir() } = {}) {
325
+ const turns = [];
326
+ for (const name of await readdir(dir).catch(() => [])) {
327
+ if (!name.endsWith(TURN_SUFFIX)) continue;
328
+ try {
329
+ const turn = JSON.parse(await readFile(join(dir, name), "utf8"));
330
+ if (typeof turn?.prompt === "string" && turn.promptSha256 === promptSha256(turn.prompt) && turn.sessionId && turn.at) turns.push(turn);
331
+ } catch {}
332
+ }
333
+ return turns;
334
+ }
230
335
 
231
336
  export async function readKindState(session) {
232
337
  if (!session) return null;
@@ -250,31 +355,75 @@ export async function writeKindState(session, update, { now = Date.now() } = {})
250
355
  }
251
356
  }
252
357
 
358
+ /**
359
+ * O3 item 6 (DEC-0569, MW1-36.5): the steward session's own long-lived
360
+ * process, the Claude or Codex runtime this CLI runs under. Null when none is
361
+ * found; then no process is sent.
362
+ */
363
+ export async function stewardRuntimeProcess({ pid = process.pid, table, startedAt } = {}) {
364
+ const tree = await import("./process-tree.js");
365
+ const runtime = tree.runtimeAncestor(table ?? tree.processTable(), pid);
366
+ if (!runtime) return null;
367
+ const { processStartedAt } = await import("./watchdog.js");
368
+ const started = startedAt ? await startedAt(runtime.pid) : await processStartedAt(runtime.pid).catch(() => null);
369
+ return started ? { pid: runtime.pid, startedAt: started } : null;
370
+ }
371
+
372
+ const isoOf = (started) => { const at = Date.parse(started); return Number.isFinite(at) ? new Date(at).toISOString() : String(started); };
373
+ const REGISTER_USAGE = "steward register --focus TEXT (--repos R,... | --scratch) [--side frontend|backend|both] [--key KEY] | steward show";
374
+
253
375
  /**
254
376
  * `nodii-dev steward register|show` (MW1-93): a steward is a lane of kind
255
377
  * `steward` with no branch or worktree, started at once on its gather step.
378
+ * `--scratch` (O3 item 12) registers a throwaway steward with no repository,
379
+ * outside the weekly numbers. Registering sends the session's runtime process
380
+ * so Dev reads the steward live or dead from it, and the watchdog sweep
381
+ * watches the run Dev returns (O3 item 6).
256
382
  */
257
- export async function stewardCommand(action, args, flags, { request = devRequest, config = readConfig } = {}) {
383
+ export async function stewardCommand(action, args, flags, { request = devRequest, config = readConfig, runtime = stewardRuntimeProcess, watch = async (record) => (await import("./watchdog.js")).recordWatchedRun(record), env = process.env, findSession = callingSession, state = writeKindState } = {}) {
258
384
  const current = await config();
259
385
  if (action === "show") {
260
386
  const steward = await activeSteward(current.agentId, { request });
261
387
  if (!steward) throw new CliError("STEWARD_NOT_REGISTERED", "This agent has no live steward registration; `nodii-dev steward register --focus TEXT --repos R,...` makes one.", 1);
262
- return { payload: { data: steward }, human: (p) => `${p.data.key} · steward · ${p.data.status}\nFocus: ${focusOf(p.data)}\nRepositories: ${(p.data.repos ?? []).join(", ")}` };
388
+ return { payload: { data: steward }, human: (p) => `${p.data.key} · steward${p.data.scratch ? " (scratch)" : ""} · ${p.data.status}\nFocus: ${focusOf(p.data)}\nRepositories: ${(p.data.repos ?? []).join(", ") || "none"}` };
263
389
  }
264
- if (action !== "register") throw new CliError("USAGE", "steward register --focus TEXT --repos R,... [--side frontend|backend] [--key KEY] | steward show", 2);
390
+ if (action !== "register") throw new CliError("USAGE", REGISTER_USAGE, 2);
265
391
  const focus = String(requireFlag(flags, "focus")).trim();
266
392
  if (!focus) throw new CliError("USAGE", "steward register --focus needs the operator's focus", 2);
267
- const repos = String(requireFlag(flags, "repos")).split(",").map((repo) => repo.trim()).filter(Boolean);
268
- if (!repos.length) throw new CliError("USAGE", "steward register --repos needs at least one repository", 2);
393
+ const scratch = flags.scratch === true || flags.scratch === "true";
394
+ if (flags.scratch !== undefined && !scratch) throw new CliError("USAGE", "steward register --scratch takes no value", 2);
395
+ if (scratch && flags.repos !== undefined) throw new CliError("USAGE", "steward register --scratch works no repository: drop --repos", 2);
396
+ const repos = scratch ? [] : String(requireFlag(flags, "repos")).split(",").map((repo) => repo.trim()).filter(Boolean);
397
+ if (!scratch && !repos.length) throw new CliError("USAGE", "steward register --repos needs at least one repository", 2);
269
398
  const side = flags.side ?? "frontend";
270
399
  if (!["frontend", "backend", "both"].includes(side)) throw new CliError("USAGE", "steward register --side is frontend, backend or both", 2);
271
400
  const agent = (await request("GET", `/api/v1/agents/${encode(current.agentId)}`)).data;
272
401
  if (!agent?.machineId) throw new CliError("MACHINE_REQUIRED", "The current agent is not assigned to a machine.", 1);
273
402
  const key = flags.key ?? `steward-${String(agent.name ?? current.agentId).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || current.agentId.slice(0, 8)}`;
274
403
  await request("POST", "/api/v1/lanes", {
275
- key, title: focus, kind: "steward", side, repos,
404
+ key, title: focus, kind: "steward", side, repos, ...(scratch ? { scratch: true } : {}),
276
405
  agentId: current.agentId, machineId: agent.machineId, issueIds: [], via: "nodii-dev",
277
406
  });
278
- const payload = await request("POST", `/api/v1/lanes/${encode(key)}/start`, { via: "nodii-dev" });
279
- return { payload, human: () => `Registered steward ${key} for: ${focus}\nNext (MW1-94): \`nodii-dev lane gather ${key} --picker agent\`. A new focus is a lane amendment: \`nodii-dev lane amend ${key} --objective "<focus>" --reason TEXT\`.` };
407
+ const session = await runtime().catch(() => null);
408
+ const payload = await request("POST", `/api/v1/lanes/${encode(key)}/start`, {
409
+ via: "nodii-dev", ...(session ? { process: { pid: session.pid, startedAt: isoOf(session.startedAt) } } : {}),
410
+ });
411
+ const runId = payload?.data?.runId ?? payload?.data?.run?.id ?? payload?.runId ?? null;
412
+ let watched = null;
413
+ if (session && runId) {
414
+ try { watched = await watch({ runId, pid: session.pid, processStartedAt: session.startedAt, configPath: configPath(), steward: key }); }
415
+ catch (error) { watched = { error: error?.code ?? "WATCHDOG_RECORD_FAILED" }; }
416
+ }
417
+ // The calling session is the steward from its next prompt: its kind state names the key its hook delivers to (review of #505).
418
+ const caller = await findSession({ env, pid: session?.pid ?? null }).catch(() => null);
419
+ if (caller) await state(caller, { kind: "steward", source: `steward register ${key} in this session`, stewardKey: key }).catch(() => {});
420
+ const liveness = !session
421
+ ? "No Claude or Codex runtime was found above this command, so Dev has no process to read this steward's liveness from."
422
+ : runId && watched && !watched.error
423
+ ? `Liveness: run ${runId}, process ${session.pid}; the watchdog sweep reports it dead when the session ends.`
424
+ : `Liveness: process ${session.pid} sent${runId ? `; the watchdog could not record run ${runId} (${watched?.error ?? "no record"})` : "; Dev returned no run id"}.`;
425
+ return {
426
+ payload: { ...payload, ...(session ? { process: { pid: session.pid, startedAt: session.startedAt } } : {}), ...(watched && !watched.error ? { watched: true } : {}) },
427
+ human: () => `Registered ${scratch ? "scratch " : ""}steward ${key} for: ${focus}\n${liveness}\nNext (MW1-94): \`nodii-dev lane gather ${key} --picker agent\`. A new focus is a lane amendment: \`nodii-dev lane amend ${key} --objective "<focus>" --reason TEXT\`.`,
428
+ };
280
429
  }
package/dist/setup.js CHANGED
@@ -19,7 +19,7 @@ description: Drive every Nodii build lane through nodii-dev from start to verifi
19
19
 
20
20
  Use \`nodii-dev\` as the control plane. It talks only to Dev, through the platform edge, signed in with \`nodii-dev login\` as the platform tenant's OAuth app. The canonical policy is the build-workflow rulebook in Dev (\`nodii-dev rulebook list\`), §§1–8 (operator rulings A-020/A-021). Never change lane state in Dev by another route.
21
21
 
22
- 1. The machine coordinator runs \`nodii-dev coordinator start --machine NAME [--account RUNTIME:PROFILE ...]\` (each model account a lane may run on is registered once; its usage is reported then, before each launch and by the watchdog), then \`nodii-dev lane launch KEY\` with the issue (whose title is the objective), done check, build kind/side, repeated repository/branch pairs, runtime profile/model, and the lane's class (\`--class long|short|no-build\`, weighed against the account's usage band). \`--subagents N\` is optional and defaults to 4 (\`nodii-dev rules show MW1-38.15\`). A launched agent begins with \`nodii-dev lane gather\` from its worktree. Before its next action the coordinator clears what lanes wait on it for: \`nodii-dev coordinator items\` lists each item with its command (\`lane leeway grant|refuse ID\`, \`lane answer ID --text TEXT\`, \`lane defer ID --reason TEXT\`). \`lane leeway grant\` asks for no TOTP code (\`nodii-dev rules show MW1-12.7\`).
22
+ 1. The machine coordinator runs \`nodii-dev coordinator start --machine NAME [--account RUNTIME:PROFILE ...]\` (each model account a lane may run on is registered once; its usage is reported then, before each launch and by the watchdog), then \`nodii-dev lane launch KEY\` with the issue (whose title is the objective), done check, build kind/side, repeated repository/branch pairs, runtime profile/model, and the lane's class (\`--class long|short|no-build\`, weighed against the account's usage band). \`--subagents N\` is optional and defaults to 4 (\`nodii-dev rules show MW1-38.15\`). A launched agent begins with \`nodii-dev lane gather\` from its worktree. Before its next action the coordinator clears what lanes wait on it for: \`nodii-dev coordinator items\` lists each item with its command (\`lane leeway grant|refuse ID\`, \`lane defer ID --reason TEXT\`). \`lane leeway grant\` asks for no TOTP code (\`nodii-dev rules show MW1-12.7\`).
23
23
  2. Re-run \`nodii-dev lane gather\` for the current steps and rules; start, complete, or block the reported API step with \`nodii-dev lane step\`. After an authoritative \`lane amend\`, every run is blocked until its own \`lane gather --delta\` acknowledgement. For a lane blocked on an open issue that no live lane holds, the command is \`nodii-dev lane leeway KEY --blocker ISSUE --reason TEXT\`; Dev refuses a second lane with \`LEEWAY_BLOCKER_HELD\` and names the holder, and \`lane gather --delta\` acknowledges the grant. The rules are in Dev: \`nodii-dev rules show MW1-12.6\` and \`MW1-12.8\`.
24
24
  3. Record durable evidence with \`nodii-dev lane evidence KEY --pr|--commit|--figma|--deploy|--dev-check REF\` and heartbeat long-running work with \`nodii-dev lane heartbeat KEY --note "..."\` (notes are at most 500 characters).
25
25
  4. Before a push or a pull request that changes a command, route, refusal code or hook, run \`nodii-dev repo docs-check\`: it reads the \`toolingDocs\` block of \`nodii.repo.yaml\`, and \`hook tooling-docs\` refuses \`git push\` and \`gh pr create|ready\` with \`TOOLING_DOCS_STALE\` on the same finding. The rule is in Dev: \`nodii-dev rules show MW1-46.3\`.
package/dist/starting.js CHANGED
@@ -985,8 +985,8 @@ export async function currentMarker(run = execFile, load = loadJson, env = proce
985
985
  return { ...marker, runId };
986
986
  }
987
987
 
988
- // An amendment, a leeway, a question and its answer or deferral, and a lane message change no brief by themselves.
989
- const GUARD_EXEMPT_LANE_ACTIONS = new Set(["amend", "leeway", "ask", "asks", "answer", "defer", "message", "inbox"]);
988
+ // An amendment, a leeway or its deferral, and a lane message change no brief by themselves.
989
+ const GUARD_EXEMPT_LANE_ACTIONS = new Set(["amend", "leeway", "defer", "message", "inbox"]);
990
990
 
991
991
  /**
992
992
  * MW1-12.9: what a lane hook tells a long-running session about an amendment