> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wit.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Merge Queue

> Intelligent merge queue with conflict prediction and automated batching

The merge queue provides controlled, safe merging of pull requests with intelligent conflict prediction, automated testing, priority handling, and batch optimization.

## Overview

The merge queue:

* **Prevents merge conflicts** by analyzing PRs and determining optimal merge order
* **Tests PRs before merging** to prevent broken builds
* **Batches multiple PRs** for efficient CI usage with automatic bisection on failure
* **Handles priority ordering** with customizable priorities (0-100)
* **Auto-rebases PRs** to stay up-to-date with the target branch
* **Provides detailed status** and statistics

## How It Prevents Conflicts

The merge queue uses an intelligent algorithm to prevent merge conflicts:

### 1. PR Analysis

When a PR is added to the queue, the system analyzes:

```
Files Changed:      src/api/users.ts, src/db/schema.ts
Directories:        src/api, src/db, src
Conflict-Prone:     src/db/schema.ts (schema file)
Change Size:        +150 / -30 lines
```

**Conflict-prone areas** are automatically identified:

* Lock files (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`)
* Generated files (`*.generated.ts`)
* Schema and migration files
* High-churn files (100+ lines changed)

### 2. Conflict Prediction

Before processing, the queue predicts conflicts between all PR pairs:

```
PR #1 vs PR #2:
  - Direct file overlap: src/api/users.ts → +20 conflict score
  - Same directory: src/api → +2 conflict score
  - Both touch schema file → +30 conflict score
  - Conflict probability: 52%
```

### 3. Optimal Ordering

The queue uses a greedy algorithm to determine the safest merge order:

```
Queue: [PR #1, PR #2, PR #3, PR #4]

Conflict Matrix:
       #1    #2    #3    #4
  #1   -    0.52  0.10  0.05
  #2  0.52   -    0.30  0.15
  #3  0.10  0.30   -    0.80
  #4  0.05  0.15  0.80   -

Optimal Order: [#4, #1, #2, #3]
  - #4 first: lowest total conflict risk
  - #1 next: conflicts mainly with #2 (not yet merged)
  - #2 next: can now resolve against #4 and #1
  - #3 last: high conflict with #4, but #4 already merged
```

### 4. Speculative Merging

The queue performs merges in an isolated worktree:

1. Create temporary branch from target
2. Cherry-pick commits in optimal order
3. If conflict occurs, try reordering or fall back to merge commit
4. Push speculative merge for CI testing
5. Only update target branch if CI passes

### 5. Batch Processing with Bisection

When batching multiple PRs, if one fails:

```
Batch: [#1, #2, #3, #4, #5] → FAILED

Bisect:
  [#1, #2] → SUCCESS
  [#3, #4, #5]
    [#3] → FAILED (identified!)
    [#4, #5] → SUCCESS

Result: #1, #2, #4, #5 merged; #3 needs fixes
```

## Quick Start

```bash theme={null}
# Add current PR to merge queue
wit merge-queue add

# Add specific PR with priority
wit merge-queue add 123 --priority 50

# Check queue status
wit merge-queue status

# List all queued PRs
wit merge-queue list
```

## Commands

### Add to Queue

```bash theme={null}
# Add current branch's PR
wit merge-queue add

# Add specific PR
wit merge-queue add 123

# Add with priority (0-100, higher = more urgent)
wit merge-queue add 123 --priority 50
```

### Remove from Queue

```bash theme={null}
# Remove current branch's PR
wit merge-queue remove

# Remove specific PR
wit merge-queue remove 123
```

### Check Status

```bash theme={null}
$ wit merge-queue status

Merge Queue Status for PR #123

  Position: 3 of 5
  State: pending
  Estimated wait: ~15 minutes
  Conflict score: 23 (low)
```

### List Queue

```bash theme={null}
$ wit merge-queue list

Merge Queue for myrepo:main

  #  PR       State        Priority  Conflict  Title
  ─────────────────────────────────────────────────────
  1  #125     ready        80        12        Implement caching
  2  #123     testing      50        45        Add authentication
  3  #127     pending      50        23        Fix database issue
  4  #128     pending      20        67        Update dependencies
```

### Queue Statistics

```bash theme={null}
$ wit merge-queue stats

Merge Queue Statistics for myrepo:main

  Pending:           3
  Processing:        1
  Merged today:      12
  Failed today:      2
  Avg merge time:    8 minutes
```

### Configuration

View or update merge queue settings:

```bash theme={null}
# View current config
$ wit merge-queue config

Merge Queue Configuration for myrepo:main

  Enabled:           yes
  Strategy:          adaptive
  Auto-merge mode:   auto
  Max batch size:    5
  Min wait (sec):    60
  Auto rebase:       yes
  Delete branches:   yes
  Required checks:   test, build, lint

Update with: wit merge-queue config --strategy <strategy>
```

```bash theme={null}
# Update settings
wit merge-queue config --strategy adaptive
wit merge-queue config --batch-size 3
wit merge-queue config --auto-rebase
wit merge-queue config --no-delete-branch
```

### Enable/Disable

```bash theme={null}
# Enable for main branch
wit merge-queue enable

# Enable for specific branch
wit merge-queue enable --branch production

# Disable
wit merge-queue disable
```

## Queue States

PRs in the queue go through these states:

| State       | Description                           |
| ----------- | ------------------------------------- |
| `pending`   | Waiting in queue for earlier PRs      |
| `preparing` | Building speculative merge commit     |
| `testing`   | CI tests running on speculative merge |
| `ready`     | Tests passed, ready to merge          |
| `merging`   | Currently updating target branch      |
| `completed` | Successfully merged                   |
| `failed`    | Tests failed or merge conflict        |
| `cancelled` | Removed from queue                    |

## Strategies

The merge queue supports different strategies:

### Sequential

Tests and merges one PR at a time. Safest but slowest.

```bash theme={null}
wit merge-queue config --strategy sequential
```

Best for: Critical branches, low-volume repos

### Optimistic

Groups multiple PRs together for testing. Uses bisection on failure.

```bash theme={null}
wit merge-queue config --strategy optimistic --batch-size 5
```

Best for: High-volume repos with good CI

### Adaptive (Recommended)

Analyzes conflicts and determines optimal merge order, then batches.

```bash theme={null}
wit merge-queue config --strategy adaptive
```

Best for: Most use cases - balances safety and speed

## Auto-Merge Modes

Control when the queue processes:

### Auto (Default)

Queue processes automatically when PRs are ready.

```bash theme={null}
wit merge-queue config --auto-merge-mode auto
```

### Manual

Wait for explicit trigger to process.

```bash theme={null}
wit merge-queue config --auto-merge-mode manual

# Then trigger manually
wit merge-queue process
```

### Scheduled

Only process during specific time windows.

```bash theme={null}
wit merge-queue config --auto-merge-mode scheduled \
  --merge-window-start 9 \
  --merge-window-end 17 \
  --merge-window-days 1,2,3,4,5  # Monday-Friday
```

## Priority System

Higher priority PRs are processed first:

```bash theme={null}
# Low priority (default: 50)
wit merge-queue add 123

# High priority (urgent fix)
wit merge-queue add 123 --priority 80

# Critical (hotfix)
wit merge-queue add 123 --priority 100
```

Within the same priority level, conflict analysis determines order.

## Configuration Options

| Option              | Description                                       | Default  |
| ------------------- | ------------------------------------------------- | -------- |
| `--strategy`        | Merge strategy (sequential, optimistic, adaptive) | adaptive |
| `--batch-size`      | Maximum PRs per batch                             | 5        |
| `--min-wait`        | Minimum seconds before processing                 | 60       |
| `--auto-rebase`     | Auto-rebase PRs before testing                    | true     |
| `--delete-branch`   | Delete branch after merge                         | true     |
| `--auto-merge-mode` | When to process (auto, manual, scheduled)         | auto     |
| `--required-checks` | CI checks that must pass                          | none     |

## Web UI Integration

The merge queue is integrated into the PR page:

### From the Action Card

* **Merge Now**: Direct merge to branch (bypasses queue)
* **Add to Queue**: Queue for automated, conflict-free merging
* **Add with Priority**: Queue with high priority (jumps ahead)

### Queue Status

When a PR is in the queue, the action card shows:

* Current position and state
* Progress bar for active states
* Estimated wait time
* Remove from queue option

### Sidebar Card

A compact status indicator shows:

* Queue position
* Processing state
* Link to queue settings

## Workflow Example

### Adding PRs to Queue

```bash theme={null}
# Create and push a PR
wit checkout -c feature/new-feature
# ... make changes ...
wit commit -m "Add new feature"
wit push -u origin feature/new-feature
wit pr create

# Add to merge queue
wit merge-queue add
```

### Monitoring Queue Progress

```bash theme={null}
# Check your PR's position
wit merge-queue status

# Watch the full queue
wit merge-queue list

# Check if there are any issues
wit merge-queue stats
```

### Handling Failures

If your PR fails in the queue:

```bash theme={null}
# Check what happened
$ wit merge-queue status 123

PR #123 failed in merge queue
  Reason: Merge conflict in src/api/users.ts
  
Fix the issue and re-add:
  wit merge-queue add 123

# Fix the conflict
wit checkout feature/my-branch
git fetch origin main
git rebase origin/main
# ... resolve conflicts ...
wit push --force-with-lease
wit merge-queue add
```

## JSON Output

For scripting and automation:

```bash theme={null}
# Queue status as JSON
wit merge-queue status --json

# List as JSON
wit merge-queue list --json

# Stats as JSON
wit merge-queue stats --json
```

## Integration with CI/CD

The merge queue integrates with wit's built-in CI:

```yaml theme={null}
# .wit/workflows/ci.yml
name: CI
on:
  pull_request:
  merge_queue:  # Triggered by merge queue

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm test
      - run: npm run build
```

## Required Checks

Configure which CI checks must pass:

```bash theme={null}
# Set required checks
wit merge-queue config --required-checks "test,build,lint"

# The merge queue will wait for these checks to pass
```

## Best Practices

### For Fast Merges

* Keep PRs small and focused
* Ensure CI is fast and reliable
* Use the adaptive strategy for high-volume repos

### For Safety

* Enable auto-rebase to catch conflicts early
* Require status checks
* Use the sequential strategy for critical branches

### For Teams

* Set clear priority guidelines (80+ for urgent, 50 for normal)
* Monitor queue statistics regularly
* Use scheduled mode to avoid merges during critical periods

## Technical Details

### Conflict Score Calculation

```
Score = 0

For each file in PR1:
  If same file in PR2: Score += 20
  
For each directory in PR1:
  If same directory in PR2: Score += 2
  
For each conflict-prone file in PR1:
  If same file in PR2: Score += 30

Probability = min(1, Score / 100)
```

### Optimal Order Algorithm

1. Build NxN conflict matrix for N PRs
2. Greedy selection: pick PR with lowest sum of conflicts
3. Repeat until all PRs ordered
4. PRs touching unique files go first
5. PRs touching shared files go last (built on stable base)

### Speculative Merge Process

1. Create isolated git worktree from target branch
2. For each PR in optimal order:
   * Try cherry-picking each commit
   * If fails, fall back to merge commit
   * If still fails, report failure
3. Push speculative merge to temp branch
4. Run CI on speculative merge
5. If CI passes, fast-forward target branch

## Requirements

The merge queue requires:

* wit server running (`wit serve`)
* Database connected (PostgreSQL)
* CI/CD configured (optional but recommended)
* Branch protection enabled (recommended)

## Related

* [wit pr](/platform/pull-requests) - Pull request management
* [wit ci](/features/ci-cd) - CI/CD configuration
* [wit protect](/features/branch-protection) - Branch protection
