Skip to content

Commit cb5d89b

Browse files
authored
fix(maintainers): prevent duplicate merges after ambiguous responses (#132173)
* fix(maintainers): prevent duplicate merges after ambiguous responses Retain exact native merge intent across process-lock recovery and record completion before comments or cleanup. Reconcile uncertain outcomes without replaying a mutation. Fixes #132138. * fix(maintainers): validate rebase merge receipts Bind rebase and queue results to the retained source fork base, verify merge content as well as ancestry, and align routing regressions with the split test owners. Addresses the review and CI failures for #132173. * test(maintainers): distinguish cherry-picked fixture commits
1 parent ad67390 commit cb5d89b

11 files changed

Lines changed: 1313 additions & 1225 deletions

‎scripts/AGENTS.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,11 @@ This directory owns local tooling, script wrappers, and generated-artifact helpe
3232

3333
- Keep script-runner behavior, wrapper expectations, and generated-artifact guidance here.
3434
- Leave repo-global verification policy in the root `AGENTS.md`.
35+
36+
## Native Merge Outcome Recovery
37+
38+
- `merge-run` owns remote dispatch separately from the process lock. Before any merge/auto/queue request it records the exact repository identity, PR, main target, prepared head, observed main, method, route, and attempt in `refs/openclaw/pr-merge-outcomes/<PR>`. Private Git commits retain the required objects across worktree removal and GC. Do not delete or push these refs; process-lock recovery never clears them.
39+
- A failed request can already have merged. After the reported exact process-lock recovery, repeat `scripts/pr merge-run <PR>` only for reconciliation. `OPEN`, a different head, reverted/partially applied content, elapsed time, or an absent process never proves non-execution. There is no automatic clear/retry override. Inspect the PR timeline, authoritative main history, and `git show refs/openclaw/pr-merge-outcomes/<PR>:outcome.json`; unresolved uncertainty requires operator action outside this automatic path. Keep the record for that investigation. If an older wrapper left `.local/merge-output.log` without an outcome record, even an empty capture blocks a fresh dispatch; preserve it and reconcile the earlier request manually.
40+
- Fresh direct PR/main reads and stable re-reads narrow races; they do not provide global exactly-once execution or a base-OID merge precondition. Immediate squash refuses `NO NET CHANGE` without claiming the PR merged or all intended content remains present. Normal squash/merge receipts reconstruct the tree at the actual landed parent; merge also requires prepared-head ancestry. Rebase and queue receipts verify the aggregate reviewed delta in the historical landed tree using the unique source fork base of retained main/head, not the final rebased parent or recorded main itself. Missing or ambiguous source bases fail closed. Later main advancement or reverts do not authorize reapplication. A normal recorded squash that was empty at its landed parent warns for investigation; its receipt remains confirmed, with no resubmission or automatic revert.
41+
- Before recording intent, `--auto-merge` selects immediate pinned squash for `MERGEABLE/CLEAN` or auto for `MERGEABLE/BEHIND`, subject to all admission gates and queue policy. Accepted auto/queue requests are visible pending outcomes, not completion. The request carries `--match-head-commit`; confirmation still requires the exact attempted head. Existing or ambiguous auto/queue requests are never cancelled, re-armed, or followed by an immediate fallback. Ordinary `gh pr merge` can enqueue when queue policy applies.
42+
- A confirmed merge receipt precedes audits, comments, and cleanup. A comment POST has one attempt marker and is never blindly repeated. Recovery searches authoritative comments for that marker, reports completion pending, and leaves cleanup to the operator after ownership checks; it works without the original worktree/prep artifacts. Normal uninterrupted completion preserves comments and cleanup, with exact-head leased remote deletion. Authoritative branch absence completes cleanup; inspect warnings for advanced or inaccessible branches. Delayed recovery never deletes a recreated branch by name.

‎scripts/pr‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,9 @@ Usage:
211211
scripts/pr merge-verify <PR>
212212
scripts/pr merge-run <PR> [--auto-merge]
213213
OPENCLAW_PR_MERGE_METHOD=merge|rebase preserves the PR commit series.
214-
--auto-merge enables pinned squash auto-merge for a verified BEHIND head.
214+
--auto-merge selects pinned immediate squash for MERGEABLE/CLEAN, auto for MERGEABLE/BEHIND.
215215
OPENCLAW_PR_AUTO_MERGE=1 is equivalent.
216+
Repeated merge-run reconciles retained outcomes; it never retries an uncertain dispatch.
216217
217218
--dev-wrapper permits a mismatched local wrapper only for subcommands
218219
classified advisory. OPENCLAW_PR_DEV_WRAPPER=1 is equivalent.
@@ -322,7 +323,8 @@ main() {
322323

323324
require_cmds
324325

325-
if is_main_only_pr_command "$cmd"; then
326+
# merge-run reconciles retained outcomes before reading disposable artifacts or base guards.
327+
if [ "$cmd" != merge-run ] && is_main_only_pr_command "$cmd"; then
326328
require_main_target_pr "${1-}"
327329
fi
328330

‎scripts/pr-lib/merge-outcome.sh‎

Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
# Remote outcome outlives the process lock and all disposable prepare artifacts.
2+
# These private commits retain the actual head/main/landed objects as parents;
3+
# textual OIDs in a blob alone would not keep historical proof alive through GC.
4+
merge_outcome_stop() {
5+
echo "Merge outcome: $*" >&2
6+
echo "No merge retry. Repeated merge-run only reconciles a recorded attempt. Inspect the PR timeline, main history, and $MERGE_OUTCOME_REF; unresolved uncertainty requires operator action outside this automatic path." >&2
7+
return 1
8+
}
9+
10+
merge_outcome_init() {
11+
local pr="$1" identity
12+
is_canonical_pr_number "$pr" || return 1
13+
MERGE_OUTCOME_REF="refs/openclaw/pr-merge-outcomes/$pr"
14+
identity=$(gh_plain repo view --json id,nameWithOwner,url) || return 1
15+
MERGE_REPO=$(printf '%s\n' "$identity" | jq -ce '
16+
. as $repo | select((.id | type == "string" and length > 0) and
17+
(.nameWithOwner | test("^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")) and
18+
(.url | test("^https://[A-Za-z0-9.-]+/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") and endswith("/" + $repo.nameWithOwner)))
19+
') || { merge_outcome_stop "invalid repository identity"; return 1; }
20+
MERGE_REPO_URL=$(printf '%s\n' "$MERGE_REPO" | jq -r .url)
21+
MERGE_REPO_HOST="${MERGE_REPO_URL#https://}"
22+
MERGE_REPO_HOST="${MERGE_REPO_HOST%%/*}"
23+
MERGE_REPO_NAME=$(printf '%s\n' "$MERGE_REPO" | jq -r .nameWithOwner)
24+
MERGE_OUTCOME_OID=""
25+
MERGE_OUTCOME_RECORD=""
26+
if git symbolic-ref -q "$MERGE_OUTCOME_REF" >/dev/null 2>&1; then
27+
merge_outcome_stop "symbolic outcome ref; inspect without deleting it"
28+
return 1
29+
fi
30+
local ref_status=0
31+
if MERGE_OUTCOME_OID=$(git rev-parse --verify "$MERGE_OUTCOME_REF" 2>/dev/null); then
32+
local parents retained
33+
[ "$(git cat-file -t "$MERGE_OUTCOME_OID")" = commit ] || { merge_outcome_stop "outcome ref is not a commit"; return 1; }
34+
MERGE_OUTCOME_RECORD=$(git show "$MERGE_OUTCOME_OID:outcome.json" | jq -ce \
35+
--argjson repo "$MERGE_REPO" --argjson pr "$pr" '
36+
def oid: type == "string" and test("^[0-9a-f]{40}$");
37+
select(.version == 1 and .repo == $repo and .pr == $pr and .base == "main" and
38+
(.prId | type == "string" and length > 0) and (.head | oid) and (.main | oid) and
39+
(.attempt | test("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")) and
40+
(.method == "squash" or .method == "merge" or .method == "rebase") and
41+
(.route == "immediate" or .route == "admin" or .route == "auto" or .route == "queue") and
42+
(.accepted | type == "boolean") and
43+
(if .phase == "intent" then .landed == null else
44+
(.phase == "merged" or .phase == "commenting" or .phase == "commented" or .phase == "complete") and (.landed | oid) end))
45+
') || { merge_outcome_stop "corrupt or mismatched retained record"; return 1; }
46+
parents=$(git cat-file commit "$MERGE_OUTCOME_OID" | awk 'NF == 0 {exit} $1 == "parent" {printf "%s ", $2}') || return 1
47+
for retained in $(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r '[.head,.main,.landed] | .[] | select(. != null)'); do
48+
case " $parents " in *" $retained "*) ;; *) merge_outcome_stop "record does not retain required commit $retained"; return 1 ;; esac
49+
git cat-file -e "$retained^{commit}" || { merge_outcome_stop "required historical commit $retained is unavailable"; return 1; }
50+
done
51+
else
52+
git show-ref --verify --quiet "$MERGE_OUTCOME_REF" 2>/dev/null || ref_status=$?
53+
[ "$ref_status" -eq 1 ] || { merge_outcome_stop "unreadable outcome ref"; return 1; }
54+
fi
55+
}
56+
57+
merge_outcome_write() {
58+
local record="$1" blob tree next parent
59+
mark_pr_operation_side_effects_started || return 1
60+
local parents=()
61+
for parent in $(printf '%s\n' "$record" | jq -r '[.head,.main,.landed] | unique | .[] | select(. != null)'); do
62+
parents+=(-p "$parent")
63+
done
64+
[ -z "$MERGE_OUTCOME_OID" ] || parents+=(-p "$MERGE_OUTCOME_OID")
65+
blob=$(printf '%s\n' "$record" | git hash-object -w --stdin) || return 1
66+
tree=$(printf '100644 blob %s\toutcome.json\n' "$blob" | git mktree) || return 1
67+
next=$(printf 'Native PR merge outcome\n' | git -c commit.gpgsign=false commit-tree "$tree" "${parents[@]}") || return 1
68+
if git symbolic-ref -q "$MERGE_OUTCOME_REF" >/dev/null 2>&1 ||
69+
! git update-ref --no-deref "$MERGE_OUTCOME_REF" "$next" "${MERGE_OUTCOME_OID:-$(pr_operation_lock_zero_oid)}"; then
70+
merge_outcome_stop "outcome owner changed; preserved successor, no dispatch or completion action"
71+
return 1
72+
fi
73+
MERGE_OUTCOME_OID="$next"
74+
MERGE_OUTCOME_RECORD="$record"
75+
}
76+
77+
merge_outcome_read_remote() {
78+
local response
79+
response=$(gh_plain api graphql --hostname "$MERGE_REPO_HOST" \
80+
-f owner="${MERGE_REPO_NAME%/*}" -f name="${MERGE_REPO_NAME#*/}" -F number="$1" \
81+
-f 'query=query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){id url nameWithOwner ref(qualifiedName:"refs/heads/main"){target{oid}} pullRequest(number:$number){id number url state headRefOid baseRefName isDraft mergeCommit{oid} autoMergeRequest{mergeMethod} isInMergeQueue isMergeQueueEnabled mergeable mergeStateStatus}}}') || return 1
82+
printf '%s\n' "$response" | jq -ce --argjson repo "$MERGE_REPO" --argjson pr "$1" '
83+
def oid: type == "string" and test("^[0-9a-f]{40}$");
84+
select(.errors == null) | .data.repository |
85+
select({id,url,nameWithOwner} == $repo and (.ref.target.oid | oid)) |
86+
{main:.ref.target.oid, pr:.pullRequest} |
87+
select(.pr.number == $pr and (.pr.id | type == "string" and length > 0) and
88+
.pr.url == ($repo.url + "/pull/" + ($pr|tostring)) and
89+
(.pr.headRefOid | oid) and (.pr.baseRefName | type == "string" and length > 0) and
90+
(.pr.isDraft | type == "boolean") and (.pr.isInMergeQueue | type == "boolean") and
91+
(.pr.isMergeQueueEnabled | type == "boolean") and
92+
(.pr.mergeable == "MERGEABLE" or .pr.mergeable == "CONFLICTING" or .pr.mergeable == "UNKNOWN") and
93+
(.pr.mergeStateStatus | type == "string" and length > 0) and (.pr | has("autoMergeRequest")) and
94+
(.pr.autoMergeRequest == null or (.pr.autoMergeRequest.mergeMethod | IN("SQUASH","MERGE","REBASE"))) and
95+
(.pr | has("mergeCommit")) and
96+
(if .pr.state == "MERGED" then (.pr.mergeCommit.oid | oid) else
97+
(.pr.state == "OPEN" or .pr.state == "CLOSED") and .pr.mergeCommit == null end))
98+
'
99+
}
100+
101+
merge_outcome_observe() {
102+
local pr="$1" oid
103+
MERGE_OBSERVATION=$(merge_outcome_read_remote "$pr") || {
104+
merge_outcome_stop "authoritative PR/main metadata unavailable or invalid"; return 1;
105+
}
106+
# Fetch immutable objects only. Do not replace a pinned observation with the
107+
# moving origin/main tracking ref or FETCH_HEAD.
108+
oid=$(printf '%s\n' "$MERGE_OBSERVATION" | jq -r .main)
109+
if ! git cat-file -e "$oid^{commit}" 2>/dev/null; then
110+
git fetch --no-tags --no-write-fetch-head "$MERGE_REPO_URL" "$oid" || { merge_outcome_stop "cannot fetch authoritative main $oid"; return 1; }
111+
fi
112+
git cat-file -e "$oid^{commit}" || return 1
113+
}
114+
115+
merge_outcome_stable() {
116+
local reread
117+
reread=$(merge_outcome_read_remote "$1") || return 1
118+
[ "$reread" = "$MERGE_OBSERVATION" ] || {
119+
merge_outcome_stop "PR or main changed during observation; rerun for read-only reconciliation if intent exists"
120+
return 1
121+
}
122+
}
123+
124+
merge_outcome_reconcile() {
125+
local pr="$1" head state landed method route parent source_base tree phase
126+
merge_outcome_observe "$pr" || return 1
127+
head=$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .head)
128+
if ! printf '%s\n' "$MERGE_OBSERVATION" | jq -e --argjson record "$MERGE_OUTCOME_RECORD" '
129+
.pr.id == $record.prId and .pr.headRefOid == $record.head and .pr.baseRefName == $record.base
130+
' >/dev/null; then
131+
merge_outcome_stop "PR identity/head/base drift from the retained attempt"; return 1
132+
fi
133+
state=$(printf '%s\n' "$MERGE_OBSERVATION" | jq -r .pr.state)
134+
phase=$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .phase)
135+
if [ "$state" != MERGED ]; then
136+
merge_outcome_stable "$pr" || return 1
137+
if [ "$phase" = intent ] && [ "$state" = OPEN ] &&
138+
printf '%s\n' "$MERGE_OBSERVATION" | jq -e '.pr.isInMergeQueue or .pr.autoMergeRequest != null' >/dev/null; then
139+
echo "AUTO/QUEUE PENDING for PR #$pr; not merged. Retained expected head $head; no re-arm, cancellation, or immediate fallback."
140+
echo "Run scripts/pr merge-run $pr again to reconcile only; inspect GitHub queue/auto status if it does not complete."
141+
[ "$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .accepted)" = true ] && return 0
142+
fi
143+
merge_outcome_stop "prior dispatch unresolved (state=$state, phase=$phase); OPEN, process death, head changes, and elapsed time do not prove non-execution"
144+
return 1
145+
fi
146+
landed=$(printf '%s\n' "$MERGE_OBSERVATION" | jq -r .pr.mergeCommit.oid)
147+
git merge-base --is-ancestor "$landed" "$(printf '%s\n' "$MERGE_OBSERVATION" | jq -r .main)" || {
148+
merge_outcome_stop "reported landed commit is unavailable or not reachable from authoritative main"; return 1;
149+
}
150+
method=$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .method)
151+
route=$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .route)
152+
local merge_inputs=()
153+
if [ "$method" = rebase ] || [ "$route" = queue ]; then
154+
# A rebase's final parent can be a rewritten prefix; queue policy can rebase
155+
# regardless of requested method. Anchor the whole source delta at its fork,
156+
# not recorded main (which may already contain a cherry-picked prefix).
157+
source_base=$(git merge-base --all "$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .main)" "$head") &&
158+
[[ "$source_base" =~ ^[0-9a-f]{40}$ ]] || {
159+
merge_outcome_stop "require one source fork base between retained main/head for $method/$route; base missing, unavailable, or ambiguous"; return 1;
160+
}
161+
merge_inputs=(--merge-base="$source_base" "$landed" "$head")
162+
else
163+
parent=$(git rev-parse "$landed^1") || return 1
164+
if [ "$method" = merge ] && ! git merge-base --is-ancestor "$head" "$landed"; then
165+
merge_outcome_stop "landed merge does not retain prepared-head ancestry"; return 1
166+
fi
167+
merge_inputs=("$parent" "$head")
168+
fi
169+
tree=$(git merge-tree --write-tree "${merge_inputs[@]}") || {
170+
merge_outcome_stop "cannot reconstruct $method/$route landed tree at $landed"; return 1;
171+
}
172+
[ "$tree" = "$(git rev-parse "$landed^{tree}")" ] || {
173+
merge_outcome_stop "landed tree does not match the prepared source ($method/$route)"; return 1;
174+
}
175+
merge_outcome_stable "$pr" || return 1
176+
if [ "$phase" = intent ]; then
177+
merge_outcome_write "$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -c --arg landed "$landed" '.phase="merged" | .landed=$landed')" || return 1
178+
elif [ "$landed" != "$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .landed)" ]; then
179+
merge_outcome_stop "remote merge receipt differs from the retained receipt"; return 1
180+
fi
181+
if [ "$method" = squash ] && [ "$route" != queue ] && [ "$tree" = "$(git rev-parse "$parent^{tree}")" ]; then
182+
echo "Warning: recorded squash has no net change at its landed parent ($landed). Inspect main/PR history; receipt retained, no resubmission or automatic revert." >&2
183+
fi
184+
echo "MERGED exact attempted head $head as $landed; receipt retained at $MERGE_OUTCOME_REF."
185+
}
186+
187+
merge_outcome_resume() {
188+
local pr="$1" phase comments marker comment_url
189+
merge_outcome_reconcile "$pr" || return 1
190+
phase=$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .phase)
191+
[ "$phase" != intent ] || return 0
192+
if [ "$phase" = commenting ]; then
193+
marker="<!-- openclaw-merge:$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -r .attempt) -->"
194+
# Absence never permits a second POST: the first response may have been lost.
195+
if comments=$(gh_plain api --hostname "$MERGE_REPO_HOST" --paginate --slurp \
196+
"repos/$MERGE_REPO_NAME/issues/$pr/comments?per_page=100") &&
197+
comment_url=$(printf '%s\n' "$comments" | jq -er --arg marker "$marker" \
198+
'[.[][] | select(.body | contains($marker))] | select(length == 1) | .[0].html_url | select(type == "string" and length > 0)'); then
199+
echo "Completion comment observed: $comment_url"
200+
merge_outcome_write "$(printf '%s\n' "$MERGE_OUTCOME_RECORD" | jq -c '.phase="commented"')" || return 1
201+
fi
202+
fi
203+
if [ "$phase" = complete ]; then
204+
echo "merge-run already complete for PR #$pr; no side effects."
205+
else
206+
echo "Merge confirmed; completion pending. Recovery does not repeat comment POST or cleanup. Inspect the completion marker in PR comments and any remaining .worktrees/pr-$pr/local branches; verify their ownership before manual cleanup."
207+
fi
208+
}

0 commit comments

Comments
 (0)