@nodii/dev 0.6.60 → 0.6.61

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
@@ -908,6 +908,7 @@ exits 0 only when every check is `OK`. `--json` returns the same checks as
908
908
  | `figma_scopes` | With `figma_file`, when the file is registered: the change set this agent holds in the file and its lock scopes (or the whole file), or that it holds none (DEC-0032). |
909
909
  | `hooks_claude` | Whether Claude hooks are installed, trusted by that runtime, and have a private firing receipt. |
910
910
  | `hooks_codex_personal`, `hooks_codex_work` | For `~/.codex` and `~/.codex-work`, whether Codex's own hook registry reports the hooks installed and trusted (including managed status), whether the managed absolute CLI is present and new enough, and whether that profile has fired one. |
911
+ | `lane_env` | Every `claude` and `codex` process whose working directory is in an active lane's worktree on this machine, and whether its environment carries `NODII_DEV_CONFIG_PATH` naming that lane's `lane-<key>.json`. The managed hooks exit without acting for a process without it (AGENT-HARNESS-61). Run inside a lane, it checks that lane only. `MISSING` names each process; `lane launch` and `lane resume` start the agent with the variable set. `lane check` prints the same report for its lane as `lane_env:` lines, without blocking the review. |
911
912
 
912
913
  Doctor may refresh the access token, as any command does. The permission table
913
914
  is kept by hand from Dev's route policy until Dev's OpenAPI names each
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.60";
7
+ export const VERSION = "0.6.61";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/doctor.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
- import { join } from "node:path";
3
+ import { basename, join } from "node:path";
4
4
  import { devRequest, encode, isOAuthConfig, query, setAuthProvider } from "./core.js";
5
5
  import { OAuthAuthProvider, decodeClaims, loadRefreshToken } from "./oauth.js";
6
6
  import { inferGitContext, repoName } from "./lanes.js";
@@ -8,6 +8,7 @@ import { figmaFileKey, figmaLockCheck, holdsSet, notRegisteredHint, scopeText }
8
8
  import { EMBED_MODEL, EMBED_MODEL_DIGEST, EMBED_PIN, PICKER_CONTEXT, PICKER_MODEL, PICKER_MODEL_DIGEST, STALE_PIN_HINT, inspectOllama } from "./gather.js";
9
9
  import { hookDiagnostics } from "./hook-doctor.js";
10
10
  import { listAccounts } from "./accounts.js";
11
+ import { LANE_ENV_FIX, agentProcesses, laneConfigName, laneEnvProblem, laneEnvReport } from "./lane-env.js";
11
12
 
12
13
  /**
13
14
  * What a lane's commands need, in Dev's route policy (staffRuleFor in Dev's
@@ -335,6 +336,37 @@ export async function doctorCommand(deps = {}) {
335
336
  checks.push(cannot("hooks_codex", error?.message ?? String(error)));
336
337
  }
337
338
 
339
+ // 11. Lane processes: every agent working in an active lane's worktree on
340
+ // this machine runs with NODII_DEV_CONFIG_PATH naming that lane's config, or
341
+ // the managed hooks exit without acting for it (AGENT-HARNESS-61). Inside a
342
+ // lane, only that lane is checked.
343
+ if (!agent?.machineId) checks.push(cannot("lane_env", "needs a machine"));
344
+ else {
345
+ try {
346
+ const lanes = [];
347
+ for (const status of ACTIVE) {
348
+ let cursor;
349
+ do {
350
+ const page = await request("GET", `/api/v1/lanes${query({ machine: agent.machineId, status, cursor, limit: 200 })}`);
351
+ lanes.push(...(page.data ?? []));
352
+ cursor = page.nextCursor ?? undefined;
353
+ } while (cursor);
354
+ }
355
+ const own = lanes.filter((x) => laneConfigName(x.key) === basename(env.NODII_DEV_CONFIG_PATH ?? ""));
356
+ const scope = (own.length ? own : lanes).map((x) => ({ key: x.key, worktrees: [x.worktree, ...(x.repositories ?? []).map((r) => r.worktree)] }));
357
+ const report = await laneEnvReport(scope, { processes: deps.agentProcesses ?? agentProcesses });
358
+ const bad = report.filter((x) => x.state === "missing" || x.state === "other");
359
+ const unreadable = report.filter((x) => x.state === "unreadable");
360
+ const extra = { lanes: scope.map((x) => x.key), processes: report };
361
+ const what = own.length ? `lane ${own[0].key}` : `${scope.length} active lane(s) on this machine`;
362
+ if (bad.length) checks.push(missing("lane_env", `managed hooks cannot act for ${bad.map(laneEnvProblem).join("; ")}`, LANE_ENV_FIX, extra));
363
+ else if (unreadable.length) checks.push(cannot("lane_env", unreadable.map(laneEnvProblem).join("; "), extra));
364
+ else checks.push(ok("lane_env", `${report.length} agent process(es) in ${what} carry their lane config`, extra));
365
+ } catch (error) {
366
+ checks.push(cannot("lane_env", error?.code ? devReason(error) : (error?.message ?? String(error))));
367
+ }
368
+ }
369
+
338
370
  const ready = checks.every((x) => x.status === "ok");
339
371
  const width = Math.max(...checks.map((x) => x.key.length));
340
372
  const human = (p) => [
@@ -0,0 +1,114 @@
1
+ import { execFile as execFileCallback } from "node:child_process";
2
+ import { readFile, readdir, readlink, realpath } from "node:fs/promises";
3
+ import { basename, sep } from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const execFile = promisify(execFileCallback);
7
+ const RUNTIMES = new Set(["claude", "codex"]);
8
+ const CONFIG_VAR = "NODII_DEV_CONFIG_PATH=";
9
+
10
+ /**
11
+ * The file name of a lane's own Dev config. `lane launch` provisions it, and
12
+ * the managed hooks act only for a session whose NODII_DEV_CONFIG_PATH names
13
+ * one (AGENT-HARNESS-59, AGENT-HARNESS-61).
14
+ */
15
+ export const laneConfigName = (key) => `lane-${String(key).toLowerCase().replaceAll(/[^a-z0-9_-]/g, "-")}.json`;
16
+
17
+ // A command that exits non-zero (lsof or ps after a process vanished) still
18
+ // printed the rest.
19
+ const run = async (command, args) => {
20
+ try {
21
+ return (await execFile(command, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 })).stdout;
22
+ } catch (error) {
23
+ if (typeof error?.stdout === "string" && error.stdout) return error.stdout;
24
+ throw error;
25
+ }
26
+ };
27
+
28
+ const configFrom = (vars) => vars.findLast((item) => item.startsWith(CONFIG_VAR))?.slice(CONFIG_VAR.length) || null;
29
+
30
+ async function darwinProcesses(exec) {
31
+ const found = (await exec("ps", ["-axo", "pid=,comm="])).split("\n")
32
+ .map((line) => line.trim().match(/^(\d+)\s+(.+)$/))
33
+ .filter((match) => match && RUNTIMES.has(basename(match[2])))
34
+ .map((match) => ({ pid: Number(match[1]), runtime: basename(match[2]) }));
35
+ if (!found.length) return [];
36
+ const pids = found.map((x) => x.pid).join(",");
37
+ const cwds = new Map();
38
+ let pid = null;
39
+ for (const line of (await exec("lsof", ["-a", "-d", "cwd", "-Fpn", "-p", pids])).split("\n")) {
40
+ if (line.startsWith("p")) pid = Number(line.slice(1));
41
+ else if (line.startsWith("n") && pid) cwds.set(pid, line.slice(1));
42
+ }
43
+ // `ps -E` appends the process's starting environment to its arguments, so
44
+ // the environment is what follows the arguments: a prompt that spells out
45
+ // NODII_DEV_CONFIG_PATH is not the variable. A process whose environment ps
46
+ // may not read shows no PATH at all.
47
+ const lines = async (args) => new Map((await exec("ps", [...args, "-ww", "-o", "pid=,command=", "-p", pids])).split("\n")
48
+ .map((line) => line.trim().match(/^(\d+) (.*)$/)).filter(Boolean).map((match) => [Number(match[1]), match[2]]));
49
+ const commands = await lines([]);
50
+ const envs = new Map();
51
+ for (const [id, line] of await lines(["-E"])) {
52
+ const command = commands.get(id);
53
+ const words = (command !== undefined && line.startsWith(command) ? line.slice(command.length) : "").split(/\s+/);
54
+ envs.set(id, { readable: words.some((word) => word.startsWith("PATH=")), configPath: configFrom(words) });
55
+ }
56
+ return found.map((x) => ({ ...x, cwd: cwds.get(x.pid) ?? null, ...(envs.get(x.pid) ?? { readable: false, configPath: null }) }));
57
+ }
58
+
59
+ async function linuxProcesses(fs) {
60
+ const found = [];
61
+ for (const name of (await fs.readdir("/proc")).filter((entry) => /^\d+$/.test(entry))) {
62
+ const runtime = (await fs.readFile(`/proc/${name}/comm`, "utf8").catch(() => "")).trim();
63
+ if (!RUNTIMES.has(runtime)) continue;
64
+ const environ = await fs.readFile(`/proc/${name}/environ`, "utf8").catch(() => null);
65
+ found.push({
66
+ pid: Number(name),
67
+ runtime,
68
+ cwd: await fs.readlink(`/proc/${name}/cwd`).catch(() => null),
69
+ readable: environ !== null,
70
+ configPath: environ === null ? null : configFrom(environ.split("\0")),
71
+ });
72
+ }
73
+ return found;
74
+ }
75
+
76
+ /** Every claude and codex process on this machine, with its cwd and its NODII_DEV_CONFIG_PATH. */
77
+ export async function agentProcesses({ platform = process.platform, exec = run, fs = { readdir, readFile, readlink } } = {}) {
78
+ if (platform === "darwin") return darwinProcesses(exec);
79
+ if (platform === "linux") return linuxProcesses(fs);
80
+ throw new Error(`listing agent processes is not supported on ${platform}`);
81
+ }
82
+
83
+ /**
84
+ * Each agent process working in one of these lanes' worktrees, and whether
85
+ * its environment names that lane's config. Lanes are `{ key, worktrees }`.
86
+ * state: ok, missing (no NODII_DEV_CONFIG_PATH), other (names another file)
87
+ * or unreadable (the environment could not be read).
88
+ */
89
+ export async function laneEnvReport(lanes, { processes = agentProcesses, real = (path) => realpath(path).catch(() => path) } = {}) {
90
+ const roots = [];
91
+ for (const lane of lanes)
92
+ for (const worktree of new Set(lane.worktrees.filter(Boolean))) roots.push({ key: lane.key, root: await real(worktree) });
93
+ if (!roots.length) return [];
94
+ const report = [];
95
+ for (const proc of await processes()) {
96
+ if (!proc.cwd) continue;
97
+ const cwd = await real(proc.cwd);
98
+ // The deepest worktree wins, so a lane nested in another's tree is its own.
99
+ const lane = roots.filter(({ root }) => cwd === root || cwd.startsWith(`${root}${sep}`)).sort((a, b) => b.root.length - a.root.length)[0];
100
+ if (!lane) continue;
101
+ const expected = laneConfigName(lane.key);
102
+ const state = !proc.readable ? "unreadable" : !proc.configPath ? "missing" : basename(proc.configPath) === expected ? "ok" : "other";
103
+ report.push({ laneKey: lane.key, pid: proc.pid, runtime: proc.runtime, cwd: proc.cwd, state, configPath: proc.configPath, expected });
104
+ }
105
+ return report.sort((a, b) => a.laneKey.localeCompare(b.laneKey) || a.pid - b.pid);
106
+ }
107
+
108
+ /** One line for a process whose lane hooks stay silent. */
109
+ export const laneEnvProblem = (x) => `${x.laneKey} ${x.runtime} pid ${x.pid}: ${
110
+ x.state === "missing" ? "no NODII_DEV_CONFIG_PATH"
111
+ : x.state === "other" ? `NODII_DEV_CONFIG_PATH names ${x.configPath}, not ${x.expected}`
112
+ : "environment not readable"}`;
113
+
114
+ export const LANE_ENV_FIX = "stop each such process and run `nodii-dev lane resume <key>`: launch and resume run the agent with NODII_DEV_CONFIG_PATH=<config dir>/lane-<key>.json, which the managed hooks need to act";
package/dist/lanes.js CHANGED
@@ -9,6 +9,7 @@ import { storeGatherFreeze } from "./freeze.js";
9
9
  import { doneCheckRecorded } from "./lane-supervisor.js";
10
10
  import { SWAP_BOUNDARIES, componentsForScope, guidelineLookup, laneFigmaScope, loadDsCatalog } from "./figma-scope.js";
11
11
  import { designCheck } from "./design.js";
12
+ import { LANE_ENV_FIX, laneEnvProblem, laneEnvReport } from "./lane-env.js";
12
13
  import { REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, repoGeneratedPaths, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
13
14
 
14
15
  const execFileAsync = promisify(execFile);
@@ -557,6 +558,10 @@ export async function laneCommand(action, args, flags, deps = {}) {
557
558
  }
558
559
  return payload;
559
560
  };
561
+ // One line per agent process in the lane's worktrees (AGENT-HARNESS-61).
562
+ const laneEnvLines = (report) => report.error ? [`lane_env: cannot check: ${report.error}`]
563
+ : report.length ? report.map((x) => `lane_env: ${x.state === "ok" ? `${x.laneKey} ${x.runtime} pid ${x.pid} carries ${x.expected}` : `${laneEnvProblem(x)}; ${LANE_ENV_FIX}`}`)
564
+ : ["lane_env: no agent process found in the lane's worktrees"];
560
565
  const reviewSummary = (p) => {
561
566
  const findings = p.data.findings ?? [];
562
567
  const missed = findings.filter((finding) => finding.missedTrigger === true).length;
@@ -587,13 +592,16 @@ export async function laneCommand(action, args, flags, deps = {}) {
587
592
  ...(checkDeps.reviewer ? { reviewer: checkDeps.reviewer } : {}),
588
593
  ...(checkDeps.now ? { now: checkDeps.now } : {}),
589
594
  });
590
- const lines = checkLines(run.checks, run.maxIterations);
595
+ // AGENT-HARNESS-61: an agent here without the lane's config gets no managed
596
+ // hooks. Reported, never blocking: the check itself cannot fix a process.
597
+ const env = await laneEnvReport([{ key: lane.key ?? ref, worktrees }], checkDeps.processes ? { processes: checkDeps.processes } : {}).catch((error) => ({ error: error?.message ?? String(error) }));
598
+ const lines = [...checkLines(run.checks, run.maxIterations), ...laneEnvLines(env)];
591
599
  // A check still looping records nothing: the agent fixes and reruns (MW2-41).
592
600
  if (!run.body) {
593
601
  await run.saveLoop();
594
602
  const open = run.checks.filter((x) => x.outcome === null).map((x) => x.check);
595
603
  return {
596
- payload: { data: { recorded: false, outcome: "NOT_CLEAN", checks: run.checks } },
604
+ payload: { data: { recorded: false, outcome: "NOT_CLEAN", checks: run.checks, laneEnv: env } },
597
605
  human: [...lines, `run: NOT CLEAN, nothing recorded. Fix the blocking ${open.join(" and ")} finding(s), commit, and rerun nodii-dev lane check ${ref}.`].join("\n"),
598
606
  exitCode: 1,
599
607
  };
@@ -608,7 +616,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
608
616
  await run.saveLoop();
609
617
  const outcome = runOutcome(run.body.checks);
610
618
  return {
611
- payload: { ...payload, reviewFile: file },
619
+ payload: { ...payload, reviewFile: file, laneEnv: env },
612
620
  human: [...lines, `run: ${outcome === "CLEAN" ? "CLEAN" : "NOT CLEAN"}, recorded on ${ref} (${file})`].join("\n"),
613
621
  exitCode: outcome === "CLEAN" ? 0 : 1,
614
622
  };
@@ -4,6 +4,7 @@ import { homedir } from "node:os";
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { configPath } from "./core.js";
7
+ import { laneConfigName } from "./lane-env.js";
7
8
  import { recordWatchedRun } from "./watchdog.js";
8
9
 
9
10
  const RUNTIMES = new Set(["codex", "claude"]);
@@ -21,6 +22,15 @@ const absolutePath = (value, name) => {
21
22
  return value;
22
23
  };
23
24
 
25
+ // The managed hooks act only for a session whose NODII_DEV_CONFIG_PATH names
26
+ // the lane's own config, so a lane never starts on any other (AGENT-HARNESS-61).
27
+ const laneConfig = (value, laneKey, name) => {
28
+ absolutePath(value, name);
29
+ if (basename(value) !== laneConfigName(laneKey))
30
+ throw new TypeError(`${name} must be the lane's own config ${laneConfigName(laneKey)}, not ${basename(value)}: the managed hooks act only for that file`);
31
+ return value;
32
+ };
33
+
24
34
  const printable = (value) => {
25
35
  if (value === undefined || value === null || value === "") return "(none)";
26
36
  if (typeof value === "string") return value;
@@ -59,7 +69,7 @@ function validateLaunch(options) {
59
69
  if (!RUNTIMES.has(runtime)) throw new TypeError("runtime must be codex or claude");
60
70
  const model = requiredText(options?.model, "model");
61
71
  const cwd = absolutePath(options?.cwd, "cwd");
62
- const devConfigPath = absolutePath(options?.devConfigPath, "devConfigPath");
72
+ const devConfigPath = laneConfig(options?.devConfigPath, laneKey, "devConfigPath");
63
73
  const addDirs = options?.addDirs ?? [];
64
74
  if (!Array.isArray(addDirs)) throw new TypeError("addDirs must be an array");
65
75
  for (const [index, path] of addDirs.entries()) absolutePath(path, `addDirs[${index}]`);
@@ -101,7 +111,7 @@ export function buildRecoveryPrompt(data) {
101
111
  /** Build an allowlisted, fresh headless runtime invocation. No prompt is put in argv. */
102
112
  export function buildRecoveryInvocation(data, { env = process.env, home = homedir() } = {}) {
103
113
  const { runId, laneKey, runtime, model, cwd, addDirs } = validateData(data);
104
- const devConfigPath = absolutePath(data?.launch?.devConfigPath, "launch.devConfigPath");
114
+ const devConfigPath = laneConfig(data?.launch?.devConfigPath, laneKey, "launch.devConfigPath");
105
115
  return buildInvocation({ runId, laneKey, runtime, model, cwd, addDirs, profileHome: data.launch.profileHome, devConfigPath }, { env, home });
106
116
  }
107
117
 
@@ -298,7 +308,7 @@ export async function launchRecovery(payload, {
298
308
  } = {}) {
299
309
  const data = dataFrom(payload);
300
310
  const { runId, laneKey, addDirs } = validateData(data);
301
- const devConfigPath = absolutePath(data?.launch?.devConfigPath, "launch.devConfigPath");
311
+ const devConfigPath = laneConfig(data?.launch?.devConfigPath, laneKey, "launch.devConfigPath");
302
312
  const prompt = buildRecoveryPrompt(data);
303
313
  const invocation = buildRecoveryInvocation(data, { env, home });
304
314
  return launchDetached({ invocation, prompt, runId, laneKey, devConfigPath, addDirs }, {
package/dist/safety.js CHANGED
@@ -157,6 +157,10 @@ function segments(command) {
157
157
  return out.filter((x) => x.length);
158
158
  }
159
159
 
160
+ // The word splitter keeps `)` on a word, so `$(cmd 2>/dev/null)` names
161
+ // "/dev/null)". A `)` with no `(` in the word closes a subshell, not the path.
162
+ const closeParen = (target) => (target.includes("(") ? target : target.replace(/\)+$/, ""));
163
+
160
164
  function writeTargets(command) {
161
165
  const targets = [];
162
166
  for (const segment of segments(command)) {
@@ -179,7 +183,7 @@ function writeTargets(command) {
179
183
  else if (mode === "rest") targets.push(...args.slice(1));
180
184
  else targets.push(...args);
181
185
  }
182
- return targets;
186
+ return targets.map(closeParen).filter(Boolean);
183
187
  }
184
188
 
185
189
  function outsideWorktree(target, context, relativeKnown) {
package/dist/starting.js CHANGED
@@ -7,6 +7,7 @@ import { CliError, configPath, devRequest, encode, query, readConfig, requireFla
7
7
  import { assertKnownSets, checkComponentSetKey, checkFileKey, loadDsCatalog, mergeScopes, scopesFromRoutes } from "./figma-scope.js";
8
8
  import { GATHER_TIMEOUT_MS, gatherDeadline } from "./gather.js";
9
9
  import { laneCommand, nextCommand } from "./lanes.js";
10
+ import { laneConfigName } from "./lane-env.js";
10
11
  import { accountFlags, listAccounts, profilePath, registerAccount, reportUsage, usageLine } from "./accounts.js";
11
12
 
12
13
  const execFile = promisify(execFileCallback);
@@ -111,8 +112,7 @@ const stateFile = (machine) => join(dirname(configPath()), `coordinator-${encode
111
112
  export function laneConfigPath(key, current = configPath()) {
112
113
  const configDir = dirname(current);
113
114
  const agentsDir = basename(configDir) === "agents" ? configDir : join(configDir, "agents");
114
- const lane = String(key).toLowerCase().replaceAll(/[^a-z0-9_-]/g, "-");
115
- return join(agentsDir, `lane-${lane}.json`);
115
+ return join(agentsDir, laneConfigName(key));
116
116
  }
117
117
  async function saveJson(file, value, { flag = "w" } = {}) {
118
118
  await mkdir(dirname(file), { recursive: true, mode: 0o700 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.60",
3
+ "version": "0.6.61",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {