@nodii/dev 0.6.101 → 0.6.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -30,6 +30,7 @@ import { isReviewSession } from "./review-session.js";
30
30
  import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks, steerAct, stewardSteerNudges, surfaceGenPre } from "./nudges.js";
31
31
  import { activeSteward, firstPromptText, isLaneConfig, sessionStartText, stewardCommand } from "./session-kind.js";
32
32
  import { doctorCommand } from "./doctor.js";
33
+ import { installManagedLatest, managedStatus } from "./managed-version.js";
33
34
  import { dispatchManagedClaudeHook, dispatchManagedHook } from "./managed-hooks.js";
34
35
  import { governorCommand, laneClose } from "./governor.js";
35
36
  import { freezeCommand } from "./freeze.js";
@@ -863,7 +864,7 @@ export async function main(argv = process.argv.slice(2)) {
863
864
  if (command === "harness" && ["install", "update", "check"].includes(action)) {
864
865
  // `--include-drafts` is a switch: `--include-drafts false` would leave `false` here and turn drafts on.
865
866
  if (rest.length) throw new CliError("USAGE", `harness ${action} takes no arguments, got: ${rest.join(" ")}. Write a flag value as --include-drafts=false.`, 2);
866
- return emitCommand(await harnessCommand(action, f));
867
+ return emitCommand(await harnessCommand(action, f, { installManaged: installManagedLatest }));
867
868
  }
868
869
  if (command === "repo" && ["policy", "lint"].includes(action)) return emitCommand(await repoCommand(action, rest, f));
869
870
  if (command === "watchdog") {
@@ -1523,7 +1524,7 @@ export async function main(argv = process.argv.slice(2)) {
1523
1524
  await recordHookFire(payload).catch(() => {});
1524
1525
  // The session's kind and contract (MW1-92). Fails open: no output on any error.
1525
1526
  if (action === "session-start") {
1526
- const context = await sessionStartText(payload).catch(() => null);
1527
+ const context = await sessionStartText(payload, { managed: managedStatus }).catch(() => null);
1527
1528
  if (context) console.log(context);
1528
1529
  return;
1529
1530
  }
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.101";
7
+ export const VERSION = "0.6.102";
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
@@ -7,6 +7,7 @@ import { inferGitContext, repoName } from "./lanes.js";
7
7
  import { figmaFileKey, figmaLockCheck, holdsSet, notRegisteredHint, scopeText } from "./figma.js";
8
8
  import { EMBED_MODEL, EMBED_MODEL_DIGEST, EMBED_PIN, PICKER_CONTEXT, PICKER_MODEL_ENV, STALE_PIN_HINT, inspectOllama, pickerBuild, pickerModelName, pickerPin, pinDigests, pinnedDigests } from "./gather.js";
9
9
  import { hookDiagnostics } from "./hook-doctor.js";
10
+ import { managedStatus } from "./managed-version.js";
10
11
  import { hostBootedAt } from "./host.js";
11
12
  import { listAccounts } from "./accounts.js";
12
13
  import { LANE_ENV_FIX, agentProcesses, laneConfigName, laneEnvProblem, laneEnvReport } from "./lane-env.js";
@@ -401,6 +402,19 @@ export async function doctorCommand(deps = {}) {
401
402
  }
402
403
  }
403
404
 
405
+ // No managed hooks means no managed copy: the hook checks above report that.
406
+ try {
407
+ const copy = await (deps.managedStatus ?? managedStatus)();
408
+ if (copy) {
409
+ const extra = { cliPath: copy.cliPath, version: copy.version, latest: copy.latest };
410
+ if (!copy.latest) checks.push(cannot("managed_cli", `${copy.cliPath} is ${copy.version}; the latest release could not be read from npm`, extra));
411
+ else if (copy.behind) checks.push(missing("managed_cli", `${copy.cliPath} is ${copy.version}, behind the latest release ${copy.latest}`, "nodii-dev harness update", extra));
412
+ else checks.push(ok("managed_cli", `${copy.cliPath} is ${copy.version}, the latest release`, extra));
413
+ }
414
+ } catch (error) {
415
+ checks.push(cannot("managed_cli", error?.message ?? String(error)));
416
+ }
417
+
404
418
  const ready = checks.every((x) => x.status === "ok");
405
419
  const width = Math.max(...checks.map((x) => x.key.length));
406
420
  const human = (p) => [
package/dist/harness.js CHANGED
@@ -464,7 +464,7 @@ async function checkCommand(root, repo, state, fetchHarness) {
464
464
  };
465
465
  }
466
466
 
467
- export async function harnessCommand(action, flags, { request = devRequest, context = repoContext, managedHome, managedCliPath = fileURLToPath(new URL("../bin/nodii-dev", import.meta.url)), writeManaged = writeManagedHookBundle, writeManagedClaude = writeManagedClaudeHookBundle, refreshManaged = refreshManagedDispatchers, claudeManagedPath = claudeManagedSettingsPath(), readSystem = optional } = {}) {
467
+ export async function harnessCommand(action, flags, { request = devRequest, context = repoContext, managedHome, managedCliPath = fileURLToPath(new URL("../bin/nodii-dev", import.meta.url)), writeManaged = writeManagedHookBundle, writeManagedClaude = writeManagedClaudeHookBundle, refreshManaged = refreshManagedDispatchers, installManaged = async () => null, claudeManagedPath = claudeManagedSettingsPath(), readSystem = optional } = {}) {
468
468
  if (!["install", "update", "check"].includes(action)) throw new CliError("USAGE", "harness install|update|check [--repo NAME] [--service ID] [--include-drafts[=false]] [--adopt PATH,...] [--dry-run] [--check] [--system]", 2);
469
469
  if (flags.fleet || flags.all) throw new CliError("USAGE", "The harness is installed one service at a time, in that service's repository. There is no fleet mode.", 2);
470
470
  if (flags.root === true || flags.repo === true) throw new CliError("USAGE", "--root and --repo need a value.", 2);
@@ -520,13 +520,20 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
520
520
  throw new CliError("HARNESS_CONFLICT",
521
521
  `Nothing written. These files are not nodii-dev's to change:\n${plan.conflicts.map((c) => ` ${c.path}: ${c.reason}`).join("\n")}\n` +
522
522
  "Restore files nodii-dev wrote (git checkout, or remove your edits). For your own files, remove them or let nodii-dev take them over with --adopt PATH[,PATH].", 1, summary);
523
+ // Only the CLI passes a real installer, and only `update` runs it: a dry run
524
+ // changes nothing, and a failed install never fails the harness update.
525
+ const managedCli = action === "update" && !flags["dry-run"]
526
+ ? await installManaged({ system: Boolean(flags.system), runningCli: managedCliPath, ...(managedHome ? { home: managedHome } : {}) }).catch((error) => ({ error: error?.message ?? String(error) }))
527
+ : null;
528
+ const systemCli = managedCli?.cliPath ?? managedCliPath;
529
+ const systemCliVersion = managedCli?.version;
523
530
  const codexChange = plan.changes.find((change) => change.path === ".codex/hooks.json");
524
531
  const codexText = codexChange?.text ?? await optional(join(ctx.root, ".codex/hooks.json"));
525
- const managedBundle = flags.system ? managedHookBundle(codexText, { home: managedHome, cliPath: managedCliPath }) : null;
532
+ const managedBundle = flags.system ? managedHookBundle(codexText, { home: managedHome, cliPath: systemCli, cliVersion: systemCliVersion }) : null;
526
533
  // Claude's managed layer carries only Dev's generated hooks, never the user
527
534
  // entries a merged settings file on disk may also hold.
528
535
  const claudeSettings = harness.files.find((file) => file.path === ".claude/settings.json")?.content ?? "{}";
529
- const claudeBundle = flags.system ? managedClaudeHookBundle(claudeSettings, { home: managedHome, cliPath: managedCliPath }) : null;
536
+ const claudeBundle = flags.system ? managedClaudeHookBundle(claudeSettings, { home: managedHome, cliPath: systemCli, cliVersion: systemCliVersion }) : null;
530
537
  const systemCommands = managedBundle ? systemHookInstallPlan(managedBundle) : [];
531
538
  if (flags["dry-run"]) {
532
539
  const preview = managedBundle ? `\nWould stage managed Codex hooks in ${managedBundle.dir} and managed Claude hooks in ${claudeBundle.dir}. Dry run: no managed files were written and no sudo commands are printed until they exist.` : "";
@@ -553,6 +560,10 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
553
560
  // current dispatcher (its lane-free nudges included), with no sudo.
554
561
  const refreshed = claudeBundle ? [] : await refreshManaged(managedHome ? { home: managedHome } : {}).catch(() => []);
555
562
  const refreshText = refreshed.length ? `\nRefreshed the managed hook dispatcher in ${refreshed.join(", ")}.` : "";
563
+ const managedCliText = !managedCli ? ""
564
+ : managedCli.error ? `\nwarning: the managed nodii-dev was not updated: ${managedCli.error}`
565
+ : managedCli.current ? `\nThe managed nodii-dev is at the latest release, ${managedCli.version}.`
566
+ : `\nInstalled the managed nodii-dev ${managedCli.version}${managedCli.previous ? ` over ${managedCli.previous}` : ""} at ${managedCli.cliPath}.`;
556
567
  const claudeData = claudePlan ? { claudeManagedDir: claudeBundle.dir, claudeManaged: { state: claudePlan.state, target: claudePlan.target, systemCommands: claudePlan.commands } } : {};
557
- return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands: [...systemCommands, ...(claudePlan?.commands ?? [])], managedDir: managedBundle.dir } : {}), ...claudeData, ...(refreshed.length ? { managedDispatchRefreshed: refreshed } : {}) } }, human: `${lines.join("\n")}\n${plan.changes.length ? `${action === "install" ? "Installed" : "Updated"}: ${plan.changes.length} change${plan.changes.length === 1 ? "" : "s"}.` : "Harness already current."}${systemText}${refreshText}` };
568
+ return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands: [...systemCommands, ...(claudePlan?.commands ?? [])], managedDir: managedBundle.dir } : {}), ...claudeData, ...(refreshed.length ? { managedDispatchRefreshed: refreshed } : {}), ...(managedCli ? { managedCli } : {}) } }, human: `${lines.join("\n")}\n${plan.changes.length ? `${action === "install" ? "Installed" : "Updated"}: ${plan.changes.length} change${plan.changes.length === 1 ? "" : "s"}.` : "Harness already current."}${systemText}${refreshText}${managedCliText}` };
558
569
  }
@@ -0,0 +1,119 @@
1
+ // The managed nodii-dev copy against the latest release. Every hook on a
2
+ // machine runs the copy the managed dispatcher names, so a machine can enforce
3
+ // last month's rules with a current PATH and nobody sees it. SessionStart warns
4
+ // when that copy is behind, `doctor` reports it, and `harness update` installs
5
+ // the latest release over it. A failed lookup says nothing and blocks nothing.
6
+ import { execFile } from "node:child_process";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { dirname, isAbsolute, join } from "node:path";
10
+ import { promisify } from "node:util";
11
+ import { managedClaudeHooksDir, managedHooksDir } from "./managed-hooks.js";
12
+
13
+ const PACKAGE = "@nodii/dev";
14
+ const GLOBAL_INSTALL = /^(.+)\/lib\/node_modules\/@nodii\/dev\/bin\/nodii-dev$/;
15
+ const LOOKUP_TIMEOUT_MS = 3_000;
16
+ const INSTALL_TIMEOUT_MS = 120_000;
17
+ const CACHE_MS = 60 * 60 * 1000;
18
+ const runNpm = promisify(execFile);
19
+
20
+ const defaultHome = () => process.env.NODII_DEV_MANAGED_HOME || homedir();
21
+ const metadataPaths = (home) => [managedClaudeHooksDir(home), managedHooksDir(home)].map((dir) => join(dir, "metadata.json"));
22
+ const readJson = async (read, path) => { try { return JSON.parse(await read(path, "utf8")); } catch { return null; } };
23
+
24
+ const triple = (version) => {
25
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(version ?? ""));
26
+ return match ? match.slice(1).map(Number) : null;
27
+ };
28
+
29
+ /** Is `version` an older release than `latest`? An unreadable version is not behind anything. */
30
+ export function isBehind(version, latest) {
31
+ const a = triple(version);
32
+ const b = triple(latest);
33
+ if (!a || !b) return false;
34
+ const at = a.findIndex((part, i) => part !== b[i]);
35
+ return at >= 0 && a[at] < b[at];
36
+ }
37
+
38
+ /** The copy the managed dispatchers run, and the version installed there, or null with no managed hooks. */
39
+ export async function managedCopy({ home = defaultHome(), read = readFile } = {}) {
40
+ for (const path of metadataPaths(home)) {
41
+ const metadata = await readJson(read, path);
42
+ if (!isAbsolute(String(metadata?.cliPath ?? ""))) continue;
43
+ // The package beside the binary is what runs; metadata only says what ran at the last --system.
44
+ const installed = await readJson(read, join(dirname(dirname(metadata.cliPath)), "package.json"));
45
+ return { cliPath: metadata.cliPath, version: installed?.version ?? metadata.cliVersion ?? null };
46
+ }
47
+ return null;
48
+ }
49
+
50
+ /**
51
+ * The latest released version. SessionStart is on the path of every session, so
52
+ * a lookup is kept for an hour and a failed one falls back to what was last
53
+ * read. `fresh` skips the kept answer: an install must not trust an old one.
54
+ */
55
+ export async function latestRelease({ home = defaultHome(), exec = runNpm, read = readFile, now = Date.now, fresh = false, timeout = LOOKUP_TIMEOUT_MS } = {}) {
56
+ const path = join(home, ".config/nodii-dev/latest-release.json");
57
+ const kept = await readJson(read, path);
58
+ if (!fresh && kept?.version && now() - kept.checkedAt < CACHE_MS) return kept.version;
59
+ try {
60
+ const { stdout } = await exec("npm", ["view", PACKAGE, "version"], { timeout });
61
+ const version = String(stdout).trim();
62
+ if (!triple(version)) return kept?.version ?? null;
63
+ await mkdir(dirname(path), { recursive: true });
64
+ const temporary = `${path}.${process.pid}`;
65
+ await writeFile(temporary, `${JSON.stringify({ version, checkedAt: now() })}\n`);
66
+ await rename(temporary, path);
67
+ return version;
68
+ } catch {
69
+ return kept?.version ?? null;
70
+ }
71
+ }
72
+
73
+ /** Where the managed copy stands: null with no managed hooks; `latest` null when no release could be read. */
74
+ export async function managedStatus(options = {}) {
75
+ const copy = await managedCopy(options);
76
+ if (!copy) return null;
77
+ const latest = await latestRelease(options);
78
+ return { ...copy, latest, behind: isBehind(copy.version, latest) };
79
+ }
80
+
81
+ export const managedBehindText = ({ version, latest }) =>
82
+ `WARNING: the managed nodii-dev on this machine is ${version}, behind the latest release ${latest}, and every hook here runs that copy. Fix: \`nodii-dev harness update\`.`;
83
+
84
+ /**
85
+ * `harness update`: put the latest release where the managed dispatcher looks.
86
+ * Returns null with no managed copy to update, `{ cliPath, version, previous }`
87
+ * after an install or `{ cliPath, version, current: true }` with nothing to do.
88
+ * Throws when it could not install; the caller reports that and carries on.
89
+ */
90
+ export async function installManagedLatest({ system = false, runningCli = null, home = defaultHome(), exec = runNpm, read = readFile, write = writeFile, now = Date.now } = {}) {
91
+ const copy = await managedCopy({ home, read });
92
+ if (!copy && !system) return null;
93
+ const latest = await latestRelease({ home, exec, read, now, fresh: true });
94
+ if (!latest) throw new Error(`could not read the latest ${PACKAGE} release from npm`);
95
+ const prefix = await installPrefix({ copy, system, runningCli, exec });
96
+ 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.
103
+ for (const path of metadataPaths(home)) {
104
+ const metadata = await readJson(read, path);
105
+ if (metadata?.cliPath === cliPath) await write(path, `${JSON.stringify({ ...metadata, cliVersion: latest }, null, 2)}\n`, { mode: 0o600 });
106
+ }
107
+ return { cliPath, version: latest, previous: installed?.version ?? null };
108
+ }
109
+
110
+ async function installPrefix({ copy, system, runningCli, exec }) {
111
+ const named = GLOBAL_INSTALL.exec(String(copy?.cliPath ?? ""));
112
+ if (named) return named[1];
113
+ if (!system) throw new Error(`the managed copy at ${copy.cliPath} is not a global npm install; run \`nodii-dev harness update --system\` from one`);
114
+ const running = GLOBAL_INSTALL.exec(String(runningCli ?? ""));
115
+ if (running) return running[1];
116
+ // Run from npx or a checkout: that path is not somewhere to pin every hook on the machine.
117
+ const { stdout } = await exec("npm", ["prefix", "-g"], { timeout: LOOKUP_TIMEOUT_MS });
118
+ return String(stdout).trim();
119
+ }
@@ -13,6 +13,7 @@ import { basename, dirname, join } from "node:path";
13
13
  import { CliError, configPath, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
14
14
  import { currentLane, regroundLane } from "./freeze.js";
15
15
  import { gatherText } from "./gather.js";
16
+ import { managedBehindText } from "./managed-version.js";
16
17
 
17
18
  export const SESSION_KINDS = ["lane", "coordinator", "steward", "operator_assistant"];
18
19
  const KIND_LABEL = { lane: "lane", coordinator: "coordinator", steward: "steward", operator_assistant: "operator assistant" };
@@ -140,12 +141,14 @@ async function stewardClauseMap(steward, request) {
140
141
  }
141
142
 
142
143
  /** Plain text for SessionStart: the kind, its contract and, where it has one, its stored contract. */
143
- export async function sessionStartText(payload, { request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, state = writeKindState } = {}) {
144
+ export async function sessionStartText(payload, { managed = async () => null, request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, state = writeKindState } = {}) {
144
145
  const cwd = payload?.cwd ?? process.cwd();
145
146
  const compact = payload?.source === "compact";
146
147
  const resolved = { ...(await dev({ cwd, env }, { request, config })), notes: [] };
147
148
  await state(payload?.session_id, { kind: resolved.kind, source: resolved.source }).catch(() => {});
148
149
  const parts = [await kindText(resolved, { request })];
150
+ const copy = await managed().catch(() => null);
151
+ if (copy?.behind) parts[0] = `${managedBehindText(copy)}\n${parts[0]}`;
149
152
  if (resolved.kind === "lane" && resolved.lane && compact) {
150
153
  let context = "";
151
154
  const result = await regroundLane(resolved.lane, { force: true, write: (text) => { context += text; } }, { request }).catch(() => ({ shown: false }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.101",
3
+ "version": "0.6.102",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {