neurastream 0.3.18 → 0.3.21

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 (66) hide show
  1. package/README.md +88 -490
  2. package/package.json +1 -1
  3. package/src/adapters/index.ts +3 -2
  4. package/src/adapters/omp/adapter.ts +2 -1
  5. package/src/adapters/omp/auto-close.ts +64 -0
  6. package/src/adapters/omp/chat-commands.ts +161 -0
  7. package/src/adapters/omp/inbox.ts +221 -0
  8. package/src/adapters/omp/index.ts +138 -1050
  9. package/src/adapters/omp/launch.ts +35 -9
  10. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  11. package/src/adapters/omp/rollover-controller.ts +334 -0
  12. package/src/adapters/omp/types.ts +143 -0
  13. package/src/cli/claim.ts +1 -3
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +55 -30
  16. package/src/cli/guard.ts +0 -3
  17. package/src/cli/incident.ts +2 -2
  18. package/src/cli/metrics.ts +1 -1
  19. package/src/cli/recall.ts +6 -8
  20. package/src/cli/results-build.ts +2 -4
  21. package/src/cli/workspace.ts +13 -5
  22. package/src/core/adapter.ts +16 -0
  23. package/src/core/autonomy.ts +24 -21
  24. package/src/core/blockers.ts +326 -30
  25. package/src/core/file-lock.ts +71 -12
  26. package/src/core/guards/plan-edit.ts +338 -0
  27. package/src/core/guards/planner.ts +70 -0
  28. package/src/core/guards/review.ts +391 -0
  29. package/src/core/guards/spawn.ts +699 -0
  30. package/src/core/guards/state.ts +581 -0
  31. package/src/core/guards/stop.ts +235 -0
  32. package/src/core/guards/tool.ts +541 -0
  33. package/src/core/guards.ts +12 -2661
  34. package/src/core/incidents.ts +134 -99
  35. package/src/core/machine-guard.ts +23 -5
  36. package/src/core/main-start.ts +11 -9
  37. package/src/core/mr-sweep.ts +4 -2
  38. package/src/core/notify.ts +15 -15
  39. package/src/core/owner-log.ts +19 -17
  40. package/src/core/owner-topics.ts +38 -48
  41. package/src/core/owner-ui/auth.ts +164 -0
  42. package/src/core/owner-ui/data.ts +437 -0
  43. package/src/core/owner-ui/handlers.ts +250 -0
  44. package/src/core/owner-ui/messages.ts +209 -0
  45. package/src/core/owner-ui/render.ts +714 -0
  46. package/src/core/owner-ui/results.ts +266 -0
  47. package/src/core/owner-ui/server.ts +142 -0
  48. package/src/core/owner-ui.ts +11 -2118
  49. package/src/core/page-notes.ts +25 -0
  50. package/src/core/pages.ts +452 -78
  51. package/src/core/plan-approval.ts +24 -26
  52. package/src/core/queue/lib.ts +170 -137
  53. package/src/core/queue-cancel.ts +29 -15
  54. package/src/core/queue-check.ts +5 -7
  55. package/src/core/queue-close.ts +54 -29
  56. package/src/core/queue-finished.ts +9 -10
  57. package/src/core/queue-migrate.ts +1 -3
  58. package/src/core/queue-trim.ts +2 -4
  59. package/src/core/results.ts +0 -2
  60. package/src/core/rollover.ts +2 -3
  61. package/src/core/secret-redact.ts +65 -14
  62. package/src/core/tailscale.ts +79 -3
  63. package/src/core/team-client.ts +18 -6
  64. package/src/core/uninstall.ts +2 -0
  65. package/src/core/watch.ts +3 -2
  66. package/src/core/queue/env.ts +0 -14
@@ -9,23 +9,23 @@ import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSyn
9
9
  import path from "node:path";
10
10
  import { configFile, loadConfig, type Config } from "./config.ts";
11
11
  import { checkEdited, setConfigKeys, yamlValue } from "./config-edit.ts";
12
- import { stateDirPath } from "./queue/lib.ts";
12
+ import type { QueuePaths } from "./queue/lib.ts";
13
13
 
14
14
  export type Tier = "strict" | "opinionated" | "full";
15
15
  const TIERS: readonly Tier[] = ["strict", "opinionated", "full"];
16
16
 
17
- export function tierFile(): string {
18
- return path.join(stateDirPath(), "autonomy-tier");
17
+ export function tierFile(paths: Pick<QueuePaths, "queue_state">): string {
18
+ return path.join(paths.queue_state, "autonomy-tier");
19
19
  }
20
20
 
21
- export function goFile(): string {
22
- return path.join(stateDirPath(), "autonomy-go");
21
+ export function goFile(paths: Pick<QueuePaths, "queue_state">): string {
22
+ return path.join(paths.queue_state, "autonomy-go");
23
23
  }
24
24
 
25
25
  /** The tier the guards follow: `<state dir>/autonomy-tier` when it names one of the three (one word), else the config value. */
26
26
  export function currentTier(cfg: Config): Tier {
27
27
  try {
28
- const word = readFileSync(tierFile(), "utf8").trim().toLowerCase();
28
+ const word = readFileSync(tierFile(cfg.paths), "utf8").trim().toLowerCase();
29
29
  if ((TIERS as readonly string[]).includes(word)) return word as Tier;
30
30
  } catch {}
31
31
  return cfg.autonomy.tier;
@@ -52,8 +52,8 @@ export function chatTier(text: string, cfg: Config, source: string, word: "chat"
52
52
  const m = TIER_CMD.exec(text.trim());
53
53
  if (!m) return { applied: false };
54
54
  const tier = (m[1] ?? "").toLowerCase() as Tier;
55
- mkdirSync(stateDirPath(), { recursive: true });
56
- writeFileSync(tierFile(), `${tier}\n`);
55
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
56
+ writeFileSync(tierFile(cfg.paths), `${tier}\n`);
57
57
  try {
58
58
  appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} TIER ${tier} ${word} source=${source}\n`);
59
59
  } catch {}
@@ -80,8 +80,8 @@ const goWords = (s: string): string => s.trim().toLowerCase().replace(/\s+/g, "
80
80
  export function chatGo(text: string, cfg: Config, source: string, word: "chat" | "ui" = "chat"): ChatGoResult {
81
81
  if (!cfg.guards.chat_unlock) return { applied: false };
82
82
  if (goWords(text) !== goWords(cfg.autonomy.go_phrase)) return { applied: false };
83
- mkdirSync(stateDirPath(), { recursive: true });
84
- writeFileSync(goFile(), "");
83
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
84
+ writeFileSync(goFile(cfg.paths), "");
85
85
  try {
86
86
  appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} GO ${word} source=${source} minutes=${cfg.autonomy.go_minutes}\n`);
87
87
  } catch {}
@@ -93,13 +93,14 @@ export function chatGo(text: string, cfg: Config, source: string, word: "chat" |
93
93
  * autonomy.go_minutes; a stale or missing file is false (a stale one is removed).
94
94
  */
95
95
  export function takeGo(cfg: Config, now = Date.now()): boolean {
96
+ const file = goFile(cfg.paths);
96
97
  let mtimeMs: number;
97
98
  try {
98
- mtimeMs = statSync(goFile()).mtimeMs;
99
+ mtimeMs = statSync(file).mtimeMs;
99
100
  } catch {
100
101
  return false;
101
102
  }
102
- rmSync(goFile(), { force: true });
103
+ rmSync(file, { force: true });
103
104
  return now - mtimeMs < cfg.autonomy.go_minutes * 60_000;
104
105
  }
105
106
 
@@ -111,8 +112,8 @@ export function takeGo(cfg: Config, now = Date.now()): boolean {
111
112
  export type PlannerMode = "main" | "delegated";
112
113
  const PLANNER_MODES: readonly PlannerMode[] = ["main", "delegated"];
113
114
 
114
- export function plannerFile(): string {
115
- return path.join(stateDirPath(), "planner-mode");
115
+ export function plannerFile(paths: Pick<QueuePaths, "queue_state">): string {
116
+ return path.join(paths.queue_state, "planner-mode");
116
117
  }
117
118
 
118
119
  // The effective mode facts are owner-only (P2 d). A guard baseline beside the config file records
@@ -130,10 +131,11 @@ export function plannerFile(): string {
130
131
  export interface PlannerPin {
131
132
  file: string;
132
133
  home: string;
134
+ stateDir?: string;
133
135
  }
134
136
 
135
137
  export function plannerPin(cfg: Config): PlannerPin {
136
- return { file: cfg.file ?? configFile(cfg.paths.home), home: cfg.paths.home };
138
+ return { file: cfg.file ?? configFile(cfg.paths.home), home: cfg.paths.home, stateDir: cfg.paths.queue_state };
137
139
  }
138
140
 
139
141
  /** The baseline file: beside the config file it describes. */
@@ -253,7 +255,8 @@ export function verifyPlannerMode(pin: PlannerPin): PlannerVerifyResult {
253
255
  else if (base !== null) reverted = writeConfig(pin, base.config.bytes) || reverted;
254
256
  }
255
257
  // The state file: pinned by the baseline; with no baseline it may not exist at all.
256
- const pinnedDir = base?.state_dir ?? stateDirPath();
258
+ const liveStateDir = pin.stateDir ?? facts?.queue_state ?? base?.state_dir ?? path.join(pin.home, ".local/state/queue");
259
+ const pinnedDir = base?.state_dir ?? liveStateDir;
257
260
  const pinnedFile = path.join(pinnedDir, "planner-mode");
258
261
  const want = base?.planner ?? { exists: false, bytes: null };
259
262
  const cur = readPlannerState(pinnedFile);
@@ -268,7 +271,7 @@ export function verifyPlannerMode(pin: PlannerPin): PlannerVerifyResult {
268
271
  reverted = true;
269
272
  }
270
273
  // A mode file beside the freshly configured state dir is foreign: the baseline pins the dir.
271
- const live = plannerFile();
274
+ const live = plannerFile({ queue_state: liveStateDir });
272
275
  if (live !== pinnedFile && readPlannerState(live).exists) {
273
276
  rmSync(live, { force: true });
274
277
  reverted = true;
@@ -285,7 +288,7 @@ export function stampPlannerMode(pin: PlannerPin): void {
285
288
  try {
286
289
  const text = readFileSync(pin.file, "utf8");
287
290
  const facts = fileFacts(pin);
288
- const dir = stateDirPath();
291
+ const dir = pin.stateDir ?? facts.queue_state;
289
292
  const base: PlannerBaseline = {
290
293
  version: 1,
291
294
  state_dir: dir,
@@ -300,7 +303,7 @@ export function stampPlannerMode(pin: PlannerPin): void {
300
303
  /** The planner mode in force: the file twin of tierFile() when it names one of the two (one word), else the config value. */
301
304
  export function currentPlanner(cfg: Config): PlannerMode {
302
305
  try {
303
- const word = readFileSync(plannerFile(), "utf8").trim().toLowerCase();
306
+ const word = readFileSync(plannerFile(cfg.paths), "utf8").trim().toLowerCase();
304
307
  if ((PLANNER_MODES as readonly string[]).includes(word)) return word as PlannerMode;
305
308
  } catch {}
306
309
  return cfg.autonomy.planner;
@@ -331,8 +334,8 @@ export function chatPlanner(text: string, cfg: Config, source: string, word: "ch
331
334
  // The owner's own switch: revert any dirt first, write, then record the new state. The mode
332
335
  // file is written in-process, so no tool call sees it.
333
336
  verifyPlannerMode(pin);
334
- mkdirSync(stateDirPath(), { recursive: true });
335
- writeFileSync(plannerFile(), `${planner}\n`);
337
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
338
+ writeFileSync(plannerFile(cfg.paths), `${planner}\n`);
336
339
  stampPlannerMode(pin);
337
340
  try {
338
341
  appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} PLANNER ${planner} ${word} source=${source}\n`);
@@ -52,7 +52,7 @@ function isDir(p: string): boolean {
52
52
 
53
53
  // Eval code (JS or Python) keeps the whole-text test; shell commands are judged per command.
54
54
  const CODE_MUTATING =
55
- /(\brm\b|\bmv\b|\bcp\b|\btruncate\b|\bsed\s+-i|\btee\b|>{1,2}\s*\S|\bgit\s+(rm|mv|checkout|restore)\b|writeFile|Bun\.write|unlink|\bpatch\b)/;
55
+ /(\brm\b|\bmv\b|\bcp\b|\bln\b|\bdd\b|\bchmod\b|\bchown\b|\btouch\b|\bmkdir\b|\brmdir\b|\binstall\b|\brsync\b|\btruncate\b|\bsed\s+-i|\btee\b|\bcurl\b[^;\n]*(?:\s-[a-zA-Z]*o|--output)|\bwget\b[^;\n]*(?:\s-[a-zA-Z]*O|--output-document)|>{1,2}\s*\S|\bgit\s+(rm|mv|checkout|restore|reset|clean|merge|rebase|cherry-pick)\b|writeFile|Bun\.write|unlink|\bpatch\b)/;
56
56
 
57
57
  export function blockerEnv(call: BlockerCall, args: string[]): BlockerEnv {
58
58
  const shell = call.tool === "bash" || call.tool === "eval";
@@ -409,9 +409,65 @@ const INTERPRETERS: Record<string, true> = {
409
409
  perl: true,
410
410
  ruby: true,
411
411
  };
412
- const GIT_VALUE_OPTS: Record<string, true> = { "-C": true, "-c": true, "--git-dir": true, "--work-tree": true, "--namespace": true };
413
- const MUTATING_NAMES: Record<string, true> = { rm: true, mv: true, truncate: true, tee: true, patch: true };
414
- const GIT_MUTATING: Record<string, true> = { rm: true, mv: true, checkout: true, restore: true };
412
+ const GIT_VALUE_OPTS: Record<string, true> = {
413
+ "-C": true,
414
+ "-c": true,
415
+ "--git-dir": true,
416
+ "--work-tree": true,
417
+ "--namespace": true,
418
+ "--super-prefix": true,
419
+ "--config-env": true,
420
+ };
421
+ const GH_GLAB_VALUE_OPTS: Record<string, true> = {
422
+ "-R": true,
423
+ "--repo": true,
424
+ "-H": true,
425
+ "--hostname": true,
426
+ };
427
+ const SUBCMD_TOOLS: Record<string, { valueOpts: Record<string, true>; depth: number }> = {
428
+ git: { valueOpts: GIT_VALUE_OPTS, depth: 1 },
429
+ npm: { valueOpts: { "--prefix": true, "-C": true, "--userconfig": true, "--cache": true, "--registry": true }, depth: 1 },
430
+ bun: { valueOpts: { "--cwd": true, "-c": true, "--config": true, "--env-file": true, "-e": true, "--eval": true, "-p": true, "--print": true }, depth: 1 },
431
+ gh: { valueOpts: GH_GLAB_VALUE_OPTS, depth: 2 },
432
+ glab: { valueOpts: GH_GLAB_VALUE_OPTS, depth: 2 },
433
+ docker: { valueOpts: { "-H": true, "--host": true, "--context": true, "--config": true, "-c": true, "-l": true, "--log-level": true }, depth: 2 },
434
+ kubectl: { valueOpts: { "-n": true, "--namespace": true, "--context": true, "--kubeconfig": true, "--cluster": true, "--user": true }, depth: 1 },
435
+ cargo: { valueOpts: { "--manifest-path": true, "-C": true, "--target-dir": true }, depth: 1 },
436
+ uv: { valueOpts: { "--directory": true, "--project": true, "--cache-dir": true, "--config-file": true }, depth: 1 },
437
+ yarn: { valueOpts: { "--cwd": true }, depth: 1 },
438
+ pnpm: { valueOpts: { "-C": true, "--dir": true, "--filter": true, "-F": true }, depth: 1 },
439
+ };
440
+ const MUTATING_NAMES: Record<string, true> = {
441
+ rm: true,
442
+ mv: true,
443
+ truncate: true,
444
+ tee: true,
445
+ patch: true,
446
+ chmod: true,
447
+ chown: true,
448
+ touch: true,
449
+ mkdir: true,
450
+ rmdir: true,
451
+ unlink: true,
452
+ };
453
+ const DEST_LAST_NAMES: Record<string, true> = { cp: true, ln: true, install: true, rsync: true };
454
+ const DEST_LAST_VALUE_OPTS: Record<string, Record<string, true>> = {
455
+ cp: { "-S": true, "--suffix": true },
456
+ ln: { "-S": true, "--suffix": true },
457
+ install: { "-m": true, "--mode": true, "-o": true, "--owner": true, "-g": true, "--group": true, "-S": true, "--suffix": true },
458
+ rsync: { "-e": true, "--rsh": true, "--exclude": true, "--include": true, "--filter": true, "-f": true },
459
+ };
460
+ const GIT_MUTATING: Record<string, true> = {
461
+ rm: true,
462
+ mv: true,
463
+ checkout: true,
464
+ restore: true,
465
+ reset: true,
466
+ clean: true,
467
+ merge: true,
468
+ rebase: true,
469
+ "cherry-pick": true,
470
+ };
415
471
  // Code-write forms, one list for shell and eval: the code parts of queue/lib.ts MUTATING plus
416
472
  // Ruby's File.write. Never fork a second list.
417
473
  const CODE_WRITE =
@@ -420,9 +476,10 @@ const CODE_WRITE =
420
476
  interface ShellCommand {
421
477
  name: string;
422
478
  args: ShellWord[];
479
+ headIndex: number;
423
480
  }
424
481
 
425
- // The command a segment runs: leading assignments, wrapper words, options and durations are skipped.
482
+ /** Resolve the command a segment runs, skipping leading assignments, wrapper words, options, and durations. */
426
483
  function commandOf(seg: ShellSegment): ShellCommand | null {
427
484
  let k = 0;
428
485
  for (; k < seg.words.length; k++) {
@@ -432,7 +489,23 @@ function commandOf(seg: ShellSegment): ShellCommand | null {
432
489
  if (!skippable) break;
433
490
  }
434
491
  const head = seg.words[k];
435
- return head ? { name: path.basename(head.text), args: seg.words.slice(k + 1) } : null;
492
+ return head ? { name: path.basename(head.text), args: seg.words.slice(k + 1), headIndex: k } : null;
493
+ }
494
+
495
+ /** Extract non-option subcommand words from CLI args, skipping leading flags and their value arguments. */
496
+ function cliSubcommands(args: ShellWord[], valueOpts: Record<string, true>, limit = 2): string[] {
497
+ const out: string[] = [];
498
+ for (let k = 0; k < args.length && out.length < limit; k++) {
499
+ const t = args[k]?.text ?? "";
500
+ if (t === "--") break;
501
+ if (valueOpts[t] === true) {
502
+ k++;
503
+ continue;
504
+ }
505
+ if (t.startsWith("-")) continue;
506
+ out.push(t);
507
+ }
508
+ return out;
436
509
  }
437
510
 
438
511
  // git's subcommand and the words after it, skipping global options (-C <dir>, --git-dir=...).
@@ -487,9 +560,109 @@ function executed(command: string): ShellSegment[] {
487
560
  return out;
488
561
  }
489
562
 
490
- // Words a segment changes: its output redirections, the operands of mutating commands, the last
491
- // operand of cp (its destination; the source is only read), and the file arguments of code an
492
- // interpreter runs.
563
+ /** Extract destination target path(s) for copy/link/sync commands (`cp`, `ln`, `install`, `rsync`). */
564
+ function destLastTargets(cmd: ShellCommand): string[] {
565
+ const valueOpts = DEST_LAST_VALUE_OPTS[cmd.name] ?? {};
566
+ let targetDir: string | null = null;
567
+ let installDirMode = false;
568
+ const operands: string[] = [];
569
+ let afterDoubleDash = false;
570
+ for (let k = 0; k < cmd.args.length; k++) {
571
+ const t = cmd.args[k]?.text ?? "";
572
+ if (!t) continue;
573
+ if (!afterDoubleDash && t === "--") {
574
+ afterDoubleDash = true;
575
+ continue;
576
+ }
577
+ if (!afterDoubleDash) {
578
+ if (t === "-t" || t === "--target-directory") {
579
+ const dir = cmd.args[++k]?.text ?? "";
580
+ if (dir) targetDir = dir;
581
+ continue;
582
+ }
583
+ if (t.startsWith("--target-directory=")) {
584
+ const dir = t.slice("--target-directory=".length);
585
+ if (dir) targetDir = dir;
586
+ continue;
587
+ }
588
+ if (/^-t.+$/.test(t)) {
589
+ targetDir = t.slice(2);
590
+ continue;
591
+ }
592
+ if (cmd.name === "install" && (t === "-d" || t === "--directory")) {
593
+ installDirMode = true;
594
+ continue;
595
+ }
596
+ if (valueOpts[t] === true) {
597
+ k++;
598
+ continue;
599
+ }
600
+ if (t.startsWith("-")) continue;
601
+ }
602
+ operands.push(t);
603
+ }
604
+ if (targetDir !== null) {
605
+ const base = targetDir.replace(/\/+$/, "");
606
+ const children = operands.length > 0 ? operands.map((src) => `${base}/${path.basename(src)}`) : [`${base}/_`];
607
+ return [targetDir, ...children];
608
+ }
609
+ if (installDirMode) return operands;
610
+ if (operands.length === 0) return [];
611
+ if (cmd.name === "ln" && operands.length === 1) return [path.basename(operands[0]!)];
612
+ const dest = operands[operands.length - 1]!;
613
+ return dest.endsWith("/") ? [dest, `${dest}_`] : [dest];
614
+ }
615
+
616
+ /** Extract output file targets from `curl` (`-o`, `--output`) or `wget` (`-O`, `--output-document`). */
617
+ function downloadTargets(cmd: ShellCommand): string[] {
618
+ const out: string[] = [];
619
+ const shortFlag = cmd.name === "curl" ? "o" : "O";
620
+ const longFlag = cmd.name === "curl" ? "--output" : "--output-document";
621
+ const longPrefix = `${longFlag}=`;
622
+ const combinedEnd = new RegExp(`^-[a-zA-Z]+${shortFlag}$`);
623
+ const shortAttached = new RegExp(`^-${shortFlag}(.+)$`);
624
+ for (let k = 0; k < cmd.args.length; k++) {
625
+ const t = cmd.args[k]?.text ?? "";
626
+ if (!t) continue;
627
+ if (t === `-${shortFlag}` || t === longFlag || combinedEnd.test(t)) {
628
+ const next = cmd.args[++k]?.text ?? "";
629
+ if (next && next !== "-") out.push(next);
630
+ } else if (t.startsWith(longPrefix)) {
631
+ const val = t.slice(longPrefix.length);
632
+ if (val && val !== "-") out.push(val);
633
+ } else {
634
+ const m = shortAttached.exec(t);
635
+ if (m?.[1] && m[1] !== "-") out.push(m[1]);
636
+ }
637
+ }
638
+ return out;
639
+ }
640
+
641
+ /** Extract target directory paths when `tar` runs in extraction mode (`-x` / `--extract` / `xf`) with `-C`/`--directory`. */
642
+ function tarExtractTargets(args: ShellWord[]): string[] {
643
+ const first = args[0]?.text ?? "";
644
+ const extracting =
645
+ /^[a-zA-Z]*x[a-zA-Z]*$/.test(first) ||
646
+ args.some((w) => w.text === "-x" || w.text === "--extract" || /^-[a-zA-Z]*x/.test(w.text));
647
+ if (!extracting) return [];
648
+ const out: string[] = [];
649
+ for (let k = 0; k < args.length; k++) {
650
+ const t = args[k]?.text ?? "";
651
+ let dir = "";
652
+ if (t === "-C" || t === "--directory") dir = args[++k]?.text ?? "";
653
+ else if (t.startsWith("--directory=")) dir = t.slice("--directory=".length);
654
+ else if (/^-C.+$/.test(t)) dir = t.slice(2);
655
+ if (dir) {
656
+ out.push(dir, `${dir.replace(/\/+$/, "")}/_`);
657
+ }
658
+ }
659
+ return out;
660
+ }
661
+
662
+ /**
663
+ * Words a segment changes: output redirections, operands of mutating commands, destination targets of
664
+ * copy/link/sync/download/dd/tar-extract commands, and file arguments of interpreter write code.
665
+ */
493
666
  function mutationTargets(seg: ShellSegment): string[] {
494
667
  const out = [...seg.writes];
495
668
  const cmd = commandOf(seg);
@@ -503,7 +676,13 @@ function mutationTargets(seg: ShellSegment): string[] {
503
676
  }
504
677
  const ops = args.filter((w) => w.text !== "" && !w.text.startsWith("-")).map((w) => w.text);
505
678
  if (mutating) out.push(...ops);
506
- else if (cmd.name === "cp" && ops.length) out.push(ops[ops.length - 1] ?? "");
679
+ else if (DEST_LAST_NAMES[cmd.name] === true) out.push(...destLastTargets(cmd));
680
+ else if (cmd.name === "dd") {
681
+ for (const w of cmd.args) {
682
+ if (w.text.startsWith("of=") && w.text.length > 3) out.push(w.text.slice(3));
683
+ }
684
+ } else if (cmd.name === "curl" || cmd.name === "wget") out.push(...downloadTargets(cmd));
685
+ else if (cmd.name === "tar") out.push(...tarExtractTargets(cmd.args));
507
686
  else if (cmd.name === "sed" && cmd.args.some((a) => /^-[a-zA-Z]*i|^--in-place/.test(a.text))) out.push(...ops.slice(1));
508
687
  const raw = [...seg.words.map((w) => w.raw), ...seg.bodies].join(" ");
509
688
  if (INTERPRETERS[cmd.name] === true && CODE_WRITE.test(raw)) {
@@ -546,23 +725,135 @@ function shellTargets(env: BlockerEnv): string[] {
546
725
  function evalPaths(env: BlockerEnv): string[] {
547
726
  const base = expandHome(String(env.call.input?.cwd || env.call.cwd || "/"));
548
727
  const out: string[] = [];
549
- for (const w of env.command.split(/[\s;&|<>()'"]+/)) {
728
+ for (const w of env.command.split(/[\s;&|<>()'"`]+/)) {
550
729
  const t = w.trim();
551
730
  if (t && !t.startsWith("-")) out.push(path.normalize(path.join(base, expandHome(t))));
552
731
  }
553
732
  return out;
554
733
  }
555
734
 
556
- // A segment that pushes (git push) or merges an MR/PR (glab mr merge, gh pr merge), as a command.
735
+ /** True when a segment pushes (`git push`) or merges an MR/PR (`glab mr merge`, `gh pr merge`), skipping leading flags. */
557
736
  function pushesOrMerges(seg: ShellSegment): boolean {
558
737
  const cmd = commandOf(seg);
559
738
  if (!cmd) return false;
560
739
  if (cmd.name === "git") return gitSub(cmd.args)?.sub === "push";
561
- const words = cmd.args.map((w) => w.text);
562
- return (
563
- (cmd.name === "glab" && words[0] === "mr" && words[1] === "merge") ||
564
- (cmd.name === "gh" && words[0] === "pr" && words[1] === "merge")
565
- );
740
+ if (cmd.name === "glab") {
741
+ const subs = cliSubcommands(cmd.args, GH_GLAB_VALUE_OPTS);
742
+ return subs[0] === "mr" && subs[1] === "merge";
743
+ }
744
+ if (cmd.name === "gh") {
745
+ const subs = cliSubcommands(cmd.args, GH_GLAB_VALUE_OPTS);
746
+ return subs[0] === "pr" && subs[1] === "merge";
747
+ }
748
+ return false;
749
+ }
750
+
751
+ const GIT_PROSE_SUBS: Record<string, true> = {
752
+ commit: true,
753
+ tag: true,
754
+ merge: true,
755
+ notes: true,
756
+ stash: true,
757
+ revert: true,
758
+ };
759
+
760
+ /** True when a command/subcommand accepts short prose flags (`-m`, `-am`, `-F`) for message text. */
761
+ function hasShortProseFlags(cmdName: string | undefined, firstSub: string | undefined): boolean {
762
+ return cmdName === "git" && firstSub !== undefined && GIT_PROSE_SUBS[firstSub] === true;
763
+ }
764
+
765
+ /** True when a flag takes a prose message/search argument in the immediately following word. */
766
+ function isProseNextFlag(token: string, shortProse: boolean): boolean {
767
+ if (token === "--message" || token === "--grep") return true;
768
+ if (!shortProse) return false;
769
+ return token === "-m" || token === "-F" || /^-[a-zA-Z]*m$/.test(token);
770
+ }
771
+
772
+ /** True when a single word combines a prose flag with its attached value (e.g. `--message=--no-verify`, `-m--no-verify`). */
773
+ function isProseAttachedFlag(token: string, shortProse: boolean): boolean {
774
+ if (token.startsWith("--message=") || token.startsWith("--grep=")) return true;
775
+ if (!shortProse) return false;
776
+ return /^-[a-zA-Z]*m.+$/.test(token) || /^-F.+$/.test(token);
777
+ }
778
+
779
+ /**
780
+ * Build the match text(s) for `deny-command` from one shell segment.
781
+ * Preserves the resolved command head, subcommands (skipping global value options), non-prose
782
+ * flags (even if quoted), `git add` single-token quoted pathspecs like `"."`, and unquoted words,
783
+ * while excluding prose arguments (`--message`, `--grep`, and git message-subcommand `-m`/`-F`/`-am`)
784
+ * and quoted prose.
785
+ */
786
+ function commandMatchText(seg: ShellSegment): string[] {
787
+ const cmd = commandOf(seg);
788
+ const subIndices: number[] = [];
789
+ if (cmd) {
790
+ const spec = SUBCMD_TOOLS[cmd.name];
791
+ if (spec) {
792
+ for (let j = 0; j < cmd.args.length && subIndices.length < spec.depth; j++) {
793
+ const t = cmd.args[j]?.text ?? "";
794
+ if (t === "--") break;
795
+ if (spec.valueOpts[t] === true) {
796
+ j++;
797
+ continue;
798
+ }
799
+ if (t.startsWith("-")) continue;
800
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(t)) break;
801
+ subIndices.push(cmd.headIndex + 1 + j);
802
+ }
803
+ }
804
+ }
805
+ const subIndexSet = new Set(subIndices);
806
+ const firstSub = subIndices.length > 0 ? seg.words[subIndices[0]!]?.text : undefined;
807
+ const isGitAdd = cmd?.name === "git" && firstSub === "add";
808
+ const shortProse = hasShortProseFlags(cmd?.name, firstSub);
809
+
810
+ const keptIndices: number[] = [];
811
+ let skipProseNext = false;
812
+ for (let i = 0; i < seg.words.length; i++) {
813
+ const w = seg.words[i]!;
814
+ if (skipProseNext) {
815
+ skipProseNext = false;
816
+ continue;
817
+ }
818
+ if (cmd !== null && i === cmd.headIndex) {
819
+ keptIndices.push(i);
820
+ continue;
821
+ }
822
+ if (subIndexSet.has(i)) {
823
+ keptIndices.push(i);
824
+ continue;
825
+ }
826
+ if (isProseNextFlag(w.text, shortProse)) {
827
+ // Keep the flag token itself and skip only the following prose argument.
828
+ keptIndices.push(i);
829
+ skipProseNext = true;
830
+ continue;
831
+ }
832
+ if (isProseAttachedFlag(w.text, shortProse)) {
833
+ continue;
834
+ }
835
+ if (!w.quoted) {
836
+ keptIndices.push(i);
837
+ } else if (/^--?[A-Za-z0-9]/.test(w.text)) {
838
+ keptIndices.push(i);
839
+ } else if (isGitAdd && w.text !== "" && !/\s/.test(w.text)) {
840
+ keptIndices.push(i);
841
+ }
842
+ }
843
+
844
+ const fullText = keptIndices.map((idx) => seg.words[idx]!.text).join(" ");
845
+ if (cmd === null) return [fullText];
846
+
847
+ // Also emit a canonical command form with head basename and leading global options before the
848
+ // subcommand stripped, so `gi\t -C repo "tag" v1` matches `/git\s+tag/`.
849
+ const lastSubIdx = subIndices.length > 0 ? subIndices[subIndices.length - 1]! : cmd.headIndex;
850
+ const canonicalParts = [
851
+ cmd.name,
852
+ ...subIndices.map((idx) => seg.words[idx]!.text),
853
+ ...keptIndices.filter((idx) => idx > lastSubIdx).map((idx) => seg.words[idx]!.text),
854
+ ];
855
+ const canonicalText = canonicalParts.join(" ");
856
+ return canonicalText !== fullText ? [fullText, canonicalText] : [fullText];
566
857
  }
567
858
 
568
859
  // The text a call would write: write content, the added lines of an edit, the whole input of an
@@ -580,14 +871,11 @@ function writtenText(env: BlockerEnv): string {
580
871
  return env.command;
581
872
  }
582
873
 
583
- /** deny-command <regex>...: refuse shell commands matching any regex (use \s for spaces). Each command is matched by its unquoted words, so quoted arguments and heredoc bodies never match; eval code is matched whole. */
874
+ /** deny-command <regex>...: refuse shell commands matching any regex (use \s for spaces). Matches resolved command heads, subcommands, flags, and unquoted tokens while excluding prose arguments and heredoc bodies; eval code is matched whole. */
584
875
  export function denyCommand(env: BlockerEnv): void {
585
876
  if (!env.args.length) block("deny-command needs at least one regex in the plan");
586
877
  if (!env.shell) return;
587
- const texts =
588
- env.call.tool === "eval"
589
- ? [env.command]
590
- : executed(env.command).map((seg) => seg.words.filter((w) => !w.quoted).map((w) => w.text).join(" "));
878
+ const texts = env.call.tool === "eval" ? [env.command] : executed(env.command).flatMap(commandMatchText);
591
879
  for (const rx of env.args) {
592
880
  const re = new RegExp(rx);
593
881
  if (texts.some((t) => re.test(t))) block(`command matches forbidden pattern /${rx}/ (plan Forbidden list)`);
@@ -625,24 +913,32 @@ export function denyText(env: BlockerEnv): void {
625
913
  }
626
914
 
627
915
  // Eval code's words: the same subcommand test as the bash path, so `git stash push` is not a push
628
- // (I-20261027-266). Global options before the subcommand (-C <dir>, -c k=v) are skipped as there.
916
+ // (I-20261027-266), while flag-prefixed `gh -R owner/repo pr merge` and `glab --repo g/p mr merge`
917
+ // are caught with the same `cliSubcommands` logic.
629
918
  const CODE_WORDS = /[A-Za-z0-9_@%+=:.,/~-]+/g;
630
919
 
631
- function evalPushes(code: string): boolean {
920
+ /** True when eval code invokes `git push`, `glab mr merge`, or `gh pr merge` (even with leading flags). */
921
+ function evalPushesOrMerges(code: string): boolean {
632
922
  const words = code.match(CODE_WORDS) ?? [];
633
923
  return words.some((w, i) => {
634
- if (w !== "git" && !w.endsWith("/git")) return false;
924
+ const base = path.basename(w);
635
925
  const args = words.slice(i + 1).map((text) => ({ text, raw: text, quoted: false }));
636
- return gitSub(args)?.sub === "push";
926
+ if (base === "git") return gitSub(args)?.sub === "push";
927
+ if (base === "glab") {
928
+ const subs = cliSubcommands(args, GH_GLAB_VALUE_OPTS);
929
+ return subs[0] === "mr" && subs[1] === "merge";
930
+ }
931
+ if (base === "gh") {
932
+ const subs = cliSubcommands(args, GH_GLAB_VALUE_OPTS);
933
+ return subs[0] === "pr" && subs[1] === "merge";
934
+ }
935
+ return false;
637
936
  });
638
937
  }
639
938
 
640
939
  /** no-push: subagents never push or merge (Main pushes and merges). Matched as commands, never as words inside arguments. */
641
940
  export function noPush(env: BlockerEnv): void {
642
941
  if (!env.shell || env.call.agent === "main") return;
643
- const hit =
644
- env.call.tool === "eval"
645
- ? evalPushes(env.command) || /\bglab\s+mr\s+merge\b|\bgh\s+pr\s+merge\b/.test(env.command)
646
- : executed(env.command).some(pushesOrMerges);
942
+ const hit = env.call.tool === "eval" ? evalPushesOrMerges(env.command) : executed(env.command).some(pushesOrMerges);
647
943
  if (hit) block("subagents never push or merge; commit on the feature branch and report");
648
944
  }