@nodii/dev 0.6.79 → 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.
Files changed (3) hide show
  1. package/dist/core.js +114 -2
  2. package/dist/safety.js +232 -11
  3. package/package.json +1 -1
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.79";
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");
@@ -135,7 +135,7 @@ const withSignal = (promise, signal) => {
135
135
  });
136
136
  };
137
137
 
138
- async function devFetch(method, path, bodyText, contentType, accept, extra = {}, signal) {
138
+ async function devFetchOnce(method, path, bodyText, contentType, accept, extra = {}, signal) {
139
139
  const wait = async (promise) => {
140
140
  try {
141
141
  return await withSignal(promise, signal);
@@ -175,6 +175,118 @@ async function devFetch(method, path, bodyText, contentType, accept, extra = {},
175
175
  }
176
176
  }
177
177
 
178
+ // hub-254: an operator-only route refuses the CLI's sign-in (an
179
+ // OAuth agent) with 403 OPERATOR_REQUIRED. When a person is at the terminal,
180
+ // the CLI asks for their TOTP code, Dev verifies it against the signed-in
181
+ // person, and the call is sent again with the ten-minute grant Dev returns.
182
+ // The code is never stored, logged or passed on; the grant lives only in this
183
+ // process's memory. Without a TTY (an agent) the refusal is surfaced as it is.
184
+ export const OPERATOR_STEP_UP_PATH = "/api/v1/operator/step-up";
185
+ export const OPERATOR_STEP_UP_HEADER = "x-operator-step-up";
186
+ let stepUpGrant = null; // { grant, expiresAt } for this process only
187
+ let pendingStepUp = null; // the step-up in flight, shared by concurrent refusals
188
+ let totpPrompt = defaultTotpPrompt;
189
+
190
+ /** Tests replace the TTY prompt; `null` restores the default. Also forgets the grant. */
191
+ export function setTotpPrompt(fn) {
192
+ totpPrompt = fn ?? defaultTotpPrompt;
193
+ stepUpGrant = null;
194
+ pendingStepUp = null;
195
+ }
196
+
197
+ /** Reads one code from the terminal without echoing it, or null when there is no TTY. */
198
+ async function defaultTotpPrompt() {
199
+ if (!process.stdin.isTTY || !process.stderr.isTTY) return null;
200
+ const { createInterface } = await import("node:readline");
201
+ const { Writable } = await import("node:stream");
202
+ let muted = false;
203
+ const output = new Writable({
204
+ write(chunk, encoding, done) {
205
+ if (!muted) process.stderr.write(chunk, encoding);
206
+ done();
207
+ },
208
+ });
209
+ const rl = createInterface({ input: process.stdin, output, terminal: true });
210
+ try {
211
+ return await new Promise((resolvePromise, rejectPromise) => {
212
+ rl.once("close", () => resolvePromise(null));
213
+ // In raw mode Ctrl-C reaches readline, not the process: without this the
214
+ // prompt would pause and never settle.
215
+ rl.once("SIGINT", () => {
216
+ rejectPromise(new CliError("OPERATOR_STEP_UP_CANCELLED", "Cancelled at the TOTP prompt.", 130));
217
+ rl.close();
218
+ });
219
+ rl.question("Enter your TOTP code: ", (answer) => resolvePromise(answer.trim()));
220
+ muted = true;
221
+ });
222
+ } finally {
223
+ rl.close();
224
+ process.stderr.write("\n");
225
+ }
226
+ }
227
+
228
+ const refusalCode = (raw) => {
229
+ try {
230
+ return JSON.parse(raw)?.code ?? null;
231
+ } catch {
232
+ return null;
233
+ }
234
+ };
235
+
236
+ const liveGrant = () => (stepUpGrant && Date.parse(stepUpGrant.expiresAt) - Date.now() > 5_000 ? stepUpGrant.grant : null);
237
+
238
+ /** Ask for the code once and trade it for a grant; null when there is no TTY and the refusal stands. */
239
+ async function stepUpOnce(refusal, signal) {
240
+ const typed = await totpPrompt();
241
+ if (typed === null || typed === undefined) {
242
+ if (refusal !== "OPERATOR_REQUIRED") return null;
243
+ throw new CliError(
244
+ "OPERATOR_REQUIRED",
245
+ "This is operator-only. Run it yourself in a terminal: the CLI then asks for your TOTP code. An agent cannot answer it.",
246
+ 1,
247
+ );
248
+ }
249
+ if (!/^[0-9]{6}$/.test(typed)) throw new CliError("OPERATOR_STEP_UP_CODE_REJECTED", "A TOTP code is six digits.", 1);
250
+ const stepUp = await devFetchOnce("POST", OPERATOR_STEP_UP_PATH, JSON.stringify({ code: typed }), "application/json", "application/json", {}, signal);
251
+ let payload = {};
252
+ try {
253
+ payload = JSON.parse(stepUp.raw);
254
+ } catch {}
255
+ if (!stepUp.response.ok)
256
+ throw new CliError(payload.code ?? `HTTP_${stepUp.response.status}`, payload.message ?? `Dev returned HTTP ${stepUp.response.status}`, 1, payload.details);
257
+ const grant = payload?.data?.grant;
258
+ const expiresAt = payload?.data?.expiresAt;
259
+ if (typeof grant !== "string" || typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)))
260
+ throw new CliError("OPERATOR_STEP_UP_UNAVAILABLE", "Dev's step-up answer carried no usable grant.", 1);
261
+ stepUpGrant = { grant, expiresAt };
262
+ return grant;
263
+ }
264
+
265
+ async function devFetch(method, path, bodyText, contentType, accept, extra = {}, signal) {
266
+ const send = (grant) =>
267
+ devFetchOnce(method, path, bodyText, contentType, accept, grant ? { ...extra, [OPERATOR_STEP_UP_HEADER]: grant } : extra, signal);
268
+ if (path === OPERATOR_STEP_UP_PATH) return devFetchOnce(method, path, bodyText, contentType, accept, extra, signal);
269
+ const held = liveGrant();
270
+ const first = await send(held);
271
+ const code = refusalCode(first.raw);
272
+ const refused =
273
+ (first.response.status === 403 && code === "OPERATOR_REQUIRED") ||
274
+ (first.response.status === 401 && code === "OPERATOR_STEP_UP_INVALID");
275
+ if (!refused) return first;
276
+ // Drop only the grant this call was refused with; one obtained meanwhile by
277
+ // a concurrent call is used as it is, without a second prompt.
278
+ if (stepUpGrant?.grant === held) stepUpGrant = null;
279
+ const fresh = liveGrant();
280
+ if (fresh && fresh !== held) return send(fresh);
281
+ // Concurrent refusals share one prompt and one grant (one TTY, one code).
282
+ pendingStepUp ??= stepUpOnce(code, signal).finally(() => {
283
+ pendingStepUp = null;
284
+ });
285
+ const grant = await pendingStepUp;
286
+ if (grant === null) return first;
287
+ return send(grant);
288
+ }
289
+
178
290
  /** A JSON call that keeps the status: `{ status, payload }`. Errors throw as devRawRequest's do. */
179
291
  export async function devExchange(method, path, bodyText, { contentType = "application/json", headers = {}, signal } = {}) {
180
292
  const { response, raw } = await devFetch(method, path, bodyText, contentType, "application/json", headers, signal);
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.79",
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": {