@memnexus-ai/mx-agent-cli 0.1.255 → 0.1.257

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.
@@ -396,21 +396,314 @@ if [[ ! "$COMMAND" =~ $PUSH_RE ]]; then
396
396
  fi
397
397
 
398
398
  # ── Resolve repo root ────────────────────────────────────────────────────────
399
- # The hook runs from the worktree's .claude/hooks/ dir; scripts/ is at the
400
- # repo root. Find it by walking up from cwd.
401
- REPO_ROOT=""
402
- DIR="$(pwd)"
403
- for _ in $(seq 1 8); do
404
- if [[ -f "$DIR/package.json" && -f "$DIR/pnpm-workspace.yaml" ]]; then
405
- REPO_ROOT="$DIR"
406
- break
399
+ # >>> #4808 BEGIN push-target resolution
400
+ # Everything between these markers is the #4808 fix. Deleting the region restores
401
+ # the pre-fix behaviour — walk up from $(pwd) to find the repo root — and
402
+ # ci-validate-target.test.sh builds exactly that mutant and asserts every #4808
403
+ # test fails against it.
404
+ #
405
+ # The pre-fix walk started from the hook subprocess's cwd, which is always the
406
+ # session's own team worktree. So a push from a scratch worktree had its changed-
407
+ # package set computed from `git diff origin/main...HEAD` in the SHARED worktree
408
+ # — a different file set entirely, often empty. The gate then linted and tested
409
+ # whichever packages the shared worktree happened to touch, and returned a
410
+ # verdict on a package set the push does not contain. When both trees are clean
411
+ # the wrong answer and the right answer coincide, which is why it went unnoticed.
412
+ #
413
+ # >>> SHARED push-target resolver v1 (#4803, #4808) — KEEP BYTE-IDENTICAL ─────
414
+ # Duplicated verbatim in mx-guard-hook.sh and ci-validate-hook.sh, exactly the
415
+ # way PUSH_RE already is, and pinned byte-for-byte by push-target-parity.test.sh.
416
+ # Deliberately NOT a sourced library: each hook must stay a standalone file (that
417
+ # is how settings.json invokes them and how bundle-config ships them), and two
418
+ # gates that fail independently are worth more than one shared file that can take
419
+ # both of them down at once.
420
+ #
421
+ # Reads: COMMAND (the tool command), INPUT (the PreToolUse payload), PUSH_RE
422
+ # Writes: MXPT_BASE_DIR — the directory the HOOK itself is standing in
423
+ # MXPT_BASE_TOP — git toplevel of that directory
424
+ # MXPT_DIRS — every DISTINCT local git toplevel this command pushes
425
+ # to, in command order; empty when every push is remote
426
+ # MXPT_TARGET_DIR — MXPT_DIRS[0], "" when there is none. Single-target
427
+ # callers read this; multi-target callers read MXPT_DIRS
428
+ # MXPT_TARGET_RAW — the path as it appeared in the command: the offending
429
+ # push's when resolution failed, otherwise the first
430
+ # local push's ("" for a bare push)
431
+ # MXPT_UNRESOLVED — why resolution failed, "" on success
432
+ # MXPT_REMOTE — 1 when at least one push executes on another host
433
+ # Acts: nothing. Each hook decides what to do with the verdict and says so in
434
+ # its own voice. There is deliberately no `exit` in this block: a
435
+ # resolver that exits takes the verdict away from the gate that owns it,
436
+ # and push-target-parity.test.sh fails if one appears.
437
+ #
438
+ # The two Should Fix findings from the security review of #4811 live here, both
439
+ # instances of the same "gate stands down without examining its subject" shape
440
+ # #4803 and #4808 are about:
441
+ # SF-1 remote-push detection substring-matched `ssh`/`scp` ANYWHERE in the
442
+ # command, and an unresolvable target then produced a silent skip while
443
+ # the LOCAL push still ran — a trailing `# over ssh tunnel` comment was
444
+ # enough. The remote token must now LEAD the segment the push belongs to,
445
+ # or lead the segment whose still-open quote encloses it (the
446
+ # `ssh host "cd X && git push"` form). Everything else fails CLOSED on
447
+ # the caller's loud path. Remote segments are skipped BEFORE resolution,
448
+ # so a remote push whose path happens to exist locally is never resolved
449
+ # against the wrong tree.
450
+ # SF-2 the walk stopped at the first push segment, so the second half of
451
+ # `git -C /treeA push && git -C /treeB push` was never examined. Every
452
+ # push segment is now collected and every distinct toplevel reported.
453
+ #
454
+ # `.cwd` is supplied by the harness on the PreToolUse payload (the same field
455
+ # reload-checkpoint.sh reads). It is the session's DEFAULT working directory, not
456
+ # the invoking command's, so it is only ever the right answer for a bare
457
+ # `git push`; $PWD is the fallback when the field is absent.
458
+ MXPT_BASE_DIR=$(echo "$INPUT" | jq -r '.cwd // empty' 2>/dev/null) || MXPT_BASE_DIR=""
459
+ if [ -z "$MXPT_BASE_DIR" ] || [ ! -d "$MXPT_BASE_DIR" ]; then
460
+ MXPT_BASE_DIR="$PWD"
461
+ fi
462
+
463
+ # Expand only the two path variables the harness sets identically in this
464
+ # subprocess and in the tool command's shell. Anything else stays unexpanded and
465
+ # is reported as unresolvable rather than guessed at.
466
+ mxpt_expand_known_vars() {
467
+ local p="$1"
468
+ if [ -n "${CLAUDE_WORKTREE_PATH:-}" ]; then
469
+ p="${p//\$\{CLAUDE_WORKTREE_PATH\}/$CLAUDE_WORKTREE_PATH}"
470
+ p="${p//\$CLAUDE_WORKTREE_PATH/$CLAUDE_WORKTREE_PATH}"
471
+ fi
472
+ if [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then
473
+ p="${p//\$\{CLAUDE_PROJECT_DIR\}/$CLAUDE_PROJECT_DIR}"
474
+ p="${p//\$CLAUDE_PROJECT_DIR/$CLAUDE_PROJECT_DIR}"
475
+ fi
476
+ # Literal leading tilde in the command text — expand it ourselves (SC2088 is
477
+ # about tildes we write; this one arrived as data).
478
+ # shellcheck disable=SC2088
479
+ case "$p" in
480
+ "~"|"~/"*) p="${HOME}${p#\~}" ;;
481
+ esac
482
+ printf '%s' "$p"
483
+ }
484
+
485
+ mxpt_dequote() {
486
+ local p="$1"
487
+ p="${p%\"}"; p="${p#\"}"
488
+ p="${p%\'}"; p="${p#\'}"
489
+ printf '%s' "$p"
490
+ }
491
+
492
+ # Walk the command's segments in order, tracking the last `cd <path>` seen, and
493
+ # recording EVERY segment that begins a push (SF-2). A `-C <path>` on a push
494
+ # segment wins over the tracked `cd` (git applies it last). Segment splitting is
495
+ # the same approximation the sibling guards use — it is a guardrail, not a
496
+ # parser, and every ambiguity it cannot settle lands on the caller's loud path
497
+ # rather than on a silent verdict.
498
+ MXPT_PUSH_RAWS=() # one entry per push segment: the path text, "" = bare push
499
+ MXPT_PUSH_REMOTE=() # "1" iff that push segment runs on another host
500
+ MXPT_CD_RAW=""
501
+ MXPT_IN_QUOTE=0 # quote parity carried across segments
502
+ MXPT_REMOTE_CTX=0 # remote-launcher context of the current quoting level
503
+ while IFS= read -r mxpt_rawseg; do
504
+ mxpt_seg="${mxpt_rawseg#"${mxpt_rawseg%%[![:space:]]*}"}"
505
+ mxpt_seg="${mxpt_seg#\(}"; mxpt_seg="${mxpt_seg#\{}"
506
+ mxpt_seg="${mxpt_seg#"${mxpt_seg%%[![:space:]]*}"}"
507
+ if [[ "$mxpt_seg" =~ ^(then|do|else)[[:space:]]+(.*)$ ]]; then
508
+ mxpt_seg="${BASH_REMATCH[2]}"
509
+ fi
510
+
511
+ # Remote context (SF-1). Re-evaluated only at the top quoting level: a segment
512
+ # that begins inside a quote opened by an earlier segment inherits that
513
+ # segment's verdict, which is how the push inside `ssh host "..."` is
514
+ # recognised while `ssh host uptime && git push` (quote closed, new lead token
515
+ # `git`) is not.
516
+ MXPT_SEG_IN_QUOTE=$MXPT_IN_QUOTE
517
+ if [ "$MXPT_SEG_IN_QUOTE" -eq 0 ]; then
518
+ MXPT_REMOTE_CTX=0
519
+ MXPT_LEAD="${mxpt_seg%%[[:space:]]*}"
520
+ case "$MXPT_LEAD" in
521
+ ssh|scp|sftp|rsh) MXPT_REMOTE_CTX=1 ;;
522
+ docker|podman|kubectl|oc)
523
+ if [[ "$mxpt_seg" =~ [[:space:]]exec([[:space:]]|$) ]]; then MXPT_REMOTE_CTX=1; fi ;;
524
+ esac
525
+ fi
526
+ MXPT_SEG_REMOTE=$MXPT_REMOTE_CTX
527
+
528
+ # Quote parity for the NEXT segment. Deliberately naive — an apostrophe inside
529
+ # a word can skew it. Skew can only ever extend a remote context that a lead
530
+ # token already established; with no remote lead the parity is unused and the
531
+ # command still fails closed.
532
+ MXPT_Q="${mxpt_rawseg//[^\"\']/}"
533
+ if [ $(( ${#MXPT_Q} % 2 )) -eq 1 ]; then
534
+ MXPT_IN_QUOTE=$(( 1 - MXPT_IN_QUOTE ))
535
+ fi
536
+
537
+ if [[ "$mxpt_seg" =~ ^cd[[:space:]]+([^[:space:]]+) ]]; then
538
+ MXPT_CD_RAW="${BASH_REMATCH[1]}"
539
+ continue
540
+ fi
541
+ if [[ "$mxpt_seg" =~ $PUSH_RE ]]; then
542
+ MXPT_RAW=""
543
+ if [[ "$mxpt_seg" =~ (^|[[:space:]])-C[[:space:]]+([^[:space:]]+) ]]; then
544
+ MXPT_RAW="${BASH_REMATCH[2]}"
545
+ fi
546
+ # A relative `-C` is applied on top of the tracked `cd`, matching git.
547
+ if [ -n "$MXPT_RAW" ] && [ -n "$MXPT_CD_RAW" ]; then
548
+ case "$MXPT_RAW" in
549
+ /*|'~'*|'$'*) ;;
550
+ *) MXPT_RAW="$MXPT_CD_RAW/$MXPT_RAW" ;;
551
+ esac
552
+ elif [ -z "$MXPT_RAW" ]; then
553
+ MXPT_RAW="$MXPT_CD_RAW"
554
+ fi
555
+ MXPT_PUSH_RAWS+=("$MXPT_RAW")
556
+ MXPT_PUSH_REMOTE+=("$MXPT_SEG_REMOTE")
557
+ fi
558
+ done < <(printf '%s\n' "$COMMAND" | sed -e 's/&&/\n/g' -e 's/||/\n/g' -e 's/[;&|]/\n/g') || true
559
+ # printf's trailing newline is deliberate: without it `read` hits EOF on the
560
+ # final segment and the loop body never sees it, which silently drops the `-C` on
561
+ # the common single-segment form `git -C <path> push`. The `|| true` keeps the
562
+ # loop's own exit status away from ci-validate-hook.sh's fail-open ERR trap,
563
+ # where a non-zero status would turn this resolver into a silent `exit 0`.
564
+
565
+ # The whole-command matcher fired but no segment did — the push is in a form the
566
+ # splitter does not model. Treat it as a bare push against the hook's own tree
567
+ # rather than skipping: reporting something is the fail-closed side here.
568
+ if [ "${#MXPT_PUSH_RAWS[@]}" -eq 0 ]; then
569
+ MXPT_PUSH_RAWS=("")
570
+ MXPT_PUSH_REMOTE=(0)
571
+ fi
572
+
573
+ MXPT_BASE_TOP=$(git -C "$MXPT_BASE_DIR" rev-parse --show-toplevel 2>/dev/null) || MXPT_BASE_TOP="$MXPT_BASE_DIR"
574
+
575
+ # Resolve every push segment. Remote segments are skipped first and never
576
+ # resolved (SF-1); the first local segment that cannot be resolved stops
577
+ # resolution and is handed to the caller, which owns the loud path.
578
+ MXPT_DIRS=()
579
+ MXPT_TARGET_DIR=""
580
+ MXPT_TARGET_RAW=""
581
+ MXPT_UNRESOLVED=""
582
+ MXPT_REMOTE=0
583
+ for mxpt_i in "${!MXPT_PUSH_RAWS[@]}"; do
584
+ if [ "${MXPT_PUSH_REMOTE[$mxpt_i]}" = "1" ]; then
585
+ MXPT_REMOTE=1
586
+ continue
587
+ fi
588
+ if [ -n "$MXPT_UNRESOLVED" ]; then
589
+ continue
590
+ fi
591
+ mxpt_raw="${MXPT_PUSH_RAWS[$mxpt_i]}"
592
+ mxpt_dir=""
593
+ mxpt_why=""
594
+ if [ -z "$mxpt_raw" ]; then
595
+ # Bare `git push` — the hook's own directory really is the push target.
596
+ mxpt_dir="$MXPT_BASE_DIR"
597
+ else
598
+ MXPT_CAND=$(mxpt_expand_known_vars "$(mxpt_dequote "$mxpt_raw")")
599
+ case "$MXPT_CAND" in
600
+ *'$'*|*'`'*|*'*'*|*'?'*)
601
+ mxpt_why="it contains a shell expression this hook cannot expand" ;;
602
+ *)
603
+ case "$MXPT_CAND" in
604
+ /*) ;;
605
+ *) MXPT_CAND="$MXPT_BASE_DIR/$MXPT_CAND" ;;
606
+ esac
607
+ if [ ! -d "$MXPT_CAND" ]; then
608
+ mxpt_why="no such directory on this machine"
609
+ elif ! mxpt_dir=$(git -C "$MXPT_CAND" rev-parse --show-toplevel 2>/dev/null); then
610
+ mxpt_why="it is not inside a git work tree"
611
+ fi ;;
612
+ esac
613
+ fi
614
+ if [ -n "$mxpt_why" ]; then
615
+ MXPT_TARGET_RAW="$mxpt_raw"
616
+ MXPT_UNRESOLVED="$mxpt_why"
617
+ continue
618
+ fi
619
+ mxpt_seen=0
620
+ for mxpt_d in ${MXPT_DIRS[@]+"${MXPT_DIRS[@]}"}; do
621
+ if [ "$mxpt_d" = "$mxpt_dir" ]; then
622
+ mxpt_seen=1
623
+ fi
624
+ done
625
+ if [ "$mxpt_seen" -eq 0 ]; then
626
+ if [ "${#MXPT_DIRS[@]}" -eq 0 ]; then
627
+ MXPT_TARGET_RAW="$mxpt_raw"
628
+ fi
629
+ MXPT_DIRS+=("$mxpt_dir")
407
630
  fi
408
- DIR="$(dirname "$DIR")"
409
631
  done
632
+ if [ -z "$MXPT_UNRESOLVED" ] && [ "${#MXPT_DIRS[@]}" -gt 0 ]; then
633
+ # shellcheck disable=SC2034 # read by the caller, not inside the block; a
634
+ # multi-target caller (mx-guard-hook.sh) reads MXPT_DIRS instead and leaves
635
+ # this one unread, which is what SC2034 sees.
636
+ MXPT_TARGET_DIR="${MXPT_DIRS[0]}"
637
+ fi
638
+ # <<< SHARED push-target resolver v1
639
+
640
+ # The resolver hands back the git toplevel of the tree being pushed. This hook
641
+ # additionally needs that tree to BE the monorepo (the routing table and the
642
+ # validate scripts are repo-relative), so the marker check the pre-fix walk did
643
+ # is kept — but applied to the push target rather than to the hook's cwd.
644
+
645
+ # Every push in this command runs on another host (SF-1): there is no local tree
646
+ # to validate, and blocking would be a false block. The resolver skips remote
647
+ # segments before resolution, so this is checked before the unresolvable path
648
+ # rather than inside it.
649
+ if [ "${#MXPT_DIRS[@]}" -eq 0 ] && [ -z "$MXPT_UNRESOLVED" ]; then
650
+ if [ "$MXPT_REMOTE" = "1" ]; then
651
+ echo "ci-validate: push runs on a remote host — skipping local validation." >&2
652
+ fi
653
+ exit 0
654
+ fi
655
+
656
+ if [ -n "$MXPT_UNRESOLVED" ]; then
657
+ # Deliberately fail-CLOSED, unlike the fail-open paths around it. Falling back
658
+ # to the hook's cwd here is what produced verdicts on the wrong package set;
659
+ # `exit 0` would restore that silence in the other direction. This joins the
660
+ # lock timeout and a confirmed regression as an explicit exit 2, so the ERR
661
+ # trap never downgrades it.
662
+ {
663
+ echo "ci-validate: push BLOCKED — cannot identify the tree this push targets."
664
+ echo ""
665
+ echo " the push names: $MXPT_TARGET_RAW"
666
+ echo " problem: $MXPT_UNRESOLVED"
667
+ echo " would have used: $MXPT_BASE_TOP"
668
+ echo ""
669
+ echo " Validating $MXPT_BASE_TOP would lint and test whichever packages THAT"
670
+ echo " tree happens to have changed, which is not what is being pushed."
671
+ echo " Re-run the push with a literal absolute path, e.g."
672
+ echo " git -C /abs/path/to/worktree push <remote> <branch>"
673
+ } >&2
674
+ exit 2
675
+ fi
676
+
677
+ # More than one distinct local tree in a single push command (SF-2). Unlike
678
+ # mx-guard, whose `mx-guard check` is a per-tree call it can simply repeat, this
679
+ # hook's routing, lock, and validate pipeline below is built around ONE repo root
680
+ # per invocation. Validating the first and staying silent about the rest would be
681
+ # the same defect SF-2 named — a verdict that does not cover its subject — so
682
+ # this blocks and says how to proceed instead.
683
+ if [ "${#MXPT_DIRS[@]}" -gt 1 ]; then
684
+ {
685
+ echo "ci-validate: push BLOCKED — this command pushes ${#MXPT_DIRS[@]} different trees."
686
+ echo ""
687
+ for mxpt_d in "${MXPT_DIRS[@]}"; do
688
+ echo " $mxpt_d"
689
+ done
690
+ echo ""
691
+ echo " This gate validates one repo root per invocation, so a single run would"
692
+ echo " produce a verdict covering only the first of them. Push them as separate"
693
+ echo " commands and each one gets validated."
694
+ } >&2
695
+ exit 2
696
+ fi
697
+
698
+ REPO_ROOT="$MXPT_TARGET_DIR"
699
+ if [[ ! -f "$REPO_ROOT/package.json" || ! -f "$REPO_ROOT/pnpm-workspace.yaml" ]]; then
700
+ exit 0 # Push target isn't the monorepo — nothing routable here, fail-open
701
+ fi
410
702
 
411
- if [[ -z "$REPO_ROOT" ]]; then
412
- exit 0 # Can't find repo root — fail-open
703
+ if [ "$REPO_ROOT" != "$MXPT_BASE_TOP" ]; then
704
+ echo "ci-validate: push targets $REPO_ROOT (shell cwd is $MXPT_BASE_TOP) — validating the push target." >&2
413
705
  fi
706
+ # <<< #4808 END push-target resolution
414
707
 
415
708
  # ── Detect changed packages ──────────────────────────────────────────────────
416
709
  # Use three-dot diff against origin/main to find files changed on this branch.
@@ -0,0 +1,313 @@
1
+ #!/bin/bash
2
+ # gh-pr-edit-guard — PreToolUse(Bash) guard against `gh pr edit`, which on the
3
+ # `gh` this repo ships does nothing and says almost nothing about it.
4
+ #
5
+ # Contract: reads the tool-call JSON on stdin, extracts .tool_input.command.
6
+ # exit 0 = allow, exit 2 = block (non-zero exit blocks the Bash command).
7
+ # Fails OPEN (exit 0) on any parse ambiguity or internal error, so a broken
8
+ # guard never wedges legitimate work.
9
+ #
10
+ # OUTPUT ROUTING (KI-HOOKS-STDERR-SYSTEMIC): the harness surfaces a blocking
11
+ # hook's STDERR, not its stdout. All refuse() output goes to stderr (>&2). The
12
+ # allow paths stay silent.
13
+ #
14
+ # WHY. Recorded twice and still spreading: the sub-case "a tool that reports
15
+ # success and does nothing" in
16
+ # mx-agent-system/coe/nominations/2026-07-27-controls-report-healthy-while-doing-
17
+ # nothing-appendix.md (lines ~83, 110-140, 425), and the instance on PR #4616 it
18
+ # documents. (The appendix labels the first instance "#4563"; that issue number is
19
+ # a different defect — the revert-command one — so it is not repeated here.)
20
+ # The devcontainer installs `gh` from Debian
21
+ # (.devcontainer/Dockerfile:21, unpinned): version 2.46.0, March 2024. Trixie has
22
+ # no newer candidate and never will. In that version `gh pr edit`'s
23
+ # `PullRequestByNumber` prefetch unconditionally selects `projectCards`; GitHub
24
+ # now returns the whole `repository.pullRequest` node as null plus a NOT_FOUND
25
+ # error, and gh ABORTS BEFORE SENDING THE MUTATION. It exits 1 and prints one
26
+ # line — a GraphQL notice that Projects (classic) "is being deprecated". Nothing
27
+ # in that message mentions the body, the edit, or failure. Upstream fixed it in
28
+ # v2.73.0 (May 2025) via feature detection.
29
+ #
30
+ # WHY A HOOK AND NOT A LESSON. This defect has now been documented twice and hit
31
+ # a third team afterwards. The recorded lesson from the first instance was
32
+ # "don't discard exit statuses"; on the second instance the exit status was
33
+ # never wrong, and every defence that lesson implies would have passed while
34
+ # nothing was written. A mechanical block is the only control that reaches an
35
+ # agent who has not read either document.
36
+ #
37
+ # SCOPE — WHAT IS BLOCKED AND ON WHAT EVIDENCE. Every `gh pr edit` invocation is
38
+ # blocked, including the label / assignee / milestone forms. That is measured,
39
+ # not inferred: on 2026-08-01, against live PR #4785 with gh 2.46.0,
40
+ # `--add-label`, `--remove-label`, `--add-assignee` and `--milestone` each
41
+ # produced the identical projectCards error and exit 1. Each probe used a
42
+ # deliberately nonexistent label / user / milestone, so gh could not have
43
+ # mutated anything even had the prefetch succeeded, and #4785's labels,
44
+ # assignees and milestone were confirmed unchanged afterwards. The defect is the
45
+ # prefetch, which runs before any flag is acted on, so no flag combination
46
+ # escapes it. `--help` / `-h` is allowed: it prints usage without an API call.
47
+ #
48
+ # SCOPE — WHAT THIS IS NOT. This is a signpost, not a containment boundary. It
49
+ # matches gh invocations that START a command segment, after heredoc bodies with
50
+ # inert consumers are dropped and quoted text in sink commands (echo, printf,
51
+ # `gh --body`, `git commit -m`, ...) is blanked — so writing ABOUT `gh pr edit`
52
+ # in a report, commit message or PR body is not blocked. Deliberately NOT
53
+ # defended: indirection through a script file, shell-variable or `eval`
54
+ # assembly, an alias, or a payload handed to a remote shell. The cost of a miss
55
+ # here is one confusing gh failure, not lost work, and matching the whole
56
+ # command loosely instead of anchoring per segment is its own defect (#4804).
57
+
58
+ set -uo pipefail
59
+
60
+ # Read stdin with the bash redirection builtin rather than `cat`. A hook whose
61
+ # very first statement needs an external binary cannot fail open when the thing
62
+ # that is broken is the environment itself: with PATH unset or wrong, `cat`
63
+ # exits 127 and the hook exits 127 with it. The probe covers this case.
64
+ INPUT=$(</dev/stdin)
65
+
66
+ # No jq, no parse, no opinion. Explicit rather than relying on a pipe failure,
67
+ # so the fail-open path is the one that is tested.
68
+ if ! command -v jq >/dev/null 2>&1; then
69
+ exit 0
70
+ fi
71
+
72
+ COMMAND=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // .command // empty' 2>/dev/null || true)
73
+
74
+ # Can't parse (malformed JSON, no command field, jq missing) — fail open.
75
+ if [[ -z "$COMMAND" ]]; then
76
+ exit 0
77
+ fi
78
+
79
+ # --- heredoc-body stripping (consumer-aware) --------------------------------
80
+ # Drop a heredoc body ONLY when its consuming command does not execute it (cat,
81
+ # tee, a redirect to a file, a non-shell interpreter) — such a body is data. When
82
+ # the operator line names a shell (bash/sh/zsh/dash/ksh/eval/source/`.`) or pipes
83
+ # the body into one, the body IS executed and is kept for scanning. The operator
84
+ # line itself is always preserved. Mirrors git-mutation-guard.sh, deliberately:
85
+ # the two guards should agree about what counts as a command.
86
+ strip_heredocs() {
87
+ awk '
88
+ !inbody {
89
+ line = $0
90
+ if (match(line, /<<[-]?[[:space:]]*["'"'"']?[A-Za-z_][A-Za-z0-9_]*["'"'"']?/)) {
91
+ d = substr(line, RSTART, RLENGTH)
92
+ gsub(/<<[-]?[[:space:]]*["'"'"']?/, "", d)
93
+ gsub(/["'"'"'].*/, "", d)
94
+ delim = d
95
+ inbody = 1
96
+ keepbody = 0
97
+ if (line ~ /(^|[^[:alnum:]_])(bash|sh|zsh|dash|ksh|eval|source)([^[:alnum:]_]|$)/) keepbody = 1
98
+ if (line ~ /(^|[[:space:]])\.[[:space:]]/) keepbody = 1
99
+ if (line ~ /\|[^|]*(bash|sh|zsh|dash|ksh|eval)([^[:alnum:]_]|$)/) keepbody = 1
100
+ }
101
+ print line
102
+ next
103
+ }
104
+ {
105
+ t = $0
106
+ gsub(/^[[:space:]]+/, "", t)
107
+ if (t == delim) { inbody = 0; keepbody = 0; next }
108
+ if (keepbody) print $0
109
+ }
110
+ ' 2>/dev/null || true
111
+ }
112
+
113
+ # --- segment split + sink-scoped quote blanking -------------------------------
114
+ # Emits one command segment per line, splitting on unquoted `;` `&&` `||` `|`.
115
+ # Segments whose leading command is a text SINK have their quoted content
116
+ # blanked, so prose that merely mentions `gh pr edit` is not mistaken for an
117
+ # invocation. `gh` itself counts as a sink only for its own --body/--title/
118
+ # --comment ARGUMENT text; the segment's own `gh pr edit ...` words are outside
119
+ # the quotes and still scanned, so `gh pr edit --body "x"` is still blocked
120
+ # while `gh pr comment 1 --body "use gh pr edit"` is not.
121
+ split_segments() {
122
+ awk '
123
+ function get_lead_cmd(seg, s) {
124
+ s = seg; gsub(/^[[:space:]]+/, "", s)
125
+ while (match(s, /^[A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*[[:space:]]+/))
126
+ s = substr(s, RSTART + RLENGTH)
127
+ while (match(s, /^[0-9]*[<>][>&]?[^[:space:]]*[[:space:]]+/))
128
+ s = substr(s, RSTART + RLENGTH)
129
+ if (match(s, /^[^[:space:]]+/)) return substr(s, RSTART, RLENGTH)
130
+ return ""
131
+ }
132
+ function check_sink(seg, cmd, s, sc) {
133
+ cmd = get_lead_cmd(seg)
134
+ if (cmd == "echo" || cmd == "printf" || cmd == "cat" || cmd == "tee" || cmd == "write")
135
+ return 1
136
+ if (cmd == "gh" && (seg ~ /--body/ || seg ~ /--title/ || seg ~ /--comment/))
137
+ return 1
138
+ if (cmd == "git") {
139
+ s = seg; gsub(/^[[:space:]]+/, "", s); sub(/^git[[:space:]]+/, "", s)
140
+ while (match(s, /^(-C[[:space:]]+[^[:space:]]+|-c[[:space:]]+[^[:space:]]+|--[a-z][-a-z0-9]*(=[^[:space:]]*)?)[[:space:]]+/))
141
+ s = substr(s, RSTART + RLENGTH)
142
+ if (match(s, /^[^[:space:]]+/)) {
143
+ sc = substr(s, RSTART, RLENGTH)
144
+ if ((sc == "commit" || sc == "tag" || sc == "notes") && \
145
+ (seg ~ /-[a-zA-Z]*m[[:space:]]/ || seg ~ /--message/))
146
+ return 1
147
+ }
148
+ }
149
+ return 0
150
+ }
151
+ function blank_quotes(seg, n, i, c, out, isq, idq) {
152
+ n = length(seg); out = ""; isq = 0; idq = 0
153
+ for (i = 1; i <= n; i++) {
154
+ c = substr(seg, i, 1)
155
+ if (isq) {
156
+ if (c == "'"'"'") { isq = 0; out = out c } else out = out " "
157
+ continue
158
+ }
159
+ if (idq) {
160
+ if (c == "\\") { out = out " "; i++; continue }
161
+ if (c == "\"") { idq = 0; out = out c } else out = out " "
162
+ continue
163
+ }
164
+ if (c == "'"'"'") { isq = 1; out = out c; continue }
165
+ if (c == "\"") { idq = 1; out = out c; continue }
166
+ out = out c
167
+ }
168
+ return out
169
+ }
170
+ {
171
+ line = $0; n = length(line)
172
+ isq = 0; idq = 0; num = 0; seg_s = 1
173
+ for (i = 1; i <= n; i++) {
174
+ c = substr(line, i, 1)
175
+ if (isq) { if (c == "'"'"'") isq = 0; continue }
176
+ if (idq) { if (c == "\\") { i++; continue }; if (c == "\"") idq = 0; continue }
177
+ if (c == "'"'"'") { isq = 1; continue }
178
+ if (c == "\"") { idq = 1; continue }
179
+ sp = 0; sl = 1
180
+ if (c == ";") sp = 1
181
+ else if (c == "&" && i < n && substr(line, i+1, 1) == "&") { sp = 1; sl = 2 }
182
+ else if (c == "|" && i < n && substr(line, i+1, 1) == "|") { sp = 1; sl = 2 }
183
+ else if (c == "|") sp = 1
184
+ if (sp) {
185
+ num++; segs[num] = substr(line, seg_s, i - seg_s)
186
+ seg_s = i + sl; if (sl == 2) i++
187
+ }
188
+ }
189
+ num++; segs[num] = substr(line, seg_s)
190
+ for (s = 1; s <= num; s++) {
191
+ if (check_sink(segs[s])) print blank_quotes(segs[s])
192
+ else print segs[s]
193
+ }
194
+ }
195
+ ' 2>/dev/null || true
196
+ }
197
+
198
+ # Reduce untrusted command text to something safe to print back: first line
199
+ # only, control characters and non-ASCII removed, truncated. The command arrives
200
+ # from the model and is echoed into a message another agent reads.
201
+ sanitize() {
202
+ printf '%s' "$1" \
203
+ | head -n 1 \
204
+ | LC_ALL=C tr -d '\000-\037\177' \
205
+ | LC_ALL=C tr -c 'A-Za-z0-9 _.,:/=@+~^-' '?' \
206
+ | cut -c1-200
207
+ }
208
+
209
+ refuse() {
210
+ local flags="$1" safe_cmd
211
+ safe_cmd="$(sanitize "$COMMAND")"
212
+ {
213
+ echo ""
214
+ echo "BLOCKED: gh pr edit ($flags)"
215
+ echo " Command: $safe_cmd"
216
+ echo ""
217
+ echo "WHY: our gh is 2.46.0, where every \`gh pr edit\` aborts in a prefetch that"
218
+ echo "asks for deprecated Projects-classic data. It NEVER SENDS THE MUTATION, exits"
219
+ echo "1, and prints only a GraphQL deprecation notice — so it looks like an unrelated"
220
+ echo "warning while your edit silently does not happen. Fixed upstream in gh 2.73.0;"
221
+ echo "Debian trixie has no such package. Measured for --body, --body-file, --title,"
222
+ echo "--add-label, --remove-label, --add-assignee and --milestone alike."
223
+ echo ""
224
+ echo "USE INSTEAD:"
225
+ echo " replace a PR body mx-agent pr set-body <pr> --body-file <file>"
226
+ echo " (PATCHes via the REST API, then verifies the stored body"
227
+ echo " twice and exits non-zero if it did not land)"
228
+ echo " append to a PR gh pr comment <pr> --body-file <file>"
229
+ echo " title / other fields gh api -X PATCH repos/{owner}/{repo}/pulls/<pr> -f title=..."
230
+ echo " labels gh api -X POST repos/{owner}/{repo}/issues/<pr>/labels -f 'labels[]=...'"
231
+ echo ""
232
+ echo "gh pr create, gh pr comment, gh pr view and gh issue edit are all unaffected."
233
+ echo ""
234
+ } >&2
235
+ exit 2
236
+ }
237
+
238
+ # --- matching -----------------------------------------------------------------
239
+ # GHSEG requires `gh` to START a command segment: at start-of-line (grep is
240
+ # line-oriented and segments are emitted one per line), after a separator, or
241
+ # after a shell keyword — optionally preceded by leading redirections, env-var
242
+ # assignments, and launcher words that exec their argv. Without this, the bare
243
+ # substring `gh pr edit` matches prose and every mention of the defect in a
244
+ # report would be blocked (that loose-match failure is #4804).
245
+ #
246
+ # SF-4 (security review): the command word had to be BARE `gh`, so
247
+ # `/usr/bin/gh pr edit` and `./gh pr edit` ran the same broken binary and were
248
+ # not matched — the guard's own message names `gh pr edit`, which is exactly
249
+ # what those commands are. An optional path prefix is now accepted before `gh`.
250
+ # The prefix must END in `/`, so `mygh pr edit` and `foo/mygh pr edit` still do
251
+ # not match: only a path whose final component is `gh` does.
252
+ GHSEG='(^|[;&|({`]|\s(then|do|else)\s)\s*([0-9]*[<>][^[:space:]]*\s+|[A-Za-z_][A-Za-z0-9_]*=[^[:space:];&|]*\s+|(sudo|env|nice|nohup|time|timeout|ionice|stdbuf|command|xargs|setsid|doas|nsenter)\s+([0-9]+\s+)?)*([^[:space:];&|]*/)?gh\s+pr\s+edit(\s|$)'
253
+
254
+ # Everything after `... gh pr edit` in a matched segment, as argv-ish tokens.
255
+ # Quoted text inside sink commands is already blanked upstream, so a `-h` that
256
+ # appears inside a message body cannot reach here.
257
+ GH_EDIT_TAIL='([^[:space:];&|]*/)?gh[[:space:]]+pr[[:space:]]+edit([[:space:]]+(.*))?$'
258
+
259
+ # `gh pr edit --help` prints usage and makes no API call, so it is allowed. But
260
+ # SF-4: a `-h` ANYWHERE in the segment used to allow it, so
261
+ # `gh pr edit 4785 --body-file b.md -h` — a real edit attempt with a stray short
262
+ # flag — was waved through by the guard whose whole job is to stop it. Allow the
263
+ # help form only when help is unambiguous:
264
+ # * `--help`/`-h` is the token IMMEDIATELY after `edit`, or
265
+ # * `--help`/`-h` appears with no write flag anywhere in the tail.
266
+ # Anything that both asks for help and names a field to change is treated as the
267
+ # edit it is. --repo/-R names WHICH pr, not what to change, so it does not count
268
+ # as a write flag.
269
+ is_help_only() {
270
+ local tail="$1" tok first=1 saw_help=0 saw_write=0
271
+ # shellcheck disable=SC2206 # deliberate word-splitting: this is argv, not a path
272
+ local toks=($tail)
273
+ for tok in ${toks[@]+"${toks[@]}"}; do
274
+ case "$tok" in
275
+ --help|-h)
276
+ [[ $first -eq 1 ]] && return 0 # immediately after `edit`
277
+ saw_help=1 ;;
278
+ --repo|--repo=*|-R) ;; # selects the PR, does not change it
279
+ -*) saw_write=1 ;;
280
+ esac
281
+ first=0
282
+ done
283
+ [[ $saw_help -eq 1 && $saw_write -eq 0 ]]
284
+ }
285
+
286
+ SCAN=$(printf '%s' "$COMMAND" | strip_heredocs)
287
+
288
+ while IFS= read -r seg; do
289
+ [[ -n "$seg" ]] || continue
290
+ printf '%s' "$seg" | grep -qE "$GHSEG" || continue
291
+
292
+ GH_TAIL=""
293
+ if [[ "$seg" =~ $GH_EDIT_TAIL ]]; then
294
+ GH_TAIL="${BASH_REMATCH[3]}"
295
+ fi
296
+ if is_help_only "$GH_TAIL"; then
297
+ continue
298
+ fi
299
+
300
+ # Name the flag family in the refusal so the message points at the right
301
+ # replacement route rather than a generic one.
302
+ if printf '%s' "$seg" | grep -qE '(^|\s)--body-file(\s|=)'; then
303
+ refuse "--body-file"
304
+ elif printf '%s' "$seg" | grep -qE '(^|\s)--body(\s|=)'; then
305
+ refuse "--body"
306
+ elif printf '%s' "$seg" | grep -qE '(^|\s)--title(\s|=)'; then
307
+ refuse "--title"
308
+ else
309
+ refuse "all flag forms are broken, not just the body ones"
310
+ fi
311
+ done < <(printf '%s\n' "$SCAN" | split_segments)
312
+
313
+ exit 0