@nodii/dev 0.6.57 → 0.6.60

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
@@ -544,6 +544,26 @@ depend on `PATH`, and refreshes it on every update. Outside a lane, or when
544
544
  that executable is missing or too old, it fails open without diagnostics;
545
545
  `doctor` reports that fail-open state for each Codex profile.
546
546
 
547
+ Claude reads one machine-wide managed settings file for every profile
548
+ (`CLAUDE_CONFIG_DIR` never moves it), so `--system` also refreshes
549
+ `~/.config/nodii-dev/claude-managed-hooks` (dispatcher, `hooks.json` from Dev's
550
+ generated Claude hooks, and `managed-settings.json`) and prints the one-time
551
+ `sudo install` lines that place `managed-settings.json` in
552
+ `/Library/Application Support/ClaudeCode/` (macOS) or `/etc/claude-code/`
553
+ (Linux). Every Claude event goes to the dispatcher, which acts only when
554
+ `NODII_DEV_CONFIG_PATH` is a lane config (`lane-*.json`): the operator's own
555
+ sessions see no lane policy. A handler's exit-2 denial becomes Claude's JSON
556
+ decision; every other failure fails open. No user settings file can switch
557
+ it off: it runs every matching handler. A repository that still carries the
558
+ same direct hooks runs them too, so those fire twice until the repository
559
+ harness stops generating them. A
560
+ managed file nodii-dev did not write, or one the operator merged by hand, is
561
+ never overwritten: `--system` says how to update it instead. The managed
562
+ command is a no-op for root and for any user who does not own the dispatcher;
563
+ like the Codex layer, its owner can still edit their own dispatcher. `doctor` checks the hooks of every runner profile
564
+ registered for the machine (`machine accounts`), one `hooks_<profile>` check
565
+ each, including whether the system file matches the staged one.
566
+
547
567
  Until Dev exposes a lane's owned paths (AGENT-HARNESS-10), an edit with no
548
568
  ownership field emits a nudge instead of claiming it is safe or blocking an
549
569
  unproven violation. Likewise, a deploy with no `NODII_DEV_GO_FILE` source
package/dist/cli.js CHANGED
@@ -27,7 +27,7 @@ import { harnessCommand } from "./harness.js";
27
27
  import { hookRuntime, recordHookFire, safetyContext, safetyPostHook, safetyPreHook } from "./safety.js";
28
28
  import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks } from "./nudges.js";
29
29
  import { doctorCommand } from "./doctor.js";
30
- import { dispatchManagedHook } from "./managed-hooks.js";
30
+ import { dispatchManagedClaudeHook, dispatchManagedHook } from "./managed-hooks.js";
31
31
  import { freezeCommand } from "./freeze.js";
32
32
  import {
33
33
  figmaChangeSetShow,
@@ -161,7 +161,7 @@ Usage: nodii-dev <command> [options] [--json]
161
161
  figma changeset show CHANGE_SET # write-up, items, context, variants, round, decision and comment (with the previous round's)
162
162
  figma file add FILE_KEY --name TEXT --kind design-system|surfaces|prototype [--module M]
163
163
  # register a Figma file in Dev so it can be locked
164
- hook claude-figma-pre|claude-figma-post|safety-pre|safety-post|nudge-pre|nudge-stop|session-start|managed-dispatch|print-settings
164
+ hook claude-figma-pre|claude-figma-post|safety-pre|safety-post|nudge-pre|nudge-stop|session-start|managed-dispatch|claude-managed-dispatch|print-settings
165
165
  setup [--yes|--check] # dry-run by default; installs/checks Ollama and pulls the Gather model
166
166
  harness install|update [--include-drafts[=false]] [--adopt PATH,...] [--dry-run] [--system]
167
167
  # --system stages managed hooks and only prints operator-reviewed sudo commands
@@ -172,7 +172,9 @@ Usage: nodii-dev <command> [options] [--json]
172
172
  # and re-report account usage every 5 min
173
173
  docs check|validate|upload <path...> --class ruling|conformance|editorial
174
174
  [--base CODE=VERSION] [--decision FILE] [--conformance-ref REF]
175
- [--meaning-unchanged REASON] [--wait]
175
+ [--meaning-unchanged REASON] [--wait] [--no-embed]
176
+ # upload embeds the sections Dev has no vector for with the
177
+ # pinned local model and sends them; --no-embed leaves them to Dev
176
178
  docs ratify --domain KEY [--domain KEY ...] --decision FILE [--wait]
177
179
  docs parked [CODE] [--status pending|acknowledged]
178
180
  rulebook list|show CODE [--version V]|diff CODE
@@ -1121,6 +1123,12 @@ export async function main(argv = process.argv.slice(2)) {
1121
1123
  if (output) process.stdout.write(output);
1122
1124
  return;
1123
1125
  }
1126
+ if (action === "claude-managed-dispatch") {
1127
+ if (!rest[0] || rest.length > 1) throw new CliError("USAGE", "hook claude-managed-dispatch needs one event name", 2);
1128
+ const output = await dispatchManagedClaudeHook(rest[0], await stdinText());
1129
+ if (output) process.stdout.write(output);
1130
+ return;
1131
+ }
1124
1132
  if (["claude-figma-pre", "figma-pre"].includes(action)) {
1125
1133
  let payload;
1126
1134
  try {
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.57";
7
+ export const VERSION = "0.6.60";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -222,7 +222,7 @@ export async function checkLogin() {
222
222
  export const encode = (value) => encodeURIComponent(value);
223
223
  // Switches never take the next token as their value, so
224
224
  // `docs upload --wait rulebook/` keeps rulebook/ as a path.
225
- const SWITCHES = new Set(["json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical"]);
225
+ const SWITCHES = new Set(["json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical", "no-embed"]);
226
226
  export function parseArgs(argv) {
227
227
  const flags = {};
228
228
  const args = [];
package/dist/doctor.js CHANGED
@@ -5,8 +5,9 @@ import { devRequest, encode, isOAuthConfig, query, setAuthProvider } from "./cor
5
5
  import { OAuthAuthProvider, decodeClaims, loadRefreshToken } from "./oauth.js";
6
6
  import { inferGitContext, repoName } from "./lanes.js";
7
7
  import { figmaFileKey, figmaLockCheck, holdsSet, notRegisteredHint, scopeText } from "./figma.js";
8
- import { PICKER_CONTEXT, PICKER_MODEL, PICKER_MODEL_DIGEST, STALE_PIN_HINT, inspectOllama } from "./gather.js";
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
+ import { listAccounts } from "./accounts.js";
10
11
 
11
12
  /**
12
13
  * What a lane's commands need, in Dev's route policy (staffRuleFor in Dev's
@@ -281,21 +282,49 @@ export async function doctorCommand(deps = {}) {
281
282
  if (context === null) checks.push(ok("picker_context", `${PICKER_MODEL} not loaded; Gather loads it with num_ctx ${PICKER_CONTEXT}`, { model: PICKER_MODEL, context: null, requiredContext: PICKER_CONTEXT }));
282
283
  else if (context === PICKER_CONTEXT) checks.push(ok("picker_context", `${PICKER_MODEL} loaded with num_ctx ${PICKER_CONTEXT}`, { model: PICKER_MODEL, context, requiredContext: PICKER_CONTEXT }));
283
284
  else checks.push(missing("picker_context", `${PICKER_MODEL} is loaded with context ${context}, not ${PICKER_CONTEXT}; the next lane gather reloads it`, `ollama stop ${PICKER_MODEL}`, { model: PICKER_MODEL, context, requiredContext: PICKER_CONTEXT }));
285
+ // The section embedding pin `docs upload` embeds changed sections with
286
+ // (AGENT-HARNESS-58), checked like the picker.
287
+ const embed = await (deps.ollamaInspector ?? inspectOllama)({ model: EMBED_PIN });
288
+ if (embed.modelInstalled && embed.modelMatches)
289
+ checks.push(ok("embed_model", `${EMBED_MODEL} installed${embed.digest ? ` (${embed.digest})` : ""}`, { model: EMBED_MODEL, digest: embed.digest ?? null }));
290
+ else if (!embed.modelInstalled) checks.push(missing("embed_model", `${EMBED_MODEL} is not installed; docs upload cannot embed changed sections`, "nodii-dev setup --yes", { model: EMBED_MODEL }));
291
+ else checks.push(missing("embed_model", `${EMBED_MODEL} digest is ${embed.digest ?? "unknown"}; this CLI pins ${EMBED_MODEL_DIGEST}; ${STALE_PIN_HINT}`, "nodii-dev setup --yes", { model: EMBED_MODEL, digest: embed.digest ?? null, requiredDigest: EMBED_MODEL_DIGEST }));
284
292
  } catch (error) {
285
293
  checks.push(missing("ollama", error?.message ?? "Ollama is unavailable", "nodii-dev setup --yes", { code: error?.code ?? null }));
286
294
  checks.push(cannot("picker_model", `needs local Ollama; expected ${PICKER_MODEL}`, { model: PICKER_MODEL }));
287
295
  checks.push(cannot("picker_context", `needs local Ollama; expected num_ctx ${PICKER_CONTEXT}`, { model: PICKER_MODEL, requiredContext: PICKER_CONTEXT }));
296
+ checks.push(cannot("embed_model", `needs local Ollama; expected ${EMBED_MODEL}`, { model: EMBED_MODEL }));
288
297
  }
289
298
 
290
- // 10. Runtime hooks: present, accepted by that runtime, and observed firing.
299
+ // 10. Runtime hooks: present, accepted by that runtime, and observed firing,
300
+ // for every runner profile registered for this machine (machine accounts).
291
301
  const hookRoot = context?.worktree ?? deps.cwd ?? process.cwd();
302
+ let profiles;
303
+ if (agent?.machineId) {
304
+ try {
305
+ const accounts = await (deps.listAccounts ?? listAccounts)(agent.machineId, { request });
306
+ const registered = accounts.filter((account) => (account.kind ?? "account") === "account" && ["claude", "codex"].includes(account.runtime) && account.profile);
307
+ if (registered.length) profiles = registered.map((account) => ({ runtime: account.runtime, home: account.profile }));
308
+ } catch {}
309
+ }
310
+ const systemFix = "run `nodii-dev harness update --system`, then have an operator run the sudo lines it prints";
292
311
  try {
293
- const runtimes = await (deps.hookDiagnostics ?? hookDiagnostics)(hookRoot);
312
+ const runtimes = await (deps.hookDiagnostics ?? hookDiagnostics)(hookRoot, profiles ? { profiles } : {});
294
313
  for (const runtime of runtimes) {
295
314
  const key = `hooks_${runtime.runtime.replace(/[^a-z0-9]+/gi, "_")}`;
296
- const extra = { runtime: runtime.runtime, installed: runtime.installed, trusted: runtime.trusted, firing: runtime.firing, managed: runtime.managed, lastFiredAt: runtime.lastFiredAt ?? null, ...(runtime.cliStatus ? { cliStatus: runtime.cliStatus } : {}) };
315
+ const extra = { runtime: runtime.runtime, ...(runtime.profileHome ? { profileHome: runtime.profileHome } : {}), installed: runtime.installed, trusted: runtime.trusted, firing: runtime.firing, managed: runtime.managed, lastFiredAt: runtime.lastFiredAt ?? null, ...(runtime.managedState ? { managedState: runtime.managedState, managedPath: runtime.managedPath } : {}), ...(runtime.cliStatus ? { cliStatus: runtime.cliStatus } : {}) };
316
+ const claude = runtime.runtime.startsWith("claude");
297
317
  if (runtime.installed === null) checks.push(cannot(key, runtime.error ?? "runtime hook registry unavailable", extra));
318
+ else if (!runtime.installed && claude && runtime.managedState === "unreadable") checks.push(cannot(key, runtime.managedMessage ?? `cannot read ${runtime.managedPath}`, extra));
319
+ else if (!runtime.installed && claude && runtime.managedState === "other_user")
320
+ checks.push(missing(key, `hooks are not installed: ${runtime.managedPath} routes Claude to another user's nodii-dev dispatcher`, "run lanes as the user whose dispatcher the managed file names, or have an operator reinstall it for this user", extra));
321
+ else if (!runtime.installed && claude && runtime.managedState === "foreign")
322
+ checks.push(missing(key, `hooks are not installed: ${runtime.managedPath} exists and was not written by nodii-dev`, "merge the staged ~/.config/nodii-dev/claude-managed-hooks/managed-settings.json into it by hand", extra));
323
+ else if (!runtime.installed && claude)
324
+ checks.push(missing(key, `hooks are not installed for ${runtime.profileHome ?? "this profile"}${runtime.managedState === "staged" ? `; managed hooks are staged but ${runtime.managedPath} is not installed` : ""}`, systemFix, extra));
298
325
  else if (!runtime.installed) checks.push(missing(key, "hooks are not installed", "nodii-dev harness install (or setup --yes)", extra));
326
+ else if (claude && runtime.managedState === "stale") checks.push(missing(key, `${runtime.managedPath} differs from the staged managed settings`, systemFix, extra));
327
+ else if (claude && runtime.managedState === "merged_stale") checks.push(missing(key, `${runtime.managedPath} was merged by hand and its nodii-dev routes are out of date`, "update its hooks by hand from ~/.config/nodii-dev/claude-managed-hooks/managed-settings.json", extra));
299
328
  else if (!runtime.trusted) checks.push(missing(key, `hooks are installed but not trusted${runtime.trustStatuses?.length ? ` (${runtime.trustStatuses.join(", ")})` : ""}`, runtime.runtime.startsWith("codex") ? "review /hooks, or have an operator run the commands printed by `nodii-dev harness update --system`" : "review the runtime hook configuration", extra));
300
329
  else if (runtime.managed && runtime.cliStatus?.ok === false) checks.push(missing(key, `${runtime.cliStatus.message}; managed hooks fail open until this is fixed`, "update nodii-dev, then run `nodii-dev harness update --system` to refresh the absolute CLI path", extra));
301
330
  else if (!runtime.firing) checks.push(missing(key, `hooks are installed and trusted${runtime.managed ? " (managed)" : ""}, but no firing receipt exists`, "start a fresh runtime session and run doctor again", extra));
package/dist/embed.js ADDED
@@ -0,0 +1,89 @@
1
+ // `docs upload` embeds the sections Dev has no vector for on this Mac, with
2
+ // the model Dev pins, and sends the vectors with the upload
3
+ // (AGENT-HARNESS-58). Dev's validate names each section's exact input and
4
+ // hash; Dev checks the pin again and stores them as the version lands.
5
+ import { CliError } from "./core.js";
6
+ import { inspectOllama, ollamaUrl } from "./gather.js";
7
+
8
+ export { EMBED_DIMENSIONS, EMBED_MODEL, EMBED_MODEL_DIGEST, EMBED_PIN } from "./gather.js";
9
+ // Dev's pinned input format cuts every input at 512 tokens (embedding-formats.ts).
10
+ export const EMBED_NUM_CTX = 512;
11
+ export const EMBED_BATCH = 16;
12
+ export const EMBED_TIMEOUT_MS = 120_000;
13
+ /** Dev's per-upload cap; the rest are left to Dev's worker. */
14
+ export const EMBED_UPLOAD_MAX = 2_000;
15
+ export const NO_EMBED_HINT = "Run `nodii-dev setup --yes`, or pass --no-embed to let Dev's worker embed them.";
16
+
17
+ const bare = (digest) => String(digest ?? "").replace(/^sha256:/, "");
18
+
19
+ /** Local Ollama serves `pin.model` at exactly `pin.digest`, or a refusal saying how to fix it. */
20
+ export async function requireEmbedder(pin, { inspect = inspectOllama } = {}) {
21
+ let status;
22
+ try { status = await inspect({ model: { name: pin.model, digest: pin.digest } }); }
23
+ catch (error) { throw new CliError("EMBED_UNAVAILABLE", `Local Ollama is unavailable for section embedding: ${error.message}`, 1, error.details); }
24
+ if (!status.modelInstalled)
25
+ throw new CliError("EMBED_MODEL_MISSING", `Dev pins ${pin.model} for section vectors and it is not installed here. ${NO_EMBED_HINT}`, 1, status);
26
+ if (!status.modelMatches)
27
+ throw new CliError("EMBED_MODEL_VERSION_MISMATCH", `Local ${pin.model} is ${status.digest ?? "an unknown digest"}; Dev pins ${pin.digest}. ${NO_EMBED_HINT}`, 1, status);
28
+ return status;
29
+ }
30
+
31
+ /** One vector per input, in order, from local Ollama's /api/embed. */
32
+ export async function embedInputs(inputs, pin, { fetchImpl = fetch, baseUrl = ollamaUrl(), batch = EMBED_BATCH, timeoutMs = EMBED_TIMEOUT_MS } = {}) {
33
+ const out = [];
34
+ for (let i = 0; i < inputs.length; i += batch) {
35
+ const chunk = inputs.slice(i, i + batch);
36
+ let response;
37
+ try {
38
+ response = await fetchImpl(`${baseUrl}/api/embed`, {
39
+ method: "POST",
40
+ headers: { "content-type": "application/json" },
41
+ body: JSON.stringify({ model: pin.model, input: chunk, truncate: true, options: { num_ctx: EMBED_NUM_CTX } }),
42
+ signal: AbortSignal.timeout(timeoutMs),
43
+ });
44
+ } catch (error) {
45
+ throw new CliError("EMBED_UNAVAILABLE", `Local Ollama did not embed: ${error.message}. ${NO_EMBED_HINT}`, 1);
46
+ }
47
+ const payload = await response.json().catch(() => ({}));
48
+ if (!response.ok) throw new CliError("EMBED_UNAVAILABLE", `Local Ollama returned HTTP ${response.status}: ${payload.error ?? "no detail"}`, 1);
49
+ const vectors = payload.embeddings;
50
+ if (!Array.isArray(vectors) || vectors.length !== chunk.length)
51
+ throw new CliError("EMBED_INVALID", `Local Ollama returned ${Array.isArray(vectors) ? vectors.length : "no"} vectors for ${chunk.length} inputs.`, 1);
52
+ const wrong = vectors.find((v) => !Array.isArray(v) || v.length !== pin.dimensions);
53
+ if (wrong) throw new CliError("EMBED_INVALID", `Local ${pin.model} returned a ${wrong?.length ?? 0}-d vector; Dev pins ${pin.dimensions}-d.`, 1);
54
+ out.push(...vectors);
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * From Dev's validate result, embed every section Dev has no vector for and
61
+ * return the upload's `embeddings` block, or undefined when Dev pins no
62
+ * model or every section already has one. A refusal is never swallowed: an
63
+ * upload that cannot embed says so, and --no-embed is the explicit way out.
64
+ */
65
+ export async function embedPlanned(validated, { log = () => {}, inspect, fetchImpl, baseUrl } = {}) {
66
+ const plans = (validated?.documents ?? []).map((d) => d.embedding).filter(Boolean);
67
+ if (!plans.length) return undefined;
68
+ const pin = plans[0].pin;
69
+ const missing = new Map();
70
+ for (const plan of plans)
71
+ for (const s of plan.sections) if (!s.stored && s.input) missing.set(s.inputSha256, s.input);
72
+ const total = plans.reduce((n, p) => n + p.sections.length, 0);
73
+ if (!missing.size) {
74
+ log(`Section vectors: all ${total} sections already embedded on Dev; nothing to embed here.`);
75
+ return undefined;
76
+ }
77
+ const todo = [...missing].slice(0, EMBED_UPLOAD_MAX);
78
+ if (missing.size > todo.length) log(`Section vectors: ${missing.size} to embed; sending ${todo.length}, Dev's worker embeds the rest.`);
79
+ await requireEmbedder(pin, { inspect });
80
+ const started = Date.now();
81
+ const vectors = await embedInputs(todo.map(([, input]) => input), pin, { fetchImpl, ...(baseUrl ? { baseUrl } : {}) });
82
+ log(`Section vectors: embedded ${todo.length} of ${total} sections with ${pin.model}@${bare(pin.digest).slice(0, 12)} in ${((Date.now() - started) / 1000).toFixed(1)} s; the rest are already on Dev.`);
83
+ return {
84
+ model: pin.model,
85
+ digest: pin.digest,
86
+ dimensions: pin.dimensions,
87
+ vectors: todo.map(([inputSha256], i) => ({ inputSha256, embedding: vectors[i] })),
88
+ };
89
+ }
package/dist/flags.js CHANGED
@@ -42,7 +42,7 @@ export const COMMAND_FLAGS = {
42
42
  "drift resolve": ["reason", "resolution-md", "status", "decision", "related-decision-id"],
43
43
  "drift supersede": ["reason", "by", "resolution-md", "superseding-drift-id"],
44
44
  "request file": ["from", "to", "kind", "summary", "spec", "spec-file", "required-capability", "target-artifact-type", "target-artifact-id"],
45
- "docs upload": ["class", "change-class", "pending", "decision", "meaning-unchanged", "conformance-ref", "base", ...WAIT],
45
+ "docs upload": ["class", "change-class", "pending", "decision", "meaning-unchanged", "conformance-ref", "base", "no-embed", ...WAIT],
46
46
  "docs ratify": ["domain", "decision", ...WAIT],
47
47
  "figma submit": ["file", "figma-version", ...SUBMIT_MODE, "dry-run"],
48
48
  "figma resubmit": [...SUBMIT_MODE, "dry-run"],
package/dist/gather.js CHANGED
@@ -21,6 +21,13 @@ export const TUNING_MODELS = {
21
21
  "gemma-12b": { name: PICKER_MODEL, digest: PICKER_MODEL_DIGEST },
22
22
  "gemma-26b": { name: "gemma4:26b", digest: "sha256:001e5dafc3c77684c2307ebc6ab8e336e10c9b18eca52acf547d72fc83c3ca8c" },
23
23
  };
24
+ // The section embedding pin (Dev's GATHER_EMBEDDING_*): `setup` pulls it,
25
+ // `doctor` checks it, and `docs upload` embeds changed sections with it
26
+ // (AGENT-HARNESS-58). Ollama lists it as `nomic-embed-text:latest`.
27
+ export const EMBED_MODEL = "nomic-embed-text";
28
+ export const EMBED_MODEL_DIGEST = "sha256:0a109f422b47e3a30ba2b10eca18548e944e8a23073ee3f3e947efcf3c45e59f";
29
+ export const EMBED_DIMENSIONS = 768;
30
+ export const EMBED_PIN = { name: EMBED_MODEL, digest: EMBED_MODEL_DIGEST };
24
31
  export const PICKER_CONTEXT = 8192;
25
32
  // A hard per-pick deadline: a pick that has not answered by then is stopped
26
33
  // (PICKER_TIMEOUT) so the next one never queues behind it.
@@ -118,7 +125,9 @@ export async function inspectOllama(options = {}) {
118
125
  jsonRequest("/api/tags", options),
119
126
  jsonRequest("/api/ps", options),
120
127
  ]);
121
- const model = (tags.models ?? []).find((x) => x?.name === pin.name || x?.model === pin.name) ?? null;
128
+ // An untagged pin is listed as `<name>:latest`.
129
+ const names = pin.name.includes(":") ? [pin.name] : [pin.name, `${pin.name}:latest`];
130
+ const model = (tags.models ?? []).find((x) => names.includes(x?.name) || names.includes(x?.model)) ?? null;
122
131
  return {
123
132
  loadedContext: residentContext(ps, pin.name),
124
133
  available: true,
@@ -576,7 +585,10 @@ async function run(command, args, exec = execFileAsync) {
576
585
  export async function setupOllama({ check = false, inspect = inspectOllama, exec = execFileAsync, os = platform() } = {}) {
577
586
  try {
578
587
  const current = await inspect();
579
- if (current.modelInstalled && current.modelMatches) return { changed: [], ...current };
588
+ if (current.modelInstalled && current.modelMatches) {
589
+ const embed = await setupEmbedModel({ check, inspect, exec });
590
+ return { changed: embed.changed, ...current, embed };
591
+ }
580
592
  if (check && current.modelInstalled)
581
593
  throw new CliError("PICKER_MODEL_VERSION_MISMATCH", `${PICKER_MODEL} digest is ${current.digest ?? "unknown"}; this CLI pins ${PICKER_MODEL_DIGEST}. Run \`nodii-dev setup --yes\` to pull it; ${STALE_PIN_HINT}`, 1, current);
582
594
  if (check) throw new CliError("PICKER_MODEL_MISSING", `${PICKER_MODEL} is not installed.`, 1, current);
@@ -592,5 +604,20 @@ export async function setupOllama({ check = false, inspect = inspectOllama, exec
592
604
  if (!ready.modelInstalled) throw new CliError("PICKER_MODEL_MISSING", `Ollama pull finished but ${PICKER_MODEL} is not installed.`, 1, ready);
593
605
  // A fresh pull is what the registry serves now, so a mismatch here is a stale pin.
594
606
  if (!ready.modelMatches) throw new CliError("PICKER_MODEL_VERSION_MISMATCH", `The Ollama registry serves ${PICKER_MODEL} at ${ready.digest ?? "an unknown digest"}, but this CLI pins ${PICKER_MODEL_DIGEST}: the pin is stale, so pulling again will not help. Update nodii-dev to a release with the current pin.`, 1, { ...ready, stalePin: true });
595
- return { changed: [PICKER_MODEL], ...ready };
607
+ const embed = await setupEmbedModel({ check, inspect, exec });
608
+ return { changed: [PICKER_MODEL, ...embed.changed], ...ready, embed };
609
+ }
610
+
611
+ /** The section embedding pin, pulled beside the picker (AGENT-HARNESS-58). */
612
+ async function setupEmbedModel({ check, inspect, exec }) {
613
+ const current = await inspect({ model: EMBED_PIN });
614
+ if (current.modelInstalled && current.modelMatches) return { changed: [], ...current };
615
+ if (check && current.modelInstalled)
616
+ throw new CliError("EMBED_MODEL_VERSION_MISMATCH", `${EMBED_MODEL} digest is ${current.digest ?? "unknown"}; this CLI pins ${EMBED_MODEL_DIGEST}. Run \`nodii-dev setup --yes\` to pull it; ${STALE_PIN_HINT}`, 1, current);
617
+ if (check) throw new CliError("EMBED_MODEL_MISSING", `${EMBED_MODEL} is not installed.`, 1, current);
618
+ await run("ollama", ["pull", EMBED_MODEL], exec);
619
+ const ready = await inspect({ model: EMBED_PIN });
620
+ if (!ready.modelInstalled) throw new CliError("EMBED_MODEL_MISSING", `Ollama pull finished but ${EMBED_MODEL} is not installed.`, 1, ready);
621
+ if (!ready.modelMatches) throw new CliError("EMBED_MODEL_VERSION_MISMATCH", `The Ollama registry serves ${EMBED_MODEL} at ${ready.digest ?? "an unknown digest"}, but this CLI pins ${EMBED_MODEL_DIGEST}: the pin is stale, so pulling again will not help. Update nodii-dev to a release with the current pin.`, 1, { ...ready, stalePin: true });
622
+ return { changed: [EMBED_MODEL], ...ready };
596
623
  }
package/dist/harness.js CHANGED
@@ -10,7 +10,7 @@ import { dirname, join, normalize, sep } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { promisify } from "node:util";
12
12
  import { CliError, devRequest, query } from "./core.js";
13
- import { managedHookBundle, nodiiCommandArgs, writeManagedHookBundle } from "./managed-hooks.js";
13
+ import { classifyClaudeManaged, claudeManagedSettingsPath, managedClaudeHookBundle, managedHookBundle, nodiiCommandArgs, writeManagedClaudeHookBundle, writeManagedHookBundle } from "./managed-hooks.js";
14
14
  import { nudgeSettingsSnippet } from "./nudges.js";
15
15
  import { codexSafetyHooksSnippet, regroundingHooksSnippet, safetySettingsSnippet } from "./safety.js";
16
16
 
@@ -384,6 +384,29 @@ export function systemHookInstallPlan(bundle) {
384
384
  ];
385
385
  }
386
386
 
387
+ /**
388
+ * Print-only operator plan for Claude's machine-wide managed settings. One
389
+ * file covers every Claude profile. Only a missing file, or one that holds
390
+ * nothing but older nodii-dev routes, gets install lines: a file the operator
391
+ * wrote or merged by hand is never overwritten.
392
+ */
393
+ export function claudeSystemInstallPlan(bundle, { target = claudeManagedSettingsPath(), current = null, unreadable = null } = {}) {
394
+ const source = join(bundle.dir, "managed-settings.json");
395
+ const state = unreadable ? "unreadable" : classifyClaudeManaged(current, bundle.managedSettings, bundle.dir);
396
+ const commands = ["absent", "stale"].includes(state)
397
+ ? [`sudo install -d -m 0755 ${shellQuote(dirname(target))}`, `sudo install -m 0644 ${shellQuote(source)} ${shellQuote(target)}`]
398
+ : [];
399
+ return { commands, state, target, source, ...(unreadable ? { reason: unreadable } : {}) };
400
+ }
401
+
402
+ const CLAUDE_PLAN_TEXT = {
403
+ installed: (plan) => `${plan.target} already routes every Claude profile to them, so no sudo is needed.`,
404
+ merged: (plan) => `${plan.target} already routes every Claude profile to them (merged by hand), so no sudo is needed.`,
405
+ merged_stale: (plan) => `${plan.target} was merged by hand and its nodii-dev routes are out of date. It was left alone: update its hooks by hand from ${plan.source}.`,
406
+ other_user: (plan) => `${plan.target} routes Claude to another user's nodii-dev dispatcher. It was left alone: one user's managed hooks serve the machine.`,
407
+ foreign: (plan) => `${plan.target} exists and was not written by nodii-dev. It was left alone: merge the hooks from ${plan.source} into it by hand.`,
408
+ unreadable: (plan) => `${plan.target} cannot be read (${plan.reason}), so it was left alone; check it, then run --system again.`,
409
+ };
387
410
  // What each planned change means for a check: how the file on disk differs from Dev's.
388
411
  const DIFFERENCE = {
389
412
  create: "missing; Dev would create it",
@@ -439,7 +462,7 @@ async function checkCommand(root, repo, state, fetchHarness) {
439
462
  };
440
463
  }
441
464
 
442
- export async function harnessCommand(action, flags, { request = devRequest, context = repoContext, managedHome, managedCliPath = fileURLToPath(new URL("../bin/nodii-dev", import.meta.url)), writeManaged = writeManagedHookBundle } = {}) {
465
+ 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, claudeManagedPath = claudeManagedSettingsPath(), readSystem = optional } = {}) {
443
466
  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);
444
467
  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);
445
468
  if (flags.root === true || flags.repo === true) throw new CliError("USAGE", "--root and --repo need a value.", 2);
@@ -498,15 +521,32 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
498
521
  const codexChange = plan.changes.find((change) => change.path === ".codex/hooks.json");
499
522
  const codexText = codexChange?.text ?? await optional(join(ctx.root, ".codex/hooks.json"));
500
523
  const managedBundle = flags.system ? managedHookBundle(codexText, { home: managedHome, cliPath: managedCliPath }) : null;
524
+ // Claude's managed layer carries only Dev's generated hooks, never the user
525
+ // entries a merged settings file on disk may also hold.
526
+ const claudeSettings = harness.files.find((file) => file.path === ".claude/settings.json")?.content ?? "{}";
527
+ const claudeBundle = flags.system ? managedClaudeHookBundle(claudeSettings, { home: managedHome, cliPath: managedCliPath }) : null;
501
528
  const systemCommands = managedBundle ? systemHookInstallPlan(managedBundle) : [];
502
529
  if (flags["dry-run"]) {
503
- const preview = managedBundle ? `\nWould stage managed Codex hooks in ${managedBundle.dir}. Dry run: no managed files were written and no sudo commands are printed until they exist.` : "";
504
- return { payload: { data: { ...summary, dryRun: true, ...(managedBundle ? { managedDir: managedBundle.dir } : {}) } }, human: `${lines.join("\n")}\n${plan.changes.length ? "Dry run: nothing written." : "No changes."}${preview}` };
530
+ 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.` : "";
531
+ return { payload: { data: { ...summary, dryRun: true, ...(managedBundle ? { managedDir: managedBundle.dir, claudeManagedDir: claudeBundle.dir } : {}) } }, human: `${lines.join("\n")}\n${plan.changes.length ? "Dry run: nothing written." : "No changes."}${preview}` };
532
+ }
533
+ let claudePlan = null;
534
+ if (claudeBundle) {
535
+ let current = null;
536
+ let unreadable = null;
537
+ try { current = await readSystem(claudeManagedPath); }
538
+ catch (error) { unreadable = error?.code ?? error?.message ?? String(error); }
539
+ claudePlan = claudeSystemInstallPlan(claudeBundle, { target: claudeManagedPath, current, unreadable });
505
540
  }
541
+ const claudeText = !claudePlan ? ""
542
+ : claudePlan.commands.length ? `\nManaged Claude hooks are staged in ${claudeBundle.dir}. One operator install covers every Claude profile on this machine and acts only in lanes; review ${claudePlan.source}, then run:\n${claudePlan.commands.join("\n")}`
543
+ : `\nManaged Claude hooks are staged in ${claudeBundle.dir}; ${CLAUDE_PLAN_TEXT[claudePlan.state](claudePlan)}`;
506
544
  const systemText = systemCommands.length
507
- ? `\nManaged Codex hooks are staged in ${managedBundle.dir}. One operator install covers codex-personal and codex-work; review ${join(managedBundle.dir, "requirements.toml")}, then run:\n${systemCommands.join("\n")}\nNo privileged command was run. Later --system updates refresh the user-owned managed directory without sudo.`
545
+ ? `\nManaged Codex hooks are staged in ${managedBundle.dir}. One operator install covers codex-personal and codex-work; review ${join(managedBundle.dir, "requirements.toml")}, then run:\n${systemCommands.join("\n")}${claudeText}\nNo privileged command was run. Later --system updates refresh the user-owned managed directories without sudo.`
508
546
  : "";
509
547
  await applyHarness(ctx.root, plan);
510
548
  if (managedBundle) await writeManaged(managedBundle);
511
- return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands, managedDir: managedBundle.dir } : {}) } }, 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}` };
549
+ if (claudeBundle) await writeManagedClaude(claudeBundle);
550
+ const claudeData = claudePlan ? { claudeManagedDir: claudeBundle.dir, claudeManaged: { state: claudePlan.state, target: claudePlan.target, systemCommands: claudePlan.commands } } : {};
551
+ return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands: [...systemCommands, ...(claudePlan?.commands ?? [])], managedDir: managedBundle.dir } : {}), ...claudeData } }, 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}` };
512
552
  }
@@ -2,11 +2,11 @@ import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, tmpdir } from "node:os";
5
- import { join } from "node:path";
5
+ import { basename, join } from "node:path";
6
6
  import { execFile } from "node:child_process";
7
7
  import { promisify } from "node:util";
8
8
  import { HOOK_EVENTS } from "./safety.js";
9
- import { managedHookCliStatus } from "./managed-hooks.js";
9
+ import { claudeManagedStatus, managedClaudeHooksDir, managedHookCliStatus } from "./managed-hooks.js";
10
10
 
11
11
  const execFileAsync = promisify(execFile);
12
12
 
@@ -86,24 +86,67 @@ export function codexHooksList(cwd, { codexBin = "codex", spawnImpl = spawn, tim
86
86
  });
87
87
  }
88
88
 
89
+ /**
90
+ * The doctor label for a runner profile: the default profiles keep their
91
+ * historical names (claude, codex-personal, codex-work); any other profile is
92
+ * named from its directory (~/.claude-hiring-at-nodii → claude-hiring-at-nodii).
93
+ */
94
+ export function profileLabel(runtime, home) {
95
+ const name = basename(home);
96
+ if (runtime === "claude") return name === ".claude" ? "claude" : `claude-${name.replace(/^\.?claude-?/, "") || name}`;
97
+ if (name === ".codex") return "codex-personal";
98
+ return `codex-${name.replace(/^\.?codex-?/, "") || name}`;
99
+ }
100
+
101
+ const defaultProfiles = (homeDir) => [
102
+ { runtime: "claude", home: join(homeDir, ".claude") },
103
+ { runtime: "codex", home: join(homeDir, ".codex") },
104
+ { runtime: "codex", home: join(homeDir, ".codex-work") },
105
+ ];
106
+
107
+ /**
108
+ * One diagnosis per runner profile. `profiles` are the machine's registered
109
+ * account runners ({ runtime, home }); without them, the default profiles.
110
+ */
89
111
  export async function hookDiagnostics(root, deps = {}) {
112
+ const homeDir = deps.home ?? homedir();
90
113
  const events = await (deps.firingEvents ?? firingEvents)(root);
91
- const fired = (runtime) => events.filter((event) => event.runtime === runtime || event.profile === runtime).at(-1) ?? null;
92
- let claude = {};
93
- try { claude = JSON.parse((await optional(join(root, ".claude/settings.json"))) ?? "{}"); }
94
- catch { claude = {}; }
95
- const claudeInstalled = nodiiEntries(claude.hooks).length > 0;
96
- const out = [{
97
- runtime: "claude", installed: claudeInstalled, trusted: claudeInstalled,
98
- firing: Boolean(fired("claude")), lastFiredAt: fired("claude")?.at ?? null,
99
- managed: false,
100
- }];
101
- const profiles = deps.codexProfiles ?? [
102
- { runtime: "codex-personal", home: join(homedir(), ".codex") },
103
- { runtime: "codex-work", home: join(homedir(), ".codex-work") },
104
- ];
105
- const cliStatus = await (deps.managedHookCliStatus ?? managedHookCliStatus)({ home: deps.home ?? homedir() });
114
+ const profiles = deps.profiles ?? (deps.codexProfiles
115
+ ? [{ runtime: "claude", home: join(homeDir, ".claude") }, ...deps.codexProfiles.map((profile) => ({ runtime: "codex", home: profile.home, label: profile.runtime }))]
116
+ : defaultProfiles(homeDir));
117
+ const fired = (profile, label) => events.filter((event) => event.profileHome
118
+ ? event.profileHome === profile.home
119
+ : event.profile === label || (label === "claude" && event.runtime === "claude")).at(-1) ?? null;
120
+ const read = deps.read ?? readFile;
121
+ let repoClaude = {};
122
+ try { repoClaude = JSON.parse((await optional(join(root, ".claude/settings.json"))) ?? "{}"); }
123
+ catch { repoClaude = {}; }
124
+ const repoClaudeHooks = nodiiEntries(repoClaude.hooks).length > 0;
125
+ const needsClaude = profiles.some((profile) => profile.runtime === "claude");
126
+ const claudeManaged = needsClaude ? await (deps.claudeManagedStatus ?? claudeManagedStatus)({ home: homeDir, ...(deps.claudeManagedPath ? { path: deps.claudeManagedPath } : {}), read }) : null;
127
+ const routed = ["installed", "merged", "stale", "merged_stale"].includes(claudeManaged?.state);
128
+ const claudeCli = routed
129
+ ? await (deps.managedHookCliStatus ?? managedHookCliStatus)({ home: homeDir, dir: managedClaudeHooksDir(homeDir) })
130
+ : null;
131
+ const codexCli = profiles.some((profile) => profile.runtime === "codex") ? await (deps.managedHookCliStatus ?? managedHookCliStatus)({ home: homeDir }) : null;
132
+ const out = [];
106
133
  for (const profile of profiles) {
134
+ const label = profile.label ?? profileLabel(profile.runtime, profile.home);
135
+ const firing = fired(profile, label);
136
+ if (profile.runtime === "claude") {
137
+ let own = {};
138
+ try { own = JSON.parse(await read(join(profile.home, "settings.json"), "utf8")); } catch {}
139
+ const managed = routed;
140
+ const installed = managed || repoClaudeHooks || nodiiEntries(own.hooks).length > 0;
141
+ out.push({
142
+ runtime: label, profileHome: profile.home, installed, trusted: installed,
143
+ firing: Boolean(firing), lastFiredAt: firing?.at ?? null,
144
+ managed, managedState: claudeManaged?.state ?? null, managedPath: claudeManaged?.path ?? null,
145
+ ...(claudeManaged?.message ? { managedMessage: claudeManaged.message } : {}),
146
+ ...(managed ? { cliStatus: claudeCli } : {}),
147
+ });
148
+ continue;
149
+ }
107
150
  try {
108
151
  const data = await (deps.codexHooksList ?? codexHooksList)(root, { ...deps, env: { ...(deps.env ?? process.env), CODEX_HOME: profile.home } });
109
152
  const record = data.find((item) => item.cwd === root) ?? data[0] ?? {};
@@ -111,15 +154,15 @@ export async function hookDiagnostics(root, deps = {}) {
111
154
  const managedHooks = hooks.filter((hook) => hook.isManaged === true || hook.trustStatus === "managed");
112
155
  const trustedHooks = hooks.filter((hook) => hook.isManaged === true || ["managed", "trusted"].includes(hook.trustStatus));
113
156
  out.push({
114
- runtime: profile.runtime, profileHome: profile.home, installed: hooks.length > 0, trusted: managedHooks.length > 0 || (hooks.length > 0 && trustedHooks.length === hooks.length),
115
- firing: Boolean(fired(profile.runtime)), lastFiredAt: fired(profile.runtime)?.at ?? null,
157
+ runtime: label, profileHome: profile.home, installed: hooks.length > 0, trusted: managedHooks.length > 0 || (hooks.length > 0 && trustedHooks.length === hooks.length),
158
+ firing: Boolean(firing), lastFiredAt: firing?.at ?? null,
116
159
  managed: managedHooks.length > 0, managedCount: managedHooks.length,
117
- ...(managedHooks.length ? { cliStatus } : {}),
160
+ ...(managedHooks.length ? { cliStatus: codexCli } : {}),
118
161
  trustStatuses: [...new Set(hooks.map((hook) => hook.trustStatus ?? "unknown"))],
119
162
  warnings: record.warnings ?? [], errors: record.errors ?? [],
120
163
  });
121
164
  } catch (error) {
122
- out.push({ runtime: profile.runtime, profileHome: profile.home, installed: null, trusted: null, firing: Boolean(fired(profile.runtime)), lastFiredAt: fired(profile.runtime)?.at ?? null, managed: null, error: error.message });
165
+ out.push({ runtime: label, profileHome: profile.home, installed: null, trusted: null, firing: Boolean(firing), lastFiredAt: firing?.at ?? null, managed: null, error: error.message });
123
166
  }
124
167
  }
125
168
  return out;
package/dist/lanes.js CHANGED
@@ -9,7 +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 { REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
12
+ import { REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, repoGeneratedPaths, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
13
13
 
14
14
  const execFileAsync = promisify(execFile);
15
15
  const via = { via: "nodii-dev" };
@@ -574,9 +574,12 @@ export async function laneCommand(action, args, flags, deps = {}) {
574
574
  throw new CliError("LANE_WORKTREE_REQUIRED", `Run lane check from one of ${ref}'s worktrees (${worktrees.join(", ") || "none recorded"}: registered, or named in its Freeze boundaries.repos); this is ${context.worktree}.`, 2);
575
575
  const current = { ...(await reviewContext()), branch: context.branch };
576
576
  const store = checkDeps.store ?? privateStore(context.worktree);
577
+ // A-037: the reviewer reads source; Dev names this repo's generated paths.
578
+ const generatedPaths = await repoGeneratedPaths(request, context.repo);
579
+ const diff = (cwd) => (checkDeps.diff ?? laneDiff)(cwd, { generatedPaths });
577
580
  const run = await runLaneCheck(ref, flags, {
578
581
  request, lane, freeze, current, cwd: context.worktree, store,
579
- diff: checkDeps.diff ?? laneDiff,
582
+ diff,
580
583
  deltaGather: checkDeps.deltaGather ?? ((key, paths) => laneCommand("gather", [key], { delta: true, paths: paths.join(",") }, deps)),
581
584
  catalog: checkDeps.catalog ?? catalog,
582
585
  designCheck: checkDeps.designCheck ?? designCheck,
@@ -598,7 +601,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
598
601
  // Dev binds a run to base and head only, so the reviewed content must be that
599
602
  // commit, unchanged since the reviewers read it.
600
603
  const committed = await (checkDeps.committed ?? worktreeCommitted)(context.worktree);
601
- if (!committed || diffDigest((await (checkDeps.diff ?? laneDiff)(context.worktree)).text) !== run.digest)
604
+ if (!committed || diffDigest((await diff(context.worktree)).text) !== run.digest)
602
605
  throw new CliError("REVIEW_WORKTREE_DIRTY", `${[...lines, `run: nothing recorded. ${committed ? "The worktree changed while the reviewers ran" : "The reviewed diff has uncommitted or untracked changes"}, and Dev records a review for commit ${run.body.head} only. Commit them (or drop them) and rerun nodii-dev lane check ${ref}; this round does not count.`].join("\n")}`, 1);
603
606
  const file = await store.write(REVIEW_FILE, run.body);
604
607
  const payload = await recordReview(flags, run.body);
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { access, chmod, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { access, chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
3
  import { constants } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { basename, isAbsolute, join } from "node:path";
@@ -13,6 +13,22 @@ export const CODEX_HOOK_EVENTS = [
13
13
  export const managedHooksDir = (home = homedir()) => join(home, ".config", "nodii-dev", "codex-managed-hooks");
14
14
  export const MANAGED_DISPATCH_MIN_VERSION = "0.6.27";
15
15
 
16
+ // Claude reads one machine-wide managed settings file for every profile
17
+ // (CLAUDE_CONFIG_DIR never moves it), so it carries the lane-gated dispatch.
18
+ export const CLAUDE_HOOK_EVENTS = [
19
+ "SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse",
20
+ "PreCompact", "PostCompact", "SubagentStart", "SubagentStop", "Stop", "Notification", "SessionEnd",
21
+ ];
22
+ export const managedClaudeHooksDir = (home = homedir()) => join(home, ".config", "nodii-dev", "claude-managed-hooks");
23
+ export const CLAUDE_MANAGED_DISPATCH_MIN_VERSION = "0.6.58";
24
+ export const CLAUDE_MANAGED_MARK = "/claude-managed-hooks/dispatch";
25
+
26
+ /** The system file Claude Code reads managed settings from. The override is for throwaway-home proofs only. */
27
+ export function claudeManagedSettingsPath({ platform = process.platform, env = process.env } = {}) {
28
+ if (env.NODII_DEV_CLAUDE_MANAGED_SETTINGS) return env.NODII_DEV_CLAUDE_MANAGED_SETTINGS;
29
+ return platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : "/etc/claude-code/managed-settings.json";
30
+ }
31
+
16
32
  /** Only a single nodii-dev invocation is allowed; shell composition is never accepted. */
17
33
  export function nodiiCommandArgs(command) {
18
34
  const text = String(command ?? "").trim();
@@ -23,9 +39,9 @@ export function nodiiCommandArgs(command) {
23
39
  return words.map((word) => /^(['"]).*\1$/.test(word) ? word.slice(1, -1) : word);
24
40
  }
25
41
 
26
- export function validateManagedHooks(hooks = {}) {
42
+ export function validateManagedHooks(hooks = {}, { events = CODEX_HOOK_EVENTS, runtime = "Codex" } = {}) {
27
43
  for (const [event, entries] of Object.entries(hooks)) {
28
- if (!CODEX_HOOK_EVENTS.includes(event)) throw new CliError("HARNESS_INVALID", `Codex does not support managed hook event ${event}.`, 1);
44
+ if (!events.includes(event)) throw new CliError("HARNESS_INVALID", `${runtime} does not support managed hook event ${event}.`, 1);
29
45
  for (const entry of entries)
30
46
  for (const handler of entry.hooks ?? []) {
31
47
  if (handler.type !== "command") throw new CliError("HARNESS_INVALID", `Managed ${event} hooks must be command handlers.`, 1);
@@ -70,12 +86,86 @@ export function managedHookBundle(hooksText, { home, cliPath, cliVersion = VERSI
70
86
  validateManagedHooks(parsed.hooks ?? {});
71
87
  if (!isAbsolute(String(cliPath ?? ""))) throw new CliError("HARNESS_INVALID", "The managed Codex dispatcher needs the absolute nodii-dev executable path.", 1);
72
88
  const dir = managedHooksDir(home);
73
- const command = shellString(cliPath);
74
- const dispatch = `#!/bin/sh\nmanaged_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nmanaged_cli=${command}\nempty_response() {\n case "$1" in Stop|SubagentStop) printf '{}\\n' ;; esac\n}\ncase "\${NODII_DEV_CONFIG_PATH##*/}" in lane-*.json) ;; *) empty_response "$1"; exit 0 ;; esac\nif [ ! -x "$managed_cli" ]; then empty_response "$1"; exit 0; fi\nexport NODII_DEV_MANAGED_HOOKS_DIR="$managed_dir"\nexport NODII_DEV_MANAGED_CLI_PATH="$managed_cli"\nmanaged_output=$("$managed_cli" hook managed-dispatch "$1" 2>/dev/null)\nmanaged_status=$?\nif [ "$managed_status" -ne 0 ]; then empty_response "$1"; exit 0; fi\nif [ -n "$managed_output" ]; then printf '%s\\n' "$managed_output"; else empty_response "$1"; fi\n`;
89
+ const dispatch = dispatchScript(cliPath, "managed-dispatch", true);
75
90
  const metadata = `${JSON.stringify({ cliPath, cliVersion, minimumVersion: MANAGED_DISPATCH_MIN_VERSION }, null, 2)}\n`;
76
91
  return { dir, hooksText: `${JSON.stringify({ hooks: parsed.hooks ?? {} }, null, 2)}\n`, dispatch, metadata, requirements: managedRequirements(dir) };
77
92
  }
78
93
 
94
+ // The stable shell entry point both runtimes call. It acts only for a lane
95
+ // config, and every failure ends in the runtime's empty answer (fail open).
96
+ function dispatchScript(cliPath, action, stopJson) {
97
+ const command = shellString(cliPath);
98
+ const empty = stopJson ? ` case "$1" in Stop|SubagentStop) printf '{}\\n' ;; esac\n` : " :\n";
99
+ return `#!/bin/sh\nmanaged_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nmanaged_cli=${command}\nempty_response() {\n${empty}}\ncase "\${NODII_DEV_CONFIG_PATH##*/}" in lane-*.json) ;; *) empty_response "$1"; exit 0 ;; esac\nif [ ! -x "$managed_cli" ]; then empty_response "$1"; exit 0; fi\nexport NODII_DEV_MANAGED_HOOKS_DIR="$managed_dir"\nexport NODII_DEV_MANAGED_CLI_PATH="$managed_cli"\nmanaged_output=$("$managed_cli" hook ${action} "$1" 2>/dev/null)\nmanaged_status=$?\nif [ "$managed_status" -ne 0 ]; then empty_response "$1"; exit 0; fi\nif [ -n "$managed_output" ]; then printf '%s\\n' "$managed_output"; else empty_response "$1"; fi\n`;
100
+ }
101
+
102
+ /** Claude's managed settings: every event goes to the stable dispatcher; later hook changes live in hooks.json. */
103
+ export function managedClaudeSettings(dir) {
104
+ return `${JSON.stringify({ hooks: Object.fromEntries(CLAUDE_HOOK_EVENTS.map((event) => [event, [{ hooks: [{ type: "command", command: managedClaudeCommand(dir, event), timeout: 30 }] }]])) }, null, 2)}\n`;
105
+ }
106
+
107
+ // The file is root-owned and machine-wide, but the dispatcher lives in one
108
+ // user's private directory and runs as whoever runs Claude. So it is a silent
109
+ // no-op for root (never run a user-writable script as root) and for any user
110
+ // who does not own it or cannot execute it. The owner can still edit their
111
+ // own dispatcher: the same trust boundary as the Codex managed dispatch.
112
+ export const managedClaudeCommand = (dir, event) => {
113
+ const dispatcher = shellString(join(dir, "dispatch"));
114
+ return `[ "$(id -u)" = 0 ] || [ ! -O ${dispatcher} ] || [ ! -x ${dispatcher} ] || ${dispatcher} ${event}`;
115
+ };
116
+
117
+ /**
118
+ * How Claude Code's system managed file relates to the staged one:
119
+ * absent, installed (identical), merged (the operator merged our routes by
120
+ * hand), stale (only this user's nodii-dev routes, but not the staged ones),
121
+ * other_user (another user's nodii-dev routes), merged_stale (merged by hand,
122
+ * routes out of date) or foreign (no nodii-dev routes).
123
+ * Only absent and stale may be overwritten.
124
+ */
125
+ export function classifyClaudeManaged(current, staged, dir) {
126
+ if (current === null || current === undefined) return "absent";
127
+ if (staged !== null && staged !== undefined && current.trim() === staged.trim()) return "installed";
128
+ if (!current.includes(CLAUDE_MANAGED_MARK)) return "foreign";
129
+ let parsed;
130
+ try { parsed = JSON.parse(current); } catch { return "foreign"; }
131
+ const handlers = Object.values(parsed?.hooks ?? {}).flat().flatMap((entry) => entry?.hooks ?? []);
132
+ const onlyOurs = Object.keys(parsed ?? {}).every((key) => key === "hooks") && handlers.every((handler) => String(handler?.command ?? "").includes(CLAUDE_MANAGED_MARK));
133
+ // Routes to another user's dispatcher are theirs: never replaced from here.
134
+ if (onlyOurs && !handlers.every((handler) => String(handler.command).includes(join(dir, "dispatch")))) return "other_user";
135
+ if (onlyOurs) return "stale";
136
+ const routed = CLAUDE_HOOK_EVENTS.every((event) => (parsed.hooks?.[event] ?? []).some((entry) => (entry.hooks ?? []).some((handler) => handler.command === managedClaudeCommand(dir, event))));
137
+ return routed ? "merged" : "merged_stale";
138
+ }
139
+
140
+ export function managedClaudeHookBundle(settingsText, { home, cliPath, cliVersion = VERSION } = {}) {
141
+ let parsed;
142
+ try { parsed = JSON.parse(String(settingsText ?? "")); }
143
+ catch { throw new CliError("HARNESS_SETTINGS_INVALID", ".claude/settings.json is not valid JSON.", 2); }
144
+ validateManagedHooks(parsed.hooks ?? {}, { events: CLAUDE_HOOK_EVENTS, runtime: "Claude" });
145
+ if (!isAbsolute(String(cliPath ?? ""))) throw new CliError("HARNESS_INVALID", "The managed Claude dispatcher needs the absolute nodii-dev executable path.", 1);
146
+ const dir = managedClaudeHooksDir(home);
147
+ const metadata = `${JSON.stringify({ cliPath, cliVersion, minimumVersion: CLAUDE_MANAGED_DISPATCH_MIN_VERSION }, null, 2)}\n`;
148
+ return { dir, hooksText: `${JSON.stringify({ hooks: parsed.hooks ?? {} }, null, 2)}\n`, dispatch: dispatchScript(cliPath, "claude-managed-dispatch", false), metadata, managedSettings: managedClaudeSettings(dir) };
149
+ }
150
+
151
+ // Each file is replaced by rename, so a dispatch during --system reads either
152
+ // the old file or the new one, never a half-written one.
153
+ async function writeAtomic(path, text, mode) {
154
+ const temp = `${path}.${process.pid}.tmp`;
155
+ await writeFile(temp, text, { mode });
156
+ await chmod(temp, mode);
157
+ await rename(temp, path);
158
+ }
159
+
160
+ export async function writeManagedClaudeHookBundle(bundle) {
161
+ await mkdir(bundle.dir, { recursive: true, mode: 0o700 });
162
+ await writeAtomic(join(bundle.dir, "hooks.json"), bundle.hooksText, 0o600);
163
+ await writeAtomic(join(bundle.dir, "dispatch"), bundle.dispatch, 0o700);
164
+ await writeAtomic(join(bundle.dir, "metadata.json"), bundle.metadata, 0o600);
165
+ // Claude Code's managed file is read by every user, so the staged copy is world-readable.
166
+ await writeAtomic(join(bundle.dir, "managed-settings.json"), bundle.managedSettings, 0o644);
167
+ }
168
+
79
169
  export async function writeManagedHookBundle(bundle) {
80
170
  await mkdir(bundle.dir, { recursive: true, mode: 0o700 });
81
171
  await writeFile(join(bundle.dir, "hooks.json"), bundle.hooksText, { mode: 0o600 });
@@ -101,7 +191,14 @@ function runHandler(args, input, { spawnImpl = spawn, env = process.env } = {})
101
191
  const matchTarget = (event, payload) => {
102
192
  if (["PreToolUse", "PermissionRequest", "PostToolUse"].includes(event)) return payload.tool_name ?? "";
103
193
  if (event === "SessionStart") return payload.source ?? "";
104
- return payload.agent_type ?? payload.source ?? "";
194
+ return payload.agent_type ?? payload.source ?? payload.trigger ?? payload.notification_type ?? "";
195
+ };
196
+
197
+ const matchingHandlers = (config, event, payload) => {
198
+ const target = matchTarget(event, payload);
199
+ return (config.hooks?.[event] ?? []).filter((entry) => {
200
+ try { return new RegExp(entry.matcher || ".*").test(target); } catch { return false; }
201
+ }).flatMap((entry) => entry.hooks ?? []);
105
202
  };
106
203
 
107
204
  function responseOf(stdout) {
@@ -118,10 +215,7 @@ export async function dispatchManagedHook(event, payloadText, deps = {}) {
118
215
  const config = JSON.parse(await (deps.read ?? readFile)(join(dir, "hooks.json"), "utf8"));
119
216
  validateManagedHooks(config.hooks ?? {});
120
217
  const payload = JSON.parse(payloadText);
121
- const target = matchTarget(event, payload);
122
- const handlers = (config.hooks?.[event] ?? []).filter((entry) => {
123
- try { return new RegExp(entry.matcher || ".*").test(target); } catch { return false; }
124
- }).flatMap((entry) => entry.hooks ?? []);
218
+ const handlers = matchingHandlers(config, event, payload);
125
219
  const results = await Promise.all(handlers.map((handler) => (deps.run ?? runHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
126
220
  // A failed handler is unavailable policy, not a denial. Ignore both its
127
221
  // output and stderr; doctor is where hook health remains visible.
@@ -147,6 +241,71 @@ export async function dispatchManagedHook(event, payloadText, deps = {}) {
147
241
  }
148
242
  }
149
243
 
244
+ // Claude's matcher: empty or "*" matches every target, a plain name list
245
+ // ("Edit|Write") matches exactly, anything else is a regular expression.
246
+ function claudeMatcherMatches(matcher, target) {
247
+ if (!matcher || matcher === "*") return true;
248
+ if (/^[A-Za-z0-9_|]+$/.test(matcher)) return matcher.split("|").includes(target);
249
+ try { return new RegExp(matcher).test(target); } catch { return false; }
250
+ }
251
+
252
+ const claudeHandlers = (config, event, payload) => {
253
+ const target = matchTarget(event, payload);
254
+ return (config.hooks?.[event] ?? []).filter((entry) => claudeMatcherMatches(entry?.matcher, target)).flatMap((entry) => entry.hooks ?? []);
255
+ };
256
+
257
+ /**
258
+ * Claude's side of the managed dispatch. Claude handlers deny with exit 2 and
259
+ * stderr; the dispatcher turns that into Claude's JSON decision on stdout, so
260
+ * the shell entry point can keep failing open on every other status.
261
+ */
262
+ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
263
+ try {
264
+ if (!CLAUDE_HOOK_EVENTS.includes(event)) return "";
265
+ const env = deps.env ?? process.env;
266
+ if (!laneConfig(env)) return "";
267
+ const read = deps.read ?? readFile;
268
+ const dir = deps.dir ?? env.NODII_DEV_MANAGED_HOOKS_DIR ?? managedClaudeHooksDir();
269
+ const config = JSON.parse(await read(join(dir, "hooks.json"), "utf8"));
270
+ validateManagedHooks(config.hooks ?? {}, { events: CLAUDE_HOOK_EVENTS, runtime: "Claude" });
271
+ const payload = JSON.parse(payloadText);
272
+ // hooks.json is Dev's Claude settings, so its matchers follow Claude's rules.
273
+ // Every matching handler runs: no user settings file can switch managed
274
+ // policy off. Where a repository also carries the same direct hook, both run.
275
+ const handlers = claudeHandlers(config, event, payload);
276
+ const results = await Promise.all(handlers.map((handler) => (deps.run ?? runHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
277
+ const blocked = results.find((result) => result.status === 2 && result.stderr.trim());
278
+ const successful = results.filter((result) => result.status === 0);
279
+ const messages = successful.map((result) => responseOf(result.stdout)).filter(Boolean);
280
+ const contexts = messages.map((message) => message.hookSpecificOutput?.additionalContext).filter(Boolean);
281
+ const context = (extra = []) => [...contexts, ...extra].join("\n");
282
+ if (event === "PreToolUse") {
283
+ const denied = messages.find((message) => message.hookSpecificOutput?.permissionDecision === "deny");
284
+ if (denied) return `${JSON.stringify(denied)}\n`;
285
+ if (blocked) return `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, permissionDecision: "deny", permissionDecisionReason: blocked.stderr.trim() } })}\n`;
286
+ return contexts.length ? `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context() } })}\n` : "";
287
+ }
288
+ if (event === "PermissionRequest") {
289
+ const denied = messages.find((message) => message.hookSpecificOutput?.decision?.behavior === "deny");
290
+ if (denied) return `${JSON.stringify(denied)}\n`;
291
+ return blocked ? `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, decision: { behavior: "deny", message: blocked.stderr.trim() } } })}\n` : "";
292
+ }
293
+ if (["Stop", "SubagentStop", "PostToolUse", "UserPromptSubmit"].includes(event)) {
294
+ const block = messages.find((message) => message.decision === "block" && typeof message.reason === "string");
295
+ const reason = block?.reason ?? blocked?.stderr.trim();
296
+ if (reason) return `${JSON.stringify({ decision: "block", reason })}\n`;
297
+ }
298
+ // Plain stdout reaches the model only on these two events; elsewhere it is debug noise.
299
+ const plain = ["SessionStart", "UserPromptSubmit"].includes(event)
300
+ ? successful.map((result) => responseOf(result.stdout) ? "" : result.stdout.trim()).filter(Boolean)
301
+ : [];
302
+ if (!["SessionStart", "UserPromptSubmit", "PostToolUse", "PostCompact", "SubagentStart"].includes(event)) return "";
303
+ return contexts.length || plain.length ? `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context(plain) } })}\n` : "";
304
+ } catch {
305
+ return "";
306
+ }
307
+ }
308
+
150
309
  const versionParts = (value) => String(value ?? "").split(".").map((part) => Number.parseInt(part, 10));
151
310
  const atLeast = (actual, minimum) => {
152
311
  const a = versionParts(actual);
@@ -159,9 +318,9 @@ const atLeast = (actual, minimum) => {
159
318
  };
160
319
 
161
320
  /** The managed dispatcher deliberately fails open; doctor makes that visible. */
162
- export async function managedHookCliStatus({ home = homedir(), read = readFile, accessImpl = access } = {}) {
321
+ export async function managedHookCliStatus({ home = homedir(), dir = managedHooksDir(home), read = readFile, accessImpl = access } = {}) {
163
322
  let metadata;
164
- try { metadata = JSON.parse(await read(join(managedHooksDir(home), "metadata.json"), "utf8")); }
323
+ try { metadata = JSON.parse(await read(join(dir, "metadata.json"), "utf8")); }
165
324
  catch (error) {
166
325
  return { ok: false, reason: "metadata_missing", message: `managed hook metadata is unavailable (${error.code ?? error.message})` };
167
326
  }
@@ -172,3 +331,19 @@ export async function managedHookCliStatus({ home = homedir(), read = readFile,
172
331
  if (!atLeast(metadata.cliVersion, minimum)) return { ...metadata, ok: false, reason: "cli_too_old", message: `managed hook CLI ${metadata.cliVersion ?? "unknown"} is older than ${minimum}` };
173
332
  return { ...metadata, ok: true };
174
333
  }
334
+
335
+ /**
336
+ * Whether Claude Code's system managed-settings file is the one nodii-dev
337
+ * staged. Read-only: installing it stays the operator's sudo step.
338
+ */
339
+ export async function claudeManagedStatus({ home = homedir(), path = claudeManagedSettingsPath(), read = readFile } = {}) {
340
+ const dir = managedClaudeHooksDir(home);
341
+ let staged = null;
342
+ try { staged = await read(join(dir, "managed-settings.json"), "utf8"); } catch {}
343
+ let installed = null;
344
+ try { installed = await read(path, "utf8"); }
345
+ catch (error) { if (error.code !== "ENOENT") return { path, dir, state: "unreadable", message: `cannot read ${path} (${error.code ?? error.message})` }; }
346
+ const state = classifyClaudeManaged(installed, staged, dir);
347
+ return { path, dir, state: state === "absent" && staged !== null ? "staged" : state };
348
+ }
349
+
package/dist/review.js CHANGED
@@ -99,21 +99,53 @@ export async function gatesReceipt(commands, { cwd, current, store, diff, run =
99
99
  return changed;
100
100
  }
101
101
 
102
- /** DEV-REV-6: the worktree against its origin/main merge base, tracked and untracked. */
103
- export async function laneDiff(cwd, { exec = execFileAsync } = {}) {
102
+ /**
103
+ * A-037: the repo's generated-artifact prefixes, as Dev serves them on its
104
+ * harness definition (`generatedPaths`, NODII-DEV-CLI-23). Dev is the only
105
+ * source (DEV-OV-1), so a lane cannot widen the list from its own diff. No
106
+ * list, nothing excluded.
107
+ */
108
+ export async function repoGeneratedPaths(request, repo) {
109
+ const get = (drafts) => request("GET", `/api/v1/harness?repo=${encodeURIComponent(repo.toLowerCase())}${drafts ? "&includeDrafts=true" : ""}`);
110
+ // The same draft fallback as harness install: the list is per repo, not per methodology.
111
+ const harness = (await get(false).catch((error) => { if (error?.code === "METHODOLOGY_NOT_AVAILABLE") return get(true); throw error; })).data;
112
+ return (Array.isArray(harness?.generatedPaths) ? harness.generatedPaths : []).filter((path) => typeof path === "string" && path.trim());
113
+ }
114
+
115
+ /** One exclude pathspec per prefix, never per file, so a big regeneration cannot hit E2BIG. */
116
+ export const generatedPathspecs = (prefixes) => prefixes.map((prefix) => `:(exclude,glob)${prefix}**`);
117
+
118
+ /**
119
+ * DEV-REV-6: the worktree against its origin/main merge base, tracked and
120
+ * untracked. `text` is every change (the receipt and the digest cover it);
121
+ * `reviewText` leaves out the generated paths (A-037), which `paths` and
122
+ * `generated` still name. One set of pathspecs decides both, so the list and
123
+ * the diff the reviewer reads never disagree.
124
+ */
125
+ export async function laneDiff(cwd, { exec = execFileAsync, generatedPaths = [] } = {}) {
104
126
  const git = async (...args) => (await exec("git", ["-C", cwd, ...args], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 })).stdout;
105
127
  const mergeBase = (await git("merge-base", "origin/main", "HEAD")).trim();
128
+ const changedNames = async (...specs) => (await git("diff", "--name-only", mergeBase, ...(specs.length ? ["--", ".", ...specs] : []))).split("\n").map((x) => x.trim()).filter(Boolean);
129
+ const untrackedNames = async (...specs) => (await git("ls-files", "--others", "--exclude-standard", "-z", ...(specs.length ? ["--", ".", ...specs] : []))).split("\0").filter(Boolean);
130
+ const specs = generatedPathspecs(generatedPaths);
106
131
  const tracked = await git("diff", "--no-color", "--no-ext-diff", mergeBase);
107
- const names = (await git("diff", "--name-only", mergeBase)).split("\n");
108
- const untracked = (await git("ls-files", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean);
132
+ const names = await changedNames();
133
+ const untracked = await untrackedNames();
134
+ const kept = new Set(specs.length ? [...await changedNames(...specs), ...await untrackedNames(...specs)] : [...names, ...untracked]);
135
+ const paths = [...new Set([...names, ...untracked])];
136
+ const generated = paths.filter((path) => !kept.has(path));
109
137
  const added = [];
138
+ const reviewAdded = [];
110
139
  for (const path of untracked) {
140
+ let chunk;
111
141
  // --no-index exits 1 when the files differ, which they always do here.
112
- try { added.push(await git("diff", "--no-color", "--no-ext-diff", "--no-index", "--", "/dev/null", path)); }
113
- catch (error) { if (error.code === 1 && typeof error.stdout === "string") added.push(error.stdout); else throw error; }
142
+ try { chunk = await git("diff", "--no-color", "--no-ext-diff", "--no-index", "--", "/dev/null", path); }
143
+ catch (error) { if (error.code === 1 && typeof error.stdout === "string") chunk = error.stdout; else throw error; }
144
+ added.push(chunk);
145
+ if (kept.has(path)) reviewAdded.push(chunk);
114
146
  }
115
- const paths = [...new Set([...names, ...untracked].map((x) => x.trim()).filter(Boolean))];
116
- return { mergeBase, text: tracked + added.join(""), paths };
147
+ const reviewTracked = names.some((path) => !kept.has(path)) ? await git("diff", "--no-color", "--no-ext-diff", mergeBase, "--", ".", ...specs) : tracked;
148
+ return { mergeBase, text: tracked + added.join(""), reviewText: reviewTracked + reviewAdded.join(""), paths, generated };
117
149
  }
118
150
 
119
151
  /** True when the worktree is its commit: no uncommitted or untracked (not ignored) change. */
@@ -147,7 +179,7 @@ const clauseText = (clauses) => clauses.map((clause) => [
147
179
  ].join("\n")).join("\n\n");
148
180
 
149
181
  /** The reviewer's whole input: instructions, the clauses, the diff. */
150
- export function reviewerPrompt(check, { diff, clauses = [] }) {
182
+ export function reviewerPrompt(check, { diff, clauses = [], generated = [] }) {
151
183
  const ask = check === "rules"
152
184
  ? [
153
185
  "You are the rules check of a lane review (DEV-REV). You have no tools: judge only the diff and the clauses below.",
@@ -169,6 +201,7 @@ export function reviewerPrompt(check, { diff, clauses = [] }) {
169
201
  "```diff",
170
202
  diff,
171
203
  "```",
204
+ ...(generated.length ? ["", `## Generated files changed, left out of the diff (A-037: built from source, not reviewed by reading) (${generated.length})`, ...generated] : []),
172
205
  ].join("\n");
173
206
  }
174
207
 
@@ -398,8 +431,12 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
398
431
  if (!changed.text.trim()) throw new CliError("LANE_DIFF_EMPTY", `${ref}: this worktree has no change against origin/main, so there is nothing to review.`, 1);
399
432
  const runtime = lane.launch?.runtime === "codex" ? "codex" : "claude";
400
433
  const runner = { runtime, model: lane.launch?.model, profile: lane.launch?.profile };
401
- const tooLarge = changed.text.length > MAX_DIFF_CHARS
402
- ? new ReviewerError(UNAVAILABLE, `the diff is ${changed.text.length} characters; a reviewer takes at most ${MAX_DIFF_CHARS}. Split the lane.`)
434
+ // A-037: the reviewer reads source, not the generated artifacts built from it.
435
+ const reviewed = changed.reviewText ?? changed.text;
436
+ const generated = changed.generated ?? [];
437
+ const excluded = generated.length ? { generatedPaths: generated.length } : {};
438
+ const tooLarge = reviewed.length > MAX_DIFF_CHARS
439
+ ? new ReviewerError(UNAVAILABLE, `the diff is ${reviewed.length} characters${generated.length ? ` without its ${generated.length} generated file(s)` : ""}; a reviewer takes at most ${MAX_DIFF_CHARS}. Split the lane.`)
403
440
  : null;
404
441
  const loop = (await store.read(REVIEW_LOOP)) ?? {};
405
442
  const laneLoop = loop[ref]?.branch === current.branch ? loop[ref].checks ?? {} : {};
@@ -422,9 +459,9 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
422
459
  rules = errorCheck("rules", error, firstRound("rules"), { clauseIds: [], deltaGatherId: null, clauseMapGatherId: freeze?.clauseMap?.gatherId ?? null });
423
460
  }
424
461
  if (!rules) {
425
- const inputs = { clauseIds: gathered.clauseIds, clauseMapGatherId: gathered.clauseMapGatherId, deltaGatherId: gathered.deltaGatherId, runtime, diffDigest: diffDigest(changed.text) };
462
+ const inputs = { clauseIds: gathered.clauseIds, clauseMapGatherId: gathered.clauseMapGatherId, deltaGatherId: gathered.deltaGatherId, runtime, diffDigest: diffDigest(changed.text), ...excluded };
426
463
  try {
427
- const findings = await reviewer("rules", { ...runner, prompt: reviewerPrompt("rules", { diff: changed.text, clauses: gathered.clauses }), clauseIds: gathered.clauseIds });
464
+ const findings = await reviewer("rules", { ...runner, prompt: reviewerPrompt("rules", { diff: reviewed, clauses: gathered.clauses, generated }), clauseIds: gathered.clauseIds });
428
465
  rules = round("rules", findings, inputs);
429
466
  } catch (error) {
430
467
  if (!(error instanceof ReviewerError)) throw error;
@@ -460,10 +497,10 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
460
497
  let code;
461
498
  if (!critical) code = { check: "code", outcome: "NOT_REQUIRED", iterationCount: 0, reviewerErrors: [], inputs: { critical: false }, notRequired: CODE_NOT_REQUIRED, findings: [] };
462
499
  else {
463
- const inputs = { critical: true, clauseIds: gathered?.clauseIds ?? [], runtime, diffDigest: diffDigest(changed.text) };
500
+ const inputs = { critical: true, clauseIds: gathered?.clauseIds ?? [], runtime, diffDigest: diffDigest(changed.text), ...excluded };
464
501
  try {
465
502
  if (tooLarge) throw tooLarge;
466
- const findings = await reviewer("code", { ...runner, prompt: reviewerPrompt("code", { diff: changed.text, clauses: gathered?.clauses ?? [] }) });
503
+ const findings = await reviewer("code", { ...runner, prompt: reviewerPrompt("code", { diff: reviewed, clauses: gathered?.clauses ?? [], generated }) });
467
504
  code = round("code", findings, inputs);
468
505
  } catch (error) {
469
506
  if (!(error instanceof ReviewerError)) throw error;
package/dist/safety.js CHANGED
@@ -40,6 +40,9 @@ export async function recordHookFire(payload) {
40
40
  ...(payload?.tool_name ? { tool: payload.tool_name } : {}),
41
41
  };
42
42
  if (event.runtime === "codex") event.profile = basename(process.env.CODEX_HOME ?? ".codex") === ".codex-work" ? "codex-work" : "codex-personal";
43
+ // The profile directory lets doctor prove each registered runner profile fired.
44
+ event.profileHome = event.runtime === "codex" ? (process.env.CODEX_HOME ?? join(homedir(), ".codex")) : (process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"));
45
+ if (process.env.NODII_DEV_MANAGED_HOOKS_DIR) event.via = "managed";
43
46
  await mkdir(dirname(path), { recursive: true });
44
47
  await appendFile(path, `${JSON.stringify(event)}\n`, { mode: 0o600 });
45
48
  return event;
package/dist/setup.js CHANGED
@@ -3,7 +3,7 @@ import { dirname, join, resolve } from "node:path";
3
3
  import { CliError, checkLogin } from "./core.js";
4
4
  import { codexHooksFromClaude } from "./harness.js";
5
5
  import { regroundingHooksSnippet, safetySettingsSnippet } from "./safety.js";
6
- import { PICKER_MODEL, setupOllama } from "./gather.js";
6
+ import { EMBED_MODEL, PICKER_MODEL, setupOllama } from "./gather.js";
7
7
 
8
8
  export const SKILL_PATH = ".claude/skills/nodii-build-workflow/SKILL.md";
9
9
  const START = "<!-- nodii-dev build workflow:start -->";
@@ -131,10 +131,13 @@ export async function setupCommand(flags, { root = process.cwd(), authCheck = ch
131
131
  pickerReady = false;
132
132
  pickerStatus = { code: error?.code ?? "PICKER_UNAVAILABLE", message: error?.message ?? String(error) };
133
133
  }
134
+ // Only the section embedding pin is missing: the picker itself is ready.
135
+ const embedOnly = !pickerReady && String(pickerStatus.code).startsWith("EMBED_");
136
+ const missingModels = embedOnly ? [EMBED_MODEL] : [PICKER_MODEL, EMBED_MODEL];
134
137
  if (flags.check) {
135
138
  const drift = [
136
139
  ...(changes.length ? [`Workflow harness drift: ${changes.map((x) => x.relative).join(", ")}`] : []),
137
- ...(!pickerReady ? [`Gather picker: ${pickerStatus.message}`] : []),
140
+ ...(!pickerReady ? [`${embedOnly ? "Section embedding" : "Gather picker"}: ${pickerStatus.message}`] : []),
138
141
  ];
139
142
  if (drift.length) throw new CliError("SETUP_DRIFT", drift.join("; "), 1);
140
143
  return { payload: { ok: true, changed: [], authenticated, picker: pickerStatus }, human: authenticated ? "Workflow harness and Gather picker are current." : "Workflow harness and Gather picker are current. Not logged in; run `nodii-dev login`." };
@@ -142,14 +145,14 @@ export async function setupCommand(flags, { root = process.cwd(), authCheck = ch
142
145
  if (!flags.yes) {
143
146
  const preview = [
144
147
  ...(changes.length ? changes.map((x) => `${x.before === null ? "+ create" : "~ update"} ${x.relative}`) : ["No workflow changes."]),
145
- pickerReady ? `Gather picker: ${PICKER_MODEL} is ready.` : `+ install Ollama and pull ${PICKER_MODEL}`,
148
+ pickerReady ? `Gather picker: ${PICKER_MODEL} and ${EMBED_MODEL} are ready.` : `+ ${embedOnly ? "" : "install Ollama and "}pull ${missingModels.join(" and ")}`,
146
149
  ].join("\n");
147
- return { payload: { dryRun: true, changed: [...changes.map((x) => x.relative), ...(!pickerReady ? [`ollama:${PICKER_MODEL}`] : [])], authenticated, picker: pickerStatus }, human: `${preview}\n${authenticated ? "Authentication: ready." : "Authentication: not logged in; run `nodii-dev login`."}\nRun \`nodii-dev setup --yes\` to apply.` };
150
+ return { payload: { dryRun: true, changed: [...changes.map((x) => x.relative), ...(!pickerReady ? missingModels.map((m) => `ollama:${m}`) : [])], authenticated, picker: pickerStatus }, human: `${preview}\n${authenticated ? "Authentication: ready." : "Authentication: not logged in; run `nodii-dev login`."}\nRun \`nodii-dev setup --yes\` to apply.` };
148
151
  }
149
152
  if (!pickerReady) throw new CliError(pickerStatus.code, pickerStatus.message, 1);
150
153
  for (const change of changes) {
151
154
  await mkdir(dirname(change.path), { recursive: true });
152
155
  await writeFile(change.path, change.content);
153
156
  }
154
- return { payload: { applied: true, changed: [...changes.map((x) => x.relative), ...(pickerStatus.changed ?? []).map((x) => `ollama:${x}`)], authenticated, picker: pickerStatus }, human: `${changes.length ? `Applied: ${changes.map((x) => x.relative).join(", ")}` : "Workflow harness already current."}\nGather picker: ${PICKER_MODEL} ready on Ollama ${pickerStatus.version}.\n${authenticated ? "Authentication: ready." : "Not logged in; run `nodii-dev login`."}` };
157
+ return { payload: { applied: true, changed: [...changes.map((x) => x.relative), ...(pickerStatus.changed ?? []).map((x) => `ollama:${x}`)], authenticated, picker: pickerStatus }, human: `${changes.length ? `Applied: ${changes.map((x) => x.relative).join(", ")}` : "Workflow harness already current."}\nGather picker: ${PICKER_MODEL} and ${EMBED_MODEL} ready on Ollama ${pickerStatus.version}.\n${authenticated ? "Authentication: ready." : "Not logged in; run `nodii-dev login`."}` };
155
158
  }
package/dist/upload.js CHANGED
@@ -8,6 +8,7 @@ import { join, relative, resolve } from "node:path";
8
8
  import { setTimeout as sleep } from "node:timers/promises";
9
9
  import { CliError, devRequest, devTextRequest, encode, query } from "./core.js";
10
10
  import { CHANGE_CLASSES, validateDocument } from "./docs.js";
11
+ import { embedPlanned } from "./embed.js";
11
12
  import { rulesFindText } from "./gather.js";
12
13
 
13
14
  /** Exit code when Dev is waiting on the operator to acknowledge parked items. */
@@ -175,7 +176,7 @@ const uploadBody = (docs, cls, flags, decision) => ({
175
176
  // hub #406); there is no pending decision to draft any more.
176
177
  export const PENDING_NO_OP = "--pending does nothing now: decisions lock on upload.";
177
178
 
178
- export async function docsCommand(action, args, flags, { request = devRequest, log = console.error, cwd = process.cwd(), waitInterval } = {}) {
179
+ export async function docsCommand(action, args, flags, { request = devRequest, log = console.error, cwd = process.cwd(), waitInterval, embedder = {} } = {}) {
179
180
  const json = Boolean(flags.json);
180
181
  if (action === "check") {
181
182
  const docs = await checkDocuments(args, cwd);
@@ -197,6 +198,8 @@ export async function docsCommand(action, args, flags, { request = devRequest, l
197
198
  if (flags.pending && cls !== "ruling")
198
199
  throw new CliError("USAGE", "--pending requires --class ruling and --decision FILE.", 2);
199
200
  if (flags.pending) log(PENDING_NO_OP);
201
+ if (flags["no-embed"] !== undefined && action !== "upload")
202
+ throw new CliError("USAGE", "--no-embed is valid only with docs upload.", 2);
200
203
  const decision = await readJsonFile(flags.decision, "decision");
201
204
  if (cls === "ruling" && !decision) throw new CliError("RULING_NEEDS_DECISION", "A ruling write needs its decision: --decision DECISION.json (title, context, options, ruling, consequences, provenance, amends).", 2);
202
205
  if (cls !== "ruling" && decision) throw new CliError("DECISION_NEEDS_RULING", "--decision goes with --class ruling only.", 2);
@@ -227,11 +230,22 @@ export async function docsCommand(action, args, flags, { request = devRequest, l
227
230
  };
228
231
  }
229
232
 
233
+ // AGENT-HARNESS-58: Dev's dry run names each section's exact input; the
234
+ // ones Dev has no vector for are embedded here and ride with the upload.
235
+ if (flags["no-embed"]) log("Section vectors: not embedded here (--no-embed); Dev's worker embeds them.");
236
+ else {
237
+ const validated = (await request("POST", "/api/v1/documents/validate", body).catch((e) => { throw withDocumentErrors(e); })).data;
238
+ const embeddings = await embedPlanned(validated, { log, ...embedder });
239
+ if (embeddings) body.embeddings = embeddings;
240
+ }
230
241
  const result = (await withParkedGate(() => request("POST", "/api/v1/documents/upload", body), flags, { request, log, waitInterval })).data;
231
242
  return {
232
243
  payload: { data: result },
233
244
  human: [
234
- ...result.documents.map((d) => `${d.created ? "+" : "~"} ${d.code} ${d.version}\t${d.changeNote}`),
245
+ ...result.documents.flatMap((d) => [
246
+ `${d.created ? "+" : "~"} ${d.code} ${d.version}\t${d.changeNote}`,
247
+ ...(d.embedding ? [` vectors ${d.embedding.embedded}/${d.embedding.sections} (${d.embedding.fromUpload} from this Mac, ${d.embedding.reused} reused)${d.embedding.queued ? "; the rest are queued on Dev" : ""}`] : []),
248
+ ]),
235
249
  ...(result.decision
236
250
  ? [`${result.decision.status === "pending" ? "Drafted" : "Locked"} ${result.decision.id}: ${result.decision.title}`]
237
251
  : []),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.57",
3
+ "version": "0.6.60",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {