neurastream 0.3.20 → 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 (49) hide show
  1. package/package.json +1 -1
  2. package/src/adapters/index.ts +3 -2
  3. package/src/adapters/omp/adapter.ts +2 -1
  4. package/src/adapters/omp/auto-close.ts +64 -0
  5. package/src/adapters/omp/chat-commands.ts +161 -0
  6. package/src/adapters/omp/inbox.ts +221 -0
  7. package/src/adapters/omp/index.ts +115 -1039
  8. package/src/adapters/omp/launch.ts +31 -3
  9. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  10. package/src/adapters/omp/rollover-controller.ts +334 -0
  11. package/src/adapters/omp/types.ts +143 -0
  12. package/src/cli/commands.ts +33 -2
  13. package/src/cli/dispatch.ts +37 -16
  14. package/src/cli/recall.ts +3 -2
  15. package/src/cli/results-build.ts +1 -1
  16. package/src/cli/workspace.ts +13 -2
  17. package/src/core/adapter.ts +16 -0
  18. package/src/core/blockers.ts +326 -30
  19. package/src/core/file-lock.ts +71 -12
  20. package/src/core/guards/plan-edit.ts +338 -0
  21. package/src/core/guards/planner.ts +70 -0
  22. package/src/core/guards/review.ts +391 -0
  23. package/src/core/guards/spawn.ts +699 -0
  24. package/src/core/guards/state.ts +581 -0
  25. package/src/core/guards/stop.ts +235 -0
  26. package/src/core/guards/tool.ts +541 -0
  27. package/src/core/guards.ts +12 -2658
  28. package/src/core/incidents.ts +125 -91
  29. package/src/core/machine-guard.ts +23 -5
  30. package/src/core/main-start.ts +10 -8
  31. package/src/core/owner-topics.ts +2 -13
  32. package/src/core/owner-ui/auth.ts +164 -0
  33. package/src/core/owner-ui/data.ts +437 -0
  34. package/src/core/owner-ui/handlers.ts +250 -0
  35. package/src/core/owner-ui/messages.ts +209 -0
  36. package/src/core/owner-ui/render.ts +714 -0
  37. package/src/core/owner-ui/results.ts +266 -0
  38. package/src/core/owner-ui/server.ts +142 -0
  39. package/src/core/owner-ui.ts +11 -2121
  40. package/src/core/page-notes.ts +25 -0
  41. package/src/core/pages.ts +452 -77
  42. package/src/core/plan-approval.ts +12 -14
  43. package/src/core/queue/lib.ts +88 -39
  44. package/src/core/queue-cancel.ts +21 -17
  45. package/src/core/queue-close.ts +48 -23
  46. package/src/core/secret-redact.ts +65 -14
  47. package/src/core/tailscale.ts +79 -3
  48. package/src/core/team-client.ts +13 -2
  49. package/src/core/uninstall.ts +2 -0
@@ -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
  }
@@ -1,4 +1,5 @@
1
- import { closeSync, mkdirSync, openSync } from "node:fs";
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, closeSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
3
  import { dirname } from "node:path";
3
4
  import { dlopen, FFIType, read, type Pointer } from "bun:ffi";
4
5
 
@@ -9,9 +10,12 @@ const LOCK_UN = 8;
9
10
  const EINTR = 4;
10
11
  const EWOULDBLOCK = process.platform === "darwin" ? 35 : 11;
11
12
 
12
- // errno is thread-local; __error (Darwin) and __errno_location (glibc) return its address.
13
+ // errno is thread-local; __error (Darwin) and __errno_location (Linux glibc/musl) return its address.
13
14
  const errnoFn = process.platform === "darwin" ? "__error" : "__errno_location";
14
- const LIBC_NAME = process.platform === "darwin" ? "libc.dylib" : "libc.so.6";
15
+ const LIBC_CANDIDATES =
16
+ process.platform === "darwin"
17
+ ? ["libc.dylib"]
18
+ : ["libc.so.6", "libc.musl-x86_64.so.1", "libc.musl-aarch64.so.1", "libc.so"];
15
19
 
16
20
  /** The libc symbols this module calls. */
17
21
  export interface LibcSymbols {
@@ -23,20 +27,25 @@ export interface Libc {
23
27
  symbols: LibcSymbols;
24
28
  }
25
29
 
26
- // libc opens on first lock use, not at import: a failed load throws from the lock call, naming the
30
+ // libc opens on first lock use, not at import: a failed load throws from the lock call, naming every
27
31
  // library tried, instead of breaking every importer of this module.
28
32
  let libcHandle: Libc | undefined;
29
33
  function libc(): Libc {
30
34
  if (libcHandle) return libcHandle;
31
- try {
32
- libcHandle = dlopen(LIBC_NAME, {
33
- flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
34
- [errnoFn]: { args: [], returns: FFIType.ptr },
35
- });
36
- return libcHandle;
37
- } catch (e) {
38
- throw new Error(`file-lock: cannot load ${LIBC_NAME}: ${(e as Error).message}`);
35
+ let lastErr: unknown;
36
+ for (const name of LIBC_CANDIDATES) {
37
+ try {
38
+ libcHandle = dlopen(name, {
39
+ flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
40
+ [errnoFn]: { args: [], returns: FFIType.ptr },
41
+ });
42
+ return libcHandle;
43
+ } catch (e) {
44
+ lastErr = e;
45
+ }
39
46
  }
47
+ const detail = lastErr instanceof Error ? lastErr.message : String(lastErr);
48
+ throw new Error(`file-lock: cannot load ${LIBC_CANDIDATES.join(", ")}: ${detail}`);
40
49
  }
41
50
 
42
51
  function errno(lib: Libc): number {
@@ -60,8 +69,11 @@ function acquire(path: string, op: number): HeldLock | null {
60
69
  if (err === EWOULDBLOCK && (op & LOCK_NB) !== 0) return null;
61
70
  throw new Error(`flock(${path}) failed: errno ${err}`);
62
71
  }
72
+ let released = false;
63
73
  return {
64
74
  release() {
75
+ if (released) return;
76
+ released = true;
65
77
  lib.symbols.flock(fd, LOCK_UN);
66
78
  closeSync(fd);
67
79
  },
@@ -80,6 +92,53 @@ export function lock(path: string): HeldLock {
80
92
  return held;
81
93
  }
82
94
 
95
+ /**
96
+ * Run `fn` while holding an exclusive blocking file lock at `lockPath`, guaranteeing release.
97
+ *
98
+ * Args:
99
+ * lockPath (string): Path to the lock file
100
+ * fn (() => T): Critical section to execute while the lock is held
101
+ *
102
+ * Returns:
103
+ * T: Value returned by `fn`
104
+ */
105
+ export function withFileLock<T>(lockPath: string, fn: () => T): T {
106
+ const held = lock(lockPath);
107
+ try {
108
+ return fn();
109
+ } finally {
110
+ held.release();
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Atomically write UTF-8 `data` to `filePath` via a unique sibling temp file and rename.
116
+ * When `mode` is provided, `chmodSync` runs on the temp file before `renameSync` so the
117
+ * destination never passes through a more permissive window.
118
+ *
119
+ * Args:
120
+ * filePath (string): Target file path
121
+ * data (string): UTF-8 content to write
122
+ * mode (number | undefined): Optional POSIX file permissions applied before rename
123
+ *
124
+ * Returns:
125
+ * void
126
+ */
127
+ export function writeAtomicSync(filePath: string, data: string, mode?: number): void {
128
+ mkdirSync(dirname(filePath), { recursive: true });
129
+ const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
130
+ try {
131
+ writeFileSync(tmp, data);
132
+ if (mode !== undefined) chmodSync(tmp, mode);
133
+ renameSync(tmp, filePath);
134
+ } catch (err) {
135
+ try {
136
+ rmSync(tmp, { force: true });
137
+ } catch {}
138
+ throw err;
139
+ }
140
+ }
141
+
83
142
  /** True when another open file description holds the lock right now. */
84
143
  export function isBusy(path: string): boolean {
85
144
  const held = tryLock(path);