@nodii/dev 0.6.80 → 0.6.81

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/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.80";
7
+ export const VERSION = "0.6.81";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/safety.js CHANGED
@@ -63,6 +63,80 @@ function words(command) {
63
63
  return out;
64
64
  }
65
65
 
66
+ // A heredoc body read as text by a known text reader is not commands the shell
67
+ // runs, so it is dropped before the command is judged: a note that says
68
+ // "git push" is not a push (hub-266). The readers are `cat` and `tee`, and a
69
+ // message read from stdin (`git commit -F -`, `--body-file -`), with nothing
70
+ // piped after it. Every other heredoc (`bash <<EOF`, `ssh host <<EOF`,
71
+ // `cat <<EOF | sh`, a program this list does not know) is judged as commands:
72
+ // the hook fails closed (P-8). A body is dropped only when its delimiter is a
73
+ // whole word the hook reads exactly as the shell does, the rest of the command
74
+ // has no group, loop or substitution, and the command is one of two shapes
75
+ // that cannot run the text: only commands that never run a file (FILE_ONLY;
76
+ // no git, which runs hooks and aliases), or one lone `git`, `gh` or
77
+ // `nodii-dev` reading its message from stdin. Anything else (`bash x.sh`,
78
+ // `python3 x.py`, `./x.sh`, `git commit` after writing a hook) might run it.
79
+ const HEREDOC = /(?<!<)<<(?!<)(-?)\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\2(?=$|[\s;&|<>()])/g;
80
+ const HEREDOC_START = /(?<!<)<<(?!<)-?\s*\S/;
81
+ const GROUPED = /[(){}`]|\$\(|<\(|>\(/;
82
+ const FILE_ONLY = new Set(["cat", "tee", "echo", "printf", "true", "cd", "mkdir", "ls", "pwd", "wc", "head", "tail"]);
83
+ const MESSAGE_READERS = new Set(["git", "gh", "nodii-dev"]);
84
+ const GH_MESSAGE_VERBS = new Set(["pr", "issue", "release"]);
85
+ // Options that name a program to run: git's -c (an alias `!sh x.sh`), --exec-path, --config-env; nodii-dev's gates.
86
+ const RUNS_PROGRAM = /^(?:-c|--exec-path(?:=.*)?|--config-env(?:=.*)?|--gate(?:=.*)?|--run(?:=.*)?)$/;
87
+ function runsNothing(command) {
88
+ if (GROUPED.test(command.replace(/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g, "x"))) return false;
89
+ const parts = segments(command).map((segment) => {
90
+ const texts = segment.map((x) => x.text);
91
+ const at = texts.findIndex((x) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(x));
92
+ return at === -1 ? null : { texts, at, name: texts[at].startsWith("./") ? null : texts[at].replace(/^\S*\//, "") };
93
+ }).filter(Boolean);
94
+ if (parts.every((x) => FILE_ONLY.has(x.name))) return true;
95
+ if (parts.length !== 1 || !MESSAGE_READERS.has(parts[0].name)) return false;
96
+ const { texts, at, name } = parts[0];
97
+ if (texts.slice(at + 1).some((x) => RUNS_PROGRAM.test(x))) return false;
98
+ return name !== "gh" || GH_MESSAGE_VERBS.has(texts[at + 1]);
99
+ }
100
+ const TEXT_READER = /^(?:\S*\/)?(?:cat|tee)$/;
101
+ const STDIN_MESSAGE = /(?:^|\s)(?:-F\s*-|--file(?:=|\s+)-|--body-file(?:=|\s+)-|--comment-file(?:=|\s+)-)(?:\s|$)/;
102
+ function textHeredoc(line, at, length) {
103
+ // Inside a substitution ($(...), `...`, <(...)) the text becomes another command's input or arguments.
104
+ if (/\$\(|<\(|>\(|`/.test(line.slice(0, at))) return false;
105
+ const owner = line.slice(0, at).split(/&&|\|\||[;|(]/).at(-1).trim();
106
+ const after = line.slice(at + length).split(/&&|\|\||;/)[0];
107
+ if (/[|`]|\$\(|<\(|>\(/.test(after)) return false;
108
+ const name = owner.split(/\s+/).find((x) => x && !/^[A-Z_][A-Z0-9_]*=/.test(x)) ?? "";
109
+ if (TEXT_READER.test(name)) return true;
110
+ return /^(?:\S*\/)?(?:git|gh|nodii-dev)$/.test(name) && STDIN_MESSAGE.test(`${owner} ${after}`);
111
+ }
112
+ export function withoutHeredocBodies(command) {
113
+ const lines = String(command).split("\n");
114
+ const out = [];
115
+ // The command lines alone, without delimiter lines, for the check that nothing runs the text.
116
+ const commands = [];
117
+ const pending = [];
118
+ for (const line of lines) {
119
+ if (pending.length) {
120
+ const next = pending[0];
121
+ const text = next.tabs ? line.replace(/^\t+/, "") : line;
122
+ if (text === next.word) { pending.shift(); out.push(line); continue; }
123
+ if (next.keep) { out.push(line); commands.push(line); }
124
+ continue;
125
+ }
126
+ out.push(line);
127
+ commands.push(line);
128
+ const found = [...line.matchAll(HEREDOC)];
129
+ // A heredoc whose delimiter the hook cannot read exactly (`<<E"OF"`, `<<\EOF`) keeps everything after it.
130
+ if (line.split(HEREDOC_START).length - 1 !== found.length) { pending.push({ word: null, keep: true }); continue; }
131
+ for (const match of found)
132
+ pending.push({ word: match[3], tabs: match[1] === "-", keep: !textHeredoc(line, match.index, match[0].length) });
133
+ }
134
+ const stripped = out.join("\n");
135
+ // The text is dropped only when nothing else in the command can run it.
136
+ if (stripped !== String(command) && !runsNothing(commands.join("\n"))) return String(command);
137
+ return stripped;
138
+ }
139
+
66
140
  function commandHas(tokens, ...sequence) {
67
141
  return tokens.some((_, at) => sequence.every((part, offset) => tokens[at + offset] === part));
68
142
  }
@@ -118,7 +192,10 @@ function createsBranch(after) {
118
192
  // A hook bypass by another name is still --no-verify: lefthook's and husky's
119
193
  // off switches, and pointing Git's hooks somewhere else.
120
194
  const HOOK_BYPASS = /(?:^|[\s;&|(])(?:export\s+|env\s+)?(?:LEFTHOOK\s*=\s*["']?(?:0|false|off)\b|HUSKY\s*=\s*["']?0\b)|\bcore\.hooks[Pp]ath\b/;
121
- const usesNoVerify = (command) => gitInvocations(words(command)).some((x) => x.args.includes("--no-verify")) || HOOK_BYPASS.test(command);
195
+ const usesNoVerify = (raw) => {
196
+ const command = withoutHeredocBodies(raw);
197
+ return gitInvocations(words(command)).some((x) => x.args.includes("--no-verify")) || HOOK_BYPASS.test(command);
198
+ };
122
199
 
123
200
  // Operator, 29 Oct: a pattern kill on macOS once killed every agent on the
124
201
  // machine. Only a PID the caller started (and saved) may be killed.
@@ -197,7 +274,7 @@ function outsideWorktree(target, context, relativeKnown) {
197
274
  path = resolve(context.cwd, path);
198
275
  }
199
276
  const inside = (root) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
200
- return !inside(context.root) && !WRITABLE_ELSEWHERE().some(inside);
277
+ return !inside(context.root) && !(context.laneRoots ?? []).some(inside) && !WRITABLE_ELSEWHERE().some(inside);
201
278
  }
202
279
 
203
280
  function gitOutsideWorktree(tokens, context) {
@@ -217,6 +294,129 @@ function gitOutsideWorktree(tokens, context) {
217
294
  return null;
218
295
  }
219
296
 
297
+ const insideRoot = (root, path) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
298
+
299
+ /**
300
+ * The directory each `git push` in a command runs in: its `-C`/`--work-tree`,
301
+ * resolved against the last `cd`/`pushd`/`popd` before it. null when a variable,
302
+ * a substitution, `--git-dir`, a GIT_DIR/GIT_WORK_TREE/GIT_COMMON_DIR setting or
303
+ * `env --chdir` makes it unknowable; the hook refuses such a push.
304
+ */
305
+ const GIT_PLACE_ENV = /^GIT_(?:DIR|WORK_TREE|COMMON_DIR)=/;
306
+ export function pushTargets(raw, cwd) {
307
+ const out = [];
308
+ let dir = cwd;
309
+ // A path from `from`, as the shell and git place it; null when unknowable.
310
+ const place = (path, from) => {
311
+ if (path === undefined) return homedir();
312
+ if (path.includes("$") || path.includes("`")) return null;
313
+ if (path === "~" || path.startsWith("~/")) return join(homedir(), path.slice(1));
314
+ if (isAbsolute(path)) return resolve(path);
315
+ return from === null ? null : resolve(from, path);
316
+ };
317
+ // A `cd` inside `( ... )` ends with the subshell.
318
+ const outer = [];
319
+ // pushd's directory stack, for popd. A popd or bare pushd it cannot follow makes the directory unknown.
320
+ const pushed = [];
321
+ // An exported or assigned GIT_DIR (or kin) moves every later git command somewhere the hook cannot follow.
322
+ let gitEnvMoved = false;
323
+ for (const segment of segments(withoutHeredocBodies(raw))) {
324
+ const all = segment.map((x) => x.text);
325
+ const lead = all.findIndex((x) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(x));
326
+ const texts = lead === -1 ? [] : all.slice(lead);
327
+ const movesGit = all.some((x) => GIT_PLACE_ENV.test(x));
328
+ const envAt = texts.findIndex((x) => /^(?:\S*\/)?env$/.test(x));
329
+ const envChdir = envAt !== -1 && texts.slice(envAt + 1).some((x, i, rest) => rest.slice(0, i).every((y) => y.startsWith("-") || y.includes("=")) && /^(?:-[a-zA-Z]*C.*|--chdir(?:=.*)?)$/.test(x));
330
+ if (movesGit && !texts.some((x) => x === "git" || x.endsWith("/git"))) gitEnvMoved = true;
331
+ while (texts[0]?.startsWith("(")) { texts[0] = texts[0].slice(1); outer.push(dir); if (!texts[0]) texts.shift(); }
332
+ const closing = texts.length && !texts.at(-1).includes("(") ? /\)+$/.exec(texts.at(-1))?.[0].length ?? 0 : 0;
333
+ if (closing) texts[texts.length - 1] = texts.at(-1).slice(0, -closing);
334
+ // A builtin's arguments, without redirects (`> /dev/null`, `2>&1`).
335
+ const args = texts.slice(1).filter((x, i, all) => !/^\d*[<>]/.test(x) && !/^\d*[<>]{1,2}&?$/.test(all[i - 1] ?? ""));
336
+ const where = args.find((x) => !/^-[a-zA-Z]*$/.test(x));
337
+ if (texts[0] === "cd") dir = args.includes("-") ? null : place(where, dir);
338
+ else if (texts[0] === "pushd") { if (where === undefined || /^[+-]\d+$/.test(where)) dir = null; else { pushed.push(dir); dir = place(where, dir); } }
339
+ else if (texts[0] === "popd") dir = where === undefined && pushed.length ? pushed.pop() : null;
340
+ else for (let at = 0; at < texts.length; at += 1) {
341
+ if (texts[at] !== "git" && !texts[at].endsWith("/git")) continue;
342
+ let cursor = at + 1;
343
+ let target = envChdir ? null : dir;
344
+ let gitDir = false;
345
+ while (cursor < texts.length && texts[cursor].startsWith("-")) {
346
+ const option = texts[cursor];
347
+ // Each -C is relative to the one before it, as git reads them.
348
+ if (["-C", "--work-tree"].includes(option) && texts[cursor + 1] !== undefined) target = place(texts[cursor + 1], target);
349
+ else if (option.startsWith("--work-tree=")) target = place(option.slice("--work-tree=".length), target);
350
+ else if (option === "--git-dir" || option.startsWith("--git-dir=")) gitDir = true;
351
+ cursor += ["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"].includes(option) ? 2 : 1;
352
+ }
353
+ // 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);
355
+ }
356
+ for (let n = 0; n < closing && outer.length; n += 1) dir = outer.pop();
357
+ }
358
+ return out;
359
+ }
360
+
361
+ /** Every worktree the lane declares: its repositories, its own worktree and its Freeze boundaries.repos. */
362
+ export async function laneWorktrees(lane, { request = devRequest, root = null } = {}) {
363
+ const paths = [
364
+ root,
365
+ lane?.worktree,
366
+ ...(lane?.repositories ?? []).map((x) => x?.worktree),
367
+ ...(lane?.freeze?.boundaries?.repos ?? []).map((x) => x?.worktree),
368
+ ];
369
+ if (lane?.key && !lane?.freeze?.boundaries?.repos) {
370
+ try {
371
+ const freeze = (await request("GET", `/api/v1/lanes/${encode(lane.key)}/freeze`)).data?.freeze;
372
+ paths.push(...(freeze?.boundaries?.repos ?? []).map((x) => x?.worktree));
373
+ } catch {}
374
+ }
375
+ const real = await Promise.all(paths.filter((x) => typeof x === "string" && x).map((x) => realpath(x).catch(() => resolve(x))));
376
+ return [...new Set(real)];
377
+ }
378
+
379
+ /** The head, origin/main and local review receipt of one worktree. */
380
+ export async function repoReviewState(dir) {
381
+ const root = await realpath(await git(dir, "rev-parse", "--show-toplevel"));
382
+ const receiptText = await optional(await gitPrivatePath(root, REVIEW_RECEIPT));
383
+ return {
384
+ root,
385
+ head: await git(root, "rev-parse", "HEAD"),
386
+ base: await git(root, "rev-parse", "origin/main").catch(() => null),
387
+ receipt: receiptText ? JSON.parse(receiptText) : null,
388
+ };
389
+ }
390
+
391
+ const SCOPE_CODES = new Set(["SAFETY_OTHER_WORKTREE", "SAFETY_WRITE_OUTSIDE_WORKTREE"]);
392
+
393
+ /**
394
+ * A multi-repo lane owns every worktree it declares (hub-266). When a
395
+ * command reaches past the hook's own worktree, load the lane's worktrees, and
396
+ * judge each push by the repository it pushes. Only a proven lane context with
397
+ * resolvers (from safetyContext) is expanded; a plain context is left as given.
398
+ */
399
+ export async function expandLaneScope(command, context, { reviewState = repoReviewState } = {}) {
400
+ if (!provenLane(context) || typeof context.loadLaneRoots !== "function") return context;
401
+ const targets = pushTargets(command, context.cwd);
402
+ const reaches = targets.some((x) => x && !insideRoot(context.root, x)) || commandViolations(command, context).some((x) => SCOPE_CODES.has(x.code));
403
+ if (!reaches) return context;
404
+ context.laneRoots = await context.loadLaneRoots();
405
+ if (!targets.length) return context;
406
+ const repos = [];
407
+ for (const target of targets) {
408
+ if (!target || insideRoot(context.root, target)) {
409
+ repos.push({ root: context.root, head: context.head, base: context.base, receipt: context.reviewReceipt });
410
+ continue;
411
+ }
412
+ const state = await reviewState(target).catch(() => null);
413
+ if (!state || !context.laneRoots.includes(state.root)) repos.push({ root: state?.root ?? target, foreign: true });
414
+ else repos.push(state);
415
+ }
416
+ context.pushRepos = repos;
417
+ return context;
418
+ }
419
+
220
420
  function deployCommand(tokens, command) {
221
421
  if (commandHas(tokens, "tofu", "apply")) return true;
222
422
  if (commandHas(tokens, "terraform", "apply")) return true;
@@ -277,7 +477,8 @@ const provenLane = (context) => context.provenLane === true || (context.provenLa
277
477
  const nudgeViolation = (violation) => `nodii-dev safety: unproven lane context; ${violation.message.replace(/\bblocked\b/gi, "would be blocked")}`;
278
478
 
279
479
  /** Data-dependent checks nudge, rather than silently passing, when their source is not available yet. */
280
- export function commandNudges(command, context) {
480
+ export function commandNudges(raw, context) {
481
+ const command = withoutHeredocBodies(raw);
281
482
  const tokens = words(command);
282
483
  const nudges = [];
283
484
  if (deployCommand(tokens, command) && !context.deployGrantKnown)
@@ -294,7 +495,8 @@ export function commandNudges(command, context) {
294
495
  }
295
496
 
296
497
  /** Every costly or irreversible shell mistake AGENT-HARNESS-15 blocks. */
297
- export function commandViolations(command, context) {
498
+ export function commandViolations(raw, context) {
499
+ const command = withoutHeredocBodies(raw);
298
500
  const tokens = words(command);
299
501
  const gitCommands = gitInvocations(tokens);
300
502
  const violations = [];
@@ -329,7 +531,7 @@ export function commandViolations(command, context) {
329
531
  block("SAFETY_FORCE_PUSH", "A force push rewrites history others may hold; a lane pushes fast-forward only. Ask the coordinator.");
330
532
  if (context.root) {
331
533
  const other = gitOutsideWorktree(tokens, context);
332
- if (other) block("SAFETY_OTHER_WORKTREE", `git ${other.verb} in ${other.target} touches a checkout outside this lane's worktree ${context.root}.`);
534
+ if (other) block("SAFETY_OTHER_WORKTREE", `git ${other.verb} in ${other.target} touches a checkout outside this lane's worktree${context.laneRoots?.length > 1 ? `s (${context.laneRoots.join(", ")})` : ` ${context.root}`}.`);
333
535
  const relativeKnown = !/(?:^|[;&|(\s])(?:cd|pushd)\s/.test(command);
334
536
  const outside = writeTargets(command).filter((target) => outsideWorktree(target, context, relativeKnown));
335
537
  if (outside.length)
@@ -341,13 +543,27 @@ export function commandViolations(command, context) {
341
543
  else if (!context.noVerifyReason) block("SAFETY_NO_VERIFY_REASON", "A coordinator may use --no-verify only with a recorded reason.");
342
544
  }
343
545
 
546
+ // A push whose repository cannot be named (a variable, a substitution, --git-dir)
547
+ // cannot have its review checked, so it is refused, not judged as the hook's own (P-8).
548
+ if (lane && gitCommands.some((x) => x.verb === "push") && pushTargets(command, context.cwd ?? context.root).includes(null))
549
+ block("SAFETY_PUSH_TARGET_UNKNOWN", "Push blocked: the hook cannot tell which repository this push runs in. Push with a literal path: git -C <worktree> push, or cd <worktree> && git push.");
344
550
  if (lane && context.reviewFlowKnown && gitCommands.some((x) => x.verb === "push")) {
345
- const receipt = context.reviewReceipt;
346
- if (!receipt) block("SAFETY_REVIEW_REQUIRED", `Push blocked: no review receipt for ${context.head}. Run nodii-dev lane review after the gates are green.`);
347
- else if (receipt.commit !== context.head)
348
- block("SAFETY_REVIEW_COMMIT", `Push blocked: review covers ${receipt.commit}, not ${context.head}.`);
349
- else if (receipt.base !== context.base)
350
- block("SAFETY_REVIEW_BASE", `Push blocked: review used base ${receipt.base}, but origin/main is ${context.base}. Re-review the current diff.`);
551
+ // Each push is judged against the repository it pushes (hub-266):
552
+ // its own head, origin/main and review receipt, in its own worktree.
553
+ const repos = context.pushRepos?.length ? context.pushRepos : [{ root: context.root, head: context.head, base: context.base, receipt: context.reviewReceipt }];
554
+ for (const repo of repos) {
555
+ if (repo.foreign) {
556
+ block("SAFETY_OTHER_WORKTREE", `git push in ${repo.root} touches a checkout outside this lane's worktrees (${[context.root, ...(context.laneRoots ?? []).filter((x) => x !== context.root)].join(", ")}).`);
557
+ continue;
558
+ }
559
+ const where = repo.root && repo.root !== context.root ? ` in ${repo.root}` : "";
560
+ const receipt = repo.receipt;
561
+ if (!receipt) block("SAFETY_REVIEW_REQUIRED", `Push blocked: no review receipt for ${repo.head}${where}. Run nodii-dev lane check from that worktree after the gates are green.`);
562
+ else if (receipt.commit !== repo.head)
563
+ block("SAFETY_REVIEW_COMMIT", `Push blocked: review covers ${receipt.commit}, not ${repo.head}${where}.`);
564
+ else if (receipt.base !== repo.base)
565
+ block("SAFETY_REVIEW_BASE", `Push blocked: review used base ${receipt.base}, but origin/main is ${repo.base}${where}. Re-review the current diff.`);
566
+ }
351
567
  }
352
568
 
353
569
  if (/(?:^|[\s/])(?:nodii-dev|@nodii\/dev(?:@[^\s]+)?)\s+(?:login|logout|agent\s+register)(?:\s|$)/.test(command))
@@ -509,6 +725,8 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
509
725
  const goText = env.NODII_DEV_GO_FILE ? await optional(env.NODII_DEV_GO_FILE) : null;
510
726
  const ownership = laneOwnership(lane, root);
511
727
  const laneProject = laneStack(lane?.key);
728
+ let laneRoots = null;
729
+ const loadLaneRoots = lane ? async () => (laneRoots ??= await laneWorktrees(lane, { request, root })) : null;
512
730
  return {
513
731
  cwd: await realpath(cwd).catch(() => payloadCwd(cwd)), root, branch, head, base, role, lane, provenLane: Boolean(lane), reviewFlowKnown,
514
732
  ownedPaths: ownership.paths,
@@ -520,6 +738,8 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
520
738
  deployGrants: deployGrantsFrom(goText),
521
739
  deployGrantKnown: goText !== null,
522
740
  noVerifyReason: env.NODII_DEV_NO_VERIFY_REASON?.trim() || null,
741
+ laneRoots: [root],
742
+ loadLaneRoots,
523
743
  };
524
744
  }
525
745
 
@@ -542,6 +762,7 @@ export async function safetyPreHook(payload, contextOrResolver = safetyContext)
542
762
  context.cwd = await realpath(cwd).catch(() => resolve(cwd));
543
763
  if (SHELL_TOOLS.has(tool)) {
544
764
  const command = String(payload.tool_input?.command ?? "");
765
+ await expandLaneScope(command, context);
545
766
  const violation = commandViolations(command, context)[0];
546
767
  if (violation && provenLane(context)) blocked(violation);
547
768
  if (usesNoVerify(command) && context.role === "coordinator" && context.noVerifyReason)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.80",
3
+ "version": "0.6.81",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {