---
name: "Quality gates run after fast-forward to master instead of before"
---

# Bug 142: Quality gates run after fast-forward to master instead of before

## Description

## Bug

The `merge_agent_work` function in `server/src/agents.rs` runs quality gates AFTER the squash merge has already been fast-forwarded to master. This means broken code lands on master before gates catch it.

### Current Flow (broken)
1. `run_squash_merge()` creates merge-queue branch + temp worktree
2. Squash merge + conflict resolution in temp worktree
3. **Fast-forward master to merge-queue commit** (line 2522)
4. Clean up temp worktree + branch
5. `run_merge_quality_gates()` runs on master (line 1047)
6. If gates fail, broken code is already on master

### Expected Flow
1. `run_squash_merge()` creates merge-queue branch + temp worktree
2. Squash merge + conflict resolution in temp worktree
3. **Run quality gates in the merge-queue worktree BEFORE fast-forward**
4. If gates fail: report failure back to mergemaster with the temp worktree still intact, so mergemaster can attempt fixes there (up to 2 attempts per story 135's prompt)
5. If gates still fail after mergemaster's retry attempts: tear down temp worktree + branch, leave master untouched, report to human
6. If gates pass: fast-forward master, clean up

### Key Files
- `server/src/agents.rs` line 1013: `merge_agent_work()` — orchestrator
- `server/src/agents.rs` line 2367: `run_squash_merge()` — does merge + fast-forward
- `server/src/agents.rs` line 2522: fast-forward step that should happen AFTER gates
- `server/src/agents.rs` line 1047: `run_merge_quality_gates()` — runs too late

### Impact
Broken merges (conflict markers, missing braces) land on master and break all worktrees that pull from it. Mergemaster then has to fix master directly, adding noise commits.

## How to Reproduce

1. Have a feature branch with code that conflicts with master
2. Call merge_agent_work for that story
3. run_squash_merge resolves conflicts (possibly incorrectly)
4. Fast-forwards master to the merge-queue commit BEFORE gates run
5. run_merge_quality_gates runs on master and finds broken code
6. Master is already broken

## Actual Result

Broken code (conflict markers, missing braces) lands on master. Mergemaster then fixes master directly, adding noise commits. All active worktrees pulling from master also break.

## Expected Result

Quality gates should run in the merge-queue worktree BEFORE fast-forwarding master. If gates fail, master should remain untouched.

## Acceptance Criteria

- [ ] Bug is fixed and verified
