@nodii/dev 0.6.100 → 0.6.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -30,6 +30,7 @@ import { isReviewSession } from "./review-session.js";
30
30
  import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks, steerAct, stewardSteerNudges, surfaceGenPre } from "./nudges.js";
31
31
  import { activeSteward, firstPromptText, isLaneConfig, sessionStartText, stewardCommand } from "./session-kind.js";
32
32
  import { doctorCommand } from "./doctor.js";
33
+ import { installManagedLatest, managedStatus } from "./managed-version.js";
33
34
  import { dispatchManagedClaudeHook, dispatchManagedHook } from "./managed-hooks.js";
34
35
  import { governorCommand, laneClose } from "./governor.js";
35
36
  import { freezeCommand } from "./freeze.js";
@@ -863,7 +864,7 @@ export async function main(argv = process.argv.slice(2)) {
863
864
  if (command === "harness" && ["install", "update", "check"].includes(action)) {
864
865
  // `--include-drafts` is a switch: `--include-drafts false` would leave `false` here and turn drafts on.
865
866
  if (rest.length) throw new CliError("USAGE", `harness ${action} takes no arguments, got: ${rest.join(" ")}. Write a flag value as --include-drafts=false.`, 2);
866
- return emitCommand(await harnessCommand(action, f));
867
+ return emitCommand(await harnessCommand(action, f, { installManaged: installManagedLatest }));
867
868
  }
868
869
  if (command === "repo" && ["policy", "lint"].includes(action)) return emitCommand(await repoCommand(action, rest, f));
869
870
  if (command === "watchdog") {
@@ -1523,7 +1524,7 @@ export async function main(argv = process.argv.slice(2)) {
1523
1524
  await recordHookFire(payload).catch(() => {});
1524
1525
  // The session's kind and contract (MW1-92). Fails open: no output on any error.
1525
1526
  if (action === "session-start") {
1526
- const context = await sessionStartText(payload).catch(() => null);
1527
+ const context = await sessionStartText(payload, { managed: managedStatus }).catch(() => null);
1527
1528
  if (context) console.log(context);
1528
1529
  return;
1529
1530
  }
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.100";
7
+ export const VERSION = "0.6.102";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/doctor.js CHANGED
@@ -7,6 +7,7 @@ import { inferGitContext, repoName } from "./lanes.js";
7
7
  import { figmaFileKey, figmaLockCheck, holdsSet, notRegisteredHint, scopeText } from "./figma.js";
8
8
  import { EMBED_MODEL, EMBED_MODEL_DIGEST, EMBED_PIN, PICKER_CONTEXT, PICKER_MODEL_ENV, STALE_PIN_HINT, inspectOllama, pickerBuild, pickerModelName, pickerPin, pinDigests, pinnedDigests } from "./gather.js";
9
9
  import { hookDiagnostics } from "./hook-doctor.js";
10
+ import { managedStatus } from "./managed-version.js";
10
11
  import { hostBootedAt } from "./host.js";
11
12
  import { listAccounts } from "./accounts.js";
12
13
  import { LANE_ENV_FIX, agentProcesses, laneConfigName, laneEnvProblem, laneEnvReport } from "./lane-env.js";
@@ -401,6 +402,19 @@ export async function doctorCommand(deps = {}) {
401
402
  }
402
403
  }
403
404
 
405
+ // No managed hooks means no managed copy: the hook checks above report that.
406
+ try {
407
+ const copy = await (deps.managedStatus ?? managedStatus)();
408
+ if (copy) {
409
+ const extra = { cliPath: copy.cliPath, version: copy.version, latest: copy.latest };
410
+ if (!copy.latest) checks.push(cannot("managed_cli", `${copy.cliPath} is ${copy.version}; the latest release could not be read from npm`, extra));
411
+ else if (copy.behind) checks.push(missing("managed_cli", `${copy.cliPath} is ${copy.version}, behind the latest release ${copy.latest}`, "nodii-dev harness update", extra));
412
+ else checks.push(ok("managed_cli", `${copy.cliPath} is ${copy.version}, the latest release`, extra));
413
+ }
414
+ } catch (error) {
415
+ checks.push(cannot("managed_cli", error?.message ?? String(error)));
416
+ }
417
+
404
418
  const ready = checks.every((x) => x.status === "ok");
405
419
  const width = Math.max(...checks.map((x) => x.key.length));
406
420
  const human = (p) => [
package/dist/harness.js CHANGED
@@ -464,7 +464,7 @@ async function checkCommand(root, repo, state, fetchHarness) {
464
464
  };
465
465
  }
466
466
 
467
- export async function harnessCommand(action, flags, { request = devRequest, context = repoContext, managedHome, managedCliPath = fileURLToPath(new URL("../bin/nodii-dev", import.meta.url)), writeManaged = writeManagedHookBundle, writeManagedClaude = writeManagedClaudeHookBundle, refreshManaged = refreshManagedDispatchers, claudeManagedPath = claudeManagedSettingsPath(), readSystem = optional } = {}) {
467
+ export async function harnessCommand(action, flags, { request = devRequest, context = repoContext, managedHome, managedCliPath = fileURLToPath(new URL("../bin/nodii-dev", import.meta.url)), writeManaged = writeManagedHookBundle, writeManagedClaude = writeManagedClaudeHookBundle, refreshManaged = refreshManagedDispatchers, installManaged = async () => null, claudeManagedPath = claudeManagedSettingsPath(), readSystem = optional } = {}) {
468
468
  if (!["install", "update", "check"].includes(action)) throw new CliError("USAGE", "harness install|update|check [--repo NAME] [--service ID] [--include-drafts[=false]] [--adopt PATH,...] [--dry-run] [--check] [--system]", 2);
469
469
  if (flags.fleet || flags.all) throw new CliError("USAGE", "The harness is installed one service at a time, in that service's repository. There is no fleet mode.", 2);
470
470
  if (flags.root === true || flags.repo === true) throw new CliError("USAGE", "--root and --repo need a value.", 2);
@@ -520,13 +520,20 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
520
520
  throw new CliError("HARNESS_CONFLICT",
521
521
  `Nothing written. These files are not nodii-dev's to change:\n${plan.conflicts.map((c) => ` ${c.path}: ${c.reason}`).join("\n")}\n` +
522
522
  "Restore files nodii-dev wrote (git checkout, or remove your edits). For your own files, remove them or let nodii-dev take them over with --adopt PATH[,PATH].", 1, summary);
523
+ // Only the CLI passes a real installer, and only `update` runs it: a dry run
524
+ // changes nothing, and a failed install never fails the harness update.
525
+ const managedCli = action === "update" && !flags["dry-run"]
526
+ ? await installManaged({ system: Boolean(flags.system), runningCli: managedCliPath, ...(managedHome ? { home: managedHome } : {}) }).catch((error) => ({ error: error?.message ?? String(error) }))
527
+ : null;
528
+ const systemCli = managedCli?.cliPath ?? managedCliPath;
529
+ const systemCliVersion = managedCli?.version;
523
530
  const codexChange = plan.changes.find((change) => change.path === ".codex/hooks.json");
524
531
  const codexText = codexChange?.text ?? await optional(join(ctx.root, ".codex/hooks.json"));
525
- const managedBundle = flags.system ? managedHookBundle(codexText, { home: managedHome, cliPath: managedCliPath }) : null;
532
+ const managedBundle = flags.system ? managedHookBundle(codexText, { home: managedHome, cliPath: systemCli, cliVersion: systemCliVersion }) : null;
526
533
  // Claude's managed layer carries only Dev's generated hooks, never the user
527
534
  // entries a merged settings file on disk may also hold.
528
535
  const claudeSettings = harness.files.find((file) => file.path === ".claude/settings.json")?.content ?? "{}";
529
- const claudeBundle = flags.system ? managedClaudeHookBundle(claudeSettings, { home: managedHome, cliPath: managedCliPath }) : null;
536
+ const claudeBundle = flags.system ? managedClaudeHookBundle(claudeSettings, { home: managedHome, cliPath: systemCli, cliVersion: systemCliVersion }) : null;
530
537
  const systemCommands = managedBundle ? systemHookInstallPlan(managedBundle) : [];
531
538
  if (flags["dry-run"]) {
532
539
  const preview = managedBundle ? `\nWould stage managed Codex hooks in ${managedBundle.dir} and managed Claude hooks in ${claudeBundle.dir}. Dry run: no managed files were written and no sudo commands are printed until they exist.` : "";
@@ -553,6 +560,10 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
553
560
  // current dispatcher (its lane-free nudges included), with no sudo.
554
561
  const refreshed = claudeBundle ? [] : await refreshManaged(managedHome ? { home: managedHome } : {}).catch(() => []);
555
562
  const refreshText = refreshed.length ? `\nRefreshed the managed hook dispatcher in ${refreshed.join(", ")}.` : "";
563
+ const managedCliText = !managedCli ? ""
564
+ : managedCli.error ? `\nwarning: the managed nodii-dev was not updated: ${managedCli.error}`
565
+ : managedCli.current ? `\nThe managed nodii-dev is at the latest release, ${managedCli.version}.`
566
+ : `\nInstalled the managed nodii-dev ${managedCli.version}${managedCli.previous ? ` over ${managedCli.previous}` : ""} at ${managedCli.cliPath}.`;
556
567
  const claudeData = claudePlan ? { claudeManagedDir: claudeBundle.dir, claudeManaged: { state: claudePlan.state, target: claudePlan.target, systemCommands: claudePlan.commands } } : {};
557
- return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands: [...systemCommands, ...(claudePlan?.commands ?? [])], managedDir: managedBundle.dir } : {}), ...claudeData, ...(refreshed.length ? { managedDispatchRefreshed: refreshed } : {}) } }, human: `${lines.join("\n")}\n${plan.changes.length ? `${action === "install" ? "Installed" : "Updated"}: ${plan.changes.length} change${plan.changes.length === 1 ? "" : "s"}.` : "Harness already current."}${systemText}${refreshText}` };
568
+ return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands: [...systemCommands, ...(claudePlan?.commands ?? [])], managedDir: managedBundle.dir } : {}), ...claudeData, ...(refreshed.length ? { managedDispatchRefreshed: refreshed } : {}), ...(managedCli ? { managedCli } : {}) } }, human: `${lines.join("\n")}\n${plan.changes.length ? `${action === "install" ? "Installed" : "Updated"}: ${plan.changes.length} change${plan.changes.length === 1 ? "" : "s"}.` : "Harness already current."}${systemText}${refreshText}${managedCliText}` };
558
569
  }
@@ -0,0 +1,119 @@
1
+ // The managed nodii-dev copy against the latest release. Every hook on a
2
+ // machine runs the copy the managed dispatcher names, so a machine can enforce
3
+ // last month's rules with a current PATH and nobody sees it. SessionStart warns
4
+ // when that copy is behind, `doctor` reports it, and `harness update` installs
5
+ // the latest release over it. A failed lookup says nothing and blocks nothing.
6
+ import { execFile } from "node:child_process";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { dirname, isAbsolute, join } from "node:path";
10
+ import { promisify } from "node:util";
11
+ import { managedClaudeHooksDir, managedHooksDir } from "./managed-hooks.js";
12
+
13
+ const PACKAGE = "@nodii/dev";
14
+ const GLOBAL_INSTALL = /^(.+)\/lib\/node_modules\/@nodii\/dev\/bin\/nodii-dev$/;
15
+ const LOOKUP_TIMEOUT_MS = 3_000;
16
+ const INSTALL_TIMEOUT_MS = 120_000;
17
+ const CACHE_MS = 60 * 60 * 1000;
18
+ const runNpm = promisify(execFile);
19
+
20
+ const defaultHome = () => process.env.NODII_DEV_MANAGED_HOME || homedir();
21
+ const metadataPaths = (home) => [managedClaudeHooksDir(home), managedHooksDir(home)].map((dir) => join(dir, "metadata.json"));
22
+ const readJson = async (read, path) => { try { return JSON.parse(await read(path, "utf8")); } catch { return null; } };
23
+
24
+ const triple = (version) => {
25
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(version ?? ""));
26
+ return match ? match.slice(1).map(Number) : null;
27
+ };
28
+
29
+ /** Is `version` an older release than `latest`? An unreadable version is not behind anything. */
30
+ export function isBehind(version, latest) {
31
+ const a = triple(version);
32
+ const b = triple(latest);
33
+ if (!a || !b) return false;
34
+ const at = a.findIndex((part, i) => part !== b[i]);
35
+ return at >= 0 && a[at] < b[at];
36
+ }
37
+
38
+ /** The copy the managed dispatchers run, and the version installed there, or null with no managed hooks. */
39
+ export async function managedCopy({ home = defaultHome(), read = readFile } = {}) {
40
+ for (const path of metadataPaths(home)) {
41
+ const metadata = await readJson(read, path);
42
+ if (!isAbsolute(String(metadata?.cliPath ?? ""))) continue;
43
+ // The package beside the binary is what runs; metadata only says what ran at the last --system.
44
+ const installed = await readJson(read, join(dirname(dirname(metadata.cliPath)), "package.json"));
45
+ return { cliPath: metadata.cliPath, version: installed?.version ?? metadata.cliVersion ?? null };
46
+ }
47
+ return null;
48
+ }
49
+
50
+ /**
51
+ * The latest released version. SessionStart is on the path of every session, so
52
+ * a lookup is kept for an hour and a failed one falls back to what was last
53
+ * read. `fresh` skips the kept answer: an install must not trust an old one.
54
+ */
55
+ export async function latestRelease({ home = defaultHome(), exec = runNpm, read = readFile, now = Date.now, fresh = false, timeout = LOOKUP_TIMEOUT_MS } = {}) {
56
+ const path = join(home, ".config/nodii-dev/latest-release.json");
57
+ const kept = await readJson(read, path);
58
+ if (!fresh && kept?.version && now() - kept.checkedAt < CACHE_MS) return kept.version;
59
+ try {
60
+ const { stdout } = await exec("npm", ["view", PACKAGE, "version"], { timeout });
61
+ const version = String(stdout).trim();
62
+ if (!triple(version)) return kept?.version ?? null;
63
+ await mkdir(dirname(path), { recursive: true });
64
+ const temporary = `${path}.${process.pid}`;
65
+ await writeFile(temporary, `${JSON.stringify({ version, checkedAt: now() })}\n`);
66
+ await rename(temporary, path);
67
+ return version;
68
+ } catch {
69
+ return kept?.version ?? null;
70
+ }
71
+ }
72
+
73
+ /** Where the managed copy stands: null with no managed hooks; `latest` null when no release could be read. */
74
+ export async function managedStatus(options = {}) {
75
+ const copy = await managedCopy(options);
76
+ if (!copy) return null;
77
+ const latest = await latestRelease(options);
78
+ return { ...copy, latest, behind: isBehind(copy.version, latest) };
79
+ }
80
+
81
+ export const managedBehindText = ({ version, latest }) =>
82
+ `WARNING: the managed nodii-dev on this machine is ${version}, behind the latest release ${latest}, and every hook here runs that copy. Fix: \`nodii-dev harness update\`.`;
83
+
84
+ /**
85
+ * `harness update`: put the latest release where the managed dispatcher looks.
86
+ * Returns null with no managed copy to update, `{ cliPath, version, previous }`
87
+ * after an install or `{ cliPath, version, current: true }` with nothing to do.
88
+ * Throws when it could not install; the caller reports that and carries on.
89
+ */
90
+ export async function installManagedLatest({ system = false, runningCli = null, home = defaultHome(), exec = runNpm, read = readFile, write = writeFile, now = Date.now } = {}) {
91
+ const copy = await managedCopy({ home, read });
92
+ if (!copy && !system) return null;
93
+ const latest = await latestRelease({ home, exec, read, now, fresh: true });
94
+ if (!latest) throw new Error(`could not read the latest ${PACKAGE} release from npm`);
95
+ const prefix = await installPrefix({ copy, system, runningCli, exec });
96
+ const cliPath = `${prefix}/lib/node_modules/@nodii/dev/bin/nodii-dev`;
97
+ const installed = await readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
98
+ if (installed?.version && !isBehind(installed.version, latest)) return { cliPath, version: installed.version, current: true };
99
+ await exec("npm", ["install", "-g", `${PACKAGE}@${latest}`, "--prefix", prefix], { timeout: INSTALL_TIMEOUT_MS });
100
+ const after = await readJson(read, join(prefix, "lib/node_modules/@nodii/dev/package.json"));
101
+ if (after?.version !== latest) throw new Error(`npm finished but ${cliPath} is at ${after?.version ?? "no version"}, not ${latest}`);
102
+ // The dispatcher's version check reads this (MW5-6), so it follows the copy.
103
+ for (const path of metadataPaths(home)) {
104
+ const metadata = await readJson(read, path);
105
+ if (metadata?.cliPath === cliPath) await write(path, `${JSON.stringify({ ...metadata, cliVersion: latest }, null, 2)}\n`, { mode: 0o600 });
106
+ }
107
+ return { cliPath, version: latest, previous: installed?.version ?? null };
108
+ }
109
+
110
+ async function installPrefix({ copy, system, runningCli, exec }) {
111
+ const named = GLOBAL_INSTALL.exec(String(copy?.cliPath ?? ""));
112
+ if (named) return named[1];
113
+ if (!system) throw new Error(`the managed copy at ${copy.cliPath} is not a global npm install; run \`nodii-dev harness update --system\` from one`);
114
+ const running = GLOBAL_INSTALL.exec(String(runningCli ?? ""));
115
+ if (running) return running[1];
116
+ // Run from npx or a checkout: that path is not somewhere to pin every hook on the machine.
117
+ const { stdout } = await exec("npm", ["prefix", "-g"], { timeout: LOOKUP_TIMEOUT_MS });
118
+ return String(stdout).trim();
119
+ }
package/dist/safety.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
2
3
  import { appendFile, mkdir, readFile, realpath, writeFile } from "node:fs/promises";
3
4
  import { homedir, tmpdir } from "node:os";
4
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -185,8 +186,59 @@ function commandRef(after, verb) {
185
186
  return null;
186
187
  }
187
188
 
189
+ /**
190
+ * The one form the record can allow, and nothing else: `-c NAME [START]` or `-b NAME [START]`.
191
+ * An allowlist on purpose. Git takes the last of a repeated option and accepts abbreviated long
192
+ * ones, so any other argument could change the branch or discard work.
193
+ */
194
+ function createdBranchName(args) {
195
+ if (args.length < 2 || args.length > 3 || !["-c", "-b"].includes(args[0])) return null;
196
+ const operands = args.slice(1);
197
+ // Only plain ref characters: the shell would expand anything else, such as `{-f,x}`, into new arguments.
198
+ if (operands.some((item) => !/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(item))) return null;
199
+ return operands[0];
200
+ }
201
+
202
+ /**
203
+ * True only when every branch-creating switch or checkout in the command creates the
204
+ * branch Dev's boundary record names, in the worktree that record names. `boundaries`
205
+ * is read from Dev for this call (safetyPreHook); there is no local way to supply it,
206
+ * and with no record nothing is allowed.
207
+ */
208
+ function createsRecordedBranch(raw, context, gitCommands) {
209
+ const boundaries = context.devBoundaries;
210
+ if (!Array.isArray(boundaries)) return false;
211
+ const creating = gitPlaces(raw, context.cwd).filter((x) => ["switch", "checkout"].includes(x.verb) && createsBranch(x.args));
212
+ // The block below reads commands with another parser: if the two disagree, allow nothing.
213
+ const blocking = gitCommands.filter((x) => ["switch", "checkout"].includes(x.verb) && createsBranch(x.args));
214
+ if (creating.length !== blocking.length) return false;
215
+ const real = (path) => { try { return realpathSync(path); } catch { return resolve(path); } };
216
+ return creating.length > 0 && creating.every((x) => {
217
+ // Exactly one absolute -C and no other git option: git fails if it can't go there, where a failed cd would leave
218
+ // the command in another repository, and --work-tree or -c could change what it acts on.
219
+ const name = createdBranchName(x.args);
220
+ const named = x.globals.length === 2 && x.globals[0] === "-C" && isAbsolute(x.globals[1]);
221
+ return Boolean(name && x.target && named) && boundaries.some((b) => b.branch === name && typeof b.worktree === "string" && real(b.worktree) === real(x.target));
222
+ });
223
+ }
224
+
225
+ const createsAnyBranch = (raw) => gitPlaces(raw, null).some((x) => ["switch", "checkout"].includes(x.verb) && createsBranch(x.args));
226
+
227
+ /** The lane's current repository boundaries, read from Dev. null when Dev can't say: the caller refuses. */
228
+ async function devBoundaries(key, request) {
229
+ if (!key) return null;
230
+ try {
231
+ const repos = (await request("GET", `/api/v1/lanes/${encode(key)}/freeze`)).data?.freeze?.boundaries?.repos;
232
+ if (!Array.isArray(repos)) return null;
233
+ return await Promise.all(repos.map(async (x) => ({ branch: x?.branch, worktree: typeof x?.worktree === "string" ? await realpath(x.worktree).catch(() => x.worktree) : null })));
234
+ } catch {
235
+ return null;
236
+ }
237
+ }
238
+
239
+ // Every way git spells it: `-c X`, glued `-cX`, bundled `-fB X`, `--create=X` and abbreviations such as `--cr X`.
188
240
  function createsBranch(after) {
189
- return after.some((item) => ["-b", "-B", "-c", "-C", "--orphan", "--create", "--force-create"].includes(item));
241
+ return after.some((item) => /^-[a-zA-Z]*[bBcC]/.test(item) || /^--(?:cr|or|force-)/.test(item));
190
242
  }
191
243
 
192
244
  // A hook bypass by another name is still --no-verify: lefthook's and husky's
@@ -304,6 +356,11 @@ const insideRoot = (root, path) => { const rel = relative(root, path); return re
304
356
  */
305
357
  const GIT_PLACE_ENV = /^GIT_(?:DIR|WORK_TREE|COMMON_DIR)=/;
306
358
  export function pushTargets(raw, cwd) {
359
+ return gitPlaces(raw, cwd).filter((x) => x.verb === "push").map((x) => x.target);
360
+ }
361
+
362
+ /** Each git command in `raw`, with its verb, arguments and directory (null when unknowable). */
363
+ function gitPlaces(raw, cwd) {
307
364
  const out = [];
308
365
  let dir = cwd;
309
366
  // A path from `from`, as the shell and git place it; null when unknowable.
@@ -342,6 +399,7 @@ export function pushTargets(raw, cwd) {
342
399
  let cursor = at + 1;
343
400
  let target = envChdir ? null : dir;
344
401
  let gitDir = false;
402
+ const start = cursor;
345
403
  while (cursor < texts.length && texts[cursor].startsWith("-")) {
346
404
  const option = texts[cursor];
347
405
  // Each -C is relative to the one before it, as git reads them.
@@ -351,7 +409,7 @@ export function pushTargets(raw, cwd) {
351
409
  cursor += ["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"].includes(option) ? 2 : 1;
352
410
  }
353
411
  // A repository named apart from the directory (--git-dir, GIT_DIR) cannot be placed, whatever -C says.
354
- if (texts[cursor] === "push") out.push(gitDir || gitEnvMoved || movesGit ? null : target);
412
+ if (texts[cursor]) out.push({ verb: texts[cursor], args: texts.slice(cursor + 1), target: gitDir || gitEnvMoved || movesGit ? null : target, globals: texts.slice(start, cursor) });
355
413
  }
356
414
  for (let n = 0; n < closing && outer.length; n += 1) dir = outer.pop();
357
415
  }
@@ -523,11 +581,11 @@ export function commandViolations(raw, context) {
523
581
  if (gitCommands.some((x) => x.verb === "stash"))
524
582
  block("SAFETY_GIT_STASH", "git stash is shared by every worktree; lanes and subagents use a work-in-progress commit.");
525
583
 
526
- for (const verb of ["checkout", "switch"]) {
527
- const invocation = gitCommands.find((x) => x.verb === verb);
528
- if (!invocation) continue;
584
+ const recordedCreate = createsRecordedBranch(raw, context, gitCommands);
585
+ for (const invocation of gitCommands.filter((x) => x.verb === "checkout" || x.verb === "switch")) {
586
+ const { verb } = invocation;
529
587
  if (createsBranch(invocation.args)) {
530
- block("SAFETY_GIT_BRANCH", `git ${verb} would create and leave the lane branch ${context.branch}.`);
588
+ if (!recordedCreate) block("SAFETY_GIT_BRANCH", `git ${verb} would create and leave the lane branch ${context.branch}.${context.devBoundaries === null ? " Dev couldn't be read, so no branch can be checked against this lane's record." : ""}`);
531
589
  continue;
532
590
  }
533
591
  const ref = commandRef(invocation.args, verb);
@@ -769,7 +827,7 @@ function blocked(violation) {
769
827
  }
770
828
 
771
829
  /** Runtime-neutral PreToolUse entrypoint. Silent return means allowed. */
772
- export async function safetyPreHook(payload, contextOrResolver = safetyContext) {
830
+ export async function safetyPreHook(payload, contextOrResolver = safetyContext, { request = devRequest } = {}) {
773
831
  const tool = payload.tool_name ?? "";
774
832
  if (!SHELL_TOOLS.has(tool) && !EDIT_TOOLS.has(tool)) return { allowed: true, ignored: true };
775
833
  if (SHELL_TOOLS.has(tool)) {
@@ -782,6 +840,8 @@ export async function safetyPreHook(payload, contextOrResolver = safetyContext)
782
840
  if (SHELL_TOOLS.has(tool)) {
783
841
  const command = String(payload.tool_input?.command ?? "");
784
842
  await expandLaneScope(command, context);
843
+ // Read here, for this call, so it can only come from Dev. A failed read leaves null, which refuses.
844
+ context.devBoundaries = provenLane(context) && createsAnyBranch(command) ? await devBoundaries(context.lane?.key, request) : null;
785
845
  const violation = commandViolations(command, context)[0];
786
846
  if (violation && provenLane(context)) blocked(violation);
787
847
  if (usesNoVerify(command) && context.role === "coordinator" && context.noVerifyReason)
@@ -13,6 +13,7 @@ import { basename, dirname, join } from "node:path";
13
13
  import { CliError, configPath, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
14
14
  import { currentLane, regroundLane } from "./freeze.js";
15
15
  import { gatherText } from "./gather.js";
16
+ import { managedBehindText } from "./managed-version.js";
16
17
 
17
18
  export const SESSION_KINDS = ["lane", "coordinator", "steward", "operator_assistant"];
18
19
  const KIND_LABEL = { lane: "lane", coordinator: "coordinator", steward: "steward", operator_assistant: "operator assistant" };
@@ -140,12 +141,14 @@ async function stewardClauseMap(steward, request) {
140
141
  }
141
142
 
142
143
  /** Plain text for SessionStart: the kind, its contract and, where it has one, its stored contract. */
143
- export async function sessionStartText(payload, { request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, state = writeKindState } = {}) {
144
+ export async function sessionStartText(payload, { managed = async () => null, request = devRequest, config = readConfig, env = process.env, dev = kindFromDev, state = writeKindState } = {}) {
144
145
  const cwd = payload?.cwd ?? process.cwd();
145
146
  const compact = payload?.source === "compact";
146
147
  const resolved = { ...(await dev({ cwd, env }, { request, config })), notes: [] };
147
148
  await state(payload?.session_id, { kind: resolved.kind, source: resolved.source }).catch(() => {});
148
149
  const parts = [await kindText(resolved, { request })];
150
+ const copy = await managed().catch(() => null);
151
+ if (copy?.behind) parts[0] = `${managedBehindText(copy)}\n${parts[0]}`;
149
152
  if (resolved.kind === "lane" && resolved.lane && compact) {
150
153
  let context = "";
151
154
  const result = await regroundLane(resolved.lane, { force: true, write: (text) => { context += text; } }, { request }).catch(() => ({ shown: false }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.100",
3
+ "version": "0.6.102",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {