Skip to content

Merge stage: gate-check, auto-rebase, CI-fix & review-revision

The merge stage monitors open PRs and handles several scenarios: gate-checking new PRs before notifying humans, auto-rebasing conflicting PRs, auto-fixing failing CI, and autonomously addressing human reviewer change requests.

Gate-check: IMPLEMENT_COMPLETE → HUMAN_MR_APPROVAL

After the deliver stage creates a PR, the ticket enters IMPLEMENT_COMPLETE instead of HUMAN_MR_APPROVAL. The merge stage polls this new state and verifies two gates before promoting the ticket:

  1. CI is green — the PR's CI checks must all pass.
  2. PR is mergeable — no conflicts with the target branch.

When both gates pass, the ticket transitions to HUMAN_MR_APPROVAL (triggering an ntfy notification to the human). If either gate fails:

  • Failing CI → FIXING_CI (auto-fix agent runs next poll).
  • Conflicting PR → REBASING (rebase agent runs next poll).
  • After auto-fix, the ticket returns to IMPLEMENT_COMPLETE so both gates are re-verified before another human notification.

This means humans are only notified when the PR is actually ready for review and merge — no premature noise for PRs with failing CI or conflicts.

Green but blocked by a renamed required context

A PR can be fully green yet mergeable_state='blocked' when branch protection on the target branch requires a check context the PR no longer reports — typically an inline job that was renamed or moved into a shared reusable workflow (e.g. CodeQL → CodeQL / Analyze). The stage diffs the target branch's required checks (classic protection required_status_checks and rulesets) against the head's check-runs, matching by name and app. A same-named check-run from a different app does not satisfy a context pinned to another app (e.g. a CodeQL run from github-advanced-security does not satisfy a CodeQL context pinned to github-actions).

When a required context is unsatisfied, the ticket parks BLOCKED with a note starting repo setting required: that names each missing context, its pinned app, and the closest run name to switch protection to, e.g. required context 'CodeQL' (app 15368) is not reported by any check-run on <sha>; the PR renames/removes it — update branch protection to 'CodeQL / Analyze'. The operator updates branch protection; agents cannot edit it. If the head's check-runs cannot be listed, the diff falls back to job names (app unknown).

Operator-initiated re-implement from HUMAN_MR_APPROVAL

While reviewing a PR in HUMAN_MR_APPROVAL, an operator who wants code changes without closing and reopening the PR can send the ticket back to the implement stage via the board's Re‑implement button (or the POST /tickets/{id}/request-implementation-changes API / chat skill). This posts a change-request comment and transitions the ticket from HUMAN_MR_APPROVAL → READY, so the implement agent re-runs against the existing PR branch — picking up the change-request context from the comment — and pushes updated commits to the same PR, which then returns to HUMAN_MR_APPROVAL for re-review once green.

This is distinct from request-changes (the human_issue_approval rework path, which re-refines the spec from a new draft and discards the implementation). Requesting implementation changes keeps the branch, the open PR, and the implemented work; only the code is reworked. The operator's comment body is required (a blank request is rejected) and is recorded as a ticket comment — the channel the implement stage reads operator feedback from. The stale-spec fingerprint guard and the implement spawn counter are cleared, so an operator request is never refused for an unchanged spec or an exhausted retry budget.

Silent fallback from HUMAN_MR_APPROVAL

If a ticket is already in HUMAN_MR_APPROVAL (gates passed) and the merge stage later detects CI failure or a merge conflict, it silently transitions back to IMPLEMENT_COMPLETE. No ntfy notification is fired — the ticket leaves the human-review state and the robot attempts auto-fix. The human is only re-notified when both gates pass again.

Auto-rebase

The rebase agent (agents/rebasing.py) resolves git rebase conflicts using the LLM. It is invoked from two paths:

  1. Implement-stage defensive rebase — before the implement agent runs, try_rebase_onto rebases the ticket branch onto the latest remote target. If that rebase fails (conflict), the ticket transitions to REBASING instead of blocking.

  2. Stale-PR conflict — when a PR sits in IMPLEMENT_COMPLETE or HUMAN_MR_APPROVAL while other PRs merge onto the target branch, it may become stale and develop merge conflicts. The forge's mergeable flag drives this detection.

In both paths, once the rebase agent runs:

  • On success the ticket branch is force-pushed and the ticket returns to IMPLEMENT_COMPLETE for gate re-verification.
  • If no PR exists yet (implement-stage path), the ticket routes to READY and re-enters the implement stage on the next worker tick.
  • On failure (after exhausting retries) the ticket escalates to BLOCKED (resumable) — no half-rebased state is ever pushed.
Variable Default Description
MILL_REBASE_MAX_ATTEMPTS 5 Max rebase attempts per ticket before escalating to BLOCKED. Each attempt is one LLM invocation.

The rebase agent uses the same sandboxed shell + file tools as the implement agent, scoped to the ticket's clone. It never pushes, opens PRs, or interacts with the forge.

Multi-repo conflict handling

A multi-repo ticket may have conflicts on individual repos while others remain mergeable. The merge stage handles this by running the rebase agent inline during the polling loop, one conflicting repo per poll (bounded by a per-repo attempt counter).

Unlike the single-repo path (which uses the REBASING state), a multi-repo ticket has a single state (IMPLEMENT_COMPLETE), so conflict recovery must run inline:

  • When one or more repos report mergeable: False, the merge stage invokes the rebase agent on the first conflicting repo's workspace clone.
  • On success the rebased branch is force-pushed to that repo's remote, and the ticket remains in IMPLEMENT_COMPLETE to re-poll.
  • The remaining conflicting repos are picked up on the next poll (one at a time, so agents can stabilize the repo between attempts).
  • On failure after exhausting retries (per-repo attempt counter) the ticket escalates to BLOCKED (resumable).

This mirrors the single-repo path but runs synchronously during the poll cycle rather than as a deferred state machine. The rebase attempt counter is tracked per-repo (e.g., rebase_repo-b.count) so each repo gets a fresh budget if it later becomes conflicting again.

Auto-fix of failing remote CI

When a PR has failing remote CI checks (GitHub Actions), the merge stage transitions the ticket to FIXING_CI and invokes a ci-fix agent (agents/ci_fixing.py) that analyses the failing check-run output and applies minimal fixes.

  • The forge adapter fetches check-run status (and falls back to the combined commit-statuses API for older repos).
  • If a PR has failing CI, the merge stage transitions to FIXING_CI (from either IMPLEMENT_COMPLETE or HUMAN_MR_APPROVAL).
  • The CI-fix stage invokes run_ci_fix_agent on the ticket's workspace clone, passing it a summary of the failing checks and file-level annotations.
  • On success the ticket branch is force-pushed (the ticket goes back to IMPLEMENT_COMPLETE for the next poll to re-verify both gates).
  • On failure the ticket escalates to BLOCKED (resumable) — no half-fixed state is ever pushed.
  • Repository-setting gate. When a failing check is refused because a GitHub repository setting is off (Dependency graph for dependency-review, or code scanning / Advanced Security for upload-sarif), the stage skips the ci-fix agent entirely. The ticket parks BLOCKED with a note starting repo setting required: that names the setting and links https://github.com/<owner>/<repo>/settings/security_analysis. The block is not auto-resumable. The operator is escalated once per (repo, setting). After enabling the setting, resume the ticket (/transition ready) to re-enter FIXING_CI and re-poll CI.
Variable Default Description
MILL_CI_FIX_MAX_ATTEMPTS 2 Max CI-fix attempts per ticket before escalating to BLOCKED. Each attempt is one LLM invocation.

The ci-fix agent uses the same sandboxed shell + file tools as the implement agent, scoped to the ticket's clone. It never pushes, opens PRs, or interacts with the forge. The agent does NOT have web-search access — it works only from the failing summary and local files.

Deterministic dependency-audit remediation

When the failing check is a uv audit / pip-audit CVE gate (log lines of the form <pkg> <version> … GHSA-… / PYSEC-…, or Found N known vulnerabilities), the stage remediates it before any ci-fix agent turn, with no LLM call:

  • Runs uv lock --upgrade-package <pkg> for each flagged package, then uv lock --check and uv sync --frozen --group dev.
  • Commits the lockfile with the note CI Security Audit failed on <advisories> in transitive dep(s) <pkgs>; remediated via uv lock --upgrade-package; no source changes. and pushes the ticket branch. No doc agent runs.
  • The ticket is returned to IMPLEMENT_COMPLETE only when the audit gate was the sole failing step. If another check is still failing, the bump is pushed, the history note says so, and the remaining failure goes to the ci-fix agent. A dependency bump never closes a ticket whose other failing step is still open.
  • If the upgrade fails or changes nothing, the tree is reset and the normal agent path runs.

Failing-job log excerpts in the CI-monitor ticket body are narrowed to the failing step (the step's conclusion: failure time range), and the body names that step, with a link to the job, so the cause is visible without opening the run.

Stale-branch refresh (out-of-scope failures)

When the ci-fix agent classifies a failure as out-of-scope (i.e., the failing check cannot be fixed by changes in this ticket's diff), the stage first checks whether the PR branch is behind its base. If the branch is stale, a fix that landed on the target branch while the ci-fix agent was running may have already resolved the failure. In this case, the stage calls the forge's update_branch API to merge the target branch into the PR branch server-side, records a history note, and returns to IMPLEMENT_COMPLETE to re-poll CI.

This stale-branch refresh happens at most once per out-of-scope cycle (tracked by an internal counter). If the failure still exists after a refresh, the stage proceeds to spawn a dedicated dependency-fix ticket as before.

  • The refresh is deterministic and non-fatal — it never blocks forward progress and gracefully falls back to the normal out-of-scope spawn if the API call fails.
  • This optimization reduces spurious dependency-fix tickets on fast-moving target branches where fixes land frequently.

Transient CI failure auto-retry

Before spawning a ci_fix_dependency fix ticket, the ci-fix stage classifies the failure as transient (an infrastructure flake) vs deterministic (a real lint/test/type error). Transient failures — network resets (ECONNRESET/ECONNREFUSED), buildx "booting buildkit" timeouts, astral-sh/setup-uv fetch failures, runner shutdown / lost communication, HTTP 5xx / API rate limits, package-manager network unreachability, lychee link-checker network errors / timeouts — are not code-fixable, so instead of spawning a blocking fix ticket the stage automatically re-runs the failing workflow runs via the forge's rerun_workflow primitive, records a history note, and returns to IMPLEMENT_COMPLETE to re-poll CI.

  • Classification is performed by a signature-pattern matcher (stages/ci_transient.py) against the full failing summary.
  • Retries are bounded by ci_transient_max_retries (default 3, set to 0 to disable) and tracked across pipeline passes via a persistent per-ticket counter.
  • Once the retry budget is exhausted, the failure escalates to a deterministic ci_fix_dependency fix ticket as before.
  • Only the failed workflow runs for the current head SHA are re-queued; the operation is best-effort and never raises.

Lychee link-checker: The lychee pre-commit hook may report network errors or timeouts when checking external URLs — these are self-clearing upstream outages and are automatically classified as transient. However, a concrete HTTP 4xx status (e.g., [404] for a moved link, [403] for access denied) indicates a broken link and is classified as deterministic. When lychee fails transient and retries are exhausted, the spawned dependency-fix ticket includes specific guidance to add the failing URL(s) to the lychee exclude list (e.g., exclude entries in lychee.toml or .pre-commit-config.yaml hook args).

This prevents transient infra flakes from being converted into deterministic fix tickets that block, and de-duplicates identical flakes that would otherwise spawn duplicate dependency-fix tickets.

Auto-fix of review feedback (opt-in)

When MILL_REVIEW_FEEDBACK_ENABLED=true and a human reviewer submits a "request changes" review on the PR, the merge stage detects the CHANGES_REQUESTED state and transitions the ticket to ADDRESSING_REVIEW. On the next poll, it invokes a review-revision agent (agents/review_revision.py) that reads the review comments, makes the requested code changes, runs local tests, and commits.

  • The forge adapter queries the PR's review status via pr_review_status(). Only GitHub is supported — GitLab always returns PENDING, so the feedback loop never triggers.
  • If the review has body text or line comments, the comments are persisted as review_feedback.json in the ticket's artifacts directory so the agent can read them even if the forge becomes unreachable on the next poll.
  • The review-revision agent is invoked on the ticket's workspace clone with the formatted comments and changed file list.
  • On success the ticket branch is force-pushed (the ticket goes back to HUMAN_MR_APPROVAL for human re-review).
  • On failure with retries remaining the ticket stays in ADDRESSING_REVIEW for the next poll.
  • On failure after exhausting retries the ticket escalates to BLOCKED (resumable) — no half-fixed state is ever pushed.
  • If the review has an empty body and no line comments, it is treated as a no-op and the ticket stays in HUMAN_MR_APPROVAL.
Variable Default Description
MILL_REVIEW_FEEDBACK_ENABLED false Enable autonomous review-revision agent (opt-in).
MILL_REVIEW_REVISION_MAX_ATTEMPTS 2 Max review-revision LLM invocations per ticket before escalating to BLOCKED.
MILL_REVIEW_REVISION_MODEL (level 2) Model for the review-revision agent.

The review-revision agent uses the same sandboxed shell + file tools as the implement agent, scoped to the ticket's clone. It never pushes, opens PRs, or interacts with the forge. The agent does NOT have web-search access — it works only from the review comments and local files. The agent's system prompt explicitly forbids gate weakening (removing test assertions, lint rules, or security checks).

State flow summary

DELIVERABLE
    │ (deliver stage opens PR)
    ▼
IMPLEMENT_COMPLETE  ←────────────────────────────────┐
    │ (merge stage polls gates)                       │
    ├── CI green + mergeable → HUMAN_MR_APPROVAL      │
    ├── CI failing            → FIXING_CI ────────────┤
    ├── conflicting           → REBASING ─────────────┤
    └── CI pending            → IMPLEMENT_COMPLETE (wait)
                                                        │
HUMAN_MR_APPROVAL                                      │
    │ (merge stage re-polls)                           │
    ├── merged               → DONE                    │
    ├── closed unmerged      → BLOCKED                │
    ├── CI failing           → IMPLEMENT_COMPLETE ─────┘
    ├── conflicting          → IMPLEMENT_COMPLETE ─────┘
    ├── changes requested    → ADDRESSING_REVIEW ──────┐
    ├── operator Re‑implement (request-implementation-changes)
    │                         → READY ─────────────────┤
    ├── CI green + eligible  → DONE (auto-merge)       │
    ├── CI pending + eligible → WAITING_AUTO_MERGE     │
    └── CI green + not eligible → HUMAN_MR_APPROVAL (wait)
                                                       │
ADDRESSING_REVIEW                                      │
    │ (merge stage runs review-revision agent)         │
    ├── agent success        → HUMAN_MR_APPROVAL ──────┘
    ├── agent retry          → ADDRESSING_REVIEW
    └── agent exhausted      → BLOCKED

READY
    │ (implement agent re-runs against the existing PR branch;
    │  reads the change-request comment, pushes updated commits)
    │ → DELIVERABLE → IMPLEMENT_COMPLETE → HUMAN_MR_APPROVAL (re-review)

See also