Skip to content

fix(bin): harden guarded merge execution in fm-pr-merge - #241

Open
HelloWorldSungin wants to merge 31 commits into
mainfrom
fm/fm-stale-base-check-before-merge
Open

HelloWorldSungin wants to merge 31 commits into
mainfrom
fm/fm-stale-base-check-before-merge

Conversation

@HelloWorldSungin

@HelloWorldSungin HelloWorldSungin commented Sep 2, 2026 •

Copy link
Copy Markdown
Owner

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:

  1. MERGE-TARGET CONTRACT: refuse a pull request whose actual target is not the current default branch, naming that target branch, and tell the operator to retarget, bring the branch up, and re-run validation. This check runs before merge-queue, auto-merge, or any other rejection path on both forges, so the required message is never pre-empted.
  2. ALREADY-MERGED RECOVERY: recognise an already-merged request before enforcing pre-merge validation and route it to outcome reporting with no second mutation. Use GitHub baseRefOid, which is non-null even after the base branch is deleted, rather than the nullable baseRef.target.oid, and branch on MERGED before any open-only validation.
  3. HOST-QUALIFIED MUTATION: the GitHub merge call is qualified with the parsed host, so the script cannot validate one forge and mutate a same-named repository on another via ambient GH_HOST.
  4. IMMEDIATE-EXECUTION GUARANTEE AND FINAL PREFLIGHT: establish immediate execution before merging and refuse anything that defers it, treating undeterminable merge-queue or auto-merge state as refusal-grade since unknown is not absent; re-read the default tip immediately before the merge call with no network read inside that window; and read the PR state back afterwards, treating queued or pending as refusal-grade. Merge arguments are an ALLOW-LIST - merge-method selectors, subject/body message arguments, and post-execution branch-cleanup flags only - each recording why it is safe, namely that it acts after execution and cannot defer it. GitLab --rebase and -r are deliberately NOT admitted because --rebase changes the branch before merging and leaves it changed even when the SHA-bound merge fails. GitLab automatic-rebase-before-merge is rejected, bounded to the real risk window: refuse when the branch is behind with merge_method rebase_merge or ff on a pre-19.4 deployment; permit when the field is absent and merge_method is merge; refuse on 19.4+ when the field exists but cannot be read. Automatic rebase was generally available in GitLab 19.2 while the automatic_rebase_enabled API field only appears in 19.4, and that gap is why the check is shaped this way. Identity is bound by OBJECT rather than endpoint spelling at merge time only, using fields on forge state reads the merge path already performs, with no added round trip.

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.sh now 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 GitHub baseRefOid (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-commit so ambient GH_HOST cannot redirect the mutation to a same-named repository on another forge.
  • Immediate execution is now established before merging and anything that would defer it is refused, with undeterminable merge-queue, auto-merge, identity, or automatic-rebase state treated as refusal-grade: forwarded arguments became an allow-list of merge-method selectors, subject/body inputs, and post-execution branch cleanup (GitLab --rebase/-r deliberately excluded), GitLab passes --auto-merge=false and 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.
  • Supporting changes: fm_project_origin_identity in bin/fm-project-origin-lib.sh plus fm_pr_remote_matches_identity/fm_pr_remote_git in bin/fm-pr-lib.sh bind and bound the origin probe (FM_PR_MERGE_PROBE_TIMEOUT); fm_merge_outcome_report returns 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.sh and bin/fm-wake-lib.sh split command substitutions out of local/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

⚠️ Medium: All four required intent fixes and the landed-outcome contract are present and trace correctly on every path I exercised, and the only defect found is an unreachable branch, but the change is large (~3100 insertions) and lands on the forge-mutation path, where the acknowledged sub-second check-to-mutation window remains a deliberate residual.

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/repo even 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 --auto and --admin before anything is recorded, and refusing GitLab --rebase/-r that 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)
Guarded merge - operator transcript, bin/fm-pr-merge.sh
Every block below is a real invocation of the real entrypoint against the
suite forge fixtures. Lines beginning with the supervision bullet are
elided: the fixture home has an in-flight task and no watcher, so the
unrelated "WATCHER DOWN" banner prints on every run.

================================================================
\### FIX 1 - MERGE-TARGET CONTRACT: a PR whose real target is not the current default branch is refused, by name, before any other rejection path

-- github --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/89
    error: refusing to merge https://github.com/example/repo/pull/89 because GitHub reports actual target branch release, but guarded merging is limited to current default branch main
    action: retarget the PR to current default branch main, bring the branch up to current main, and re-run validation
  exit status: 1

  gh command log:
    pr view https://github.com/example/repo/pull/89 --json headRefOid -q .headRefOid
    pr view 89 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup
    api graphql --hostname github.com -f owner=example -f name=repo -F number=89 -f query=query($owner: String!, $name: String!, $number: Int!) {

  glab command log:
    (empty - no forge command was issued)

  durable merge poll still armed: yes
  merge-queue wording pre-empted the target message: no (target contract reported first)

-- gitlab --
$ fm-pr-merge.sh task-x1 https://gitlab.example/group/subgroup/project/-/merge_requests/7
    error: refusing to merge https://gitlab.example/group/subgroup/project/-/merge_requests/7 because GitLab reports actual target branch release, but guarded merging is limited to current default branch main
    action: retarget the PR to current default branch main, bring the branch up to current main, and re-run validation
  exit status: 1

  gh command log:
    (empty - no forge command was issued)

  glab command log:
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7/approvals
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7

  durable merge poll still armed: yes
  merge-queue wording pre-empted the target message: no (target contract reported first)


================================================================
\### FIX 2 - ALREADY-MERGED RECOVERY: a request already merged (base branch since deleted, so baseRef.target.oid is null) is recognised before open-only validation and reported without a second mutation

$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/91
    observed: merged https://github.com/example/repo/pull/91; recording the landed outcome
    warning: PR merge succeeded: https://github.com/example/repo/pull/91; the cached PR state could not be refreshed: fm-pr-status: gh exited 0 for example/repo#91 but returned non-JSON output; the forge CLI likely ignored an unknown flag (the gh-axi wrapper ignores --json). Refresh left the previous observation in place.
  exit status: 0

  gh command log:
    pr view https://github.com/example/repo/pull/91 --json headRefOid -q .headRefOid
    pr view 91 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup
    api graphql --hostname github.com -f owner=example -f name=repo -F number=91 -f query=query($owner: String!, $name: String!, $number: Int!) {
    pr view 91 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup

  durable outcome recorded in the wake queue:
    1788390194	1	check	merged-task-x1-https://github.com/example/repo/pull/91	check: merge landed: task-x1 https://github.com/example/repo/pull/91
  a second merge mutation was issued: no
  open-only validation blocked the recovery: no

================================================================
\### FIX 3 - HOST-QUALIFIED MUTATION: the GitHub merge call names the host parsed from the URL, so an ambient GH_HOST cannot redirect it to a same-named repository on another forge

  ambient environment for this run: GH_HOST=evil.example.com
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/42
    observed: merged https://github.com/example/repo/pull/42; recording the landed outcome
    warning: PR merge succeeded: https://github.com/example/repo/pull/42; the cached PR state could not be refreshed: fm-pr-status: gh exited 0 for example/repo#42 but returned non-JSON output; the forge CLI likely ignored an unknown flag (the gh-axi wrapper ignores --json). Refresh left the previous observation in place.
  exit status: 0

  gh command log (note the host-qualified --repo / --hostname):
    pr view https://github.com/example/repo/pull/42 --json headRefOid -q .headRefOid
    pr view 42 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup
    api graphql --hostname github.com -f owner=example -f name=repo -F number=42 -f query=query($owner: String!, $name: String!, $number: Int!) {
    api graphql --hostname github.com -f owner=example -f name=repo -F number=42 -f query=query($owner: String!, $name: String!, $number: Int!) {
    pr merge 42 --repo github.com/example/repo --match-head-commit 375f1c66224fdb8d00d10dcc819720acd8fc3235 --squash
    api graphql --hostname github.com -f owner=example -f name=repo -F number=42 -f query=query($owner: String!, $name: String!, $number: Int!) {
    pr view 42 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup

================================================================
\### FIX 4a - IMMEDIATE-EXECUTION GUARANTEE: a merge queue defers execution, and an unreadable immediacy state is treated as refusal-grade because unknown is not absent

-- merge-queue --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/74
    error: refusing to merge https://github.com/example/repo/pull/74 because the GitHub merge queue on target branch main would defer execution
  exit status: 1

  gh command log:
    pr view https://github.com/example/repo/pull/74 --json headRefOid -q .headRefOid
    pr view 74 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup
    api graphql --hostname github.com -f owner=example -f name=repo -F number=74 -f query=query($owner: String!, $name: String!, $number: Int!) {

-- unknown --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/74
    error: refusing to merge https://github.com/example/repo/pull/74 because GitHub immediate execution state is unknown, and unknown does not prove deferral is absent
  exit status: 1

  gh command log:
    pr view https://github.com/example/repo/pull/74 --json headRefOid -q .headRefOid
    pr view 74 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup
    api graphql --hostname github.com -f owner=example -f name=repo -F number=74 -f query=query($owner: String!, $name: String!, $number: Int!) {


================================================================
\### FIX 4b - FINAL PREFLIGHT: the default tip is re-read immediately before the merge call, and a tip that moved since the inspected snapshot refuses on both forges

-- github (main advanced from d3792c7e14e6 to ca11d2be2744 inside the merge window) --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/79
    error: refusing to merge https://github.com/example/repo/pull/79 because current default branch main moved from inspected tip d3792c7e14e637c112d01218643975381f411163 to live tip ca11d2be274494ba2b81f00f5ddfb8323a011022 before merge
    action: bring the branch up to current main and re-run validation
  exit status: 1

  gh command log:
    pr view https://github.com/example/repo/pull/79 --json headRefOid -q .headRefOid
    pr view 79 --repo example/repo --json state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefOid,statusCheckRollup
  

... [11245 bytes truncated] ...

ead 3ce051ceceb604a80de50f284bb8ff1fc6649548
    error: refusing to merge https://gitlab.example/group/subgroup/project/-/merge_requests/7 because this pre-19.4 GitLab instance does not expose automatic_rebase_enabled and the source branch is behind the target, so automatic rebase cannot be ruled out
    action: bring the branch up to current main and re-run validation
  exit status: 1

  glab command log:
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7/approvals
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api graphql -f fullPath=group/subgroup/project -f iid=7 -f targetRef=refs/heads/main -f sourceRef=refs/merge-requests/7/head -f query=query($fullPath: ID!, $iid: String!, $sourceRef: 
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject
    GITLAB_HOST=gitlab.example api version
    GITLAB_HOST=gitlab.example api graphql -f fullPath=group/subgroup/project -f iid=7 -f targetRef=refs/heads/main -f sourceRef=refs/merge-requests/7/head -f query=query($fullPath: ID!, $iid: String!, $sourceRef: 

-- PERMIT: field absent and merge method is merge --
   project settings: {"merge_method":"merge"}   instance version: {"version":"19.4.0"}   source branch: up to date
$ fm-pr-merge.sh task-x1 https://gitlab.example/group/subgroup/project/-/merge_requests/7
    verified: https://gitlab.example/group/subgroup/project/-/merge_requests/7 is open and mergeable, with a successful pipeline at head 3ce051ceceb604a80de50f284bb8ff1fc6649548
    observed: merged https://gitlab.example/group/subgroup/project/-/merge_requests/7; recording the landed outcome
  exit status: 0

  glab command log:
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7/approvals
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api graphql -f fullPath=group/subgroup/project -f iid=7 -f targetRef=refs/heads/main -f sourceRef=refs/merge-requests/7/head -f query=query($fullPath: ID!, $iid: String!, $sourceRef: 
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject
    GITLAB_HOST=gitlab.example api graphql -f fullPath=group/subgroup/project -f iid=7 -f targetRef=refs/heads/main -f sourceRef=refs/merge-requests/7/head -f query=query($fullPath: ID!, $iid: String!, $sourceRef: 
    GITLAB_HOST=gitlab.example mr merge 7 -R https://gitlab.example/group/subgroup/project --sha 3ce051ceceb604a80de50f284bb8ff1fc6649548 --yes --auto-merge=false
    GITLAB_HOST=gitlab.example mr view 7 -R https://gitlab.example/group/subgroup/project -F json
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7/approvals

-- REFUSE: 19.4+ instance where the setting cannot be read - unknown is not absent --
   project settings: {}   instance version: {"version":"19.4.0"}   source branch: up to date
$ fm-pr-merge.sh task-x1 https://gitlab.example/group/subgroup/project/-/merge_requests/7
    verified: https://gitlab.example/group/subgroup/project/-/merge_requests/7 is open and mergeable, with a successful pipeline at head 70975906865d02b24db309f7d20540ffe559b792
    error: refusing to merge https://gitlab.example/group/subgroup/project/-/merge_requests/7 because the GitLab project setting automatic_rebase_enabled could not be determined, and unknown does not prove automatic rebase is disabled
    action: bring the branch up to current main and re-run validation
  exit status: 1

  glab command log:
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7/approvals
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject/merge_requests/7
    GITLAB_HOST=gitlab.example api graphql -f fullPath=group/subgroup/project -f iid=7 -f targetRef=refs/heads/main -f sourceRef=refs/merge-requests/7/head -f query=query($fullPath: ID!, $iid: String!, $sourceRef: 
    GITLAB_HOST=gitlab.example api projects/group%2Fsubgroup%2Fproject
    GITLAB_HOST=gitlab.example api graphql -f fullPath=group/subgroup/project -f iid=7 -f targetRef=refs/heads/main -f sourceRef=refs/merge-requests/7/head -f query=query($fullPath: ID!, $iid: String!, $sourceRef: 

================================================================
\### OUTCOME CONTRACT - a merge that LANDED but whose outcome could not be recorded exits ZERO, loudly, keeps the durable outcome, and leaves the retry poll armed

-- the merge lands, but the notification marker cannot be committed --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/67
    observed: merged https://github.com/example/repo/pull/67; recording the landed outcome
    actionable: merged https://github.com/example/repo/pull/67 and recorded its outcome, but could not commit the notification marker; the merge poll remains armed for retry
    warning: PR merge succeeded: https://github.com/example/repo/pull/67; the cached PR state could not be refreshed: fm-pr-status: gh exited 0 for example/repo#67 but returned non-JSON output; the forge CLI likely ignored an unknown flag (the gh-axi wrapper ignores --json). Refresh left the previous observation in place.
  exit status: 0

  durable outcome preserved in the wake queue:
    1788390200	1	check	merged-task-x1-https://github.com/example/repo/pull/67	check: merge landed: task-x1 https://github.com/example/repo/pull/67
  retry poll left armed: yes
  notified marker left absent: yes

-- the operator (or the armed poll) re-runs; the retry completes the record --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/67
    WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
    This is a supervision warning only; the guarded operation WILL still run.
    WARNING: queued wakes pending - drain them with bin/fm-wake-drain.sh before anything else.
    This is a supervision warning only; the guarded operation WILL still run.
    observed: merged https://github.com/example/repo/pull/67; recording the landed outcome
    warning: PR merge succeeded: https://github.com/example/repo/pull/67; the cached PR state could not be refreshed: fm-pr-status: gh exited 0 for example/repo#67 but returned non-JSON output; the forge CLI likely ignored an unknown flag (the gh-axi wrapper ignores --json). Refresh left the previous observation in place.
  exit status: 0
  notified marker now committed: yes

-- a secondmate home that landed the merge but has no parent binding to report to --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/65
    observed: merged https://github.com/example/repo/pull/65; recording the landed outcome
    actionable: merged https://github.com/example/repo/pull/65 but could not report it upward: this home has no readable secondmate identity or parent binding (.fm-secondmate-home, .fm-secondmate-parent)
    warning: PR merge succeeded: https://github.com/example/repo/pull/65; the cached PR state could not be refreshed: fm-pr-status: gh exited 0 for example/repo#65 but returned non-JSON output; the forge CLI likely ignored an unknown flag (the gh-axi wrapper ignores --json). Refresh left the previous observation in place.
  exit status: 0

-- for contrast, a merge that genuinely did NOT land --
$ fm-pr-merge.sh task-x1 https://github.com/example/repo/pull/12
    error: GitHub rejected the merge
    error: refusing to treat https://github.com/example/repo/pull/12 as merged because the GitHub merge command exited with status 1 and GitHub still reports state OPEN with no queue entry and no auto-merge: GitHub rejected the merge rather than deferring it; the merge poll remains armed
  exit status: 1

  landed outcome recorded: no

================================================================
demo complete
Evidence: Evidence driver (20 real fm-pr-merge.sh invocations against the suite forge fixtures)
#!/usr/bin/env bash
# Operator-level demonstration of the four guarded-merge fixes in
# bin/fm-pr-merge.sh, driven through the real entrypoint with the suite's
# forge fixtures. Every block below is a real invocation: the exit code,
# stderr and the forge command log are captured verbatim.
set -u
cd "$(dirname "${BASH_SOURCE[0]}")"
# shellcheck source=/dev/null
. ./_helpers.sh

hr() { printf '\n================================================================\n'; }
printf 'Guarded merge - operator transcript, bin/fm-pr-merge.sh\n'
printf 'Every block below is a real invocation of the real entrypoint against the\n'
printf 'suite forge fixtures. Lines beginning with the supervision bullet are\n'
printf 'elided: the fixture home has an in-flight task and no watcher, so the\n'
printf 'unrelated "WATCHER DOWN" banner prints on every run.\n'
scene() { hr; printf '### %s\n\n' "$1"; }
show() { # <case_dir> <rc> <label>
  local case_dir=$1 rc=$2
  printf '$ fm-pr-merge.sh task-x1 %s\n' "$3"
  grep -v '^●' "$case_dir/stderr" | sed 's/^/    /'
  printf '  exit status: %s\n' "$rc"
}
forge_log() { # <case_dir> <file> <label>
  printf '\n  %s:\n' "$3"
  # One line per invocation: the GraphQL PR-state query is a multi-line
  # argument, so only each entry's first line is a command start.
  if [ -s "$case_dir/$2" ]; then
    grep -E '^(pr |api |issue |GITLAB_HOST=)' "$case_dir/$2" \
      | cut -c1-210 | sed -e 's/^/    /'
  else
    printf '    (empty - no forge command was issued)\n'
  fi
}

######################################################################
scene 'FIX 1 - MERGE-TARGET CONTRACT: a PR whose real target is not the current default branch is refused, by name, before any other rejection path'

for provider in github gitlab; do
  case $provider in
    github)
      case_dir=$(make_case demo-non-default-target-github)
      add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
      : >"$case_dir/glab.log"
      url=https://github.com/example/repo/pull/89
      # A merge queue is ALSO enabled here: the target refusal must still win.
      FM_TEST_GH_BASE_REF=release FM_TEST_GH_QUEUE_ENABLED=true \
        run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr"
      ;;
    gitlab)
      case_dir=$(make_gitlab_case demo-non-default-target-gitlab target=release)
      url=$MR_URL
      run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr"
      ;;
  esac
  rc=$?
  printf -- '-- %s --\n' "$provider"
  show "$case_dir" "$rc" "$url"
  forge_log "$case_dir" gh.log 'gh command log'
  forge_log "$case_dir" glab.log 'glab command log'
  printf '\n  durable merge poll still armed: '
  [ -f "$case_dir/state/task-x1.check.sh" ] && echo yes || echo NO
  printf '  merge-queue wording pre-empted the target message: '
  grep -q 'merge queue' "$case_dir/stderr" && echo YES || echo 'no (target contract reported first)'
  printf '\n'
done

######################################################################
scene 'FIX 2 - ALREADY-MERGED RECOVERY: a request already merged (base branch since deleted, so baseRef.target.oid is null) is recognised before open-only validation and reported without a second mutation'

case_dir=$(make_case demo-already-merged-deleted-base)
add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
url=https://github.com/example/repo/pull/91
FM_TEST_GH_PRE_STATE=MERGED FM_TEST_GH_BASE_REF_DELETED=1 \
  FM_TEST_GH_QUEUE_ENABLED=unknown FM_TEST_GH_FAIL_ON_GRAPHQL=2 \
  run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
show "$case_dir" "$rc" "$url"
forge_log "$case_dir" gh.log 'gh command log'
printf '\n  durable outcome recorded in the wake queue:\n'
sed 's/^/    /' "$case_dir/state/.wake-queue"
printf '  a second merge mutation was issued: '
grep -q 'pr merge' "$case_dir/gh.log" && echo YES || echo no
printf '  open-only validation blocked the recovery: '
grep -q 'immediate execution state is unknown' "$case_dir/stderr" && echo YES || echo no

######################################################################
scene 'FIX 3 - HOST-QUALIFIED MUTATION: the GitHub merge call names the host parsed from the URL, so an ambient GH_HOST cannot redirect it to a same-named repository on another forge'

case_dir=$(make_case demo-host-qualified-merge)
add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
url=https://github.com/example/repo/pull/42
GH_HOST=evil.example.com \
  run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
printf '  ambient environment for this run: GH_HOST=evil.example.com\n'
show "$case_dir" "$rc" "$url"
forge_log "$case_dir" gh.log 'gh command log (note the host-qualified --repo / --hostname)'

######################################################################
scene 'FIX 4a - IMMEDIATE-EXECUTION GUARANTEE: a merge queue defers execution, and an unreadable immediacy state is treated as refusal-grade because unknown is not absent'

for name in merge-queue unknown; do
  case_dir=$(make_case "demo-github-immediate-$name")
  add_gh_mocks "$case_dir" 9898989898989898989898989898989898989898
  : >"$case_dir/gh-axi.log"
  url=https://github.com/example/repo/pull/74
  case $name in
    merge-queue) FM_TEST_GH_QUEUE_ENABLED=true run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr" ;;
    unknown)     FM_TEST_GH_STATE_UNAVAILABLE=1 run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr" ;;
  esac
  rc=$?
  printf -- '-- %s --\n' "$name"
  show "$case_dir" "$rc" "$url"
  forge_log "$case_dir" gh.log 'gh command log'
  printf '\n'
done

######################################################################
scene 'FIX 4b - FINAL PREFLIGHT: the default tip is re-read immediately before the merge call, and a tip that moved since the inspected snapshot refuses on both forges'

for provider in github gitlab; do
  case $provider in
    github)
      case_dir=$(make_case demo-default-tip-move-github)
      add_gh_mocks "$case_dir" 9797979797979797979797979797979797979797
      : >"$case_dir/gh-axi.log"
      url=https://github.com/example/repo/pull/79
      ;;
    gitlab)
      case_dir=$(make_gitlab_case demo-default-tip-move-gitlab)
      url=$MR_URL
      ;;
  esac
  old_tip=$(git --git-dir="$case_dir/origin.git" rev-parse refs/heads/main)
  new_tip=$(prepare_advanced_default "$case_dir")
  FM_TEST_ADVANCE_DEFAULT_ON_LS_REMOTE=2 FM_TEST_ADVANCED_BASE=$new_tip \
    run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr"
  rc=$?
  printf -- '-- %s (main advanced from %s to %s inside the merge window) --\n' \
    "$provider" "${old_tip:0:12}" "${new_tip:0:12}"
  show "$case_dir" "$rc" "$url"
  forge_log "$case_dir" gh.log 'gh command log'
  forge_log "$case_dir" glab.log 'glab command log'
  printf '\n'
done

######################################################################
scene 'FIX 4c - POST-MERGE READBACK: a queued or pending forge result after the merge call is refusal-grade and leaves the durable poll armed'

case_dir=$(make_case demo-queued-github-post-merge)
add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
url=https://github.com/example/repo/pull/77
FM_TEST_GH_POST_STATE=OPEN FM_TEST_GH_POST_IN_QUEUE=true FM_TEST_GH_POST_QUEUE_ENTRY=QUEUED \
  run_pr_merge "$case_dir" task-x1 "$url" >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
show "$case_dir" "$rc" "$url"
printf '\n  durable merge poll still armed: '
[ -f "$case_dir/state/task-x1.check.sh" ] && echo yes || echo NO
printf '  landed outcome wrongly recorded: '
[ -s "$case_dir/state/.wake-queue" ] && echo YES || echo no

######################################################################
scene 'FIX 4d - MERGE ARGUMENT ALLOW-LIST: method selectors, message inputs and post-execution branch cleanup are forwarded; anything that could defer execution is refused before anything is recorded'

case_dir=$(make_case demo-allowlisted-args)
add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
url=https://github.com/example/repo/pull/55
run_pr_merge "$case_dir" task-x1 "$url" -- --squash --subject 'ship it' --delete-branch \
  >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
printf -- '-- allowed: --squash --subject "ship it" --delete-branch --\n'
show "$case_dir" "$rc" "$url -- --squash --subject 'ship it' --delete-branch"
forge_log "$case_dir" gh.log 'gh command log'

for arg in --auto --admin; do
  case_dir=$(make_case "demo-refused-arg-${arg#--}")
  add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
  run_pr_merge "$case_dir" task-x1 "$url" -- "$arg" >"$case_dir/stdout" 2>"$case_dir/stderr"
  rc=$?
  printf -- '\n-- refused: %s --\n' "$arg"
  show "$case_dir" "$rc" "$url -- $arg"
  printf '  pr= recorded into task meta before the refusal: '
  grep -q '^pr=' "$case_dir/state/task-x1.meta" && echo YES || echo no
done

# --rebase is a GitHub merge-METHOD selector, but on GitLab it rewrites the
# source branch before merging and leaves it rewritten even when the SHA-bound
# merge then fails. Same spelling, opposite verdict, per forge.
case_dir=$(make_case demo-github-rebase-method)
add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
url=https://github.com/example/repo/pull/56
run_pr_merge "$case_dir" task-x1 "$url" -- --rebase >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
printf -- '\n-- allowed on GitHub: --rebase, which is a merge-method selector there --\n'
show "$case_dir" "$rc" "$url -- --rebase"
forge_log "$case_dir" gh.log 'gh command log'

for arg in --rebase -r; do
  case_dir=$(make_gitlab_case "demo-refused-gitlab-rebase-${arg#-}")
  run_pr_merge "$case_dir" task-x1 "$MR_URL" -- "$arg" >"$case_dir/stdout" 2>"$case_dir/stderr"
  rc=$?
  printf -- '\n-- refused on GitLab: %s, which rewrites the branch before a SHA-bound merge --\n' "$arg"
  show "$case_dir" "$rc" "$MR_URL -- $arg"
  forge_log "$case_dir" glab.log 'glab command log'
done

######################################################################
scene 'FIX 4e - GITLAB AUTOMATIC REBASE, BOUNDED TO THE REAL RISK WINDOW (automatic rebase shipped in 19.2; the automatic_rebase_enabled field only appears in 19.4)'

demo_gitlab_rebase() { # <name> <project.json> <version.json> <behind?> <caption>
  local name=$1 project=$2 version=$3 behind=$4 caption=$5 case_dir rc
  case_dir=$(make_gitlab_case "demo-auto-rebase-$name")
  printf '%s\n' "$project" >"$case_dir/project.json"
  printf '%s\n' "$version" >"$case_dir/version.json"
  [ "$behind" != behind ] || advance_default_with_empty_commit "$case_dir"
  run_pr_merge "$case_dir" task-x1 "$MR_URL" >"$case_dir/stdout" 2>"$case_dir/stderr"
  rc=$?
  printf -- '\n-- %s --\n' "$caption"
  printf '   project settings: %s   instance version: %s   source branch: %s\n' \
    "$project" "$version" "$([ "$behind" = behind ] && echo 'behind the target' || echo 'up to date')"
  show "$case_dir" "$rc" "$MR_URL"
  forge_log "$case_dir" glab.log 'glab command log'
}
demo_gitlab_rebase refuse-ff-behind '{"automatic_rebase_enabled":true,"merge_method":"ff"}' '{"version":"19.4.0"}' behind \
  'REFUSE: automatic rebase enabled, ff method, branch behind'
demo_gitlab_rebase permit-merge-behind '{"automatic_rebase_enabled":true,"merge_method":"merge"}' '{"version":"19.4.0"}' behind \
  'PERMIT: merge method cannot rebase, so the branch being behind is harmless'
demo_gitlab_rebase refuse-pre194-rebase '{"merge_method":"rebase_merge"}' '{"version":"19.3.2-ee"}' behind \
  'REFUSE: pre-19.4 instance cannot expose the field, rebase_merge method, branch behind'
demo_gitlab_rebase permit-absent-merge '{"merge_method":"merge"}' '{"version":"19.4.0"}' current \
  'PERMIT: field absent and merge method is merge'
demo_gitlab_rebase refuse-unreadable '{}' '{"version":"19.4.0"}' current \
  'REFUSE: 19.4+ instance where the setting cannot be read - unknown is not absent'

######################################################################
scene 'OUTCOME CONTRACT - a merge that LANDED but whose outcome could not be recorded exits ZERO, loudly, keeps the durable outcome, and leaves the retry poll armed'

printf -- '-- the merge lands, but the notification marker cannot be committed --\n'
case_dir=$(make_home_case demo-uncommitted-marker-retry)
url=https://github.com/example/repo/pull/67
add_gh_mocks "$case_dir" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
: >"$case_dir/gh-axi.log"
cat >"$case_dir/fakebin/mv" <<'SH'
#!/usr/bin/env bash
case "${!#}" in
  *.pr-poll-merge-notified)
    if mkdir "$FM_TEST_MARKER_FAILURE.claim" 2>/dev/null; then exit 1; fi
    ;;
esac
exec "$FM_TEST_REAL_MV" "$@"
SH
chmod +x "$case_dir/fakebin/mv"
export FM_TEST_MARKER_FAILURE="$case_dir/marker-failure"
FM_TEST_REAL_MV=$(command -v mv); export FM_TEST_REAL_MV
FM_TEST_HOME="$case_dir/home" run_pr_merge "$case_dir" task-x1 "$url" \
  >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
show "$case_dir" "$rc" "$url"
printf '\n  durable outcome preserved in the wake queue:\n'
sed 's/^/    /' "$case_dir/state/.wake-queue" 2>/dev/null || echo '    (none)'
printf '  retry poll left armed: '
[ -f "$case_dir/state/task-x1.check.sh" ] && echo yes || echo NO
printf '  notified marker left absent: '
[ -e "$case_dir/state/task-x1.pr-poll-merge-notified" ] && echo NO || echo yes

printf -- '\n-- the operator (or the armed poll) re-runs; the retry completes the record --\n'
FM_TEST_HOME="$case_dir/home" run_pr_merge "$case_dir" task-x1 "$url" \
  >"$case_dir/stdout-2" 2>"$case_dir/stderr-2"
rc=$?
printf '$ fm-pr-merge.sh task-x1 %s\n' "$url"
grep -v '^●' "$case_dir/stderr-2" | sed 's/^/    /'
printf '  exit status: %s\n' "$rc"
unset FM_TEST_MARKER_FAILURE FM_TEST_REAL_MV
printf '  notified marker now committed: '
[ -f "$case_dir/state/task-x1.pr-poll-merge-notified" ] && echo yes || echo NO

printf -- '\n-- a secondmate home that landed the merge but has no parent binding to report to --\n'
case_dir=$(make_home_case demo-unbound-secondmate)
url=https://github.com/example/repo/pull/65
add_gh_mocks "$case_dir" 8888888888888888888888888888888888888888
: >"$case_dir/gh-axi.log"
printf '%s\n' mate-x >"$case_dir/home/.fm-secondmate-home"
FM_TEST_HOME="$case_dir/home" run_pr_merge "$case_dir" task-x1 "$url" \
  >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
show "$case_dir" "$rc" "$url"

printf -- '\n-- for contrast, a merge that genuinely did NOT land --\n'
case_dir=$(make_case demo-merge-really-failed)
add_gh_mocks "$case_dir" "$(git -C "$case_dir/wt" rev-parse HEAD)"
url=https://github.com/example/repo/pull/12
FM_TEST_GH_MERGE_REJECTED=1 run_pr_merge "$case_dir" task-x1 "$url" \
  >"$case_dir/stdout" 2>"$case_dir/stderr"
rc=$?
show "$case_dir" "$rc" "$url"
printf '\n  landed outcome recorded: '
[ -s "$case_dir/state/.wake-queue" ] && echo YES || echo no

hr
printf 'demo complete\n'
Evidence: Operator-facing messages the transcript produced, one per guarded outcome
FIX 1 - merge-target contract (GitHub and GitLab, exit 1, no forge mutation)
error: refusing to merge <url> because GitHub reports actual target branch release, but guarded merging is limited to current default branch main
action: retarget the PR to current default branch main, bring the branch up to current main, and re-run validation

FIX 2 - already-merged recovery, base branch deleted (exit 0, no second mutation)
observed: merged https://github.com/example/repo/pull/91; recording the landed outcome
wake queue: check: merge landed: task-x1 https://github.com/example/repo/pull/91

FIX 3 - host-qualified mutation, run with GH_HOST=evil.example.com ambient
pr merge 42 --repo github.com/example/repo --match-head-commit 6968cd51... --squash

FIX 4 - immediate execution, final preflight, post-merge readback, allow-list (all exit 1)
error: refusing to merge <url> because the GitHub merge queue on target branch main would defer execution
error: refusing to merge <url> because GitHub immediate execution state is unknown, and unknown does not prove deferral is absent
error: refusing to merge <url> because current default branch main moved from inspected tip d3792c7e... to live tip ca11d2be... before merge
error: refusing to treat <url> as merged because GitHub queued it for deferred execution on target branch main; the merge poll remains armed
error: refusing extra merge argument --auto because an unbounded passthrough cannot guarantee immediate execution
error: refusing extra merge argument --rebase because an unbounded passthrough cannot guarantee immediate execution (GitLab only; GitHub forwards --rebase as a method)
error: refusing to merge <mr> because the GitLab project setting automatic_rebase_enabled is enabled and can rebase the source branch at merge time
error: refusing to merge <mr> because this pre-19.4 GitLab instance does not expose automatic_rebase_enabled and the source branch is behind the target, so automatic rebase cannot be ruled out
error: refusing to merge <mr> because the GitLab project setting automatic_rebase_enabled could not be determined, and unknown does not prove automatic rebase is disabled

OUTCOME CONTRACT - landed but unrecorded (exit 0, loud, durable, retry armed)
actionable: merged https://github.com/example/repo/pull/67 and recorded its outcome, but could not commit the notification marker; the merge poll remains armed for retry
retry poll left armed: yes / notified marker left absent: yes / wake-queue entry present
actionable: merged https://github.com/example/repo/pull/65 but could not report it upward: this home has no readable secondmate identity or parent binding

CONTRAST - merge that did NOT land (exit 1, nothing recorded)
error: refusing to treat <url> as merged because the GitHub merge command exited with status 1 and GitHub still reports state OPEN with no queue entry and no auto-merge: GitHub rejected the merge rather than deferring it; the merge poll remains armed
  • Evidence: tests/fm-pr-merge.test.sh output (local file: /home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-pr-merge.test.log)
  • Evidence: tests/fm-pr-check-security.test.sh output (local file: /home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-pr-check-security.test.log)
  • Evidence: tests/fm-issue-writeback.test.sh output (local file: /home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-issue-writeback.test.log)
  • Evidence: tests/fm-watcher-lock.test.sh output (local file: /home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/fm-watcher-lock.test.log)
Evidence: tests/fm-gotmp.test.sh output
ok - fm-teardown removes the dir pointed to by tasktmp= in meta
ok - fm-teardown skips gracefully when tasktmp= is absent (backward compat)
ok - fm-teardown skips gracefully when tasktmp= points to a nonexistent dir

all fm-gotmp tests passed

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • 🚨 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 then exit 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 absent automatic_rebase_enabled field when merge_method is merge. This path refuses first if the GitLab version is unavailable or unreadable and does not inspect merge_method until line 674. A project response containing {&#34;merge_method&#34;:&#34;merge&#34;} 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 initial opened response, 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 after gitlab_verify_mergeable reports opened and gitlab_require_attested_merge succeeds, this break retains 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 under set -e and set merge_mutation_accepted only 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 &lt;sha&gt; fails because the head moved inside the residual window; merge_command_rc=1, github_confirm_merged reads state OPEN with in_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_merged line 916 has the identical hole ("GitLab left it queued or pending"). The fix round added a command_rc-aware message to the unreadable branch of both functions but not to the confirmed-not-landed branch, even though command_rc is 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-attestation gitlab_verify_mergeable re-read now runs unconditionally with stderr unsuppressed (it previously ran only on attestation failure, under 2&gt;/dev/null). Every healthy GitLab merge therefore makes two full GraphQL reads and prints verified: &lt;url&gt; is open and mergeable, with a successful pipeline at head &lt;sha&gt; twice, plus a duplicated notice: recorded head ... disagrees with the live head when a stale pr_head= is recorded. The re-read itself is correct and needed for the merged-transition recovery; only the duplicated success notice is noise. Emit the verified: 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-zero gh pr merge / glab mr merge followed 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 in gitlab_require_attested_merge: the second merge_method read (696-698) and [ &#34;$merge_method&#34; = merge ] &amp;&amp; return 0 (699) are unreachable as merge. Control only reaches line 696 when automatic_rebase is "absent" (the true branch at 625-647 always returns) AND the case at 613 already returned 0 for merge and refused every value except rebase_merge|ff. Re-parsing the same $json with the same filter therefore always yields rebase_merge or ff, so line 699's test is always false. The || merge_method= fallback is also unreachable because that jq has an else &#34;&#34; branch and cannot error. Concrete trace: project.json {&#34;merge_method&#34;:&#34;rebase_merge&#34;} on GitLab 19.3 -> automatic_rebase=absent -> case at 613 falls through -> version gate passes (19.3 < 19.4) -> line 696 re-reads rebase_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 including test_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_success
  • bash tests/fm-pr-check-security.test.sh - includes the merge-outcome-uncommitted: landed merge was reported as failed assertion the branch decisions pin
  • bash tests/fm-issue-writeback.test.sh
  • bash tests/fm-watcher-lock.test.sh
  • bash tests/fm-gotmp.test.sh - includes the teardown exited non-zero with a valid tasktmp case from an earlier CI round
  • Manual end-to-end: bash /home/sungin/.no-mistakes/evidence/01M1J1735SQ1FD13JE6PF1N8EQ/guarded-merge-demo.sh - 20 real invocations of bin/fm-pr-merge.sh against 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 scenario
  • Manual check: GitHub merge issued as pr merge 42 --repo github.com/example/repo --match-head-commit &lt;sha&gt; --squash while GH_HOST=evil.example.com was set in the environment
  • Manual check: --rebase accepted as a GitHub merge-method selector but refused on GitLab, together with -r, before any glab call
  • Manual check: GitLab automatic-rebase decision across five settings/version/ancestry combinations spanning the 19.4 automatic_rebase_enabled field boundary
  • Manual check: landed-but-unrecorded outcome exits 0, preserves the wake-queue entry, leaves task-x1.pr-poll-merge-notified absent and task-x1.check.sh armed, and the re-run commits the marker; a forge-rejected merge exits 1 and records no landed outcome
⚠️ **Document** - 1 info
  • ℹ️ docs/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.

fm-brief-repo-detection-prose 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
HelloWorldSungin force-pushed the fm/fm-stale-base-check-before-merge branch from a25c2ed to acc6792 Compare September 2, 2026 23:16
@HelloWorldSungin HelloWorldSungin changed the title fix(bin): harden guarded merge execution fix(bin): harden guarded merge execution in fm-pr-merge Sep 2, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant