Repository navigation
fix(bin): harden guarded merge execution in fm-pr-merge - #241
Open
HelloWorldSungin wants to merge 31 commits into
Open
HelloWorldSungin wants to merge 31 commits into
HelloWorldSungin wants to merge 31 commits into
Conversation
added 29 commits
September 2, 2026 21:43
…ion window Records the rationale for 91aff587, which landed with an empty body, and carries the remaining accepted review fixes. The rationale is here rather than amended into that commit because the validation pipeline records the head it reviewed and refuses a rewritten one, so this lands additively. Why the GitLab rebase spellings came off the allow-list: --rebase and -r were admitted on the belief that rebase is a merge-method selector like --squash and therefore cannot defer execution. That belief was wrong. --squash changes how the merge commit is formed. --rebase changes the source branch before the merge happens and leaves it changed even when the SHA-bound merge subsequently fails, which is exactly the mutation the no-auto-rebase exclusion exists to prevent. The per-flag safety rationale requirement is what exposed that error, so preserving this reasoning keeps that mechanism effective rather than decorative. Also bounds the GitLab automatic-rebase check to the real risk window and qualifies the target ref as refs/heads/ so a tag sharing the default branch name cannot resolve ahead of the branch and refuse a valid merge.
All three founding cases were re-tested with read-only git merge-tree --write-tree simulations from each pre-remediation branch head against the default branch as it then stood, and every case merged cleanly without losing content. A clean three-way merge cannot silently lose untouched content: a branch can deliberately delete content, while a modify/delete collision is reported as a conflict instead of resolving silently. This holds for merge, squash, and rebase because squash commits the merge-result tree onto the base. The refined classifier could not distinguish stale divergence from an intentional revert because whole-blob equality admits a stale version plus one new line while permanently refusing an exact intentional revert. Staleness is observable, but intent is not, and two independent classifier attempts failed at that same boundary.
HelloWorldSungin
force-pushed
the
fm/fm-stale-base-check-before-merge
branch
from
September 2, 2026 23:16
a25c2ed to
acc6792
Compare
HelloWorldSungin
pushed a commit
that referenced
this pull request
Sep 3, 2026
…ence Firstmate decided on 2026-09-03, on this round's PR, that the fork keeps a merge proof a deferred execution does not satisfy, against upstream kunchenguid#3064 accepting a merge-queue entry as verified. The entry carries the reasoning rather than only the verdict, so the collision is not re-derived every round: this fleet has no merge queue for an enqueue to be deferred into, reporting an unproved merge as landed has actually happened here, and conforming to the more protective option needs nobody's permission while relaxing one does. It also records what the code does TODAY, which is upstream's permissive read, because round 1 merged kunchenguid#3064 faithfully. The stricter implementation is fork PR #241, held on a separate matter, and the reconciliation happens when that lands against this merged base. A future round must not read the merged code as evidence the fork chose upstream's contract. Retirement condition: if this fork ever adopts branch protection with a merge queue, re-examine the divergence rather than defend it.
This was referenced Sep 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Deliver FOUR CORRECTNESS FIXES TO THE GUARDED MERGE PATH in bin/fm-pr-merge.sh. This task does NOT ship a stale-base guard: the captain ruled on 2026-09-02 "drop the guard, keep the four fixes", and the classifier was removed in commit ab16e6b5. Do not reintroduce it, do not propose a replacement discriminator, and do not treat its absence as a gap. Every test on this head already passes in CI.
WHY THE GUARD WAS DROPPED, so it is not re-raised as missing: all three founding cases were re-tested by read-only git merge-tree --write-tree simulation from each pre-remediation branch head against the default branch as it then stood, and every one merged cleanly losing nothing. A clean three-way merge cannot silently lose untouched content - the only routes are a deliberate deletion by the branch, or a modify/delete collision that git raises as a conflict - and this holds for merge, squash and rebase alike since squash commits the merge-result tree onto the base. The refined classifier could not separate stale divergence from an intentional revert, because whole-blob equality admits a stale version plus one new line while permanently refusing an exact intentional revert. Staleness is observable; intent is not.
THE FOUR FIXES THIS TASK DELIVERS, all implemented and all to be preserved:
THE OUTCOME-REPORTING CONTRACT, which is deliberate and must not be "corrected": a merge that LANDED but whose outcome or upward report could not be recorded exits ZERO with a LOUD stderr message saying so, preserves the durable outcome in the wake queue, leaves the retry poll ARMED, and leaves the notified marker absent. That is neither silent success, because it is loud, nor a failed merge, because the merge landed and a retry is armed. Exit code zero means the merge itself did not fail. Only a merge that did NOT land exits nonzero. The assertions "uncommitted-wake-retry: landed merge was reported as failed" and "unbound-secondmate: the merge itself landed and must not be reported as failed" encode this; do not change them to expect a nonzero exit.
CONSTRAINTS: no --force-shaped escape hatch or override that does not name the specific content being discarded. Refusal messages tell the operator what to do next, never how to bypass. Do not amend, squash or rewrite any commit already recorded.
KNOWN AND DELIBERATELY DEFERRED, filed as follow-up and not to be implemented here: replacing gh pr merge with the synchronous REST merge boundary, GitLab merge-train detection, inspecting a non-default target branch rather than refusing it, and object-identity binding on the recording path.
What Changed
bin/fm-pr-merge.shnow inspects the merge boundary before mutating either forge: a request whose actual target is not the current default branch is refused by name with retarget/update/revalidate guidance ahead of every other rejection path, an already-merged request is recognised from GitHubbaseRefOid(non-null after base-branch deletion) and routed straight to outcome reporting with no second mutation, and the GitHub merge call is qualified as--repo <host>/<owner>/<repo>with--match-head-commitso ambientGH_HOSTcannot redirect the mutation to a same-named repository on another forge.--rebase/-rdeliberately excluded), GitLab passes--auto-merge=falseand refuses automatic rebase bounded to the pre-19.4 behind-target window, the default-branch tip is re-read as the last network read before the merge call, live forge state is bound to the fetched objects by OID, and post-merge state is read back with queued or pending refused while the poll stays armed.fm_project_origin_identityinbin/fm-project-origin-lib.shplusfm_pr_remote_matches_identity/fm_pr_remote_gitinbin/fm-pr-lib.shbind and bound the origin probe (FM_PR_MERGE_PROBE_TIMEOUT);fm_merge_outcome_reportreturns a distinct code 4 when the outcome was recorded but its notification marker could not be committed, so a landed merge with an unrecorded report exits zero with a loud stderr line, a preserved queued outcome, and an armed retry;bin/fm-watch.shandbin/fm-wake-lib.shsplit command substitutions out oflocal/arithmetic to fix ShellCheck return-value masking; docs and the merge, write-back, security, and watcher-lock test suites were updated to match.Risk Assessment
Testing
Ran the five test files this change touches - fm-pr-merge, fm-pr-check-security, fm-issue-writeback, fm-watcher-lock and fm-gotmp - and all pass, including the specific assertions earlier CI rounds fought over (
uncommitted-wake-retry,merge-outcome-uncommitted, the eight-route landed-merge invariant, and the teardown tasktmp case). Because passing unit tests alone would not show the operator experience, I also drove the real bin/fm-pr-merge.sh through twenty scenarios against the suite's GitHub and GitLab fixtures and captured a CLI transcript of what an operator actually sees: both forges refusing a non-default target by name ahead of any merge-queue wording; an already-merged PR with a deleted base branch recovering into the wake queue with no second mutation; the merge call staying pinned to--repo github.com/example/repoeven with a hostile ambient GH_HOST; merge-queue, unknown-immediacy, moved-default-tip and post-merge-queued cases each refusing with the poll left armed; the argument allow-list forwarding method/message/cleanup flags while refusing--autoand--adminbefore anything is recorded, and refusing GitLab--rebase/-rthat GitHub admits as a method; the GitLab automatic-rebase check refusing and permitting correctly on both sides of the 19.4 field boundary; and the outcome contract holding - a landed merge whose marker cannot be committed exits zero with a loud actionable line, keeps its durable wake entry, leaves the marker absent and the retry armed, while a forge-rejected merge exits one and records nothing. This is a shell CLI change with no rendered UI surface, so the reviewer-visible artifact is the command transcript rather than a screenshot. No failures, no flakiness observed across three transcript runs, and the worktree is left clean.Evidence: Guarded merge - operator CLI transcript (all four fixes + outcome contract)
Evidence: Evidence driver (20 real fm-pr-merge.sh invocations against the suite forge fixtures)
Evidence: Operator-facing messages the transcript produced, one per guarded outcome
/home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-pr-merge.test.log)/home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-pr-check-security.test.log)/home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-issue-writeback.test.log)/home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-watcher-lock.test.log)Evidence: tests/fm-gotmp.test.sh output
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-pr-merge.sh:1100- Intent requires “a merge that LANDED but whose outcome or upward report could not be recorded exits ZERO” and says only an unlanded merge exits nonzero. The rc=3 and catch-all branches instead print that the merge landed and thenexit 1; tests/fm-pr-merge.test.sh:3058 now enforces the same inversion. Restore zero exit status for post-landing reporting failures while retaining the loud message and armed retry.bin/fm-pr-merge.sh:625- Intent requires permitting an absentautomatic_rebase_enabledfield whenmerge_methodismerge. This path refuses first if the GitLab version is unavailable or unreadable and does not inspectmerge_methoduntil line 674. A project response containing{"merge_method":"merge"}is therefore incorrectly refused whenever the version request fails. Accept the non-rebasing merge method before consulting the server version.bin/fm-pr-merge.sh:1040- Intent requires branching on MERGED before open-only validation. After an initialopenedresponse, this loop runs project-setting validation before rereading the merge-request state. If another actor merges during that interval and the project-setting read then fails or refuses, the command exits without reaching the existing merged-transition recovery at line 1042. Read and handle the live MR state first, then apply automatic-rebase validation only while it remains open.🔧 Fix: Captain: restore guarded merge ordering and landed outcomes
3 issues (2 errors, 1 warning) still open:
bin/fm-pr-merge.sh:1055- The required already-merged recovery still misses the successful settings-read path. If another actor merges aftergitlab_verify_mergeablereportsopenedandgitlab_require_attested_mergesucceeds, thisbreakretains the stale open snapshot; the final tip check then reports the landed merge as a failure instead of routing it to outcome reporting. Re-read GitLab state after every settings read, not only after a failed one, and handle return 4 before mutation.bin/fm-pr-merge.sh:1012- The outcome contract says only an unlanded merge exits nonzero, but both forge commands run underset -eand setmerge_mutation_acceptedonly after a zero exit. If the forge lands the merge and then a post-execution cleanup or response transport fails, the CLI exits nonzero here and the script never performs its confirmation read or records the landed outcome. Capture the command status and always read forge state afterward; a confirmed merge must follow the landed-outcome path.docs/architecture.md:329- This changed architecture contract directly contradicts the required outcome rule: it says an already-landed merge whose outcome cannot be written returns nonzero, while the accepted behavior is exit zero with a loud message and the retry poll armed. Update the documentation to state the deliberate zero-exit behavior.🔧 Fix: Captain: preserve landed outcomes across all merge paths
3 issues (1 warning, 2 infos) still open:
bin/fm-pr-merge.sh:885- When the forge merge command exits non-zero AND the confirmation read proves the request did not land, the refusal message asserts the wrong cause. Concrete:gh pr merge --match-head-commit <sha>fails because the head moved inside the residual window;merge_command_rc=1,github_confirm_mergedreads state OPEN within_queue=false,queue_entry=none,auto_merge=none, and falls through to line 885, telling the operator "GitHub left it pending instead of executing immediately" for a merge the forge outright rejected.gitlab_confirm_mergedline 916 has the identical hole ("GitLab left it queued or pending"). The fix round added acommand_rc-aware message to the unreadable branch of both functions but not to the confirmed-not-landed branch, even thoughcommand_rcis already a parameter there. Report the merge command's exit status in these two branches instead of asserting a deferral that did not happen.bin/fm-pr-merge.sh:1076- The post-attestationgitlab_verify_mergeablere-read now runs unconditionally with stderr unsuppressed (it previously ran only on attestation failure, under2>/dev/null). Every healthy GitLab merge therefore makes two full GraphQL reads and printsverified: <url> is open and mergeable, with a successful pipeline at head <sha>twice, plus a duplicatednotice: recorded head ... disagrees with the live headwhen a stalepr_head=is recorded. The re-read itself is correct and needed for the merged-transition recovery; only the duplicated success notice is noise. Emit theverified:line once (e.g. suppress it on the re-read, or capture the re-read's stderr and print it only when it refuses).bin/fm-pr-merge.sh:48- The header contract and docs/architecture.md:328 still describe post-mutation handling as if the forge command's exit status were authoritative ("After an attempted forge mutation, this script confirms the PR is actually merged before reporting it. A queued or pending result is a refusal, while an unreadable result is actionable"). The fix round made the command status explicitly non-authoritative: a non-zerogh pr merge/glab mr mergefollowed by a confirmed-merged read is now recorded as landed and exits zero. That is the least obvious rule in the file and the one most likely to be "corrected" back by a later reader; state it in the header and in architecture.md alongside the existing zero-exit rationale.🔧 Fix: Name forge rejection, dedupe GitLab verify notices
1 info still open:
bin/fm-pr-merge.sh:696- Dead code ingitlab_require_attested_merge: the secondmerge_methodread (696-698) and[ "$merge_method" = merge ] && return 0(699) are unreachable asmerge. Control only reaches line 696 whenautomatic_rebaseis "absent" (thetruebranch at 625-647 always returns) AND thecaseat 613 already returned 0 formergeand refused every value exceptrebase_merge|ff. Re-parsing the same$jsonwith the same filter therefore always yieldsrebase_mergeorff, so line 699's test is always false. The|| merge_method=fallback is also unreachable because that jq has anelse ""branch and cannot error. Concrete trace: project.json{"merge_method":"rebase_merge"}on GitLab 19.3 -> automatic_rebase=absent -> case at 613 falls through -> version gate passes (19.3 < 19.4) -> line 696 re-readsrebase_merge-> line 699 false -> ancestry check decides. The block reads as a second merge-method escape on the pre-19.4 path that does not exist, obscuring that the merge-method decision was already made at 613. Delete lines 696-699 and let the ancestry check stand alone.✅ **Test** - passed
✅ No issues found.
bash tests/fm-pr-merge.test.sh- 80 cases includingtest_non_default_targets_refuse_both_forges,test_github_already_merged_recovers_with_deleted_base_ref,test_github_immediate_execution_preflight_refuses_queue_and_unknown,test_default_tip_move_refuses_both_forges,test_gitlab_automatic_rebase_setting_handles_version_boundary,test_uncommitted_marker_retry_is_never_silent,test_secondmate_without_parent_binding_is_loud,test_every_observed_landed_path_reports_successbash tests/fm-pr-check-security.test.sh- includes themerge-outcome-uncommitted: landed merge was reported as failedassertion the branch decisions pinbash tests/fm-issue-writeback.test.shbash tests/fm-watcher-lock.test.shbash tests/fm-gotmp.test.sh- includes theteardown exited non-zero with a valid tasktmpcase from an earlier CI roundManual end-to-end:bash /home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/guarded-merge-demo.sh- 20 real invocations ofbin/fm-pr-merge.shagainst the suite forge fixtures, capturing operator stderr, exit status, the gh/glab command log, the durable wake queue and the retry-poll marker for each scenarioManual check: GitHub merge issued aspr merge 42 --repo github.com/example/repo --match-head-commit <sha> --squashwhileGH_HOST=evil.example.comwas set in the environmentManual check:--rebaseaccepted as a GitHub merge-method selector but refused on GitLab, together with-r, before any glab callManual check: GitLab automatic-rebase decision across five settings/version/ancestry combinations spanning the 19.4automatic_rebase_enabledfield boundaryManual check: landed-but-unrecorded outcome exits 0, preserves the wake-queue entry, leavestask-x1.pr-poll-merge-notifiedabsent andtask-x1.check.sharmed, and the re-run commits the marker; a forge-rejected merge exits 1 and records no landed outcomedocs/gitlab-merge-watch.md:215- The GitLab merge transcripts and the merge half of docs/verification/issue-write-back.md record runs against the pre-change merge path; the new merge-boundary inspection means neither reproduces as written (a throwaway FM_HOME with no task worktree now refuses before any GitLab-specific condition, and stubbing gh/gh-axi alone no longer reaches the merge). Both are dated maintainer-verification records under an append-only contract, so I annotated each with a dated note pointing at the owning contract instead of rewriting the observations. Re-capturing them needs a live GitLab fixture with glab credentials and a live Gitea instance, which is not available here; that re-capture remains follow-up work.✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.