@nodii/dev 0.6.73 → 0.6.74

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/gather.js CHANGED
@@ -122,21 +122,41 @@ async function jsonRequest(path, { baseUrl = ollamaUrl(), fetchImpl = fetch, tim
122
122
  return payload;
123
123
  }
124
124
 
125
- const PINNED = { name: PICKER_MODEL, digest: PICKER_MODEL_DIGEST, digests: PICKER_MODEL_DIGESTS };
125
+ const PINNED = TUNING_MODELS["gemma-12b"];
126
+
127
+ /** Names the picker may be set to: the 12B default and every pinned tuning model. */
128
+ export const PICKER_MODEL_NAMES = Object.values(TUNING_MODELS).map((x) => x.name);
129
+ /** The environment variable that picks this machine's Gather model. */
130
+ export const PICKER_MODEL_ENV = "NODII_DEV_PICKER_MODEL";
131
+ /** The picker model name this machine is set to: the variable, else the 12B default. Never throws. */
132
+ export function pickerModelName(env = process.env) {
133
+ const value = env?.[PICKER_MODEL_ENV];
134
+ return typeof value === "string" && value.trim() ? value.trim() : PICKER_MODEL;
135
+ }
136
+ /**
137
+ * The pinned picker this machine uses (name and accepted digests). Only models
138
+ * the CLI pins are accepted, so a typo fails here, not as a silent unpinned pull.
139
+ */
140
+ export function pickerPin(env = process.env) {
141
+ const name = pickerModelName(env);
142
+ const pin = Object.values(TUNING_MODELS).find((x) => x.name === name);
143
+ if (!pin) throw new CliError("USAGE", `${PICKER_MODEL_ENV} is ${name}, which this CLI does not pin. Use one of: ${PICKER_MODEL_NAMES.join(", ")} (default ${PICKER_MODEL}), or unset it.`, 2, { allowed: PICKER_MODEL_NAMES });
144
+ return pin;
145
+ }
126
146
  // Ollama's /api/tags reports the manifest digest as bare hex; the pin carries
127
147
  // the registry's `sha256:` form. Compare them without the algorithm prefix.
128
148
  const bareDigest = (digest) => typeof digest === "string" ? digest.replace(/^sha256:/, "") : null;
129
149
  // A pin names one digest, or an allowlist of registry builds of the same tag.
130
- const pinDigests = (pin) => pin.digests ?? [pin.digest];
150
+ export const pinDigests = (pin) => pin.digests ?? [pin.digest];
131
151
  /** The accepted digest(s) of a pin, for messages: "X" or "X or Y". */
132
- export const pinnedDigests = (pin = PINNED) => pinDigests(pin).join(" or ");
152
+ export const pinnedDigests = (pin = pickerPin()) => pinDigests(pin).join(" or ");
133
153
  /** The accepted gemma4:12b build a digest is, or null when it is not one of them. */
134
154
  export function pickerBuild(digest) {
135
155
  return PICKER_MODEL_BUILDS.find((x) => bareDigest(x.digest) === bareDigest(digest)) ?? null;
136
156
  }
137
157
 
138
158
  export async function inspectOllama(options = {}) {
139
- const pin = options.model ?? PINNED;
159
+ const pin = options.model ?? pickerPin();
140
160
  const [version, tags, ps] = await Promise.all([
141
161
  jsonRequest("/api/version", options),
142
162
  jsonRequest("/api/tags", options),
@@ -159,9 +179,9 @@ export async function inspectOllama(options = {}) {
159
179
  }
160
180
 
161
181
  export async function requirePicker(options = {}) {
162
- const pin = options.model ?? PINNED;
182
+ const pin = options.model ?? pickerPin();
163
183
  // setup pulls only the 12B Gather default; tuning-only models are pulled by hand.
164
- const fix = pin.name === PICKER_MODEL ? "Run `nodii-dev setup --yes`" : `Run \`ollama pull ${pin.name}\``;
184
+ const fix = pin.name === pickerModelName() ? "Run `nodii-dev setup --yes`" : `Run \`ollama pull ${pin.name}\``;
165
185
  const status = await inspectOllama(options);
166
186
  if (!status.modelInstalled)
167
187
  throw new CliError("PICKER_MODEL_MISSING", `Local Gather picker is missing ${pin.name}. ${fix} to pull it.`, 1, status);
@@ -176,7 +196,7 @@ export async function requirePicker(options = {}) {
176
196
  */
177
197
  export async function warmPicker(options = {}) {
178
198
  const status = await requirePicker(options);
179
- const model = (options.model ?? PINNED).name;
199
+ const model = (options.model ?? pickerPin()).name;
180
200
  // Ollama keeps the context a model was loaded with; a later num_ctx does not
181
201
  // reload it (hub-58: resident at 262144). Unload a wrong-context copy first.
182
202
  if (status.loadedContext !== null && status.loadedContext !== PICKER_CONTEXT) await unloadPicker(model, options);
@@ -217,7 +237,7 @@ export function gatherDeadline(ms) {
217
237
  };
218
238
  }
219
239
 
220
- function pickerPrompt({ objective, files = [], triggers }, schema) {
240
+ export function pickerPrompt({ objective, files = [], triggers }, schema) {
221
241
  return [
222
242
  "Select every rule document that applies to this software task.",
223
243
  schema
@@ -233,13 +253,18 @@ function pickerPrompt({ objective, files = [], triggers }, schema) {
233
253
 
234
254
  const forced = (trigger) => Array.isArray(trigger?.forcedBy) ? trigger.forcedBy.length > 0 : Boolean(trigger?.forcedBy);
235
255
 
256
+ const budgetText = (ms) => (ms >= 1000 ? `${Math.round(ms / 1000)} s` : `${ms} ms`);
257
+
236
258
  /**
237
259
  * Why a lane Gather hands the pick to the agent instead (hub-58, 30 Oct): this
238
260
  * Mac has no picker model, or no Ollama at all, or a model without structured
239
- * output answered invalid JSON twice (Q-155). Null for every other failure.
261
+ * output answered invalid JSON twice (Q-155), or the model is too slow on this
262
+ * Mac to answer within the first-pick budget (rerunning only times out again).
263
+ * Null for every other failure.
240
264
  */
241
265
  export function agentFallbackReason(error) {
242
- if (error?.code === "PICKER_MODEL_MISSING") return `${error.details?.model ?? PICKER_MODEL} not installed; run nodii-dev setup`;
266
+ if (error?.code === "PICKER_MODEL_MISSING") return `${error.details?.model ?? pickerModelName()} not installed; run nodii-dev setup`;
267
+ if (error?.code === "PICKER_TIMEOUT") return `${error.details?.model ?? pickerModelName()} did not answer within ${budgetText(error.details?.timeoutMs ?? PICKER_FIRST_PICK_TIMEOUT_MS)} on this Mac`;
243
268
  if (error?.code === "PICKER_UNAVAILABLE" && error.details?.unreachable) return `no local Ollama at ${error.details.url}; run nodii-dev setup`;
244
269
  if (error?.code === "PICKER_RESPONSE_INVALID" && error.details?.unconstrained) return "gemma output invalid";
245
270
  return null;
@@ -255,7 +280,7 @@ export async function pickDocuments(input, options = {}) {
255
280
  const deadline = setTimeout(() => controller.abort(), timeoutMs);
256
281
  const signal = combineSignals([options.signal, controller.signal]);
257
282
  const timedOptions = { ...options, timeoutMs, signal };
258
- const model = (options.model ?? PINNED).name;
283
+ const model = (options.model ?? pickerPin()).name;
259
284
  const started = Date.now();
260
285
  try {
261
286
  await requirePicker(timedOptions);
@@ -281,7 +306,7 @@ export async function pickDocuments(input, options = {}) {
281
306
  if (controller.signal.aborted && !options.signal?.aborted) {
282
307
  // Not awaited: the refusal is immediate; the unload finishes before exit.
283
308
  unloadPicker(model, options).catch(() => {});
284
- throw new CliError("PICKER_TIMEOUT", `Local Gather picker ${model} did not answer within ${Math.round(timeoutMs / 1000)} s; the pick was stopped and the model unloaded. Rerun the command.`, 1);
309
+ throw new CliError("PICKER_TIMEOUT", `Local Gather picker ${model} did not answer within ${Math.round(timeoutMs / 1000)} s; the pick was stopped and the model unloaded. Rerun the command.`, 1, { model, timeoutMs });
285
310
  }
286
311
  throw error;
287
312
  } finally {
@@ -520,7 +545,7 @@ const LATENCY_PROBE = {
520
545
 
521
546
  /** Cold (model unloaded, confirmed gone) and warm pick latency for one pinned picker. */
522
547
  export async function measurePickerLatency(options = {}, { pick = pickDocuments, unload = unloadPicker, loaded = modelLoaded, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
523
- const model = (options.model ?? PINNED).name;
548
+ const model = (options.model ?? pickerPin()).name;
524
549
  await requirePicker(options);
525
550
  await unload(model, options);
526
551
  for (let i = 0; i < 50 && (await loaded(model, options)); i += 1) await sleep(200);
@@ -550,7 +575,8 @@ const tags = (clause) => {
550
575
  const parts = [
551
576
  ...(repos.length ? [`repo: ${repos.join(", ")}`] : []),
552
577
  ...(steps.length ? [`step: ${steps.join(", ")}`] : []),
553
- ...(clause.laneBase ? ["lane base"] : []),
578
+ // MW1-96: pinned for the repository and side, whatever the objective.
579
+ ...(clause.alwaysOn ? ["always-on"] : clause.laneBase ? ["lane base"] : []),
554
580
  ];
555
581
  return parts.length ? ` [${parts.join("; ")}]` : "";
556
582
  };
@@ -599,16 +625,18 @@ async function run(command, args, exec = execFileAsync) {
599
625
  catch (error) { throw new CliError("OLLAMA_SETUP_FAILED", `${command} ${args.join(" ")} failed: ${error.message}`, 1); }
600
626
  }
601
627
 
602
- export async function setupOllama({ check = false, inspect = inspectOllama, exec = execFileAsync, os = platform() } = {}) {
628
+ export async function setupOllama({ check = false, inspect = inspectOllama, exec = execFileAsync, os = platform(), env = process.env } = {}) {
629
+ const pin = pickerPin(env);
630
+ const model = pin.name;
603
631
  try {
604
- const current = await inspect();
632
+ const current = await inspect({ model: pin });
605
633
  if (current.modelInstalled && current.modelMatches) {
606
634
  const embed = await setupEmbedModel({ check, inspect, exec });
607
635
  return { changed: embed.changed, ...current, embed };
608
636
  }
609
637
  if (check && current.modelInstalled)
610
- throw new CliError("PICKER_MODEL_VERSION_MISMATCH", `${PICKER_MODEL} digest is ${current.digest ?? "unknown"}; this CLI pins ${pinnedDigests()}. Run \`nodii-dev setup --yes\` to pull it; ${STALE_PIN_HINT}`, 1, current);
611
- if (check) throw new CliError("PICKER_MODEL_MISSING", `${PICKER_MODEL} is not installed.`, 1, current);
638
+ throw new CliError("PICKER_MODEL_VERSION_MISMATCH", `${model} digest is ${current.digest ?? "unknown"}; this CLI pins ${pinnedDigests(pin)}. Run \`nodii-dev setup --yes\` to pull it; ${STALE_PIN_HINT}`, 1, current);
639
+ if (check) throw new CliError("PICKER_MODEL_MISSING", `${model} is not installed.`, 1, current);
612
640
  } catch (error) {
613
641
  if (check || !["PICKER_UNAVAILABLE", "PICKER_MODEL_MISSING"].includes(error?.code)) throw error;
614
642
  if (os !== "darwin")
@@ -616,13 +644,13 @@ export async function setupOllama({ check = false, inspect = inspectOllama, exec
616
644
  await run("brew", ["install", "ollama"], exec);
617
645
  await run("brew", ["services", "start", "ollama"], exec);
618
646
  }
619
- await run("ollama", ["pull", PICKER_MODEL], exec);
620
- const ready = await inspect();
621
- if (!ready.modelInstalled) throw new CliError("PICKER_MODEL_MISSING", `Ollama pull finished but ${PICKER_MODEL} is not installed.`, 1, ready);
647
+ await run("ollama", ["pull", model], exec);
648
+ const ready = await inspect({ model: pin });
649
+ if (!ready.modelInstalled) throw new CliError("PICKER_MODEL_MISSING", `Ollama pull finished but ${model} is not installed.`, 1, ready);
622
650
  // A fresh pull is what the registry serves now, so a mismatch here is a stale pin.
623
- 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 ${pinnedDigests()}: the pin is stale, so pulling again will not help. Update nodii-dev to a release with the current pin.`, 1, { ...ready, stalePin: true });
651
+ if (!ready.modelMatches) throw new CliError("PICKER_MODEL_VERSION_MISMATCH", `The Ollama registry serves ${model} at ${ready.digest ?? "an unknown digest"}, but this CLI pins ${pinnedDigests(pin)}: the pin is stale, so pulling again will not help. Update nodii-dev to a release with the current pin.`, 1, { ...ready, stalePin: true });
624
652
  const embed = await setupEmbedModel({ check, inspect, exec });
625
- return { changed: [PICKER_MODEL, ...embed.changed], ...ready, embed };
653
+ return { changed: [model, ...embed.changed], ...ready, embed };
626
654
  }
627
655
 
628
656
  /** The section embedding pin, pulled beside the picker (AGENT-HARNESS-58). */
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 { classifyClaudeManaged, claudeManagedSettingsPath, managedClaudeHookBundle, managedHookBundle, nodiiCommandArgs, writeManagedClaudeHookBundle, writeManagedHookBundle } from "./managed-hooks.js";
13
+ import { classifyClaudeManaged, claudeManagedSettingsPath, managedClaudeHookBundle, managedHookBundle, nodiiCommandArgs, refreshManagedDispatchers, writeManagedClaudeHookBundle, writeManagedHookBundle } from "./managed-hooks.js";
14
14
  import { nudgeSettingsSnippet } from "./nudges.js";
15
15
  import { codexSafetyHooksSnippet, regroundingHooksSnippet, safetySettingsSnippet } from "./safety.js";
16
16
 
@@ -462,7 +462,7 @@ async function checkCommand(root, repo, state, fetchHarness) {
462
462
  };
463
463
  }
464
464
 
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 } = {}) {
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, refreshManaged = refreshManagedDispatchers, claudeManagedPath = claudeManagedSettingsPath(), readSystem = optional } = {}) {
466
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);
467
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);
468
468
  if (flags.root === true || flags.repo === true) throw new CliError("USAGE", "--root and --repo need a value.", 2);
@@ -539,7 +539,7 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
539
539
  claudePlan = claudeSystemInstallPlan(claudeBundle, { target: claudeManagedPath, current, unreadable });
540
540
  }
541
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")}`
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, except the Surface-generation nudge (MW8-17), which every session gets; review ${claudePlan.source}, then run:\n${claudePlan.commands.join("\n")}`
543
543
  : `\nManaged Claude hooks are staged in ${claudeBundle.dir}; ${CLAUDE_PLAN_TEXT[claudePlan.state](claudePlan)}`;
544
544
  const systemText = systemCommands.length
545
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.`
@@ -547,6 +547,10 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
547
547
  await applyHarness(ctx.root, plan);
548
548
  if (managedBundle) await writeManaged(managedBundle);
549
549
  if (claudeBundle) await writeManagedClaude(claudeBundle);
550
+ // Without --system, a machine that already has managed hooks still gets the
551
+ // current dispatcher (its lane-free nudges included), with no sudo.
552
+ const refreshed = claudeBundle ? [] : await refreshManaged(managedHome ? { home: managedHome } : {}).catch(() => []);
553
+ const refreshText = refreshed.length ? `\nRefreshed the managed hook dispatcher in ${refreshed.join(", ")}.` : "";
550
554
  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}` };
555
+ 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}` };
552
556
  }
package/dist/hooks.js CHANGED
@@ -1,11 +1,10 @@
1
- import { CliError, devRequest, readConfig } from "./core.js";
1
+ import { CliError, devRequest } from "./core.js";
2
2
  import { FOUNDATIONS_ID, figmaLockCheck, outOfScopeText } from "./figma.js";
3
3
  import { assertWithinLaneScope, currentLaneFigmaScope } from "./figma-scope.js";
4
4
  import { execFile } from "node:child_process";
5
5
  import { readFile } from "node:fs/promises";
6
6
  import { promisify } from "node:util";
7
7
  import { safetySettingsSnippet } from "./safety.js";
8
- import { regroundCurrentLane } from "./freeze.js";
9
8
 
10
9
  const execFileAsync = promisify(execFile);
11
10
 
@@ -240,29 +239,6 @@ export async function heartbeatCurrentLane(request = devRequest) {
240
239
  return { heartbeated: true, key: lane.key };
241
240
  }
242
241
 
243
- /** SessionStart compact context, plain text for both Claude and Codex. */
244
- export async function sessionStartContext(payload, { request = devRequest, config = readConfig } = {}) {
245
- if (payload?.source !== "compact") return null;
246
- let context = "";
247
- const result = await regroundCurrentLane(
248
- {
249
- cwd: payload.cwd ?? process.cwd(),
250
- force: true,
251
- write: (text) => {
252
- context += text;
253
- },
254
- },
255
- { request, config },
256
- );
257
- // A Freeze written before it referenced the Clause map has no pointer to it.
258
- const pointer = result.shown && !context.includes("lane gather show")
259
- ? `\nFull Clause map: \`nodii-dev lane gather show ${result.lane.key}\`; one clause in full: \`nodii-dev rules show <ID>\`.`
260
- : "";
261
- return result.shown
262
- ? `${context.trimEnd()}${pointer}`
263
- : "Freeze re-grounding: no active Dev lane with initialized Freeze was available for this worktree; run `nodii-dev lane freeze show <key>` (and `nodii-dev lane gather show <key>` for its Clause map) before continuing.";
264
- }
265
-
266
242
  export function workflowSuggestion(payload) {
267
243
  const command = payload?.tool_input?.command ?? "";
268
244
  if (/\bgit\s+push\b/.test(command)) return "nodii-dev: pushed work; record it with `nodii-dev lane evidence <key> --commit <sha>` or `--pr <url>`.";
package/dist/lanes.js CHANGED
@@ -6,9 +6,10 @@ import { coordinatorMachineId, listAccounts, profilePath, reportUsage } from "./
6
6
  import { CliError, encode, devRequest, query, readConfig, requireFlag } from "./core.js";
7
7
  import { launchRecovery } from "./runtime-launcher.js";
8
8
  import { recordReviewReceipt, reviewCommitContext } from "./safety.js";
9
- import { GATHER_TIMEOUT_MS, PICKER_FIRST_PICK_TIMEOUT_MS, PICKER_MODEL, agentFallbackReason, gatherDeadline, gatherText, pickDocuments, pickTimingLine, pickTimingStats, readPickTimings, recordPickTiming, warmPicker, withPickLock } from "./gather.js";
9
+ import { GATHER_TIMEOUT_MS, PICKER_FIRST_PICK_TIMEOUT_MS, agentFallbackReason, gatherDeadline, gatherText, pickDocuments, pickerModelName, pickTimingLine, pickTimingStats, readPickTimings, recordPickTiming, warmPicker, withPickLock } from "./gather.js";
10
10
  import { storeGatherFreeze } from "./freeze.js";
11
11
  import { doneCheckRecorded } from "./lane-supervisor.js";
12
+ import { STEWARD_DONE_CHECK, stewardObjective } from "./session-kind.js";
12
13
  import { availableMemoryBytes } from "./host.js";
13
14
  import { assertNothingPending, devDown, queuePending, receiptEvidenceBody, signedBuiltAck } from "./receipt.js";
14
15
  import { SWAP_BOUNDARIES, componentsForScope, guidelineLookup, laneFigmaScope, loadDsCatalog } from "./figma-scope.js";
@@ -78,7 +79,7 @@ function agentPickerFlags(flags) {
78
79
  return null;
79
80
  }
80
81
  if (flags.picker !== "agent")
81
- throw new CliError("USAGE", `--picker accepts only agent; without it the local ${PICKER_MODEL} picks.`, 2);
82
+ throw new CliError("USAGE", `--picker accepts only agent; without it the local ${pickerModelName()} picks.`, 2);
82
83
  const shortlist = typeof flags.shortlist === "string" ? flags.shortlist.trim() : undefined;
83
84
  const documents = typeof flags.documents === "string" ? list(flags.documents) : undefined;
84
85
  if ((flags.shortlist !== undefined && !shortlist) || (flags.documents !== undefined && !documents?.length))
@@ -88,6 +89,13 @@ function agentPickerFlags(flags) {
88
89
  return { shortlist, documents };
89
90
  }
90
91
 
92
+ /** lane check's Delta gather flags; with an agent pick, the record step for that shortlist (hub-58). */
93
+ export const deltaGatherFlags = (paths, pick) => ({
94
+ delta: true,
95
+ paths: paths.join(","),
96
+ ...(pick ? { picker: "agent", shortlist: pick.shortlist, documents: pick.documents.join(",") } : {}),
97
+ });
98
+
91
99
  // hub-58: the reason is a fixed code (Dev stores its canonical text); a note may add context.
92
100
  export const NOT_APPLICABLE_REASON_CODES = ["pre_harness_lane"];
93
101
  function notApplicableRuling(flags) {
@@ -257,6 +265,9 @@ async function currentGatherLane(request, config, gitContext) {
257
265
  const branch = active.filter((lane) => repositories(lane).some((repository) =>
258
266
  repository.branch === context.branch && repoName(repository.repo ?? "") === context.repo));
259
267
  const matches = exact.length ? exact : branch;
268
+ // A steward has no worktree (MW1-93): outside any lane's worktree, its own lane.
269
+ const stewards = active.filter((lane) => lane.kind === "steward");
270
+ if (!matches.length && stewards.length === 1) return stewards[0].key;
260
271
  if (matches.length !== 1)
261
272
  throw new CliError("CURRENT_LANE_AMBIGUOUS", matches.length
262
273
  ? `This worktree matches ${matches.length} active lanes (${matches.map((lane) => lane.key).join(", ")}); pass one key explicitly.`
@@ -280,7 +291,7 @@ async function localPick(lane, warming, pick, { budgetMs, timings }) {
280
291
  const warmed = await warming;
281
292
  const pickStarted = Date.now();
282
293
  const entry = (outcome, picked) => ({
283
- at: new Date().toISOString(), lane, model: picked?.model ?? PICKER_MODEL, outcome,
294
+ at: new Date().toISOString(), lane, model: picked?.model ?? pickerModelName(), outcome,
284
295
  warmMs: pickStarted - started, warmLoadMs: warmed?.loadMs ?? null,
285
296
  pickMs: picked?.latency?.wallMs ?? Date.now() - pickStarted, loadMs: picked?.latency?.loadMs ?? null,
286
297
  totalMs: Date.now() - started, budgetMs,
@@ -458,14 +469,21 @@ export async function laneCommand(action, args, flags, deps = {}) {
458
469
  if (explicitObjective && durableObjective && explicitObjective !== durableObjective.trim())
459
470
  throw new CliError("GATHER_OBJECTIVE_CONFLICT", `${ref} already has a different objective. Use lane amend; Gather cannot rewrite the durable contract.`, 1);
460
471
  const issueObjective = typeof lane.issue?.bodyMd === "string" && lane.issue.bodyMd.trim() ? lane.issue.bodyMd : undefined;
461
- const objective = durableObjective ?? explicitObjective ?? issueObjective;
472
+ // A steward (MW1-93, MW1-94) gathers for its role and the operator's
473
+ // current focus: its Lane contract's ask (the title, or the latest
474
+ // objective amendment). It has no branch, worktree or changed paths.
475
+ const steward = lane.kind === "steward";
476
+ const roleObjective = steward && !durableObjective && !explicitObjective
477
+ ? stewardObjective(await request("GET", `/api/v1/lanes/${encode(id)}/contract`, undefined, { signal }).then((x) => x.data?.objective?.ask, () => null) ?? lane.title)
478
+ : undefined;
479
+ const objective = durableObjective ?? explicitObjective ?? roleObjective ?? issueObjective;
462
480
  if (!objective) throw new CliError("GATHER_OBJECTIVE_MISSING", `${ref} has no recorded objective. Amend the lane or pass --objective; the CLI does not invent one.`, 1);
463
481
  if (objective.length > 20_000) throw new CliError("USAGE", "The recorded Gather objective exceeds Dev's 20,000-character limit.", 2);
464
482
  const durableDoneCheck = [lane.doneCheck, lane.freeze?.objective?.doneCheck].find((x) => typeof x === "string" && x.trim());
465
483
  const explicitDoneCheck = typeof flags["done-check"] === "string" ? flags["done-check"].trim() : undefined;
466
484
  if (explicitDoneCheck && durableDoneCheck && explicitDoneCheck !== durableDoneCheck.trim())
467
485
  throw new CliError("GATHER_DONE_CHECK_CONFLICT", `${ref} already has a different done check. Use lane amend; Gather cannot rewrite the durable contract.`, 1);
468
- const doneCheck = durableDoneCheck ?? explicitDoneCheck;
486
+ const doneCheck = durableDoneCheck ?? explicitDoneCheck ?? (steward ? STEWARD_DONE_CHECK : undefined);
469
487
  if (!doneCheck) throw new CliError("GATHER_DONE_CHECK_MISSING", `${ref} has no recorded done check. Pass --done-check before Gather records anything.`, 1);
470
488
  if (doneCheck.length > 10_000) throw new CliError("USAGE", "The Gather done check exceeds Dev's 10,000-character limit.", 2);
471
489
  const legacyRepository = {
@@ -474,17 +492,19 @@ export async function laneCommand(action, args, flags, deps = {}) {
474
492
  worktree: lane.worktree,
475
493
  ownedPaths: lane.ownedPaths ?? [],
476
494
  };
477
- const sourceRepositories = lane.repositories?.length
478
- ? lane.repositories
479
- : lane.freeze?.boundaries?.repos?.length
480
- ? lane.freeze.boundaries.repos
481
- : [legacyRepository];
495
+ const sourceRepositories = steward
496
+ ? (lane.repos ?? []).map((repo) => ({ repo: typeof repo === "string" ? repo : repo.repo }))
497
+ : lane.repositories?.length
498
+ ? lane.repositories
499
+ : lane.freeze?.boundaries?.repos?.length
500
+ ? lane.freeze.boundaries.repos
501
+ : [legacyRepository];
482
502
  const repositories = sourceRepositories.map((repository) => Object.fromEntries(
483
503
  ["repo", "branch", "worktree", "ownedPaths"]
484
504
  .map((key) => [key, repository[key]])
485
505
  .filter(([, value]) => value !== undefined),
486
506
  ));
487
- if (!repositories.length || repositories.some((repository) => !repository.repo || !repository.branch || !repository.worktree))
507
+ if (!repositories.length || repositories.some((repository) => !repository.repo || (!steward && (!repository.branch || !repository.worktree))))
488
508
  throw new CliError("GATHER_BOUNDARIES_MISSING", `${ref} has an incomplete repository boundary. Repair its repo, branch, and worktree before Gather records anything.`, 1);
489
509
  const limit = flags.limit === undefined ? undefined : Number(flags.limit);
490
510
  if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 500))
@@ -497,7 +517,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
497
517
  ...(lane.freeze?.boundaries?.repos ?? []).flatMap((repository) => repository.ownedPaths ?? []),
498
518
  ...(lane.ownedPaths ?? []),
499
519
  ];
500
- const driftPaths = await changedPaths(lane, { signal });
520
+ const driftPaths = steward ? [] : await changedPaths(lane, { signal });
501
521
  if (driftPaths === null)
502
522
  throw new CliError("GATHER_PATHS_UNAVAILABLE", "Gather could not read every recorded worktree. Repair the lane boundary or make its repositories available before continuing.", 1);
503
523
  const paths = flags.paths ? list(flags.paths) : [...new Set([...recordedPaths, ...driftPaths])];
@@ -580,7 +600,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
580
600
  mode: flags.delta ? "delta" : "full",
581
601
  ...(sectionLimit !== undefined ? { sectionLimitPerDocument: sectionLimit } : {}),
582
602
  shortlistId,
583
- picker: byAgent ? "agent" : picked.model ?? PICKER_MODEL,
603
+ picker: byAgent ? "agent" : picked.model ?? pickerModelName(),
584
604
  doneCheck,
585
605
  }, { signal });
586
606
  const figma = figmaScope.map((file) => ({
@@ -696,11 +716,12 @@ export async function laneCommand(action, args, flags, deps = {}) {
696
716
  const run = await runLaneCheck(ref, flags, {
697
717
  request, lane, freeze, current, cwd: context.worktree, store,
698
718
  diff,
699
- deltaGather: checkDeps.deltaGather ?? ((key, paths) => laneCommand("gather", [key], { delta: true, paths: paths.join(",") }, deps)),
719
+ deltaGather: checkDeps.deltaGather ?? ((key, paths, pick) => laneCommand("gather", [key], deltaGatherFlags(paths, pick), deps)),
700
720
  catalog: checkDeps.catalog ?? catalog,
701
721
  designCheck: checkDeps.designCheck ?? designCheck,
702
722
  ...(checkDeps.gate ? { gate: checkDeps.gate } : {}),
703
723
  ...(checkDeps.reviewer ? { reviewer: checkDeps.reviewer } : {}),
724
+ ...(checkDeps.picker ? { picker: checkDeps.picker } : {}),
704
725
  ...(checkDeps.now ? { now: checkDeps.now } : {}),
705
726
  });
706
727
  // AGENT-HARNESS-61: an agent here without the lane's config gets no managed
@@ -14,7 +14,8 @@ export const managedHooksDir = (home = homedir()) => join(home, ".config", "nodi
14
14
  export const MANAGED_DISPATCH_MIN_VERSION = "0.6.27";
15
15
 
16
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.
17
+ // (CLAUDE_CONFIG_DIR never moves it), so it carries the lane-gated dispatch
18
+ // (and, outside lanes, only the MW8-17 Surface-generation nudge).
18
19
  export const CLAUDE_HOOK_EVENTS = [
19
20
  "SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse",
20
21
  "PreCompact", "PostCompact", "SubagentStart", "SubagentStop", "Stop", "Notification", "SessionEnd",
@@ -53,6 +54,16 @@ export function validateManagedHooks(hooks = {}, { events = CODEX_HOOK_EVENTS, r
53
54
  const tomlString = (value) => JSON.stringify(String(value));
54
55
  const shellString = (value) => `'${String(value).replaceAll("'", `'\\''`)}'`;
55
56
  const laneConfig = (env) => /^lane-[a-z0-9_-]+\.json$/i.test(basename(env.NODII_DEV_CONFIG_PATH ?? ""));
57
+
58
+ // A session that is not a lane still learns its kind (MW1-92), and a steward is
59
+ // nudged to cite before it steers (MW1-95): these handlers, on these events,
60
+ // run for every session. Everything else stays lane-only.
61
+ export const SESSION_SCOPED_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse"];
62
+ export const SESSION_SCOPED_COMMANDS = ["nodii-dev hook session-start", "nodii-dev hook session-kind", "nodii-dev hook nudge-pre"];
63
+ // The shell's cheap screen for a non-lane PreToolUse: only a call that could
64
+ // be a steering act (MW1-95) starts the CLI. The CLI decides exactly.
65
+ const STEER_MARKERS = ['*\'"SendMessage"\'*', "*'lane amend'*", "*'gh pr '*", "*'nodii.repo.yaml'*", "*'lefthook.yml'*", "*'.github/workflows/'*"];
66
+ const sessionScoped = (event, handler) => SESSION_SCOPED_EVENTS.includes(event) && SESSION_SCOPED_COMMANDS.includes(String(handler?.command ?? "").trim());
56
67
  const emptyResponse = (event) => ["Stop", "SubagentStop"].includes(event) ? "{}\n" : "";
57
68
 
58
69
  /** Stable managed policy: all later hook changes live in user-owned hooks.json. */
@@ -91,12 +102,21 @@ export function managedHookBundle(hooksText, { home, cliPath, cliVersion = VERSI
91
102
  return { dir, hooksText: `${JSON.stringify({ hooks: parsed.hooks ?? {} }, null, 2)}\n`, dispatch, metadata, requirements: managedRequirements(dir) };
92
103
  }
93
104
 
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) {
105
+ // The stable shell entry point both runtimes call. A lane config gets every
106
+ // event; any other session only the session-scoped ones (SessionStart,
107
+ // UserPromptSubmit, and a PreToolUse that could be a steering act), plus the
108
+ // MW8-17 Surface-generation nudge: an edit whose payload names a product page
109
+ // goes to `hook surface-gen-pre`, which reads only the edit. Every failure
110
+ // ends in the runtime's empty answer (fail open).
111
+ const SURFACE_GEN = `case "$managed_input" in *product-pages/*) case "$managed_input" in *'"Edit"'*|*'"Write"'*|*'"MultiEdit"'*|*'"apply_patch"'*) if [ -x "$managed_cli" ]; then managed_output=$(printf '%s' "$managed_input" | "$managed_cli" hook surface-gen-pre 2>/dev/null) && [ -n "$managed_output" ] && { printf '%s\\n' "$managed_output"; exit 0; }; fi ;; esac ;; esac; `;
112
+
113
+ export function dispatchScript(cliPath, action, stopJson) {
97
114
  const command = shellString(cliPath);
98
115
  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`;
116
+ // Only a non-lane PreToolUse reads its payload in the shell, to screen it;
117
+ // every other call passes stdin straight through, as before.
118
+ const session = ` SessionStart|UserPromptSubmit) ;;\n PreToolUse) managed_input=$(cat); managed_screened=1; ${SURFACE_GEN}case "$managed_input" in ${STEER_MARKERS.join("|")}) ;; *) empty_response "$1"; exit 0 ;; esac ;;\n *) empty_response "$1"; exit 0 ;;\n`;
119
+ return `#!/bin/sh\nmanaged_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nmanaged_cli=${command}\nempty_response() {\n${empty}}\nmanaged_screened=\ncase "\${NODII_DEV_CONFIG_PATH##*/}" in\n lane-*.json) ;;\n *) case "$1" in\n${session} esac ;;\nesac\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"\nif [ -n "$managed_screened" ]; then managed_output=$(printf '%s' "$managed_input" | "$managed_cli" hook ${action} "$1" 2>/dev/null); else managed_output=$("$managed_cli" hook ${action} "$1" 2>/dev/null); fi\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
120
  }
101
121
 
102
122
  /** Claude's managed settings: every event goes to the stable dispatcher; later hook changes live in hooks.json. */
@@ -166,6 +186,35 @@ export async function writeManagedClaudeHookBundle(bundle) {
166
186
  await writeAtomic(join(bundle.dir, "managed-settings.json"), bundle.managedSettings, 0o644);
167
187
  }
168
188
 
189
+ /**
190
+ * Refresh the staged dispatchers in place, for `harness update` without
191
+ * --system: each keeps the CLI path its metadata already names, so a plain
192
+ * update never repoints a machine's hooks at another nodii-dev. Only a
193
+ * dispatcher that exists, is staged by nodii-dev and differs is rewritten;
194
+ * the root-owned managed settings never change (they only call the dispatcher).
195
+ * A rewrite stamps metadata.json with `dispatchVersion`, the nodii-dev that
196
+ * generated the dispatcher now on disk (MW5-6); `cliVersion` keeps naming the
197
+ * CLI at `cliPath`, which doctor's version check reads.
198
+ * NODII_DEV_MANAGED_HOME is for throwaway-home proofs and tests only.
199
+ */
200
+ export async function refreshManagedDispatchers({ home = process.env.NODII_DEV_MANAGED_HOME || homedir(), read = readFile } = {}) {
201
+ const refreshed = [];
202
+ for (const [dir, action, stopJson] of [[managedClaudeHooksDir(home), "claude-managed-dispatch", false], [managedHooksDir(home), "managed-dispatch", true]]) {
203
+ try {
204
+ const metadata = JSON.parse(await read(join(dir, "metadata.json"), "utf8"));
205
+ const { cliPath } = metadata;
206
+ if (!isAbsolute(String(cliPath ?? ""))) continue;
207
+ const current = await read(join(dir, "dispatch"), "utf8");
208
+ const next = dispatchScript(cliPath, action, stopJson);
209
+ if (current === next) continue;
210
+ await writeAtomic(join(dir, "dispatch"), next, 0o700);
211
+ await writeAtomic(join(dir, "metadata.json"), `${JSON.stringify({ ...metadata, dispatchVersion: VERSION }, null, 2)}\n`, 0o600);
212
+ refreshed.push(dir);
213
+ } catch {}
214
+ }
215
+ return refreshed;
216
+ }
217
+
169
218
  export async function writeManagedHookBundle(bundle) {
170
219
  await mkdir(bundle.dir, { recursive: true, mode: 0o700 });
171
220
  await writeFile(join(bundle.dir, "hooks.json"), bundle.hooksText, { mode: 0o600 });
@@ -210,12 +259,13 @@ export async function dispatchManagedHook(event, payloadText, deps = {}) {
210
259
  try {
211
260
  if (!CODEX_HOOK_EVENTS.includes(event)) return emptyResponse(event);
212
261
  const env = deps.env ?? process.env;
213
- if (!laneConfig(env)) return emptyResponse(event);
262
+ const lane = laneConfig(env);
263
+ if (!lane && !SESSION_SCOPED_EVENTS.includes(event)) return emptyResponse(event);
214
264
  const dir = deps.dir ?? env.NODII_DEV_MANAGED_HOOKS_DIR ?? managedHooksDir();
215
265
  const config = JSON.parse(await (deps.read ?? readFile)(join(dir, "hooks.json"), "utf8"));
216
266
  validateManagedHooks(config.hooks ?? {});
217
267
  const payload = JSON.parse(payloadText);
218
- const handlers = matchingHandlers(config, event, payload);
268
+ const handlers = matchingHandlers(config, event, payload).filter((handler) => lane || sessionScoped(event, handler));
219
269
  const results = await Promise.all(handlers.map((handler) => (deps.run ?? runHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
220
270
  // A failed handler is unavailable policy, not a denial. Ignore both its
221
271
  // output and stderr; doctor is where hook health remains visible.
@@ -263,7 +313,8 @@ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
263
313
  try {
264
314
  if (!CLAUDE_HOOK_EVENTS.includes(event)) return "";
265
315
  const env = deps.env ?? process.env;
266
- if (!laneConfig(env)) return "";
316
+ const lane = laneConfig(env);
317
+ if (!lane && !SESSION_SCOPED_EVENTS.includes(event)) return "";
267
318
  const read = deps.read ?? readFile;
268
319
  const dir = deps.dir ?? env.NODII_DEV_MANAGED_HOOKS_DIR ?? managedClaudeHooksDir();
269
320
  const config = JSON.parse(await read(join(dir, "hooks.json"), "utf8"));
@@ -272,7 +323,7 @@ export async function dispatchManagedClaudeHook(event, payloadText, deps = {}) {
272
323
  // hooks.json is Dev's Claude settings, so its matchers follow Claude's rules.
273
324
  // Every matching handler runs: no user settings file can switch managed
274
325
  // policy off. Where a repository also carries the same direct hook, both run.
275
- const handlers = claudeHandlers(config, event, payload);
326
+ const handlers = claudeHandlers(config, event, payload).filter((handler) => lane || sessionScoped(event, handler));
276
327
  const results = await Promise.all(handlers.map((handler) => (deps.run ?? runHandler)(nodiiCommandArgs(handler.command), payloadText, deps)));
277
328
  const blocked = results.find((result) => result.status === 2 && result.stderr.trim());
278
329
  const successful = results.filter((result) => result.status === 0);