From 62e244d63116587549c4a0037a5180e4e9604acc Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 24 Nov 2026 10:24:57 -0800 Subject: [PATCH] /land-and-deploy merges directly and never deletes main (#4770) (#4795) /land-and-deploy now merges the PR directly instead of arming GitHub auto-merge, so a run that stops leaves nothing behind that can merge later with nobody watching. It keeps the head branch when that branch is the default branch, `main` (a main-to-production promotion), a fork's branch, or the base of another open PR. Nothing to do on your side: the next /land-and-deploy run uses the new merge step. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=red-team --- .../land-and-deploy-never-arms-auto-merge.md | 4 + land-and-deploy/SKILL.md | 2 +- land-and-deploy/SKILL.md.tmpl | 2 +- land-and-deploy/sections/merge-and-deploy.md | 100 +++++++++-------- .../sections/merge-and-deploy.md.tmpl | 100 +++++++++-------- .../skill-evals/land-and-deploy/gh-stub.sh | 9 +- test/helpers/carve-guards.ts | 2 +- test/land-and-deploy-ci-gate.test.ts | 25 ++--- test/land-and-deploy-flow.test.ts | 40 ++++--- test/land-and-deploy-merge-safety.test.ts | 104 ++++++++++++++++++ test/land-and-deploy-postfail.test.ts | 10 +- 11 files changed, 260 insertions(+), 138 deletions(-) create mode 100644 changelog.d/land-and-deploy-never-arms-auto-merge.md create mode 100644 test/land-and-deploy-merge-safety.test.ts diff --git a/changelog.d/land-and-deploy-never-arms-auto-merge.md b/changelog.d/land-and-deploy-never-arms-auto-merge.md new file mode 100644 index 000000000..f96d2c520 --- /dev/null +++ b/changelog.d/land-and-deploy-never-arms-auto-merge.md @@ -0,0 +1,4 @@ +--- +important: data-loss +--- +**/land-and-deploy no longer leaves an auto-merge request behind or deletes `main`.** It merges the PR directly, pinned to the reviewed head. When GitHub won't allow the merge yet, or the base branch merges only through a merge queue, it says so and stops, instead of arming a merge that could land later with nobody watching. It deletes the head branch only when that branch lives in the repository, is not the default branch or `main`, and no other open PR uses it as its base, so a main-to-production promotion keeps `main` (#4770). diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.md index 4d536a697..d4079138c 100644 --- a/land-and-deploy/SKILL.md +++ b/land-and-deploy/SKILL.md @@ -604,4 +604,4 @@ Recheck read-only evidence; never redo a merge/deploy because a section was miss - Step 3 is one `gstack-pr-wait` call; elsewhere poll at the stated interval (60 s for merge readback and deploy) with progress lines. - After merge failures, offer approved rollback when appropriate; never revert a rollback automatically. - Verify once; `/canary` does extended monitoring; rechecks need the user's choice. -- Use `--delete-branch`; reconcile failed cleanup non-destructively with confirmation. +- Merge directly; delete branches only via Step 4's guard; confirm any cleanup. diff --git a/land-and-deploy/SKILL.md.tmpl b/land-and-deploy/SKILL.md.tmpl index bb102fbe2..f1d44d116 100644 --- a/land-and-deploy/SKILL.md.tmpl +++ b/land-and-deploy/SKILL.md.tmpl @@ -444,4 +444,4 @@ Recheck read-only evidence; never redo a merge/deploy because a section was miss - Step 3 is one `gstack-pr-wait` call; elsewhere poll at the stated interval (60 s for merge readback and deploy) with progress lines. - After merge failures, offer approved rollback when appropriate; never revert a rollback automatically. - Verify once; `/canary` does extended monitoring; rechecks need the user's choice. -- Use `--delete-branch`; reconcile failed cleanup non-destructively with confirmation. +- Merge directly; delete branches only via Step 4's guard; confirm any cleanup. diff --git a/land-and-deploy/sections/merge-and-deploy.md b/land-and-deploy/sections/merge-and-deploy.md index e895eed07..881532563 100644 --- a/land-and-deploy/sections/merge-and-deploy.md +++ b/land-and-deploy/sections/merge-and-deploy.md @@ -23,18 +23,20 @@ never evidence that a request or queue entry is absent. READBACK=$(gh api graphql -f query='query($owner:String!,$name:String!,$number:Int!) { repository(owner:$owner,name:$name) { pullRequest(number:$number) { state headRefOid baseRefName mergedAt mergeCommit { oid } - autoMergeRequest { enabledAt } mergeQueueEntry { id state } + autoMergeRequest { enabledAt } mergeQueueEntry { id state } isMergeQueueEnabled } } }' -f owner="${REPO%/*}" -f name="${REPO#*/}" -F number="$PR_NUMBER") || exit 1 printf '%s' "$READBACK" | jq -e ' ((.errors // []) | length == 0) and (.data.repository.pullRequest | type == "object" and has("state") and has("headRefOid") and has("baseRefName") and has("mergeCommit") and - has("autoMergeRequest") and has("mergeQueueEntry"))' >/dev/null || exit 1 + has("autoMergeRequest") and has("mergeQueueEntry") and + (.isMergeQueueEnabled | type == "boolean"))' >/dev/null || exit 1 PR_STATE=$(printf '%s' "$READBACK" | jq -er '.data.repository.pullRequest.state') || exit 1 CURRENT_HEAD=$(printf '%s' "$READBACK" | jq -er '.data.repository.pullRequest.headRefOid') || exit 1 CURRENT_BASE=$(printf '%s' "$READBACK" | jq -er '.data.repository.pullRequest.baseRefName') || exit 1 ACTIVE_REQUEST=$(printf '%s' "$READBACK" | jq -r '.data.repository.pullRequest | .autoMergeRequest != null or .mergeQueueEntry != null') +MERGE_QUEUE=$(printf '%s' "$READBACK" | jq -r '.data.repository.pullRequest.isMergeQueueEnabled') MERGE_ACTION=STOP case "$PR_STATE" in MERGED) @@ -50,14 +52,12 @@ case "$PR_STATE" in MERGE_ACTION=BASE_CHANGED elif [ "$ACTIVE_REQUEST" = true ]; then MERGE_ACTION=WAIT - elif [ "$WAITED" = true ]; then + elif [ "$WAITED" = true ] || [ "$MERGE_ATTEMPT" != none ]; then MERGE_ACTION=STOP - elif [ "$MERGE_ATTEMPT" = none ]; then + elif [ "$MERGE_QUEUE" = true ]; then + MERGE_ACTION=QUEUE_REQUIRED + else MERGE_ACTION=START - elif [ "$MERGE_ATTEMPT" = auto ] && [ "$MERGE_EXIT" -ne 0 ]; then - case "$MERGE_ERROR" in - *"Auto-merge is not allowed for this repository"*|*"Pull request is in clean status"*|*"Pull request is in unstable status"*) MERGE_ACTION=DIRECT ;; - esac fi ;; esac printf '%s\n' "$MERGE_ACTION" @@ -69,37 +69,46 @@ and readiness for the new target. MERGED_CHANGED: report the authoritative exter merge, but **STOP** cleanup/deploy/rollback until the changed head/base is reconciled; the old scope/approval is unusable. Never replay it. WAIT goes to §4a. STOP surfaces the original stderr and current state. **If `state == "CLOSED"`: STOP**, the PR closed without merging. +QUEUE_REQUIRED: the base merges only through a merge queue, where `gh pr merge` would +queue or arm auto-merge: **STOP** and report; queueing is the user's call. -Only START makes the first attempt. Immediately before either merge command, repeat -readback and Step 1's local HEAD/branch/cleanliness check. Retargeting or local changes -invalidate readiness; `--match-head-commit` protects head, not destination. -Each merge block re-runs the CI gate with Step 3.5's approvals (also for `--auto`, -which waits on required checks only). A gate exit means no merge ran: **STOP** with -its output. Only branch protection or a merge queue makes check-to-merge -atomic. +Only START makes the one attempt. Never arm auto-merge or join a queue: a stopped run +must leave nothing that can merge later. Just before merging, repeat readback and Step +1's local HEAD/branch/cleanliness check; retargeting or local changes invalidate +readiness (`--match-head-commit` protects head, not destination). + +Deletion guard: delete the head branch only when it lives in `REPO`, is neither the +default branch nor `main` (a promotion), and no open PR uses it as its base. A failed +lookup keeps it. ```bash -CI_GATE=$(~/.claude/skills/gstack/bin/gstack-ci-gate --repo "$REPO" --pr "$PR_NUMBER" --expect-head "$PR_HEAD" "${CI_OVERRIDE[@]}") -echo "$CI_GATE" -case "${CI_GATE%%$'\n'*}" in "VERDICT PASS $PR_HEAD"|"VERDICT NO_CHECKS $NO_CI_APPROVED_HEAD") ;; *) exit 1 ;; esac -MERGE_ATTEMPT=auto -MERGE_EXIT=0 -MERGE_ERROR=$(gh pr merge "$MERGE_FLAG" --auto --delete-branch "$PR_NUMBER" --repo "$REPO" --match-head-commit "$PR_HEAD" 2>&1) || MERGE_EXIT=$? +DELETE_FLAG= +# gh leaves .headRepository.nameWithOwner empty: compose owner/name. +IFS=$'\t' read -r HEAD_REPO HEAD_BRANCH <<< "$(gh pr view "$PR_NUMBER" --repo "$REPO" --json headRepositoryOwner,headRepository,headRefName \ + --jq '"\(.headRepositoryOwner.login)/\(.headRepository.name)\t\(.headRefName)"')" +DEFAULT_BRANCH=$(gh api "repos/$REPO" --jq .default_branch) || DEFAULT_BRANCH= +OPEN_BASES= +[ -n "$HEAD_BRANCH" ] && { OPEN_BASES=$(gh pr list --repo "$REPO" --base "$HEAD_BRANCH" --state open --limit 1 --json number --jq length) || OPEN_BASES=; } +if [ -n "$HEAD_BRANCH" ] && [ -n "$DEFAULT_BRANCH" ] && [ "$HEAD_REPO" = "$REPO" ] && + [ "$HEAD_BRANCH" != "$DEFAULT_BRANCH" ] && [ "$HEAD_BRANCH" != main ] && [ "$OPEN_BASES" = 0 ]; then + DELETE_FLAG=--delete-branch +fi +echo "DELETE_FLAG=${DELETE_FLAG:-none} $HEAD_REPO $HEAD_BRANCH" ``` -Return to readback, even on exit 0. Only DIRECT permits **one direct fallback**: -readback has confirmed OPEN, no auto request and no queue entry, and the auto attempt -returned one of the two documented rejection classes: auto-merge disabled, or PR -already clean/unstable with nothing required pending. The latter does not mean -auto-merge is disabled. +The merge block re-runs the CI gate with Step 3.5's approvals; a gate exit means no +merge ran: **STOP** with its output. Only branch protection or a merge queue makes +check-to-merge atomic. ```bash CI_GATE=$(~/.claude/skills/gstack/bin/gstack-ci-gate --repo "$REPO" --pr "$PR_NUMBER" --expect-head "$PR_HEAD" "${CI_OVERRIDE[@]}") echo "$CI_GATE" case "${CI_GATE%%$'\n'*}" in "VERDICT PASS $PR_HEAD"|"VERDICT NO_CHECKS $NO_CI_APPROVED_HEAD") ;; *) exit 1 ;; esac MERGE_ATTEMPT=direct MERGE_EXIT=0 -MERGE_ERROR=$(gh pr merge "$MERGE_FLAG" --delete-branch "$PR_NUMBER" --repo "$REPO" --match-head-commit "$PR_HEAD" 2>&1) || MERGE_EXIT=$? +MERGE_ERROR=$(gh pr merge "$MERGE_FLAG" ${DELETE_FLAG:+"$DELETE_FLAG"} "$PR_NUMBER" --repo "$REPO" --match-head-commit "$PR_HEAD" 2>&1) || MERGE_EXIT=$? ``` -Return to readback. There is no fallback from a direct attempt. **Hard rule: never -replay a merge after MERGED**, or retry an unknown state/error. No `--admin` bypass. +Return to readback, even on exit 0; OPEN afterwards is STOP, with no retry or fallback. +A merge GitHub won't allow yet (pending checks or reviews, a branch rule) is reported, +never rerun with auto-merge, a queue or `--admin`. +**Hard rule: never replay a merge after MERGED**, or retry an unknown state/error. **If `state == "MERGED"`:** @@ -130,43 +139,38 @@ Identify candidates: a worktree is stale if (a) it is checked out on the base br - If any candidate has uncommitted work: list the files, tell the user, and STOP worktree cleanup without removing anything. - Do NOT use `--force`. Do NOT remove the user's primary working tree. -Remote-branch reconciliation: `--delete-branch` may not have completed. Verify the -branch outcome instead of claiming cleanup from a merge exit code: +Remote-branch reconciliation. Run the deletion guard block if it has not run. +`DELETE_FLAG=none` means the branch stays: name the check that kept it (fork, default +branch or `main`, an open PR's base, failed lookup) and skip this check. Otherwise verify the branch outcome instead of +claiming cleanup from a merge exit code, in the PR head repository the guard read +(never the checkout's `origin`): ```bash -# gh leaves .headRepository.nameWithOwner EMPTY (gh 2.83): compose owner/name -# from headRepositoryOwner.login + headRepository.name. -IFS=$'\t' read -r HEAD_REPO HEAD_BRANCH <<< "$(gh pr view "$PR_NUMBER" --repo "$REPO" --json headRepositoryOwner,headRepository,headRefName \ - --jq '"\(.headRepositoryOwner.login)/\(.headRepository.name)\t\(.headRefName)"')" -case "$HEAD_REPO" in ''|/*|*/) HEAD_BRANCH= ;; esac -[ -n "$HEAD_BRANCH" ] && echo "HEAD: $HEAD_REPO $HEAD_BRANCH" && git ls-remote --heads "https://github.com/$HEAD_REPO.git" "refs/heads/$HEAD_BRANCH" +[ -n "$DELETE_FLAG" ] && echo "HEAD: $HEAD_REPO $HEAD_BRANCH" && git ls-remote --heads "https://github.com/$HEAD_REPO.git" "refs/heads/$HEAD_BRANCH" ``` -The names are PR data: keep them in these variables, never retyped. The PR head -repository is the authoritative branch location: for same-repository PRs it is the -base repository; for fork PRs it is the fork. Do not substitute the checkout's -`origin`. No `HEAD:` line means the lookup failed: treat the branch state as unknown -and do not run the deletion path. +The names are PR data: keep them in these variables, never retyped. No `HEAD:` line +means the branch state is unknown: do not run the deletion path. Three outcomes — never read a failed check as a clean branch: - **Exit 0, empty output** — the remote branch is already gone (GitHub's post-merge deletion or a concurrent actor got there). Tell the user: "The remote branch has already been cleaned up." This makes re-runs of the recovery idempotent. -- **Exit 0, one ref line** — the branch survived: the failed merge command never reached its `--delete-branch` half. If `HEAD_REPO` equals `REPO`, OFFER deletion, confirm-first (matching the worktree-cleanup posture above): "The remote branch `` still exists in `` — the failed merge never ran its --delete-branch half. Delete it?" Only on confirmation, rerun the block's first three lines, then `git push "https://github.com/$HEAD_REPO.git" --delete "refs/heads/$HEAD_BRANCH"`. If `HEAD_REPO` is a FORK, do not offer deletion — the branch belongs to the contributor and the maintainer typically has no push rights there; report instead: "The branch lives on the contributor's fork `` — leaving it to them." If a local branch of the same name exists, offer `git branch -d "$HEAD_BRANCH"` alongside (`-d`, never `-D` — a non-fast-forwarded local branch is the user's call). +- **Exit 0, one ref line** — the branch survived: the merge never reached its branch-deletion half. OFFER deletion, confirm-first (matching the worktree-cleanup posture above): "The remote branch `` still exists in `` — the merge never deleted it. Delete it?" Only on confirmation, rerun the guard; if it still sets `DELETE_FLAG`, run `git push "https://github.com/$HEAD_REPO.git" --delete "refs/heads/$HEAD_BRANCH"`. If a local branch of the same name exists, offer `git branch -d "$HEAD_BRANCH"` alongside (`-d`, never `-D` — a non-fast-forwarded local branch is the user's call). - **Non-zero exit** — the check ITSELF failed (network, auth). Tell the user: "Couldn't verify remote branch state — leaving it alone." and skip the deletion offer entirely; a failed check is unknown state, not a clean branch. -Record the actual path (`auto`, `direct`, `queue`, or `external` when already merged -before our attempt), then continue to §4b (CI auto-deploy detection). +Record the actual path (`direct`; `auto` or `queue` when someone else's request merged it; +or `external` when already merged before our attempt), then continue to §4b (CI auto-deploy detection). ### 4a: Merge queue detection and messaging -**If `state == "OPEN"` and either request is non-null:** auto-merge is enabled or -merge queue is in use. Explain which is observed; an auto request alone does not +**If `state == "OPEN"` and either request is non-null:** someone else enabled auto-merge or +queued the PR; this skill does neither. Explain which is observed; an auto request alone does not prove a queue. A queue reruns CI against the proposed merge. Record `MERGE_PATH=queue` only when `mergeQueueEntry` was observed, otherwise `auto`. Set `WAITED=true`. Repeat the readback every 60 seconds, up to 30 minutes; report progress every 2 minutes. While OPEN with an active auto request **or** queue entry, keep waiting. Once waiting -has begun, never dispatch START or DIRECT: OPEN with confirmed absence of **both** +has begun, never dispatch START: OPEN with confirmed absence of **both** means removal/cancellation, so **STOP** and point to GitHub's checks/queue page. MERGED returns to the merge-SHA/cleanup branch above. CLOSED, head change, failed readback or timeout stops without replaying or cancelling the server-side request. diff --git a/land-and-deploy/sections/merge-and-deploy.md.tmpl b/land-and-deploy/sections/merge-and-deploy.md.tmpl index a4de77cd3..67f0e7801 100644 --- a/land-and-deploy/sections/merge-and-deploy.md.tmpl +++ b/land-and-deploy/sections/merge-and-deploy.md.tmpl @@ -21,18 +21,20 @@ never evidence that a request or queue entry is absent. READBACK=$(gh api graphql -f query='query($owner:String!,$name:String!,$number:Int!) { repository(owner:$owner,name:$name) { pullRequest(number:$number) { state headRefOid baseRefName mergedAt mergeCommit { oid } - autoMergeRequest { enabledAt } mergeQueueEntry { id state } + autoMergeRequest { enabledAt } mergeQueueEntry { id state } isMergeQueueEnabled } } }' -f owner="${REPO%/*}" -f name="${REPO#*/}" -F number="$PR_NUMBER") || exit 1 printf '%s' "$READBACK" | jq -e ' ((.errors // []) | length == 0) and (.data.repository.pullRequest | type == "object" and has("state") and has("headRefOid") and has("baseRefName") and has("mergeCommit") and - has("autoMergeRequest") and has("mergeQueueEntry"))' >/dev/null || exit 1 + has("autoMergeRequest") and has("mergeQueueEntry") and + (.isMergeQueueEnabled | type == "boolean"))' >/dev/null || exit 1 PR_STATE=$(printf '%s' "$READBACK" | jq -er '.data.repository.pullRequest.state') || exit 1 CURRENT_HEAD=$(printf '%s' "$READBACK" | jq -er '.data.repository.pullRequest.headRefOid') || exit 1 CURRENT_BASE=$(printf '%s' "$READBACK" | jq -er '.data.repository.pullRequest.baseRefName') || exit 1 ACTIVE_REQUEST=$(printf '%s' "$READBACK" | jq -r '.data.repository.pullRequest | .autoMergeRequest != null or .mergeQueueEntry != null') +MERGE_QUEUE=$(printf '%s' "$READBACK" | jq -r '.data.repository.pullRequest.isMergeQueueEnabled') MERGE_ACTION=STOP case "$PR_STATE" in MERGED) @@ -48,14 +50,12 @@ case "$PR_STATE" in MERGE_ACTION=BASE_CHANGED elif [ "$ACTIVE_REQUEST" = true ]; then MERGE_ACTION=WAIT - elif [ "$WAITED" = true ]; then + elif [ "$WAITED" = true ] || [ "$MERGE_ATTEMPT" != none ]; then MERGE_ACTION=STOP - elif [ "$MERGE_ATTEMPT" = none ]; then + elif [ "$MERGE_QUEUE" = true ]; then + MERGE_ACTION=QUEUE_REQUIRED + else MERGE_ACTION=START - elif [ "$MERGE_ATTEMPT" = auto ] && [ "$MERGE_EXIT" -ne 0 ]; then - case "$MERGE_ERROR" in - *"Auto-merge is not allowed for this repository"*|*"Pull request is in clean status"*|*"Pull request is in unstable status"*) MERGE_ACTION=DIRECT ;; - esac fi ;; esac printf '%s\n' "$MERGE_ACTION" @@ -67,37 +67,46 @@ and readiness for the new target. MERGED_CHANGED: report the authoritative exter merge, but **STOP** cleanup/deploy/rollback until the changed head/base is reconciled; the old scope/approval is unusable. Never replay it. WAIT goes to §4a. STOP surfaces the original stderr and current state. **If `state == "CLOSED"`: STOP**, the PR closed without merging. +QUEUE_REQUIRED: the base merges only through a merge queue, where `gh pr merge` would +queue or arm auto-merge: **STOP** and report; queueing is the user's call. -Only START makes the first attempt. Immediately before either merge command, repeat -readback and Step 1's local HEAD/branch/cleanliness check. Retargeting or local changes -invalidate readiness; `--match-head-commit` protects head, not destination. -Each merge block re-runs the CI gate with Step 3.5's approvals (also for `--auto`, -which waits on required checks only). A gate exit means no merge ran: **STOP** with -its output. Only branch protection or a merge queue makes check-to-merge -atomic. +Only START makes the one attempt. Never arm auto-merge or join a queue: a stopped run +must leave nothing that can merge later. Just before merging, repeat readback and Step +1's local HEAD/branch/cleanliness check; retargeting or local changes invalidate +readiness (`--match-head-commit` protects head, not destination). + +Deletion guard: delete the head branch only when it lives in `REPO`, is neither the +default branch nor `main` (a promotion), and no open PR uses it as its base. A failed +lookup keeps it. ```bash -CI_GATE=$(~/.claude/skills/gstack/bin/gstack-ci-gate --repo "$REPO" --pr "$PR_NUMBER" --expect-head "$PR_HEAD" "${CI_OVERRIDE[@]}") -echo "$CI_GATE" -case "${CI_GATE%%$'\n'*}" in "VERDICT PASS $PR_HEAD"|"VERDICT NO_CHECKS $NO_CI_APPROVED_HEAD") ;; *) exit 1 ;; esac -MERGE_ATTEMPT=auto -MERGE_EXIT=0 -MERGE_ERROR=$(gh pr merge "$MERGE_FLAG" --auto --delete-branch "$PR_NUMBER" --repo "$REPO" --match-head-commit "$PR_HEAD" 2>&1) || MERGE_EXIT=$? +DELETE_FLAG= +# gh leaves .headRepository.nameWithOwner empty: compose owner/name. +IFS=$'\t' read -r HEAD_REPO HEAD_BRANCH <<< "$(gh pr view "$PR_NUMBER" --repo "$REPO" --json headRepositoryOwner,headRepository,headRefName \ + --jq '"\(.headRepositoryOwner.login)/\(.headRepository.name)\t\(.headRefName)"')" +DEFAULT_BRANCH=$(gh api "repos/$REPO" --jq .default_branch) || DEFAULT_BRANCH= +OPEN_BASES= +[ -n "$HEAD_BRANCH" ] && { OPEN_BASES=$(gh pr list --repo "$REPO" --base "$HEAD_BRANCH" --state open --limit 1 --json number --jq length) || OPEN_BASES=; } +if [ -n "$HEAD_BRANCH" ] && [ -n "$DEFAULT_BRANCH" ] && [ "$HEAD_REPO" = "$REPO" ] && + [ "$HEAD_BRANCH" != "$DEFAULT_BRANCH" ] && [ "$HEAD_BRANCH" != main ] && [ "$OPEN_BASES" = 0 ]; then + DELETE_FLAG=--delete-branch +fi +echo "DELETE_FLAG=${DELETE_FLAG:-none} $HEAD_REPO $HEAD_BRANCH" ``` -Return to readback, even on exit 0. Only DIRECT permits **one direct fallback**: -readback has confirmed OPEN, no auto request and no queue entry, and the auto attempt -returned one of the two documented rejection classes: auto-merge disabled, or PR -already clean/unstable with nothing required pending. The latter does not mean -auto-merge is disabled. +The merge block re-runs the CI gate with Step 3.5's approvals; a gate exit means no +merge ran: **STOP** with its output. Only branch protection or a merge queue makes +check-to-merge atomic. ```bash CI_GATE=$(~/.claude/skills/gstack/bin/gstack-ci-gate --repo "$REPO" --pr "$PR_NUMBER" --expect-head "$PR_HEAD" "${CI_OVERRIDE[@]}") echo "$CI_GATE" case "${CI_GATE%%$'\n'*}" in "VERDICT PASS $PR_HEAD"|"VERDICT NO_CHECKS $NO_CI_APPROVED_HEAD") ;; *) exit 1 ;; esac MERGE_ATTEMPT=direct MERGE_EXIT=0 -MERGE_ERROR=$(gh pr merge "$MERGE_FLAG" --delete-branch "$PR_NUMBER" --repo "$REPO" --match-head-commit "$PR_HEAD" 2>&1) || MERGE_EXIT=$? +MERGE_ERROR=$(gh pr merge "$MERGE_FLAG" ${DELETE_FLAG:+"$DELETE_FLAG"} "$PR_NUMBER" --repo "$REPO" --match-head-commit "$PR_HEAD" 2>&1) || MERGE_EXIT=$? ``` -Return to readback. There is no fallback from a direct attempt. **Hard rule: never -replay a merge after MERGED**, or retry an unknown state/error. No `--admin` bypass. +Return to readback, even on exit 0; OPEN afterwards is STOP, with no retry or fallback. +A merge GitHub won't allow yet (pending checks or reviews, a branch rule) is reported, +never rerun with auto-merge, a queue or `--admin`. +**Hard rule: never replay a merge after MERGED**, or retry an unknown state/error. **If `state == "MERGED"`:** @@ -128,43 +137,38 @@ Identify candidates: a worktree is stale if (a) it is checked out on the base br - If any candidate has uncommitted work: list the files, tell the user, and STOP worktree cleanup without removing anything. - Do NOT use `--force`. Do NOT remove the user's primary working tree. -Remote-branch reconciliation: `--delete-branch` may not have completed. Verify the -branch outcome instead of claiming cleanup from a merge exit code: +Remote-branch reconciliation. Run the deletion guard block if it has not run. +`DELETE_FLAG=none` means the branch stays: name the check that kept it (fork, default +branch or `main`, an open PR's base, failed lookup) and skip this check. Otherwise verify the branch outcome instead of +claiming cleanup from a merge exit code, in the PR head repository the guard read +(never the checkout's `origin`): ```bash -# gh leaves .headRepository.nameWithOwner EMPTY (gh 2.83): compose owner/name -# from headRepositoryOwner.login + headRepository.name. -IFS=$'\t' read -r HEAD_REPO HEAD_BRANCH <<< "$(gh pr view "$PR_NUMBER" --repo "$REPO" --json headRepositoryOwner,headRepository,headRefName \ - --jq '"\(.headRepositoryOwner.login)/\(.headRepository.name)\t\(.headRefName)"')" -case "$HEAD_REPO" in ''|/*|*/) HEAD_BRANCH= ;; esac -[ -n "$HEAD_BRANCH" ] && echo "HEAD: $HEAD_REPO $HEAD_BRANCH" && git ls-remote --heads "https://github.com/$HEAD_REPO.git" "refs/heads/$HEAD_BRANCH" +[ -n "$DELETE_FLAG" ] && echo "HEAD: $HEAD_REPO $HEAD_BRANCH" && git ls-remote --heads "https://github.com/$HEAD_REPO.git" "refs/heads/$HEAD_BRANCH" ``` -The names are PR data: keep them in these variables, never retyped. The PR head -repository is the authoritative branch location: for same-repository PRs it is the -base repository; for fork PRs it is the fork. Do not substitute the checkout's -`origin`. No `HEAD:` line means the lookup failed: treat the branch state as unknown -and do not run the deletion path. +The names are PR data: keep them in these variables, never retyped. No `HEAD:` line +means the branch state is unknown: do not run the deletion path. Three outcomes — never read a failed check as a clean branch: - **Exit 0, empty output** — the remote branch is already gone (GitHub's post-merge deletion or a concurrent actor got there). Tell the user: "The remote branch has already been cleaned up." This makes re-runs of the recovery idempotent. -- **Exit 0, one ref line** — the branch survived: the failed merge command never reached its `--delete-branch` half. If `HEAD_REPO` equals `REPO`, OFFER deletion, confirm-first (matching the worktree-cleanup posture above): "The remote branch `` still exists in `` — the failed merge never ran its --delete-branch half. Delete it?" Only on confirmation, rerun the block's first three lines, then `git push "https://github.com/$HEAD_REPO.git" --delete "refs/heads/$HEAD_BRANCH"`. If `HEAD_REPO` is a FORK, do not offer deletion — the branch belongs to the contributor and the maintainer typically has no push rights there; report instead: "The branch lives on the contributor's fork `` — leaving it to them." If a local branch of the same name exists, offer `git branch -d "$HEAD_BRANCH"` alongside (`-d`, never `-D` — a non-fast-forwarded local branch is the user's call). +- **Exit 0, one ref line** — the branch survived: the merge never reached its branch-deletion half. OFFER deletion, confirm-first (matching the worktree-cleanup posture above): "The remote branch `` still exists in `` — the merge never deleted it. Delete it?" Only on confirmation, rerun the guard; if it still sets `DELETE_FLAG`, run `git push "https://github.com/$HEAD_REPO.git" --delete "refs/heads/$HEAD_BRANCH"`. If a local branch of the same name exists, offer `git branch -d "$HEAD_BRANCH"` alongside (`-d`, never `-D` — a non-fast-forwarded local branch is the user's call). - **Non-zero exit** — the check ITSELF failed (network, auth). Tell the user: "Couldn't verify remote branch state — leaving it alone." and skip the deletion offer entirely; a failed check is unknown state, not a clean branch. -Record the actual path (`auto`, `direct`, `queue`, or `external` when already merged -before our attempt), then continue to §4b (CI auto-deploy detection). +Record the actual path (`direct`; `auto` or `queue` when someone else's request merged it; +or `external` when already merged before our attempt), then continue to §4b (CI auto-deploy detection). ### 4a: Merge queue detection and messaging -**If `state == "OPEN"` and either request is non-null:** auto-merge is enabled or -merge queue is in use. Explain which is observed; an auto request alone does not +**If `state == "OPEN"` and either request is non-null:** someone else enabled auto-merge or +queued the PR; this skill does neither. Explain which is observed; an auto request alone does not prove a queue. A queue reruns CI against the proposed merge. Record `MERGE_PATH=queue` only when `mergeQueueEntry` was observed, otherwise `auto`. Set `WAITED=true`. Repeat the readback every 60 seconds, up to 30 minutes; report progress every 2 minutes. While OPEN with an active auto request **or** queue entry, keep waiting. Once waiting -has begun, never dispatch START or DIRECT: OPEN with confirmed absence of **both** +has begun, never dispatch START: OPEN with confirmed absence of **both** means removal/cancellation, so **STOP** and point to GitHub's checks/queue page. MERGED returns to the merge-SHA/cleanup branch above. CLOSED, head change, failed readback or timeout stops without replaying or cancelling the server-side request. diff --git a/test/fixtures/skill-evals/land-and-deploy/gh-stub.sh b/test/fixtures/skill-evals/land-and-deploy/gh-stub.sh index b434fdf34..c37f528da 100755 --- a/test/fixtures/skill-evals/land-and-deploy/gh-stub.sh +++ b/test/fixtures/skill-evals/land-and-deploy/gh-stub.sh @@ -15,7 +15,7 @@ jq -cn '$ARGS.positional' --args -- "$@" >> "$D/.gh-log" 2>/dev/null || printf ' cmd="${1:-} ${2:-}" [ $# -ge 2 ] && shift 2 || shift $# case "$cmd" in api\ *) apipath=${cmd#api }; cmd=api ;; esac -fields= expr= target= required= auto= delbranch= matchhead= nameonly= logfailed= +fields= expr= target= required= auto= delbranch= matchhead= nameonly= logfailed= basef= while [ $# -gt 0 ]; do a=$1; shift case "$a" in @@ -33,7 +33,8 @@ while [ $# -gt 0 ]; do --log-failed) logfailed=1 ;; -f|-F|--field|--raw-field) shift ;; --repo=*|--branch=*|--limit=*|--state=*|--method=*|--workflow=*) ;; - -R|--repo|-b|--branch|-L|--limit|-s|--state|-X|--method|-H|--head|-B|--base|-t|--title|-w|--workflow) shift ;; + -B|--base) basef=${1:-}; shift ;; + -R|--repo|-b|--branch|-L|--limit|-s|--state|-X|--method|-H|--head|-t|--title|-w|--workflow) shift ;; -*) ;; *) [ -z "$target" ] && target=$a ;; esac @@ -73,7 +74,7 @@ case "$cmd" in if [ -n "$fields" ] || [ -n "$expr" ]; then out "$(cat "$PR")"; else jq -r '"\(.title) #\(.number)\n\(.state)\n\n\(.body)\n\n\(.url)"' "$PR"; fi ;; "pr list") - if [ -f "$PR" ] && jq -e '.state == "OPEN"' "$PR" >/dev/null; then out "[$(cat "$PR")]"; else out '[]'; fi + if [ -f "$PR" ] && jq -e --arg b "$basef" '.state == "OPEN" and ($b == "" or .baseRefName == $b)' "$PR" >/dev/null; then out "[$(cat "$PR")]"; else out '[]'; fi ;; "pr diff") b=$(jq -r .baseRefOid "$PR"); h=$(jq -r .headRefOid "$PR") @@ -129,7 +130,7 @@ case "$cmd" in api) case "$apipath" in graphql) - out "$(jq -c '{data: {repository: {pullRequest: {number, state, headRefOid, baseRefName, mergedAt: (.mergedAt // null), mergeCommit: (.mergeCommit // null), autoMergeRequest: null, mergeQueueEntry: null, mergeable, title, url}}}}' "$PR")" ;; + out "$(jq -c '{data: {repository: {pullRequest: {number, state, headRefOid, baseRefName, mergedAt: (.mergedAt // null), mergeCommit: (.mergeCommit // null), autoMergeRequest: null, mergeQueueEntry: null, isMergeQueueEnabled: false, mergeable, title, url}}}}' "$PR")" ;; repos/example/app) out '{"full_name":"example/app","default_branch":"main","allow_squash_merge":true,"allow_merge_commit":true,"allow_rebase_merge":true,"delete_branch_on_merge":false}' ;; repos/example/app/contents/.github/workflows*) diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts index 59ec1e56d..b433108c0 100644 --- a/test/helpers/carve-guards.ts +++ b/test/helpers/carve-guards.ts @@ -540,7 +540,7 @@ do not launch the downstream skill or open a browser.`, mustPrecedeStop: ['land-deploy-confirmed'], mustMoveToSection: [ 'PRE-MERGE READINESS REPORT', - 'gh pr merge "$MERGE_FLAG" --auto --delete-branch', + 'gh pr merge "$MERGE_FLAG" ${DELETE_FLAG:+"$DELETE_FLAG"}', 'DEPLOY INFRASTRUCTURE VALIDATION', ], gateAfterStop: undefined, // operational skill diff --git a/test/land-and-deploy-ci-gate.test.ts b/test/land-and-deploy-ci-gate.test.ts index ebb1db733..abb08f6f6 100644 --- a/test/land-and-deploy-ci-gate.test.ts +++ b/test/land-and-deploy-ci-gate.test.ts @@ -45,16 +45,14 @@ const NONE: Reply = { err: "no checks reported on the 'feature' branch", code: 1 const NONE_REQUIRED: Reply = { err: "no required checks reported on the 'feature' branch", code: 1 }; const head = (sha: string): Reply => ({ out: `${sha}\n`, code: 0 }); -/** The two fenced blocks in Step 4 that run `gh pr merge`, keyed by mode. */ -function mergeBlocks(): Record<'auto' | 'direct', string> { +/** The one fenced block in Step 4 that runs `gh pr merge` (#4770: auto-merge is gone). */ +function mergeBlocks(): Record<'direct', string> { const blocks = [...source('sections/merge-and-deploy.md.tmpl').matchAll(/```bash\n([\s\S]*?)\n```/g)] .map(match => match[1]) .filter(block => /\bgh pr merge /.test(block)); - expect(blocks).toHaveLength(2); - const auto = blocks.find(block => block.includes('--auto')); - const direct = blocks.find(block => !block.includes('--auto')); - expect(auto && direct).toBeTruthy(); - return { auto: auto!, direct: direct! }; + expect(blocks).toHaveLength(1); + expect(blocks[0]).not.toContain('--auto'); + return { direct: blocks[0] }; } let dir: string; @@ -68,7 +66,7 @@ afterEach(() => rmSync(dir, { recursive: true, force: true })); interface Journey { heads?: Reply[]; required: Reply | Reply[]; all: Reply | Reply[]; api?: Reply; - mode: 'auto' | 'direct'; noCiApprovedHead?: string; override?: string; + mode: 'direct'; noCiApprovedHead?: string; override?: string; } function runJourney(j: Journey) { const replies: Record = { head: j.heads ?? [head(HEAD)], required: j.required, all: j.all, api: j.api ?? { err: 'HTTP 404', code: 1 } }; @@ -118,7 +116,7 @@ describe('merge blocks never merge without a PASS for the pinned head', () => { ['override approved for another head', { required: checks(['ci', 'pass']), all: checks(['ci', 'pass'], ['lint', 'fail']), override: `--override-head ${OTHER} --exclude lint` }], ['override naming a required check', { required: checks(['ci', 'fail']), all: checks(['ci', 'fail']), override: `--override-head ${HEAD} --exclude ci` }], ]; - for (const mode of ['auto', 'direct'] as const) { + for (const mode of ['direct'] as const) { for (const [name, journey] of blocked) { test(`${mode}: ${name} → zero merges`, () => { const result = runJourney({ ...journey, mode }); @@ -131,13 +129,14 @@ describe('merge blocks never merge without a PASS for the pinned head', () => { }); describe('positive controls: the same blocks do merge when the gate passes', () => { - for (const mode of ['auto', 'direct'] as const) { + for (const mode of ['direct'] as const) { test(`${mode}: all green → exactly one merge pinned to the head`, () => { const result = runJourney({ mode, required: checks(['ci', 'pass']), all: checks(['ci', 'pass'], ['docs', 'skipping']) }); expect(result.status).toBe(0); expect(result.merges).toHaveLength(1); expect(result.merges[0]).toContain(`--match-head-commit ${HEAD}`); - expect(result.merges[0].includes('--auto')).toBe(mode === 'auto'); + expect(result.merges[0]).not.toContain('--auto'); + expect(result.merges[0]).not.toContain('--delete-branch'); }); test(`${mode}: explicit per-head override of named non-required checks → one merge`, () => { @@ -175,7 +174,7 @@ describe('template wiring', () => { expect(step2).toContain('never on the exit code'); }); - test('both merge commands, including the direct fallback, run only after the gate', () => { + test('the one merge command runs only after the gate', () => { for (const block of Object.values(mergeBlocks())) { const gate = block.indexOf('bin/gstack-ci-gate'); expect(gate).toBeGreaterThanOrEqual(0); @@ -196,7 +195,7 @@ describe('template wiring', () => { test('generated skill files carry the helper calls', () => { expect(source('SKILL.md')).toContain('bin/gstack-ci-gate --repo "$REPO" --pr "$PR_NUMBER" --expect-head "$PR_HEAD"'); - expect(source('sections/merge-and-deploy.md').match(/bin\/gstack-ci-gate /g)).toHaveLength(2); + expect(source('sections/merge-and-deploy.md').match(/bin\/gstack-ci-gate /g)).toHaveLength(1); expect(source('sections/readiness-gate.md')).toContain('CI (head )'); }); }); diff --git a/test/land-and-deploy-flow.test.ts b/test/land-and-deploy-flow.test.ts index a83aa7163..a1230734e 100644 --- a/test/land-and-deploy-flow.test.ts +++ b/test/land-and-deploy-flow.test.ts @@ -16,14 +16,14 @@ describe('land-and-deploy decision ordering', () => { expect(main).toContain('headRefOid'); expect(main).toContain('LOCAL_TARGET_MISMATCH'); expect(main.indexOf('gstack-diff-scope')).toBeLessThan(main.indexOf('{{SECTION:readiness-gate}}')); - expect(merge.match(/--match-head-commit "\$PR_HEAD"/g)).toHaveLength(2); + expect(merge.match(/--match-head-commit "\$PR_HEAD"/g)).toHaveLength(1); expect(merge).toContain('invalidate the approval'); }); - test('readback precedes the only direct fallback and includes queue membership', () => { + test('readback precedes the one direct merge and includes queue membership', () => { const merge = source('sections/merge-and-deploy.md.tmpl'); expect(merge).toContain('mergeQueueEntry { id state }'); - expect(merge.indexOf('gh api graphql')).toBeLessThan(merge.indexOf('gh pr merge "$MERGE_FLAG" --delete-branch')); + expect(merge.indexOf('gh api graphql')).toBeLessThan(merge.indexOf('gh pr merge "$MERGE_FLAG" ${DELETE_FLAG:+"$DELETE_FLAG"}')); expect(merge).not.toContain('Both fall through'); expect(merge).not.toContain('never call `gh pr merge` a second time'); expect(merge).toMatch(/never\s+replay a merge after MERGED/); @@ -73,7 +73,7 @@ describe('land-and-deploy native readback dispatcher', () => { const head = 'a'.repeat(40); const pr = (extra = {}) => ({ state: 'OPEN', headRefOid: head, baseRefName: 'main', mergeCommit: null, - autoMergeRequest: null, mergeQueueEntry: null, ...extra, + autoMergeRequest: null, mergeQueueEntry: null, isMergeQueueEnabled: false, ...extra, }); const dispatch = (pullRequest: unknown, env: Record = {}, errors?: unknown[]) => { expect(shell).toBeDefined(); @@ -98,37 +98,41 @@ describe('land-and-deploy native readback dispatcher', () => { }); for (const error of [ - 'Auto-merge is not allowed for this repository', + 'Pull request is not mergeable: the base branch policy prohibits the merge.', 'Pull request is in clean status', - 'Pull request is in unstable status', + '', ]) { - test(`only an unsuccessful auto attempt permits direct fallback: ${error}`, () => { - const env = { MERGE_ATTEMPT: 'auto', MERGE_EXIT: '1', MERGE_ERROR: error }; - expect(dispatch(pr(), env).stdout.trim()).toBe('DIRECT'); - expect(dispatch(pr(), { ...env, MERGE_ATTEMPT: 'direct' }).stdout.trim()).toBe('STOP'); - expect(dispatch(pr(), { ...env, MERGE_EXIT: '0' }).stdout.trim()).toBe('STOP'); + test(`an open PR after the one direct attempt is reported, never retried: ${error || 'exit 0'}`, () => { + for (const exit of ['0', '1']) { + expect(dispatch(pr(), { MERGE_ATTEMPT: 'direct', MERGE_EXIT: exit, MERGE_ERROR: error }).stdout.trim()).toBe('STOP'); + } }); } + test('a merge-queue base is reported before any attempt, never queued', () => { + expect(dispatch(pr({ isMergeQueueEnabled: true })).stdout.trim()).toBe('QUEUE_REQUIRED'); + expect(dispatch(pr({ isMergeQueueEnabled: true }), { MERGE_ATTEMPT: 'direct', MERGE_EXIT: '1' }).stdout.trim()).toBe('STOP'); + }); + test('merged wins over the original cleanup error, without replay', () => { const result = dispatch(pr({ state: 'MERGED', mergeCommit: { oid: 'b'.repeat(40) } }), { - MERGE_ATTEMPT: 'auto', MERGE_EXIT: '1', MERGE_ERROR: 'Pull request is in clean status', + MERGE_ATTEMPT: 'direct', MERGE_EXIT: '1', MERGE_ERROR: 'Pull request is in clean status', }); expect(result.status).toBe(0); expect(result.stdout.trim()).toBe('MERGED'); }); - test('either auto request or queue entry waits even when auto request is null', () => { + test("someone else's auto request or queue entry waits even when auto request is null", () => { for (const active of [ { autoMergeRequest: { enabledAt: '2026-09-24T00:00:00Z' } }, { mergeQueueEntry: { id: 'queue-entry', state: 'QUEUED' } }, ]) { - expect(dispatch(pr(active), { MERGE_ATTEMPT: 'auto', MERGE_EXIT: '1', MERGE_ERROR: 'Pull request is in clean status' }).stdout.trim()).toBe('WAIT'); + for (const attempt of ['none', 'direct']) expect(dispatch(pr(active), { MERGE_ATTEMPT: attempt, MERGE_EXIT: '1', MERGE_ERROR: 'Pull request is in clean status' }).stdout.trim()).toBe('WAIT'); } }); test('removal after waiting never falls back or restarts the merge', () => { - for (const attempt of ['none', 'auto', 'direct']) { + for (const attempt of ['none', 'direct']) { expect(dispatch(pr(), { WAITED: 'true', MERGE_ATTEMPT: attempt, MERGE_EXIT: '1', MERGE_ERROR: 'Pull request is in clean status' }).stdout.trim()).toBe('STOP'); } }); @@ -148,15 +152,17 @@ describe('land-and-deploy native readback dispatcher', () => { }); test('permission failures and closed PRs stop rather than taking direct fallback', () => { - expect(dispatch(pr(), { MERGE_ATTEMPT: 'auto', MERGE_EXIT: '1', MERGE_ERROR: 'permission denied' }).stdout.trim()).toBe('STOP'); + expect(dispatch(pr(), { MERGE_ATTEMPT: 'direct', MERGE_EXIT: '1', MERGE_ERROR: 'permission denied' }).stdout.trim()).toBe('STOP'); expect(dispatch(pr({ state: 'CLOSED' })).stdout.trim()).toBe('STOP'); }); test('missing queue fields, GraphQL errors and failed queries are unknown, not absence', () => { const missingQueue = pr(); delete (missingQueue as Partial).mergeQueueEntry; + const missingQueueSetting = pr(); + delete (missingQueueSetting as Partial).isMergeQueueEnabled; for (const result of [ - dispatch(missingQueue), dispatch(null), dispatch(pr(), {}, [{ message: 'unsupported field' }]), + dispatch(missingQueue), dispatch(missingQueueSetting), dispatch(null), dispatch(pr(), {}, [{ message: 'unsupported field' }]), dispatch(pr(), { READBACK_EXIT: '1' }), dispatch(pr(), { READBACK_FIXTURE: 'not JSON' }), ]) { expect(result.status).not.toBe(0); diff --git a/test/land-and-deploy-merge-safety.test.ts b/test/land-and-deploy-merge-safety.test.ts new file mode 100644 index 000000000..4bb9f1a88 --- /dev/null +++ b/test/land-and-deploy-merge-safety.test.ts @@ -0,0 +1,104 @@ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { spawnSync } from 'node:child_process'; +import { runGeneration, type GenerationResult } from '../scripts/gen-skill-docs'; +import { includesSkill } from '../scripts/discover-skills'; +import { ALL_HOST_NAMES, getHostConfig } from '../hosts/index'; + +// #4770: /land-and-deploy armed GitHub auto-merge (a stopped run left a live +// request that could merge later with nobody watching) and always passed +// --delete-branch, which on a main-to-production promotion asks GitHub to delete +// main. Every host's rendered skill must merge directly and delete the head +// branch only behind the default-branch, main and open-base checks. +const root = join(import.meta.dir, '..'); +const base = mkdtempSync(join(tmpdir(), 'land-merge-safety-')); +const render = join(base, 'render'); +let generated: GenerationResult; +let hosts: Array<{ host: string; paths: string[]; text: string }> = []; + +beforeAll(async () => { + generated = await runGeneration({ host: 'all', outputRoot: render, contentLinkRoot: null }); + expect(generated.exitCode, JSON.stringify(generated.diagnostics)).toBe(0); + const rendered = generated.artifacts.filter(a => a.host && (a.kind === 'skill' || a.kind === 'section') && /(^|\/)(gstack-)?land-and-deploy\//.test(a.relativePath)); + hosts = [...new Set(rendered.map(a => a.host!))].map(host => { + const paths = rendered.filter(a => a.host === host).map(a => a.relativePath).sort(); + return { host, paths, text: paths.map(file => readFileSync(join(render, file), 'utf8')).join('\n') }; + }); +}, 180_000); +afterAll(() => rmSync(base, { recursive: true, force: true })); + +const bashBlocks = (text: string) => [...text.matchAll(/```bash\n([\s\S]*?)\n```/g)].map(m => m[1]); + +describe('land-and-deploy merge safety on every host (#4770)', () => { + test('every host that ships the skill renders its merge step', () => { + const shipping = ALL_HOST_NAMES.filter(host => includesSkill(getHostConfig(host), 'land-and-deploy')); + expect(shipping.length).toBeGreaterThan(1); + expect(hosts.map(h => h.host).sort()).toEqual([...shipping].sort()); + for (const h of hosts) expect(h.text, h.host).toContain('## Step 4: Merge the PR'); + }); + + test('no rendered file asks GitHub for auto-merge', () => { + const hits = hosts.flatMap(h => h.text.split('\n').filter(line => /--auto(?![\w-])/.test(line)).map(line => `${h.host}: ${line}`)); + expect(hits).toEqual([]); + }); + + test('--delete-branch appears only as the guarded DELETE_FLAG assignment', () => { + for (const h of hosts) { + const lines = h.text.split('\n').filter(line => line.includes('--delete-branch')); + expect(lines.map(line => line.trim()), h.host).toEqual(['DELETE_FLAG=--delete-branch']); + const guard = bashBlocks(h.text).find(block => block.includes('DELETE_FLAG=--delete-branch')); + expect(guard, h.host).toBeDefined(); + const condition = guard!.slice(0, guard!.indexOf('DELETE_FLAG=--delete-branch')); + for (const check of ['"$HEAD_REPO" = "$REPO"', '"$HEAD_BRANCH" != "$DEFAULT_BRANCH"', '"$HEAD_BRANCH" != main', '"$OPEN_BASES" = 0']) { + expect(condition, `${h.host}: ${check}`).toContain(check); + } + const merges = h.text.split('\n').filter(line => line.includes('gh pr merge "$MERGE_FLAG"')); + expect(merges, h.host).toHaveLength(1); + expect(merges[0]).toContain('${DELETE_FLAG:+"$DELETE_FLAG"}'); + expect(merges[0]).toContain('--match-head-commit "$PR_HEAD"'); + } + }); +}); + +describe('head-branch deletion guard decides from live PR data', () => { + const template = readFileSync(join(root, 'land-and-deploy', 'sections', 'merge-and-deploy.md.tmpl'), 'utf8'); + const guard = bashBlocks(template).find(block => block.startsWith('DELETE_FLAG=\n')); + const run = (env: Record) => { + expect(guard).toBeDefined(); + const fake = [ + 'gh() {', + ' case "$1 $2" in', + ' "pr view") [ "$FAIL" = view ] && return 1; printf "%s\\t%s\\n" "$T_HEAD_REPO" "$T_HEAD_BRANCH" ;;', + ' "api repos/owner/project") [ "$FAIL" = api ] && return 1; printf "%s\\n" "$T_DEFAULT" ;;', + ' "pr list") [ "$FAIL" = list ] && return 1; printf "%s\\n" "$T_OPEN" ;;', + ' *) return 99 ;;', + ' esac', + '}', + ].join('\n'); + const result = spawnSync('bash', ['-c', `${fake}\n${guard}`], { + encoding: 'utf8', timeout: 5000, + env: { PATH: process.env.PATH, REPO: 'owner/project', PR_NUMBER: '42', T_HEAD_REPO: 'owner/project', T_HEAD_BRANCH: 'feature', T_DEFAULT: 'main', T_OPEN: '0', ...env }, + }); + return result.stdout.trim().split('\n').at(-1); + }; + + test('a feature branch no open PR targets is deleted', () => { + expect(run({})).toBe('DELETE_FLAG=--delete-branch owner/project feature'); + }); + + for (const [name, env] of [ + ['main promoted to production', { T_HEAD_BRANCH: 'main', T_DEFAULT: 'trunk' }], + ['the default branch', { T_HEAD_BRANCH: 'develop', T_DEFAULT: 'develop' }], + ['a branch another open PR targets', { T_OPEN: '1' }], + ['a fork branch', { T_HEAD_REPO: 'someone/project' }], + ['a failed PR lookup', { FAIL: 'view' }], + ['a failed default-branch lookup', { FAIL: 'api' }], + ['a failed open-PR lookup', { FAIL: 'list' }], + ] as const) { + test(`${name} is kept`, () => { + expect(run(env)).toStartWith('DELETE_FLAG=none'); + }); + } +}); diff --git a/test/land-and-deploy-postfail.test.ts b/test/land-and-deploy-postfail.test.ts index 990c9ecad..4a9e87f69 100644 --- a/test/land-and-deploy-postfail.test.ts +++ b/test/land-and-deploy-postfail.test.ts @@ -60,7 +60,7 @@ describe("PR #1620 §4a-postfail in land-and-deploy template", () => { test("Authoritative state query includes auto request and queue membership", () => { const body = readTmpl(); expect(body).toMatch(/gh api graphql/); - expect(body).toContain('autoMergeRequest { enabledAt } mergeQueueEntry { id state }'); + expect(body).toContain('autoMergeRequest { enabledAt } mergeQueueEntry { id state } isMergeQueueEnabled'); }); test("All three state branches named: MERGED, OPEN, CLOSED", () => { @@ -128,12 +128,12 @@ describe("PR #1620 §4a-postfail in land-and-deploy template", () => { expect(body).toMatch(/state == "CLOSED"[\s\S]{0,200}\bstop\b/i); }); - test("Hard rule: no replay after MERGED and only one guarded direct fallback", () => { + test("Hard rule: no replay after MERGED and exactly one direct attempt (#4770)", () => { const body = readTmpl().replace(/\s+/g, " "); expect(body).toMatch(/never replay a merge after MERGED/i); - expect(body).toMatch(/one direct fallback/i); - expectMentions(body, [['no', 'fallback', 'attempt']], 'body'); - expect(body).toMatch(/confirmed OPEN, no auto request and no queue entry/i); + expect(body).toMatch(/only START makes the one attempt/i); + expect(body).toMatch(/never arm auto-merge or join a queue/i); + expectMentions(body, [['no', 'retry', 'fallback']], 'body'); }); test("Generated merge-and-deploy.md carries the §4a-postfail section (atomic regen per T-Codex-3)", () => {