@imdeadpool/guardex 7.1.1 → 8.2.0

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 (51) hide show
  1. package/README.md +123 -322
  2. package/package.json +23 -5
  3. package/skills/gitguardex/SKILL.md +83 -3
  4. package/src/agents/finish.js +15 -0
  5. package/src/ci-init/index.js +0 -1
  6. package/src/cli/args.js +142 -3
  7. package/src/cli/commands/branch.js +294 -14
  8. package/src/cli/commands/claude.js +15 -0
  9. package/src/cli/commands/doctor.js +26 -0
  10. package/src/cli/commands/onboard.js +293 -0
  11. package/src/cli/commands/prompt.js +15 -3
  12. package/src/cli/commands/review.js +18 -0
  13. package/src/cli/commands/setup.js +8 -6
  14. package/src/cli/commands/status.js +12 -0
  15. package/src/cli/main.js +2 -0
  16. package/src/cli/shared-locks.js +304 -0
  17. package/src/context.js +21 -3
  18. package/src/core/runtime.js +33 -1
  19. package/src/doctor/index.js +58 -6
  20. package/src/finish/heartbeat.js +169 -0
  21. package/src/finish/index.js +165 -18
  22. package/src/finish/progress.js +316 -0
  23. package/src/finish/review-gate.js +453 -32
  24. package/src/github-api.js +59 -0
  25. package/src/mcp/collect.js +155 -19
  26. package/src/mcp/server.js +35 -19
  27. package/src/output/index.js +210 -0
  28. package/src/pr-checks.js +121 -0
  29. package/src/pr-review.js +581 -51
  30. package/src/pr.js +143 -21
  31. package/src/provider-binary.js +101 -0
  32. package/src/review-diff.js +116 -0
  33. package/src/review-fix.js +229 -0
  34. package/src/sandbox/index.js +11 -5
  35. package/src/scaffold/index.js +4 -16
  36. package/src/shared-git-state.js +566 -0
  37. package/templates/AGENTS.multiagent-safety.md +63 -11
  38. package/templates/AGENTS.multiagent-safety.min.md +1 -0
  39. package/templates/codex/skills/gitguardex/SKILL.md +83 -3
  40. package/templates/githooks/post-checkout +4 -9
  41. package/templates/githooks/pre-commit +17 -1
  42. package/templates/github/workflows/README.md +30 -23
  43. package/templates/scripts/agent-autofinish-watch.sh +280 -0
  44. package/templates/scripts/agent-branch-finish.sh +354 -23
  45. package/templates/scripts/agent-branch-start.sh +49 -22
  46. package/templates/scripts/agent-claude-stop-finish.sh +194 -0
  47. package/templates/scripts/agent-file-locks.py +198 -29
  48. package/templates/scripts/agent-preflight.sh +14 -2
  49. package/templates/scripts/agent-stalled-report.sh +40 -0
  50. package/templates/scripts/codex-agent.sh +10 -63
  51. package/templates/github/workflows/cr.yml +0 -46
@@ -22,6 +22,16 @@ AUTO_RESOLVE_SAFE_GLOBS_RAW="${GUARDEX_FINISH_AUTO_RESOLVE_SAFE_GLOBS-$AUTO_RESO
22
22
  PREFLIGHT_ENABLED_RAW="${GUARDEX_FINISH_PREFLIGHT:-true}"
23
23
  PREFLIGHT_SCRIPT_RAW="${GUARDEX_FINISH_PREFLIGHT_SCRIPT:-scripts/agent-preflight.sh}"
24
24
  AUTO_PROMOTE_DRAFT_RAW="${GUARDEX_FINISH_AUTO_PROMOTE:-true}"
25
+ FINISH_CHECKLIST_RAW="${GUARDEX_FINISH_CHECKLIST:-false}"
26
+ FINISH_GATE_DONE_RAW="${GUARDEX_FINISH_GATE_DONE:-false}"
27
+ FINISH_EVENT_FILE="${GUARDEX_FINISH_EVENT_FILE:-}"
28
+ FINISH_RUN_ID="${GUARDEX_FINISH_RUN_ID:-}"
29
+ FINISH_EVENT_BRANCH="${GUARDEX_FINISH_EVENT_BRANCH:-}"
30
+ FINISH_EVENT_BASE="${GUARDEX_FINISH_EVENT_BASE:-}"
31
+ # Only an explicit --auto-promote FLAG lifts a persisted merge hold; the env
32
+ # default (or GUARDEX_FINISH_AUTO_PROMOTE=1) must not, or any unflagged
33
+ # re-run would silently lift holds placed by earlier runs.
34
+ AUTO_PROMOTE_EXPLICIT=0
25
35
 
26
36
  run_guardex_cli() {
27
37
  if [[ -n "$CLI_ENTRY" ]]; then
@@ -70,6 +80,68 @@ normalize_int() {
70
80
  printf '%s' "$value"
71
81
  }
72
82
 
83
+ finish_json_escape() {
84
+ local value="${1:-}"
85
+ value="${value//\\/\\\\}"
86
+ value="${value//\"/\\\"}"
87
+ value="${value//$'\n'/\\n}"
88
+ value="${value//$'\r'/\\r}"
89
+ value="${value//$'\t'/\\t}"
90
+ printf '%s' "$value"
91
+ }
92
+
93
+ finish_event() {
94
+ local stage="${1:-}"
95
+ local state="${2:-}"
96
+ local number="${3:-0}"
97
+ local label="${4:-}"
98
+ local detail="${5:-}"
99
+ local timestamp=""
100
+ [[ -n "$FINISH_EVENT_FILE" && -n "$FINISH_RUN_ID" ]] || return 0
101
+ timestamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
102
+ printf '{"schemaVersion":1,"runId":"%s","timestamp":"%s","branch":"%s","baseBranch":"%s","stage":"%s","state":"%s","index":%s,"total":8,"label":"%s","detail":"%s"}\n' \
103
+ "$(finish_json_escape "$FINISH_RUN_ID")" \
104
+ "$timestamp" \
105
+ "$(finish_json_escape "$FINISH_EVENT_BRANCH")" \
106
+ "$(finish_json_escape "$FINISH_EVENT_BASE")" \
107
+ "$(finish_json_escape "$stage")" \
108
+ "$(finish_json_escape "$state")" \
109
+ "$number" \
110
+ "$(finish_json_escape "$label")" \
111
+ "$(finish_json_escape "$detail")" \
112
+ >> "$FINISH_EVENT_FILE" 2>/dev/null || true
113
+ }
114
+
115
+ finish_progress() {
116
+ local state="${1:-running}"
117
+ local stage="${2:-}"
118
+ local detail="${3:-}"
119
+ local number=""
120
+ local label=""
121
+ local symbol="🔄"
122
+ local connector="├─"
123
+ [[ "${FINISH_CHECKLIST:-0}" -eq 1 ]] || return 0
124
+
125
+ case "$stage" in
126
+ preflight) number="2"; label="Local preflight" ;;
127
+ pr) number="3"; label="Push and open PR" ;;
128
+ merge) number="7"; label="Merge" ;;
129
+ cleanup) number="8"; label="Cleanup" ;;
130
+ *) return 0 ;;
131
+ esac
132
+ case "$state" in
133
+ complete) symbol="✅" ;;
134
+ skipped) symbol="⏭" ;;
135
+ failed) symbol="❌" ;;
136
+ finished) symbol="🏁" ;;
137
+ esac
138
+ if [[ "$stage" == "cleanup" && "$state" != "running" ]]; then
139
+ connector="╰─"
140
+ fi
141
+ echo "[gx:finish] ${connector} ${symbol} ${number}/8 ${label}${detail:+ · ${detail}}" >&2
142
+ finish_event "$stage" "$state" "$number" "$label" "$detail"
143
+ }
144
+
73
145
  # Resolve the pre-flight script path against the source worktree. The
74
146
  # caller passes either the configured path (which may be relative) or
75
147
  # an empty string; we return the absolute path if it exists and is
@@ -99,23 +171,85 @@ resolve_preflight_script() {
99
171
  run_preflight() {
100
172
  local worktree="$1"
101
173
  if [[ "$PREFLIGHT_ENABLED" -ne 1 ]]; then
174
+ finish_progress skipped preflight "disabled by flag"
102
175
  return 0
103
176
  fi
104
177
  local script_path
105
178
  script_path="$(resolve_preflight_script "$worktree" "$PREFLIGHT_SCRIPT_RAW")"
106
179
  if [[ -z "$script_path" ]]; then
180
+ finish_progress skipped preflight "no executable pre-flight script"
107
181
  echo "[agent-branch-finish] No executable pre-flight script at ${PREFLIGHT_SCRIPT_RAW} (in ${worktree}); skipping pre-flight." >&2
108
182
  return 0
109
183
  fi
184
+ finish_progress running preflight "final verification before publish"
110
185
  echo "[agent-branch-finish] Running pre-flight: ${script_path}" >&2
111
186
  if ( cd "$worktree" && "$script_path" ); then
187
+ finish_progress complete preflight "passed"
112
188
  echo "[agent-branch-finish] Pre-flight passed." >&2
113
189
  return 0
114
190
  fi
191
+ finish_progress failed preflight "failed"
115
192
  echo "[agent-branch-finish] Pre-flight FAILED; refusing push. Override with --no-preflight if you really mean it." >&2
116
193
  return 1
117
194
  }
118
195
 
196
+ # Persisted merge hold. The hold must bind EVERY finish run on the lane, not
197
+ # just the one that placed it — otherwise any unflagged re-run (the Claude
198
+ # stop hook, the doctor auto-finish sweep, `gx finish --all`) would promote
199
+ # the draft and merge, recreating exactly the incident the hold exists to
200
+ # prevent. The durable artifact is a marker in the PR body; only an explicit
201
+ # --auto-promote finish lifts it.
202
+ HOLD_MARKER='guardex:merge-hold'
203
+ HOLD_MARKER_COMMENT="<!-- ${HOLD_MARKER} -->"
204
+
205
+ # Marker state for the PR selected by $1 (URL or branch).
206
+ # Returns: 0 = marker present; 1 = no marker; 2 = PR body unreadable (no PR,
207
+ # gh missing, transient failure). Callers pick the failure direction: the PR
208
+ # flow fails CLOSED (unknown => held), the direct-push guard fails open
209
+ # (unknown usually means "no PR at all").
210
+ pr_hold_marker_state() {
211
+ local body
212
+ if ! body="$("$GH_BIN" pr view "$1" --json body --jq '.body' 2>/dev/null)"; then
213
+ return 2
214
+ fi
215
+ if grep -qF "$HOLD_MARKER_COMMENT" <<<"$body"; then
216
+ return 0
217
+ fi
218
+ return 1
219
+ }
220
+
221
+ place_hold_marker() {
222
+ local pr_url="$1" body
223
+ if ! body="$("$GH_BIN" pr view "$pr_url" --json body --jq '.body' 2>/dev/null)"; then
224
+ echo "[agent-branch-finish] Warning: could not read the PR body; NOT writing the ${HOLD_MARKER} marker (refusing to clobber the body). The hold will NOT survive an unflagged re-run." >&2
225
+ return 0
226
+ fi
227
+ if grep -qF "$HOLD_MARKER_COMMENT" <<<"$body"; then
228
+ return 0
229
+ fi
230
+ if ! "$GH_BIN" pr edit "$pr_url" --body "${body}"$'\n\n'"${HOLD_MARKER_COMMENT}" >/dev/null 2>&1; then
231
+ echo "[agent-branch-finish] Warning: could not write the ${HOLD_MARKER} marker to the PR body; the hold will NOT survive an unflagged re-run of the finish flow." >&2
232
+ fi
233
+ }
234
+
235
+ # Returns non-zero when the marker could not be removed, in which case the
236
+ # caller must keep treating the PR as held.
237
+ remove_hold_marker() {
238
+ local pr_url="$1" body
239
+ if ! body="$("$GH_BIN" pr view "$pr_url" --json body --jq '.body' 2>/dev/null)"; then
240
+ echo "[agent-branch-finish] Warning: could not read the PR body to remove the ${HOLD_MARKER} marker; the hold remains in force." >&2
241
+ return 1
242
+ fi
243
+ if ! grep -qF "$HOLD_MARKER_COMMENT" <<<"$body"; then
244
+ return 0
245
+ fi
246
+ body="$(printf '%s\n' "$body" | grep -vF "$HOLD_MARKER_COMMENT")"
247
+ if ! "$GH_BIN" pr edit "$pr_url" --body "$body" >/dev/null 2>&1; then
248
+ echo "[agent-branch-finish] Warning: could not remove the ${HOLD_MARKER} marker; the hold remains in force." >&2
249
+ return 1
250
+ fi
251
+ }
252
+
119
253
  # After a PR exists, if it is in draft and auto-promote is enabled,
120
254
  # mark it ready-for-review. With the budget-friendly CI defaults
121
255
  # (draft PRs skip CI), this is the moment when CI is allowed to fire.
@@ -145,6 +279,8 @@ WAIT_FOR_MERGE="$(normalize_bool "$WAIT_FOR_MERGE_RAW" "1")"
145
279
  WAIT_TIMEOUT_SECONDS="$(normalize_int "$WAIT_TIMEOUT_SECONDS_RAW" "1800" "30")"
146
280
  WAIT_POLL_SECONDS="$(normalize_int "$WAIT_POLL_SECONDS_RAW" "10" "0")"
147
281
  PARENT_GITLINK_AUTO_COMMIT="$(normalize_bool "$PARENT_GITLINK_AUTO_COMMIT_RAW" "1")"
282
+ FINISH_CHECKLIST="$(normalize_bool "$FINISH_CHECKLIST_RAW" "0")"
283
+ FINISH_GATE_DONE="$(normalize_bool "$FINISH_GATE_DONE_RAW" "0")"
148
284
 
149
285
  while [[ $# -gt 0 ]]; do
150
286
  case "$1" in
@@ -250,10 +386,12 @@ while [[ $# -gt 0 ]]; do
250
386
  ;;
251
387
  --no-auto-promote)
252
388
  AUTO_PROMOTE_DRAFT_RAW="false"
389
+ AUTO_PROMOTE_EXPLICIT=0
253
390
  shift
254
391
  ;;
255
392
  --auto-promote)
256
393
  AUTO_PROMOTE_DRAFT_RAW="true"
394
+ AUTO_PROMOTE_EXPLICIT=1
257
395
  shift
258
396
  ;;
259
397
  *)
@@ -284,6 +422,19 @@ case "$MERGE_MODE" in
284
422
  ;;
285
423
  esac
286
424
 
425
+ # --no-auto-promote is a merge hold: the PR must stay open (draft when the
426
+ # host supports it) until someone deliberately promotes + merges it. A direct
427
+ # push would land the commit with no PR to hold, so the hold forces the PR
428
+ # path and refuses --direct-only outright.
429
+ MERGE_HELD=0
430
+ if [[ "$AUTO_PROMOTE_DRAFT" -ne 1 ]]; then
431
+ if [[ "$MERGE_MODE" == "direct" ]]; then
432
+ echo "[agent-branch-finish] The merge hold (set via --no-auto-promote or GUARDEX_FINISH_AUTO_PROMOTE=0) keeps the merge behind a PR; it cannot be combined with --direct-only. Pass --auto-promote to override." >&2
433
+ exit 1
434
+ fi
435
+ MERGE_MODE="pr"
436
+ fi
437
+
287
438
  AUTO_RESOLVE_MODE="$(printf '%s' "$AUTO_RESOLVE_MODE_RAW" | tr '[:upper:]' '[:lower:]')"
288
439
  case "$AUTO_RESOLVE_MODE" in
289
440
  none|safe|full) ;;
@@ -643,17 +794,16 @@ is_clean_worktree() {
643
794
 
644
795
  refresh_clean_base_worktree() {
645
796
  local wt="$1"
797
+ local pull_output=""
646
798
  [[ -z "$wt" || "$PUSH_ENABLED" -ne 1 ]] && return 0
647
799
 
648
- if ! is_clean_worktree "$wt"; then
649
- echo "[agent-branch-finish] Warning: local ${BASE_BRANCH} worktree is dirty; skipping 'git pull --ff-only origin ${BASE_BRANCH}' for ${wt}." >&2
650
- return 0
651
- fi
652
-
653
- if GUARDEX_DISABLE_POST_MERGE_CLEANUP=1 GUARDEX_PRUNE_ACTIVE_CWD="$finish_active_cwd" git -C "$wt" pull --ff-only origin "$BASE_BRANCH" >/dev/null; then
800
+ if pull_output="$(GUARDEX_DISABLE_POST_MERGE_CLEANUP=1 GUARDEX_PRUNE_ACTIVE_CWD="$finish_active_cwd" git -C "$wt" -c rebase.autoStash=false -c merge.autostash=false pull --ff-only origin "$BASE_BRANCH" 2>&1)"; then
654
801
  echo "[agent-branch-finish] Refreshed local ${BASE_BRANCH} worktree with 'git pull --ff-only origin ${BASE_BRANCH}': ${wt}"
655
802
  else
656
803
  echo "[agent-branch-finish] Warning: failed to refresh local ${BASE_BRANCH} worktree with 'git pull --ff-only origin ${BASE_BRANCH}': ${wt}" >&2
804
+ if [[ -n "$pull_output" ]]; then
805
+ echo "$pull_output" >&2
806
+ fi
657
807
  fi
658
808
  }
659
809
 
@@ -894,12 +1044,28 @@ if [[ "$should_create_integration_helper" -eq 1 ]]; then
894
1044
  fi
895
1045
  fi
896
1046
 
1047
+ # True when `gh pr merge` landed the PR server-side and only its LOCAL cleanup
1048
+ # failed — the merge succeeded, so the caller must continue rather than retry.
1049
+ #
1050
+ # gh reports that cleanup two different ways, and matching only the first costs
1051
+ # a full WAIT_TIMEOUT_SECONDS wait loop per finish:
1052
+ # 1. "failed to delete local branch <b>: ... used by worktree ..."
1053
+ # 2. "failed to run git: fatal: '<base>' is already used by worktree at ..."
1054
+ # The second comes from the checkout to the base that precedes the delete, and
1055
+ # it is the NORMAL case here: gitguardex puts every agent on its own worktree
1056
+ # while the primary checkout sits on the base branch, so `--delete-branch` can
1057
+ # never check that base out. Treating it as a failed merge sent the flow into
1058
+ # the retry loop against an already-merged PR (lifted.sk-storefront #512, which
1059
+ # merged at 21:44:56Z while the finish reported nothing and kept polling).
897
1060
  is_local_branch_delete_error() {
898
1061
  local output="$1"
899
- if [[ "$output" != *"failed to delete local branch"* ]]; then
1062
+ if [[ "$output" == *"failed to delete local branch"* ]]; then
1063
+ if [[ "$output" == *"cannot delete branch"* ]] || [[ "$output" == *"used by worktree"* ]]; then
1064
+ return 0
1065
+ fi
900
1066
  return 1
901
1067
  fi
902
- if [[ "$output" == *"cannot delete branch"* ]] || [[ "$output" == *"used by worktree"* ]]; then
1068
+ if [[ "$output" == *"failed to run git"* ]] && [[ "$output" == *"already used by worktree"* ]]; then
903
1069
  return 0
904
1070
  fi
905
1071
  return 1
@@ -936,6 +1102,20 @@ delete_local_branch_for_cleanup() {
936
1102
  return 0
937
1103
  fi
938
1104
 
1105
+ # `git branch -d` insists on an ancestor link to HEAD. A squash merge — the
1106
+ # default this flow uses (`gh pr merge --squash`) — never creates one, so the
1107
+ # refusal here is the NORMAL post-merge outcome, not a sign the work is
1108
+ # unmerged. GitHub is the authority on that, so ask whether this exact head
1109
+ # landed in a merged PR and only then force the delete. When it did not (a
1110
+ # rebase during finish, or commits pushed after the merge), fall through and
1111
+ # keep the branch rather than destroying commits that never landed.
1112
+ if read_merged_pr_for_head "$(git -C "$repo_root" rev-parse "$branch" 2>/dev/null || true)"; then
1113
+ if git -C "$repo_root" branch -D "$branch" >/dev/null 2>&1; then
1114
+ echo "[agent-branch-finish] Local branch '${branch}' had no ancestor link to '${BASE_BRANCH}' (squash merge), but its head landed in a merged PR; deleted it." >&2
1115
+ return 0
1116
+ fi
1117
+ fi
1118
+
939
1119
  echo "$delete_output" >&2
940
1120
  return 1
941
1121
  }
@@ -1209,12 +1389,15 @@ run_pr_flow() {
1209
1389
  local source_head_sha=""
1210
1390
 
1211
1391
  if ! command -v "$GH_BIN" >/dev/null 2>&1; then
1392
+ [[ "$FINISH_GATE_DONE" -eq 1 ]] || finish_progress failed pr "GitHub CLI unavailable"
1212
1393
  echo "[agent-branch-finish] PR fallback requested but GitHub CLI not found: ${GH_BIN}" >&2
1213
1394
  return 1
1214
1395
  fi
1215
1396
 
1397
+ [[ "$FINISH_GATE_DONE" -eq 1 ]] || finish_progress running pr "pushing branch and opening or reusing a PR"
1216
1398
  source_head_sha="$(git -C "$repo_root" rev-parse "$SOURCE_BRANCH" 2>/dev/null || true)"
1217
1399
  if read_merged_pr_for_head "$source_head_sha"; then
1400
+ [[ "$FINISH_GATE_DONE" -eq 1 ]] || finish_progress complete pr "existing merged PR"
1218
1401
  echo "[agent-branch-finish] Source branch head already landed in a merged PR; skipping new PR creation and continuing cleanup." >&2
1219
1402
  if [[ -n "$pr_url" ]]; then
1220
1403
  echo "[agent-branch-finish] Merged PR: ${pr_url}" >&2
@@ -1231,13 +1414,35 @@ run_pr_flow() {
1231
1414
  fi
1232
1415
  pr_body="Automated by gx branch finish (PR flow)."
1233
1416
 
1417
+ pr_create_args=(
1418
+ --base "$BASE_BRANCH"
1419
+ --head "$SOURCE_BRANCH"
1420
+ --title "$pr_title"
1421
+ --body "$pr_body"
1422
+ )
1423
+ # Merge hold: open the PR as a draft so nothing — required checks going
1424
+ # green, a human clicking merge, repo auto-merge — can land it before the
1425
+ # hold is lifted.
1426
+ if [[ "$AUTO_PROMOTE_DRAFT" -ne 1 ]]; then
1427
+ pr_create_args+=(--draft)
1428
+ fi
1234
1429
  pr_create_output=""
1235
- if pr_create_output="$("$GH_BIN" pr create \
1236
- --base "$BASE_BRANCH" \
1237
- --head "$SOURCE_BRANCH" \
1238
- --title "$pr_title" \
1239
- --body "$pr_body" 2>&1)"; then
1430
+ if pr_create_output="$("$GH_BIN" pr create "${pr_create_args[@]}" 2>&1)"; then
1240
1431
  :
1432
+ elif [[ "$AUTO_PROMOTE_DRAFT" -ne 1 ]] && grep -qi 'draft pull requests are not supported' <<<"$pr_create_output"; then
1433
+ # Some plans reject drafts (e.g. private repos on GitHub Free). Fall back
1434
+ # to a ready PR — the merge-hold early return below still applies.
1435
+ echo "[agent-branch-finish] Draft PRs unsupported in this repository; opening a ready PR (merge still held)." >&2
1436
+ if ! pr_create_output="$("$GH_BIN" pr create \
1437
+ --base "$BASE_BRANCH" \
1438
+ --head "$SOURCE_BRANCH" \
1439
+ --title "$pr_title" \
1440
+ --body "$pr_body" 2>&1)"; then
1441
+ if ! grep -qiE 'already exists|a pull request for branch' <<<"$pr_create_output"; then
1442
+ echo "[agent-branch-finish] gh pr create failed:" >&2
1443
+ echo "${pr_create_output}" >&2
1444
+ fi
1445
+ fi
1241
1446
  else
1242
1447
  # Idempotent: a PR already opened for this head is fine — fall through
1243
1448
  # to `gh pr view` so we still capture the URL. Anything else is a real
@@ -1251,6 +1456,7 @@ run_pr_flow() {
1251
1456
  pr_url="$("$GH_BIN" pr view "$SOURCE_BRANCH" --json url --jq '.url' 2>/dev/null || true)"
1252
1457
 
1253
1458
  if [[ -z "$pr_url" ]]; then
1459
+ [[ "$FINISH_GATE_DONE" -eq 1 ]] || finish_progress failed pr "PR unavailable after push"
1254
1460
  echo "[agent-branch-finish] No PR found for '${SOURCE_BRANCH}' after gh pr create; cannot proceed with PR merge." >&2
1255
1461
  if [[ -n "$pr_create_output" ]]; then
1256
1462
  echo "[agent-branch-finish] Last gh pr create output:" >&2
@@ -1258,12 +1464,63 @@ run_pr_flow() {
1258
1464
  fi
1259
1465
  return 1
1260
1466
  fi
1467
+ [[ "$FINISH_GATE_DONE" -eq 1 ]] || finish_progress complete pr "$pr_url"
1261
1468
  echo "[agent-branch-finish] PR URL: ${pr_url}" >&2
1262
1469
 
1470
+ # Honor a persisted hold BEFORE any promotion or merge. Only an explicit
1471
+ # --auto-promote flag lifts it; the default (env-derived) auto-promote must
1472
+ # not, or every unflagged re-run would lift holds it never placed.
1473
+ hold_state=0
1474
+ pr_hold_marker_state "$pr_url" || hold_state=$?
1475
+ if [[ "$hold_state" -eq 2 ]]; then
1476
+ # Fail closed: a transient failure reading the body must not silently
1477
+ # lift a hold. A spurious hold is recoverable (rerun); a spurious lift
1478
+ # merges the PR.
1479
+ MERGE_HELD=1
1480
+ echo "[agent-branch-finish] Could not read the PR body to check for a merge hold; treating the PR as held (fail closed)." >&2
1481
+ return 2
1482
+ fi
1483
+ if [[ "$hold_state" -eq 0 ]]; then
1484
+ if [[ "$AUTO_PROMOTE_EXPLICIT" -eq 1 && "$AUTO_PROMOTE_DRAFT" -eq 1 ]]; then
1485
+ if ! remove_hold_marker "$pr_url"; then
1486
+ MERGE_HELD=1
1487
+ return 2
1488
+ fi
1489
+ echo "[agent-branch-finish] Merge hold lifted (explicit --auto-promote)." >&2
1490
+ else
1491
+ MERGE_HELD=1
1492
+ # Re-demote in case an outer layer (gate-review markReady, a human)
1493
+ # promoted the held PR since the hold was placed. Idempotent when the
1494
+ # PR is already draft; best-effort like the placement disarm.
1495
+ "$GH_BIN" pr ready --undo "$pr_url" >/dev/null 2>&1 || true
1496
+ echo "[agent-branch-finish] Existing merge hold (${HOLD_MARKER}) honored; not promoting or merging." >&2
1497
+ return 2
1498
+ fi
1499
+ fi
1500
+
1263
1501
  # Pre-flight already passed by the time we reach the PR; promote any
1264
1502
  # existing draft so the budget-friendly CI gate fires once.
1265
1503
  maybe_auto_promote_pr "$pr_url"
1266
1504
 
1505
+ # Merge hold (--no-auto-promote): stop before the merge attempts below.
1506
+ # Without this return the unconditional `gh pr merge` lands the PR the
1507
+ # moment the repo has no blocking checks — the exact accident the flag
1508
+ # exists to prevent.
1509
+ if [[ "$AUTO_PROMOTE_DRAFT" -ne 1 ]]; then
1510
+ MERGE_HELD=1
1511
+ # Disarm anything that could still land the PR while held: GitHub
1512
+ # auto-merge armed by an earlier run, and ready state left by an earlier
1513
+ # run or the gate-review markReady step. Best-effort; the marker below is
1514
+ # the load-bearing hold.
1515
+ "$GH_BIN" pr merge "$pr_url" --disable-auto >/dev/null 2>&1 || true
1516
+ "$GH_BIN" pr ready --undo "$pr_url" >/dev/null 2>&1 || true
1517
+ place_hold_marker "$pr_url"
1518
+ finish_progress skipped merge "merge hold active"
1519
+ echo "[agent-branch-finish] Merge held (--no-auto-promote): PR left unmerged for review/e2e." >&2
1520
+ return 2
1521
+ fi
1522
+
1523
+ finish_progress running merge "waiting for GitHub merge readiness"
1267
1524
  merge_output=""
1268
1525
  if merge_output="$("$GH_BIN" pr merge "$SOURCE_BRANCH" --squash --delete-branch 2>&1)"; then
1269
1526
  return 0
@@ -1294,15 +1551,37 @@ run_pr_flow() {
1294
1551
  return 2
1295
1552
  }
1296
1553
 
1554
+ if [[ "$PUSH_ENABLED" -ne 1 ]]; then
1555
+ finish_progress skipped pr "push disabled"
1556
+ finish_progress running merge "local merge only"
1557
+ fi
1558
+
1297
1559
  if [[ "$PUSH_ENABLED" -eq 1 ]]; then
1298
1560
  if ! run_preflight "$source_worktree"; then
1299
1561
  exit 1
1300
1562
  fi
1301
1563
  if [[ "$MERGE_MODE" != "pr" ]]; then
1302
- maybe_push_changed_submodule_branches "$start_ref" "$SOURCE_BRANCH"
1303
- if ! direct_push_output="$(git -C "$integration_worktree" push origin "HEAD:${BASE_BRANCH}" 2>&1)"; then
1304
- direct_push_error="$direct_push_output"
1564
+ finish_progress skipped pr "direct flow"
1565
+ finish_progress running merge "pushing verified integration result"
1566
+ # A persisted merge hold must also stop the direct-push shortcut, or a
1567
+ # rerun in auto/direct mode would land the held work without ever
1568
+ # consulting the marker. State 2 (no PR / body unreadable) proceeds:
1569
+ # most direct pushes have no PR at all.
1570
+ direct_hold_state=0
1571
+ pr_hold_marker_state "$SOURCE_BRANCH" || direct_hold_state=$?
1572
+ if [[ "$direct_hold_state" -eq 0 ]]; then
1573
+ if [[ "$MERGE_MODE" == "direct" ]]; then
1574
+ echo "[agent-branch-finish] Existing merge hold (${HOLD_MARKER}) on the PR for '${SOURCE_BRANCH}'; refusing the --direct-only push. Lift with 'gx branch finish --branch ${SOURCE_BRANCH} --auto-promote'." >&2
1575
+ exit 1
1576
+ fi
1577
+ echo "[agent-branch-finish] Existing merge hold (${HOLD_MARKER}) on the PR for '${SOURCE_BRANCH}'; skipping the direct push and using the PR flow." >&2
1305
1578
  merge_completed=0
1579
+ else
1580
+ maybe_push_changed_submodule_branches "$start_ref" "$SOURCE_BRANCH"
1581
+ if ! direct_push_output="$(git -C "$integration_worktree" push origin "HEAD:${BASE_BRANCH}" 2>&1)"; then
1582
+ direct_push_error="$direct_push_output"
1583
+ merge_completed=0
1584
+ fi
1306
1585
  fi
1307
1586
  else
1308
1587
  merge_completed=0
@@ -1327,10 +1606,17 @@ if [[ "$PUSH_ENABLED" -eq 1 ]]; then
1327
1606
  if [[ -n "$pr_url" ]]; then
1328
1607
  echo "[agent-branch-finish] PR: ${pr_url}" >&2
1329
1608
  fi
1609
+ if [[ "$MERGE_HELD" -eq 1 ]]; then
1610
+ echo "[agent-branch-finish] Merge hold active; worktree retained. When your gate (review/e2e) passes, lift the hold with: gx branch finish --branch ${SOURCE_BRANCH} --auto-promote" >&2
1611
+ echo "MERGE_HELD=1"
1612
+ exit 0
1613
+ fi
1330
1614
  if [[ "$WAIT_FOR_MERGE" -eq 1 ]]; then
1615
+ finish_progress failed merge "wait window expired"
1331
1616
  echo "[agent-branch-finish] Merge did not complete within wait window; keeping branch open." >&2
1332
1617
  exit 1
1333
1618
  fi
1619
+ finish_progress skipped merge "PR left pending"
1334
1620
  echo "[agent-branch-finish] PR pending review/check policy. Worktree retained for now; the autofinish watcher (or 'gx worktree prune --include-pr-merged --delete-branches') will prune it after merge. Verify with 'git worktree list' before claiming the worktree is still on disk." >&2
1335
1621
  exit 0
1336
1622
  fi
@@ -1344,6 +1630,23 @@ if [[ "$PUSH_ENABLED" -eq 1 ]]; then
1344
1630
  fi
1345
1631
  fi
1346
1632
 
1633
+ # Reaching here means the merge landed. That is the outcome the caller cares
1634
+ # about, so state it once, unmistakably, BEFORE any best-effort cleanup runs —
1635
+ # otherwise a warning from worktree/branch teardown reads as the headline and
1636
+ # the merge scrolls away. Everything below this line is cleanup: it can warn,
1637
+ # it must not fail the run, because the work is already in the base branch.
1638
+ finish_progress complete merge "landed in ${BASE_BRANCH}"
1639
+ echo "[agent-branch-finish] ✅ MERGED ${SOURCE_BRANCH} -> ${BASE_BRANCH} (${merge_status} flow)"
1640
+ if [[ -n "$pr_url" ]]; then
1641
+ echo "[agent-branch-finish] ✅ PR: ${pr_url}"
1642
+ fi
1643
+
1644
+ if [[ "$CLEANUP_AFTER_MERGE" -eq 1 ]]; then
1645
+ finish_progress running cleanup "releasing locks and pruning branch/worktree"
1646
+ else
1647
+ finish_progress skipped cleanup "disabled by flag"
1648
+ fi
1649
+
1347
1650
  run_guardex_cli locks release --branch "$SOURCE_BRANCH" >/dev/null 2>&1 || true
1348
1651
 
1349
1652
  base_worktree="$(get_worktree_for_branch "$BASE_BRANCH")"
@@ -1384,11 +1687,19 @@ if [[ "$CLEANUP_AFTER_MERGE" -eq 1 ]]; then
1384
1687
  git -C "$repo_root" worktree remove "$source_worktree" --force >/dev/null 2>&1 || true
1385
1688
  fi
1386
1689
 
1690
+ # The merge already landed (see the MERGED banner above), so a branch that
1691
+ # refuses to delete is a leftover to report, not a reason to fail the run and
1692
+ # make a successful ship look broken. Keep the branch AND its remote in that
1693
+ # case: the commits it still holds exist nowhere else.
1694
+ local_branch_cleaned=1
1387
1695
  if ! delete_local_branch_for_cleanup "$SOURCE_BRANCH"; then
1388
- exit 1
1696
+ local_branch_cleaned=0
1697
+ echo "[agent-branch-finish] Warning: kept local branch '${SOURCE_BRANCH}' — it holds commits that never landed in '${BASE_BRANCH}' (rebased during finish, or pushed after the merge)." >&2
1698
+ echo "[agent-branch-finish] Inspect: git log ${BASE_BRANCH}..${SOURCE_BRANCH}" >&2
1699
+ echo "[agent-branch-finish] Delete once you are satisfied: git branch -D ${SOURCE_BRANCH}" >&2
1389
1700
  fi
1390
1701
 
1391
- if [[ "$PUSH_ENABLED" -eq 1 && "$DELETE_REMOTE_BRANCH" -eq 1 ]]; then
1702
+ if [[ "$local_branch_cleaned" -eq 1 && "$PUSH_ENABLED" -eq 1 && "$DELETE_REMOTE_BRANCH" -eq 1 ]]; then
1392
1703
  if git -C "$repo_root" ls-remote --exit-code --heads origin "$SOURCE_BRANCH" >/dev/null 2>&1; then
1393
1704
  remote_delete_output=""
1394
1705
  if ! remote_delete_output="$(git -C "$repo_root" push origin --delete "$SOURCE_BRANCH" 2>&1)"; then
@@ -1402,9 +1713,18 @@ if [[ "$CLEANUP_AFTER_MERGE" -eq 1 ]]; then
1402
1713
  fi
1403
1714
  fi
1404
1715
 
1405
- prune_args=(--base "$BASE_BRANCH" --only-dirty-worktrees --delete-branches)
1406
- if [[ "$DELETE_REMOTE_BRANCH" -eq 1 ]]; then
1407
- prune_args+=(--delete-remote-branches)
1716
+ # prune deletes with `git branch -D`, so handing it --delete-branches right
1717
+ # after we deliberately kept a branch with unlanded commits would force-delete
1718
+ # exactly what we just protected. Skip branch deletion for this run; the next
1719
+ # finish or an explicit `gx cleanup` sweeps the rest.
1720
+ prune_args=(--base "$BASE_BRANCH" --only-dirty-worktrees)
1721
+ if [[ "$local_branch_cleaned" -eq 1 ]]; then
1722
+ prune_args+=(--delete-branches)
1723
+ if [[ "$DELETE_REMOTE_BRANCH" -eq 1 ]]; then
1724
+ prune_args+=(--delete-remote-branches)
1725
+ fi
1726
+ else
1727
+ echo "[agent-branch-finish] Skipping branch deletion during prune so '${SOURCE_BRANCH}' survives; sweep later with: gx cleanup --base ${BASE_BRANCH}" >&2
1408
1728
  fi
1409
1729
 
1410
1730
  pivot_to_repo_root_before_prune
@@ -1413,13 +1733,24 @@ if [[ "$CLEANUP_AFTER_MERGE" -eq 1 ]]; then
1413
1733
  echo "[agent-branch-finish] You can run manual cleanup: gx cleanup --base ${BASE_BRANCH}" >&2
1414
1734
  fi
1415
1735
 
1736
+ # Say what actually happened: claiming the branch was cleaned when it was
1737
+ # deliberately kept is the same misreport in the other direction. The two
1738
+ # cleaned wordings differ ("branch/remote" vs "branch/worktree") and callers
1739
+ # match on them, so keep each one exactly as it was.
1740
+ if [[ "$local_branch_cleaned" -eq 1 ]]; then
1741
+ kept_branch_summary=""
1742
+ else
1743
+ kept_branch_summary="kept source branch (commits not in '${BASE_BRANCH}')"
1744
+ fi
1745
+
1416
1746
  if [[ "$source_worktree" == "$current_worktree" && "$source_worktree" == "${agent_worktree_root}"/* && -d "$source_worktree" ]]; then
1417
- echo "[agent-branch-finish] Merged '${SOURCE_BRANCH}' into '${BASE_BRANCH}' via ${merge_status} flow and cleaned source branch/remote."
1747
+ echo "[agent-branch-finish] Merged '${SOURCE_BRANCH}' into '${BASE_BRANCH}' via ${merge_status} flow and ${kept_branch_summary:-cleaned source branch/remote}."
1418
1748
  echo "[agent-branch-finish] Current worktree '${source_worktree}' still exists because it is the active shell cwd." >&2
1419
1749
  echo "[agent-branch-finish] Leave this directory, then run: gx cleanup --base ${BASE_BRANCH}" >&2
1420
1750
  else
1421
- echo "[agent-branch-finish] Merged '${SOURCE_BRANCH}' into '${BASE_BRANCH}' via ${merge_status} flow and cleaned source branch/worktree."
1751
+ echo "[agent-branch-finish] Merged '${SOURCE_BRANCH}' into '${BASE_BRANCH}' via ${merge_status} flow and ${kept_branch_summary:-cleaned source branch/worktree}."
1422
1752
  fi
1753
+ finish_progress finished cleanup "best-effort cleanup finished; inspect warnings above"
1423
1754
  else
1424
1755
  pivot_to_repo_root_before_prune
1425
1756
  if ! run_guardex_prune --base "$BASE_BRANCH"; then