Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

ci: land agent PRs through a merge queue and split the train by trust (#436)

Ruben Lütke9d4e9293a2f6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index df44b757e5..bf8bcfe95d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -14,9 +14,9 @@
# * Every PR ran every job (~20 runners, three 45-min macOS jobs on most),
# and pushes to main cancelled each other, so main was never proven.
# -> `detect` classifies the diff into lanes (scripts/ci/classify_changes.py,
-# fail-open); only affected lanes run. Every push to main runs the whole
-# test suite and is never cancelled; the nightly run and manual
-# dispatches run every lane.
+# fail-open); only affected lanes run. Every merge-queue group and every
+# push to main runs the whole test suite and is never cancelled; the
+# nightly run and manual dispatches run every lane.
# * Branch protection listed five job names; renaming a job meant a settings
# change. -> `CI gate` aggregates every job (scripts/ci/required_results.py)
# and is the ONLY required check, for humans and for the merge train.
@@ -24,8 +24,14 @@
# runs them in one job, all of them report, and agents run the same command
# locally.
#
-# Windows: the full sharded suite on main / nightly / dispatch; on a pull
-# request only the tests the diff can reach (scripts/ci/select_tests.py).
+# Merge queue: main requires a merge queue. A pull request's own run is the
+# admission ticket; the `merge_group` run tests the exact tree main will get
+# (the PR on top of main plus every entry ahead of it) with the whole Linux +
+# Windows suite, and only a green `CI gate` there lands it. This is what keeps
+# main green when PRs that pass alone break together.
+#
+# Windows: the full sharded suite on merge groups / main / nightly / dispatch;
+# on a pull request only the tests the diff can reach (scripts/ci/select_tests.py).
# macOS (~10x runner cost): nightly and manual dispatch, plus the path-gated
# realtime contract and macOS desktop lanes.
#
@@ -35,6 +41,8 @@ name: CI
on:
pull_request:
+ merge_group:
+ types: [checks_requested]
push:
branches: [main]
schedule:
@@ -59,9 +67,12 @@ on:
# share one group: GitHub keeps a single PENDING run and drops older pending
# ones, so a burst of agent pushes cannot stack a backlog behind the
# organisation's concurrent-job limit — the newest run covers every commit
-# before it. The nightly run and manual dispatches get their own group.
+# before it. Every merge-queue entry gets its own group and is never
+# cancelled: the queue itself drops entries it no longer needs, and a dropped
+# pending run would leave `CI gate` unreported until the queue times out. The
+# nightly run and manual dispatches get their own group.
concurrency:
- group: ci-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || (github.event_name == 'workflow_dispatch' && github.ref_type == 'branch' && github.ref != 'refs/heads/main' && format('branch-{0}', github.ref)) || (github.event_name == 'push' && 'main-push') || github.run_id }}
+ group: ci-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || (github.event_name == 'merge_group' && format('merge-group-{0}', github.event.merge_group.head_ref)) || (github.event_name == 'workflow_dispatch' && github.ref_type == 'branch' && github.ref != 'refs/heads/main' && format('branch-{0}', github.ref)) || (github.event_name == 'push' && 'main-push') || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && github.ref_type == 'branch' && github.ref != 'refs/heads/main') }}
permissions:
@@ -114,15 +125,17 @@ jobs:
EVENT: ${{ github.event_name }}
IN_FULL: ${{ inputs.full }}
IN_MACOS: ${{ inputs.include_macos }}
- PR_BASE: ${{ github.event.pull_request.base.sha }}
+ PR_BASE: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
run: |
- # A push to main classifies its lanes like a pull request (the
- # concurrent-job limit is shared by every agent's PR), but always
- # runs the WHOLE test suite on Linux and Windows: post-merge proof
- # is never narrowed. Nightly and manual full runs force everything.
+ # A merge-queue group and a push to main classify their lanes like a
+ # pull request (the concurrent-job limit is shared by every agent's
+ # PR), but always run the WHOLE test suite on Linux and Windows: the
+ # proof that lands on main is never narrowed. A merge group's lanes
+ # are classified against the queue base (main or the entry ahead).
+ # Nightly and manual full runs force everything.
full=false; macos=false; pr_mode=false; tests_full=false
case "$EVENT" in
- push) tests_full=true ;;
+ push|merge_group) tests_full=true ;;
schedule) full=true; macos=true; tests_full=true ;;
workflow_dispatch)
[ "$IN_FULL" = "true" ] && full=true && tests_full=true
@@ -239,6 +252,79 @@ jobs:
GOBIN="$RUNNER_TEMP/actionlint" go install github.com/rhysd/actionlint/cmd/[email protected]
"$RUNNER_TEMP/actionlint/actionlint" -shellcheck= -pyflakes=
+ # Workflow audit. A blocking part of the gate on every event, merge-queue
+ # groups included; security.yml keeps uploading the same audit to the
+ # Security tab from main. Accepted exceptions live in .github/zizmor.yml.
+ zizmor:
+ name: zizmor (workflow audit)
+ needs: detect
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ - uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4
+ with:
+ version: "1.30.1"
+ min-severity: medium
+ advanced-security: false
+ annotations: true
+ # Explicit: auto-discovery did not apply every ignore in a local
+ # `zizmor .` run, and a blocking audit must read the same rules.
+ config: .github/zizmor.yml
+
+ # Fails when the diff ADDS a dependency with a known high or critical
+ # advisory. Only a pull request has a dependency diff; on every other
+ # event (merge queue, main, nightly) it skips and the gate accepts that.
+ dependency-review:
+ name: dependency review
+ needs: detect
+ if: github.event_name == 'pull_request'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
+ with:
+ fail-on-severity: high
+
+ # Third-party websites the app parses (ollama.com's model library) change
+ # without notice. Those live checks are opt-in (JARVIS_LIVE_NETWORK_TESTS)
+ # and run only in the nightly: a redesign shows up as a failed step and a
+ # warning there, never as a red pull request, merge queue or nightly gate.
+ live-network:
+ name: live third-party sites (nightly, non-blocking)
+ needs: detect
+ if: github.event_name == 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.11"
+ - name: Install
+ uses: ./.github/actions/install-locked
+ with:
+ extras: dev
+ - name: Live ollama.com library checks
+ id: live
+ continue-on-error: true
+ env:
+ JARVIS_LIVE_NETWORK_TESTS: "1"
+ run: python -m pytest -m integration tests/integration/test_ollama_library_live.py -v
+ - name: Report a drifted site without failing the run
+ if: steps.live.outcome == 'failure'
+ run: echo "::warning title=Live site check failed::A third-party page the app parses changed (see the 'Live ollama.com library checks' step). Update its parser."
+
release-qualification:
name: release qualification
needs: [detect, gates]
@@ -877,6 +963,9 @@ jobs:
needs:
- detect
- gates
+ - zizmor
+ - dependency-review
+ - live-network
- python-fast
- release-qualification
- tests-linux
diff --git a/.github/workflows/merge-train.yml b/.github/workflows/merge-train.yml
index 6dd4e2b196..5332eaf1e1 100644
--- a/.github/workflows/merge-train.yml
+++ b/.github/workflows/merge-train.yml
@@ -1,35 +1,49 @@
# Merge train — integrates several coding agents' pull requests without a human.
#
-# Every tick (a push to main, a finished CI run, every 15 minutes, or by hand):
+# main requires a merge queue. The train no longer lands anything itself; it
+# keeps agent pull requests mergeable and hands the green ones to the queue,
+# which tests each one on top of the newest main (ci.yml's `merge_group` run)
+# before GitHub squash-merges it. Every tick (a push to main, a finished CI
+# run - pull request or merge queue -, hourly, or by hand):
#
# 1. Eligible PRs: same repository, base main, not a draft, head branch
# codex/ claude/ agent/ gemini/ cursor/ bot/ — or labelled `auto-merge`.
# `no-auto-merge`, `do-not-merge`, `wip` or `needs-human` opt a PR out.
# Forks and Dependabot never qualify (supply-chain bumps stay human).
-# 2. A PR that CONFLICTS with main (or whose CI failed while it was behind)
-# gets main merged into it (scripts/ci/agent_integrate.py): generated
-# files are regenerated, append-only files union-merged, everything else
-# goes to the optional AI resolver or is reported with a `needs-rebase`
-# label. No force push. A PR that is merely behind is left alone — with
-# several agents pushing to main, re-testing every PR on every push meant
-# nothing ever landed.
-# 3. The first green, conflict-free PR is squash-merged — one per tick. The
-# full post-merge run on main is the backstop for changes that pass alone
-# and break together (the same model as GitHub's non-strict checks).
+# 2. A PR that CONFLICTS with main (or whose CI, or merge-queue run, failed
+# while it was behind) gets main merged into it
+# (scripts/ci/agent_integrate.py): generated files are regenerated,
+# append-only files union-merged, everything else goes to the optional
+# AI resolver or is reported with a `needs-rebase` label. No force push.
+# A PR that is merely behind is left alone: the queue re-tests it on
+# the newest main anyway.
+# 3. Every green, conflict-free PR joins the merge queue (pinned to the
+# head commit its CI tested). A head the queue already failed is held
+# until a new push or a train update. Without a queue on main (the
+# rollback path) the train squash-merges one green PR per tick instead.
+#
+# Trust: three jobs, three privilege levels.
+# plan read-only token, no secrets, runs no pull-request code.
+# integrate read-only token. PR code (regenerators: npm ci, the frontend
+# build, Python generators) runs here and only here. The AI
+# resolver's API keys live in ONE step, which runs before any
+# PR code on that machine; the CLIs are pinned to exact versions.
+# apply the write token, runs no PR code: pushes the integrate job's
+# git bundles (checked to build on the planned head and main),
+# labels, comments, approves parked CI runs, enqueues.
+# Only people with push access can put a branch on the train (forks are
+# excluded), so a pushed update is no more trusted than their own push: CI
+# and the merge queue test it before anything lands.
#
# Tokens: with the optional INTEGRATION_TOKEN secret (a fine-grained PAT or App
-# token with contents + pull-requests write), pushes and merges fire the normal
-# pull_request / push events. Without it the train uses GITHUB_TOKEN: the
+# token with contents + pull-requests write), pushes fire the normal
+# pull_request events. Without it the train uses GITHUB_TOKEN: the
# pull_request run its own push triggers parks in "action_required" and the
# train approves it on the next tick (a dispatched run would never count for
-# the pull request), and it dispatches ci.yml for main after every merge.
+# the pull request).
#
# AI conflict resolution is optional: set ANTHROPIC_API_KEY (Claude Code) or
# OPENAI_API_KEY (Codex CLI). Without a key, semantic conflicts are reported.
-#
-# Trust: the train runs the checked-out PR's own build scripts with a write
-# token, which is why forks are excluded — only people with push access to this
-# repository can put a branch on the train.
name: Merge train
@@ -40,11 +54,13 @@ on:
workflows: [CI]
types: [completed]
schedule:
- - cron: "*/15 * * * *"
+ # A safety net only: queue merges (push), PR and merge-queue CI results
+ # (workflow_run) drive the train. Hourly catches a missed event.
+ - cron: "23 * * * *"
workflow_dispatch:
inputs:
dry_run:
- description: "Report what the train would do without pushing or merging."
+ description: "Report what the train would do without pushing, enqueueing or merging."
type: boolean
default: false
@@ -53,28 +69,55 @@ concurrency:
group: merge-train
cancel-in-progress: false
-# Read-only by default; the one job below asks for what it writes.
-permissions:
- contents: read
+permissions: {}
jobs:
- train:
- name: merge train
+ plan:
+ name: plan
runs-on: ubuntu-latest
+ timeout-minutes: 15
permissions:
- contents: write
- pull-requests: write
- actions: write
+ contents: read
+ pull-requests: read
+ actions: read
checks: read
+ outputs:
+ updates: ${{ steps.plan.outputs.updates }}
+ steps:
+ # The repository is public: later fetches need no credentials, so none
+ # are persisted. Only main's checkout is used; no PR code runs here.
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.11"
+ - name: Decide one action per pull request
+ id: plan
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: python scripts/ci/agent_integrate.py plan --repo "$GITHUB_REPOSITORY" --dir "$RUNNER_TEMP/train"
+ - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
+ with:
+ name: merge-train-plan
+ path: ${{ runner.temp }}/train/plan.json
+ if-no-files-found: error
+ retention-days: 3
+
+ integrate:
+ name: integrate (merge main, resolve, regenerate)
+ needs: plan
+ if: needs.plan.outputs.updates != '0'
+ runs-on: ubuntu-latest
timeout-minutes: 60
- env:
- GH_TOKEN: ${{ secrets.INTEGRATION_TOKEN || github.token }}
- TOKEN_IS_BOT: ${{ secrets.INTEGRATION_TOKEN == '' }}
+ permissions:
+ contents: read
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0
- token: ${{ secrets.INTEGRATION_TOKEN || github.token }}
+ persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.11"
@@ -82,6 +125,8 @@ jobs:
with:
node-version: "22"
- name: Regenerator dependencies (mirrors, reference docs, locks)
+ # main's own checkout; each PR worktree is put first on PYTHONPATH
+ # when its generators run.
run: |
python -m pip install -e . --no-deps
python -m pip install typer platformdirs click httpx rich pyyaml pydantic loguru python-dotenv packaging uv==0.11.19
@@ -91,31 +136,86 @@ jobs:
path: .git/rr-cache
key: rerere-${{ github.run_id }}
restore-keys: rerere-
- - name: Optional AI conflict resolver
- id: resolver
+ - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
+ with:
+ name: merge-train-plan
+ path: ${{ runner.temp }}/train
+ - name: Merge main into each branch (no secrets, no PR code)
+ id: merge
+ run: |
+ git config --global user.name "jarvis-merge-train[bot]"
+ git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ python scripts/ci/agent_integrate.py merge --dir "$RUNNER_TEMP/train"
+ - name: Optional AI conflict resolver (API keys; before any PR code runs)
+ if: steps.merge.outputs.pending != '0'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
+ # Exact versions: an unpinned global install would run whatever was
+ # published a minute ago with these keys in its environment. (Claude
+ # Code's own postinstall picks its pinned platform binary.)
if [ -n "$ANTHROPIC_API_KEY" ]; then
- npm install -g @anthropic-ai/claude-code >/dev/null
- echo 'cmd=claude -p --permission-mode acceptEdits --allowedTools Read,Edit' >> "$GITHUB_OUTPUT"
+ npm install -g @anthropic-ai/[email protected] >/dev/null
+ cmd='claude -p --permission-mode acceptEdits --allowedTools Read,Edit'
elif [ -n "$OPENAI_API_KEY" ]; then
- npm install -g @openai/codex >/dev/null
- echo 'cmd=codex exec --full-auto -' >> "$GITHUB_OUTPUT"
+ npm install -g --ignore-scripts @openai/[email protected] >/dev/null
+ cmd='codex exec --full-auto -'
else
echo "No resolver key configured - semantic conflicts are reported, not resolved."
+ exit 0
fi
+ python scripts/ci/agent_integrate.py resolve --dir "$RUNNER_TEMP/train" --resolver-cmd "$cmd"
+ - name: Regenerate and bundle (runs PR code; no secrets, read-only token)
+ run: python scripts/ci/agent_integrate.py finish --dir "$RUNNER_TEMP/train"
+ - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
+ with:
+ name: merge-train-updates
+ path: |
+ ${{ runner.temp }}/train/state/
+ ${{ runner.temp }}/train/bundles/
+ if-no-files-found: warn
+ retention-days: 3
+
+ apply:
+ name: apply (push updates, enqueue, approve)
+ needs: [plan, integrate]
+ if: ${{ !cancelled() && needs.plan.result == 'success' }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ permissions:
+ contents: write
+ pull-requests: write
+ actions: write
+ env:
+ GH_TOKEN: ${{ secrets.INTEGRATION_TOKEN || github.token }}
+ TOKEN_IS_BOT: ${{ secrets.INTEGRATION_TOKEN == '' }}
+ DRY_RUN: ${{ inputs.dry_run }}
+ steps:
+ # The write token is never persisted into .git; `gh auth setup-git`
+ # hands it to git only for this step's pushes. Nothing from a pull
+ # request executes in this job: bundles are fetched as data.
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.11"
+ - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
+ with:
+ name: merge-train-plan
+ path: ${{ runner.temp }}/train
+ - name: Download prepared updates
+ if: needs.integrate.result == 'success'
+ uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
+ with:
+ name: merge-train-updates
+ path: ${{ runner.temp }}/train
- name: Run the train
- env:
- ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
- CONFLICT_RESOLVER_CMD: ${{ steps.resolver.outputs.cmd }}
- DRY_RUN: ${{ inputs.dry_run }}
run: |
- git config user.name "jarvis-merge-train[bot]"
- git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
- args=(--repo "$GITHUB_REPOSITORY")
+ gh auth setup-git
+ args=(--dir "$RUNNER_TEMP/train")
[ "$DRY_RUN" = "true" ] && args+=(--dry-run)
[ "$TOKEN_IS_BOT" = "true" ] && args+=(--token-is-bot)
- python scripts/ci/agent_integrate.py train "${args[@]}"
+ python scripts/ci/agent_integrate.py apply "${args[@]}"
diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml
index 44d96d8326..8adb4572c7 100644
--- a/.github/workflows/release-cut.yml
+++ b/.github/workflows/release-cut.yml
@@ -7,7 +7,8 @@
# 2. bumps pyproject.toml + jarvis/__init__.py and writes the CHANGELOG
# section (scripts/ci/cut_release.py: [Unreleased] notes, or the
# Conventional Commits since the last tag),
-# 3. checks the version commit through a candidate PR, then merges it normally,
+# 3. checks the version commit through a candidate PR, then lands it through
+# main's merge queue and waits for the landed commit,
# 4. pushes the annotated tag; the three publishing workflows (PyPI, desktop
# installers, signed installer) run on it. Each of them starts with
# release-gate.yml, which waits for CI on the release commit.
@@ -192,8 +193,16 @@ jobs:
GH_TOKEN: ${{ steps.land-token.outputs.token || github.token }}
DISPATCH_TOKEN: ${{ github.token }}
run: |
+ # main requires a merge queue: this adds the candidate to it (the
+ # queue squash-merges after its own CI run), or merges directly
+ # when the queue is off. Either way, wait for the landed commit.
gh pr merge "$CANDIDATE" --merge --match-head-commit "$CANDIDATE_SHA"
- merged="$(gh pr view "$CANDIDATE" --json mergeCommit --jq '.mergeCommit.oid')"
+ merged=""
+ for attempt in {1..150}; do
+ merged="$(gh pr view "$CANDIDATE" --json mergeCommit --jq '.mergeCommit.oid // empty')"
+ [ -n "$merged" ] && break
+ sleep 30
+ done
[[ "$merged" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::Missing merge commit."; exit 1; }
git fetch --no-tags origin main:refs/remotes/origin/main
git checkout --detach "$merged"
diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml
index 8803668529..ab3936fd76 100644
--- a/.github/workflows/security.yml
+++ b/.github/workflows/security.yml
@@ -1,27 +1,27 @@
# Supply-chain and workflow security scans.
#
-# Three free scanners for public repositories. Each one writes into the
-# repository's Security tab (code scanning), next to CodeQL's default setup:
+# Free scanners for public repositories that write into the repository's
+# Security tab (code scanning), next to CodeQL's default setup. They run on
+# main, weekly and by hand:
#
# zizmor audits these workflow files themselves: template
# injection, leaked checkout credentials, dangerous
# triggers, cache poisoning. Accepted exceptions live in
# .github/zizmor.yml with their reason.
-# dependency-review on pull requests only: fails when the diff ADDS a
-# dependency with a known high or critical advisory.
-# osv-scanner scans the shipped lockfiles against osv.dev on main and
-# once a week, so an advisory published after a merge
-# still surfaces. It reports; it never blocks.
+# osv-scanner scans the shipped lockfiles against osv.dev, so an
+# advisory published after a merge still surfaces. It
+# reports; it never blocks.
#
-# None of these is part of the required `CI gate` check. They inform; the
-# ratchet stays the only merge blocker.
+# The blocking checks live in ci.yml, under the required `CI gate`, so they
+# also run for merge-queue groups: the same zizmor audit on every event, and
+# dependency review (fails when a pull request ADDS a dependency with a known
+# high or critical advisory).
name: Security scans
on:
push:
branches: [main]
- pull_request:
schedule:
- cron: "41 3 * * 2" # Tuesdays, off the hour
workflow_dispatch:
@@ -30,7 +30,7 @@ permissions: {}
concurrency:
group: security-${{ github.event_name }}-${{ github.ref }}
- cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+ cancel-in-progress: false
jobs:
zizmor:
@@ -51,22 +51,10 @@ jobs:
# Low/informational hints (self-repository syntax, ad-hoc pip in the
# merge train) stay local-only instead of filling the Security tab.
min-severity: medium
-
- dependency-review:
- name: dependency review
- if: github.event_name == 'pull_request'
- runs-on: ubuntu-latest
- timeout-minutes: 10
- permissions:
- contents: read
- steps:
- - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
- with:
- fail-on-severity: high
+ config: .github/zizmor.yml
osv-scanner:
name: osv-scanner (lockfiles)
- if: github.event_name != 'pull_request'
permissions:
actions: read
contents: read
diff --git a/.github/zizmor.yml b/.github/zizmor.yml
index ce0fa3518a..0f98527e09 100644
--- a/.github/zizmor.yml
+++ b/.github/zizmor.yml
@@ -6,19 +6,17 @@ rules:
# Runs on a merged PR but checks out `main` only and executes nothing
# from the pull request; the push token reaches the commit step alone.
- contributors.yml
- # Both react to completed runs of this repository's own workflows and
- # act on main / release tags; neither checks out or runs PR head code.
+ # Both react to completed runs of this repository's own workflows.
+ # release-finalize acts on main / release tags only. merge-train runs
+ # PR code solely in its read-only `integrate` job without secrets
+ # (apart from the resolver step that precedes it); the write-token
+ # `apply` job executes nothing from a pull request.
- merge-train.yml
- release-finalize.yml
# Reacts to completed CI runs on main only (repository, branch and event
# checked in `if:` and again by flaky_report.py vet-run), checks out
# `main`, and reads the downloaded shard reports as JSON data.
- flaky-tests.yml
- artipacked:
- ignore:
- # This job pushes commits with git after checkout, so the checkout must
- # keep its credential. It does not upload the workspace.
- - merge-train.yml
unpinned-uses:
config:
policies:
diff --git a/AGENTS.md b/AGENTS.md
index 2539726983..9d2f5be497 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -234,7 +234,10 @@ unless it is listed in `scripts/ci/test-baseline-<os>.json`. Finished work in
your own worktree lands with `python scripts/agent_land.py` (rebase onto main,
auto-resolve generated files, gates, relevant tests, push); a `codex/`,
`claude/`, `agent/` branch or an `auto-merge` label puts a PR on the merge
-train, which keeps it current with main and squash-merges it once green.
+train, which resolves its conflicts with main and adds it to main's merge
+queue once green; the queue squash-merges it after `CI gate` passes again on
+the PR merged with the newest main. Direct pushes to main are blocked for
+everyone but admins.
Triage any red job against the exact base; never add to a baseline to hide a
new failure.
Run `check_boot_budget.py` after touching startup; CI cannot measure the live
diff --git a/docs/ci-pipeline.md b/docs/ci-pipeline.md
index 71c878947b..1a110f88b2 100644
--- a/docs/ci-pipeline.md
+++ b/docs/ci-pipeline.md
@@ -6,8 +6,10 @@ Python + TypeScript desktop app, three operating systems, and signed
installers.
```
-agent branch ──► pull request ──► CI (lanes) ──► CI gate ──► merge train ──► main
- │
+agent branch ──► pull request ──► CI (lanes) ──► CI gate ──► merge train ──► merge queue
+ │
+ main ◄── CI gate (merge_group, full) ◄──┘
+ │
release-cut (manual) ──► tag ──► release gate ──► PyPI / installers / signatures
└─► draft assets ──► finalize ──► updater
```
@@ -16,16 +18,18 @@ agent branch ──► pull request ──► CI (lanes) ──► CI gate ─
| Stage | What it does | Script |
| --- | --- | --- |
-| `detect` | Classifies the diff into lanes. Fails open: an empty diff, a pipeline change, the nightly run and a manual run turn every lane on. A push to main classifies its lanes too (the concurrent-job limit is shared), but always runs the whole test suite on Linux and Windows. | `scripts/ci/classify_changes.py` |
+| `detect` | Classifies the diff into lanes. Fails open: an empty diff, a pipeline change, the nightly run and a manual run turn every lane on. A merge-queue group (`merge_group`, classified against the queue base) and a push to main classify their lanes too (the concurrent-job limit is shared), but always run the whole test suite on Linux and Windows. | `scripts/ci/classify_changes.py` |
| `static gates` | ~20 repository gates (keys, bundle, mirrors, privacy, docs, CLI coverage, ratchets, bash 3.2, no new German) in one job. Every gate reports. | `scripts/ci/run_gates.py` |
+| `zizmor` / `dependency review` | Workflow security audit on every event (merge queue included, exceptions in `.github/zizmor.yml`); dependency review on pull requests only, failing on an added dependency with a high or critical advisory. `security.yml` keeps the Security-tab uploads. | — |
+| `live third-party sites` | Nightly only and non-blocking: the opt-in live checks of pages the app parses (`JARVIS_LIVE_NETWORK_TESTS=1`, ollama.com's library). A site redesign shows as a failed step and a run warning, never as a red gate. | — |
| `python contracts (fast)` | Import cleanliness on the bare install, the named contract guards, skill-routing precision and recall, plugin auth. Blocking, no baseline. | — |
| `tests linux 1..6` | The whole suite in six shards. Batches of files run in fresh processes with a wall-clock budget; a failed batch is re-run file by file, a failed file once more (a pass there is reported as flaky). | `scripts/ci/run_tests_parallel.py` |
-| `tests windows` | Four shards on full runs; on a pull request one runner takes only the tests the diff can reach. | `scripts/ci/select_tests.py` |
+| `tests windows` | Four shards on full runs (merge queue, main, nightly, manual); on a pull request one runner takes only the tests the diff can reach. | `scripts/ci/select_tests.py` |
| `tests macos 1..3` | Nightly and manual runs only (~10x runner cost). | — |
| `test report + floor` | Proves the six Linux shards cover every discovered file exactly once, enforces the min-passed floor, and on main refreshes the duration cache. Detection freezes one shared duration snapshot for all shards, including partial reruns. | `scripts/ci/ratchet_tests.py` |
| Lanes | `frontend`, `jarvisctl`, `deps`, `realtime` (3 OS + slim container), `updater` (3 OS: in-app update, native handover, restart helper), `dragdrop`, `browser`, `macOS desktop`, `installer smoke` — each only when its paths change. | — |
| `release qualification` | Tag CI requires a full run with macOS and the browser-auth E2E evidence gate: a plugin labeled verified needs a completed journey, every completed journey ships as verified, and every other plugin ships labeled preview. The step summary counts both. Ordinary branch/PR/nightly CI skips this release-only job. | `scripts/ci/check_plugin_auth_contract.py --require-e2e-pass` |
-| `CI gate` | Aggregates every job. **The only required check.** A missing or skipped selected lane fails. Unselected lanes may skip; nightly is strict except event-specific jobs. | `scripts/ci/required_results.py` |
+| `CI gate` | Aggregates every job. **The only required check**, on the pull request and again on its merge-queue group. A missing or skipped selected lane fails. Unselected lanes may skip; nightly is strict except event-specific jobs. | `scripts/ci/required_results.py` |
The realtime lane runs the subscription authentication, direct reasoning,
voice transport, session orchestration, native login provisioning and Live catalog contracts on Windows,
@@ -102,47 +106,76 @@ the recorded result and its limits are in `macos-permissions.md`, section 4.15).
### Concurrency
A pull request keeps only its
-newest run. A run on main is never cancelled once it started; pushes to main
-share one queue slot, so a burst of pushes leaves one pending run that covers
-every commit before it instead of a backlog behind the organisation's
-concurrent-job limit. The nightly run and manual runs have their own slots.
-
-## 2. Integrating several agents — `.github/workflows/merge-train.yml`
+newest run. Every merge-queue entry has its own slot and is never cancelled:
+the queue drops entries it no longer needs itself, and a dropped pending run
+would leave `CI gate` unreported until the queue times out. A run on main is
+never cancelled once it started; pushes to main share one queue slot, so a
+burst of pushes leaves one pending run that covers every commit before it
+instead of a backlog behind the organisation's concurrent-job limit. The
+nightly run and manual runs have their own slots.
+
+## 2. Integrating several agents — merge queue + `.github/workflows/merge-train.yml`
+
+`main` requires a **merge queue** (repository ruleset "main merge queue":
+squash, `CI gate` required). A pull request's own CI is its admission ticket;
+the queue then builds each entry on top of the newest main plus every entry
+ahead of it, runs `ci.yml` on that exact tree (`merge_group` event, whole
+Linux + Windows suite), and squash-merges only when `CI gate` is green there.
+Changes that pass alone and break together stop in the queue instead of on
+main. A failed entry leaves the queue; the entries behind it are rebuilt
+without it.
Agents push branches named `codex/…`, `claude/…`, `agent/…`, `gemini/…`,
`cursor/…` or `bot/…`, or add the `auto-merge` label to any pull request. The
-merge train runs on every push to main, after every CI run, and every 15
-minutes:
-
-1. A pull request that **conflicts** with main (or whose CI failed while it
- was behind) gets main merged into it (`scripts/ci/agent_integrate.py`).
- No force push, so an agent that keeps pushing to its branch is never
- overwritten. A pull request that is merely behind is left alone: with
- several agents pushing to main, re-testing every PR on every push meant
- nothing ever landed.
+merge train runs on every push to main, after every CI run (pull request or
+merge queue), and hourly as a safety net:
+
+1. A pull request that **conflicts** with main (or whose CI, or merge-queue
+ run, failed while it was behind) gets main merged into it
+ (`scripts/ci/agent_integrate.py`). No force push, so an agent that keeps
+ pushing to its branch is never overwritten. A pull request that is merely
+ behind is left alone: the queue re-tests it on the newest main anyway.
2. Conflicts resolve by file class: **generated** files (frontend `dist/`,
agent mirrors, CLI reference docs, lockfiles, timing caches) take main's
copy and are regenerated; **append-only** files (CHANGELOG, allowlists,
`.gitignore`, `docs/BUGS.md`) are union-merged; **everything else** goes
to the optional AI resolver (`ANTHROPIC_API_KEY` → Claude Code,
- `OPENAI_API_KEY` → Codex CLI). Its result must leave no conflict markers
- and must still parse, and CI re-runs on it before anything lands. What
- stays unresolved aborts cleanly, gets the `needs-rebase` label and a
- comment listing the files. `git rerere` replays recorded resolutions.
-3. The first green, conflict-free pull request is squash-merged, one per
- tick. Main's full post-merge test run is the backstop for changes that
- pass alone and break together — GitHub's non-strict model.
+ `OPENAI_API_KEY` → Codex CLI, both pinned to exact versions). Its result
+ must leave no conflict markers and must still parse, and CI re-runs on it
+ before anything lands. What stays unresolved aborts cleanly, gets the
+ `needs-rebase` label and a comment listing the files. `git rerere`
+ replays recorded resolutions.
+3. Every green, conflict-free pull request joins the merge queue, pinned to
+ the head commit its CI tested. A head the queue already failed is held
+ until a new push or a train update. Without a queue on main (the
+ rollback path: delete or disable the ruleset) the train squash-merges one
+ green pull request per tick instead.
Opt out with `no-auto-merge`, `do-not-merge`, `wip` or `needs-human`.
`priority` moves a pull request to the front. Forks and Dependabot never ride
the train.
+**Trust.** The train is three jobs with three privilege levels. `plan` has a
+read-only token and no secrets and runs no pull-request code. `integrate` has
+a read-only token: it merges main into each branch in its own worktree, gives
+the AI resolver its API keys in one step that runs before any pull-request
+code on that machine, then runs the regenerators (pull-request code) and
+hands the result on as git bundles. `apply` holds the write token, runs no
+pull-request code, and only pushes bundles that build on the planned head and
+main, labels, comments, approves parked runs and enqueues. No checkout
+persists a token.
+
**Token.** With the optional `INTEGRATION_TOKEN` secret (a fine-grained token
-with contents and pull-request write access), the train's pushes and merges
-fire the normal events. Without it the train uses `GITHUB_TOKEN`: the
-pull-request run its own push triggers waits in "action required" and the
-train approves it on the next tick, because GitHub never counts a dispatched
-run for a pull request. After each merge it dispatches `ci.yml` for main.
+with contents and pull-request write access), the train's pushes fire the
+normal events. Without it the train uses `GITHUB_TOKEN`: the pull-request run
+its own push triggers waits in "action required" and the train approves it
+on the next tick, because GitHub never counts a dispatched run for a pull
+request. The merge queue's own merges fire the normal push to main.
+
+**Rollback.** If the queue stalls, disable the "main merge queue" ruleset
+(Settings → Rules → Rulesets, or `gh api -X PUT
+repos/<owner>/<repo>/rulesets/<id> -f enforcement=disabled`). The train sees
+no queue on its next tick and merges directly again.
### Locally: `scripts/agent_land.py`
@@ -164,8 +197,8 @@ A release happens **only** when the maintainer asks for one.
* **`release-cut.yml`** (manual): refuses unless main is green, bumps
`pyproject.toml` + `jarvis/__init__.py` + the root package in `uv.lock`, moves the `[Unreleased]` notes (or
the Conventional Commits since the last tag) into a dated CHANGELOG section
- (`scripts/ci/cut_release.py`), lands the candidate through a CI-checked PR,
- tags the resulting merge commit, and dispatches full CI with macOS on that
+ (`scripts/ci/cut_release.py`), lands the candidate through a CI-checked PR
+ and the merge queue, tags the landed commit, and dispatches full CI with macOS on that
immutable tag. Its `cut` job runs in the `release-cut` environment, which
only `main` may deploy to and which holds the private key of the release
bot GitHub App (secret `RELEASE_APP_PRIVATE_KEY`, variable
diff --git a/scripts/ci/agent_integrate.py b/scripts/ci/agent_integrate.py
index 4f71461aac..191755ba3b 100644
--- a/scripts/ci/agent_integrate.py
+++ b/scripts/ci/agent_integrate.py
@@ -3,9 +3,10 @@
This is the engine behind both halves of agent integration:
-* the **merge train** (``.github/workflows/merge-train.yml`` -> ``train``)
- that keeps every open agent pull request current with main and lands the
- green ones one at a time, and
+* the **merge train** (``.github/workflows/merge-train.yml`` -> ``plan``,
+ ``merge``, ``resolve``, ``finish``, ``apply``) that keeps every open agent
+ pull request free of conflicts with main and hands the green ones to
+ main's merge queue, and
* ``scripts/agent_land.py``, which a coding agent runs locally before it
pushes.
@@ -29,7 +30,9 @@ Conflicts are resolved by file class, cheapest first:
Usage::
agent_integrate.py update --onto origin/main [--mode merge|rebase]
- agent_integrate.py train --repo OWNER/NAME [--dry-run]
+ agent_integrate.py train --repo OWNER/NAME [--dry-run] # all phases, one process
+ agent_integrate.py plan --repo OWNER/NAME --dir DIR # the workflow's phases
+ agent_integrate.py merge|resolve|finish|apply --dir DIR
"""
from __future__ import annotations
@@ -43,6 +46,7 @@ import shlex
import shutil
import subprocess
import sys
+import tempfile
from dataclasses import dataclass, field
from pathlib import Path
@@ -88,11 +92,18 @@ def git(*args: str, check: bool = True, cwd: Path = REPO_ROOT) -> subprocess.Com
)
-def _sh(cmd: list[str], *, cwd: Path = REPO_ROOT, stdin: str | None = None) -> int:
+def _sh(
+ cmd: list[str],
+ *,
+ cwd: Path = REPO_ROOT,
+ stdin: str | None = None,
+ env: dict[str, str] | None = None,
+) -> int:
print(f"[integrate] $ {' '.join(cmd)}", flush=True)
proc = subprocess.run( # noqa: S603
cmd,
cwd=cwd,
+ env=env,
input=stdin,
text=True,
encoding="utf-8",
@@ -221,6 +232,13 @@ def regenerate(keys: set[str], cwd: Path) -> list[str]:
commands["npm-lock"] = [[npm, "install", "--package-lock-only", "--ignore-scripts"]]
commands["frontend-build"] = [[npm, "ci"], [npm, "run", "build"]]
order = ["npm-lock", "uv-lock", "requirements", "mirrors", "reference-docs", "frontend-build"]
+ # The merge train regenerates inside a separate worktree per pull request
+ # while the editable install points at the main checkout; putting the
+ # worktree first on PYTHONPATH makes `import jarvis` read the merged code.
+ env = dict(os.environ)
+ env["PYTHONPATH"] = os.pathsep.join(
+ p for p in (str(cwd), os.environ.get("PYTHONPATH", "")) if p
+ )
for key in order:
if key not in keys:
continue
@@ -231,7 +249,7 @@ def regenerate(keys: set[str], cwd: Path) -> list[str]:
failures.append(key)
continue
for cmd in commands[key]:
- if _sh(cmd, cwd=workdir) != 0:
+ if _sh(cmd, cwd=workdir, env=env) != 0:
failures.append(key)
break
return failures
@@ -355,43 +373,80 @@ def update(onto: str, mode: str, resolver_cmd: str, cwd: Path = REPO_ROOT) -> di
# An emptied commit: its change already landed on main.
git("rebase", "--skip", check=False, cwd=cwd)
if regen:
- failed = regenerate(regen, cwd)
- # One missing pathspec makes `git add` stage NOTHING, so pass only the
- # generated paths that exist — a half-staged frontend bundle is the
- # exact breakage the dist-consistency gate exists for.
- specs = {p.rstrip("*").rstrip("/") for p, _ in GENERATED}
- existing = sorted(s for s in specs if (cwd / s).exists())
- if existing:
- git("add", "-A", "--", *existing, cwd=cwd)
- if "frontend-build" in regen and "frontend-build" not in failed:
- # The build keeps retired chunks on disk for open windows, and a
- # fresh clone restarts that grace period, so `add -A` just staged
- # every earlier build's chunks too. Untrack them; disk is untouched.
- _sh(
- [sys.executable, "scripts/ci/check_dist_consistency.py", "--staged", "--prune"],
- cwd=cwd,
- )
- staged = git("diff", "--cached", "--name-only", cwd=cwd).stdout.strip()
- if staged:
- commit = git(
- "commit",
- "-m",
- "chore: regenerate generated files after update",
- check=False,
- cwd=cwd,
- )
- if commit.returncode != 0:
- print(commit.stdout[-3000:] + commit.stderr[-3000:], flush=True)
- return {"status": "conflict", "unresolved": ["<regenerated files rejected>"]}
- report["regenerated"] = sorted(regen - set(failed))
- if failed:
- report["regen_failed"] = failed
+ outcome = regenerate_and_commit(regen, cwd)
+ if outcome is None:
+ return {"status": "conflict", "unresolved": ["<regenerated files rejected>"]}
+ report.update(outcome)
report["resolved"] = sorted(set(resolved))
report["ai_resolved"] = sorted(set(ai))
return report
+def regenerate_and_commit(regen: set[str], cwd: Path) -> dict[str, object] | None:
+ """Regenerate generated files and commit them. ``None`` when the commit
+ was rejected; otherwise the ``regenerated`` / ``regen_failed`` report."""
+ failed = regenerate(regen, cwd)
+ # One missing pathspec makes `git add` stage NOTHING, so pass only the
+ # generated paths that exist — a half-staged frontend bundle is the
+ # exact breakage the dist-consistency gate exists for.
+ specs = {p.rstrip("*").rstrip("/") for p, _ in GENERATED}
+ existing = sorted(s for s in specs if (cwd / s).exists())
+ if existing:
+ git("add", "-A", "--", *existing, cwd=cwd)
+ if "frontend-build" in regen and "frontend-build" not in failed:
+ # The build keeps retired chunks on disk for open windows, and a
+ # fresh clone restarts that grace period, so `add -A` just staged
+ # every earlier build's chunks too. Untrack them; disk is untouched.
+ _sh(
+ [sys.executable, "scripts/ci/check_dist_consistency.py", "--staged", "--prune"],
+ cwd=cwd,
+ )
+ staged = git("diff", "--cached", "--name-only", cwd=cwd).stdout.strip()
+ if staged:
+ commit = git(
+ "commit",
+ "-m",
+ "chore: regenerate generated files after update",
+ check=False,
+ cwd=cwd,
+ )
+ if commit.returncode != 0:
+ print(commit.stdout[-3000:] + commit.stderr[-3000:], flush=True)
+ return None
+ report: dict[str, object] = {"regenerated": sorted(regen - set(failed))}
+ if failed:
+ report["regen_failed"] = failed
+ return report
+
+
# --------------------------------------------------------------------------- merge train
+#
+# The train runs as three jobs with three trust levels (merge-train.yml):
+#
+# plan read-only token, no secrets, runs no pull-request code: one
+# decision per eligible pull request (``plan``).
+# integrate read-only token: merges main into the branches that need it,
+# one worktree each (``merge``); lets the optional AI resolver
+# edit the conflicts left over (``resolve`` - the only step that
+# holds API keys, and nothing from a pull request has executed
+# on that machine yet); then regenerates generated files, which
+# runs pull-request code, and bundles the result (``finish``).
+# apply write token, runs no pull-request code: pushes the bundles,
+# labels and comments, approves parked CI runs, and lands green
+# pull requests - through main's merge queue when it has one,
+# directly otherwise (``apply``).
+#
+# ``train`` runs every phase in one process, for a local or manual run.
+
+QUEUE_HEAD_PREFIX = "gh-readonly-queue/main/pr-"
+_QUEUE_QUERY = (
+ "query($owner:String!,$name:String!){repository(owner:$owner,name:$name){"
+ 'mergeQueue(branch:"main"){entries(first:100){nodes{pullRequest{number}}}}}}'
+)
+_ENQUEUE = (
+ "mutation($id:ID!,$head:GitObjectID!){enqueuePullRequest("
+ "input:{pullRequestId:$id,expectedHeadOid:$head}){mergeQueueEntry{position}}}"
+)
def gh_json(*args: str) -> object:
@@ -420,6 +475,7 @@ def eligible(pr: dict) -> bool:
_ACTIVE = {"queued", "in_progress", "waiting", "pending", "requested"}
+_QUEUE_FAILED = {"failure", "timed_out", "startup_failure"}
def run_state(runs: list[dict]) -> tuple[str, int | None]:
@@ -452,27 +508,107 @@ def run_state(runs: list[dict]) -> tuple[str, int | None]:
return "failure", run_id
-def gate_state(repo: str, sha: str) -> tuple[str, int | None]:
+def gate_runs(repo: str, sha: str) -> list[dict]:
data = gh_json("api", f"repos/{repo}/actions/workflows/ci.yml/runs?head_sha={sha}&per_page=50")
- runs = (data or {}).get("workflow_runs", []) if isinstance(data, dict) else []
- return run_state(runs)
+ return (data or {}).get("workflow_runs", []) if isinstance(data, dict) else []
-def dispatch_ci(ref: str) -> None:
- gh("workflow", "run", "ci.yml", "--ref", ref, "-f", "full=false")
+def gate_state(repo: str, sha: str) -> tuple[str, int | None]:
+ return run_state(gate_runs(repo, sha))
+
+
+def merge_queue_numbers(repo: str) -> set[int] | None:
+ """Pull requests in main's merge queue; ``None`` when main has no queue."""
+ owner, name = repo.split("/", 1)
+ data = gh_json(
+ "api",
+ "graphql",
+ "-f",
+ f"query={_QUEUE_QUERY}",
+ "-f",
+ f"owner={owner}",
+ "-f",
+ f"name={name}",
+ )
+ repository = ((data or {}).get("data") or {}).get("repository") or {} # type: ignore[union-attr]
+ queue = repository.get("mergeQueue")
+ if queue is None:
+ return None
+ nodes = (queue.get("entries") or {}).get("nodes") or []
+ return {n["pullRequest"]["number"] for n in nodes if n and n.get("pullRequest")}
+
+
+def queue_group_runs(repo: str) -> list[dict]:
+ data = gh_json(
+ "api", f"repos/{repo}/actions/workflows/ci.yml/runs?event=merge_group&per_page=100"
+ )
+ return (data or {}).get("workflow_runs", []) if isinstance(data, dict) else []
+
+def queue_runs_by_pr(runs: list[dict]) -> dict[int, dict]:
+ """The newest merge-queue CI run per pull request number.
-def decide(mergeable: str, state: str, behind: bool) -> str:
+ A queue entry's temporary branch is ``gh-readonly-queue/main/pr-<N>-<base>``.
+ """
+ newest: dict[int, dict] = {}
+ for run in runs:
+ branch = run.get("head_branch") or ""
+ if run.get("event") != "merge_group" or not branch.startswith(QUEUE_HEAD_PREFIX):
+ continue
+ number = branch[len(QUEUE_HEAD_PREFIX) :].split("-", 1)[0]
+ if not number.isdigit():
+ continue
+ key = int(number)
+ if key not in newest or (run.get("created_at") or "") > (
+ newest[key].get("created_at") or ""
+ ):
+ newest[key] = run
+ return newest
+
+
+def queue_rejected(queue_run: dict | None, runs: list[dict]) -> bool:
+ """True when the merge queue already failed this head after its PR run went green.
+
+ Re-adding it unchanged would fail the same way and stall every entry behind
+ it; a new push (or the train's own update with main) produces a newer green
+ pull_request run and lifts the hold. A cancelled queue run is the queue
+ rebuilding a group, not a verdict.
+ """
+ if not queue_run or queue_run.get("status") != "completed":
+ return False
+ if queue_run.get("conclusion") not in _QUEUE_FAILED:
+ return False
+ green = [
+ r.get("created_at") or ""
+ for r in runs
+ if r.get("event") == "pull_request" and r.get("conclusion") == "success"
+ ]
+ return (queue_run.get("created_at") or "") > max(green, default="")
+
+
+def decide(
+ mergeable: str,
+ state: str,
+ behind: bool,
+ *,
+ queued: bool = False,
+ queue_failed: bool = False,
+) -> str:
"""The train's action for one pull request.
- Mirrors GitHub's non-strict model (and Hermes Agent's): a branch is NOT
- brought up to date just because main moved — with several agents pushing
- to main, that re-ran every PR's CI on every push and nothing ever landed.
- A branch is updated only when it CONFLICTS with main (or its last CI failed
- while it was behind, since a newer main may be the fix). A green,
- conflict-free PR merges; main's full post-merge run is the backstop for
- changes that are fine alone and break together.
+ A branch is NOT brought up to date just because main moved — with several
+ agents pushing to main, that re-ran every PR's CI on every push and
+ nothing ever landed. The merge queue tests each PR on top of the newest
+ main before it lands, so a merely-behind branch is safe to hand over.
+ A branch is updated only when it CONFLICTS with main, or when a red
+ verdict (its own CI, or the queue's) came while it was behind, since a
+ newer main may be the fix.
+
+ Actions: update | merge (enqueue, or merge directly without a queue) |
+ approve | rerun | queued | held | wait.
"""
+ if queued:
+ return "queued" # the queue owns it now; it drops the PR itself on a conflict
if mergeable == "CONFLICTING":
return "update"
if state in ("approve", "rerun"):
@@ -480,13 +616,16 @@ def decide(mergeable: str, state: str, behind: bool) -> str:
if mergeable not in ("MERGEABLE", ""):
return "wait" # GitHub is still computing mergeability
if state == "success":
+ if queue_failed:
+ return "update" if behind else "held"
return "merge"
if state == "failure" and behind:
return "update"
return "wait"
-def train(repo: str, max_updates: int, resolver_cmd: str, dry_run: bool, token_is_bot: bool) -> int:
+def plan(repo: str, max_updates: int) -> dict[str, object]:
+ """Decide what the train does this tick. Reads only; runs no PR code."""
prs = gh_json(
"pr",
"list",
@@ -499,47 +638,325 @@ def train(repo: str, max_updates: int, resolver_cmd: str, dry_run: bool, token_i
"--limit",
"100",
"--json",
- "number,title,headRefName,headRefOid,isDraft,labels,baseRefName,isCrossRepository,mergeable",
+ "id,number,title,headRefName,headRefOid,isDraft,labels,baseRefName,"
+ "isCrossRepository,mergeable",
)
- queue = sorted(
+ queued = merge_queue_numbers(repo)
+ queue_runs = queue_runs_by_pr(queue_group_runs(repo)) if queued is not None else {}
+ git("fetch", "--quiet", "origin", "main")
+ main_sha = git("rev-parse", "origin/main").stdout.strip()
+ order = sorted(
(p for p in prs or [] if eligible(p)), # type: ignore[union-attr]
key=lambda p: (not any(lb["name"] == "priority" for lb in p["labels"]), p["number"]),
)
- print(f"[train] {len(queue)} eligible pull request(s)", flush=True)
+ print(f"[train] {len(order)} eligible pull request(s); merge queue: {queued is not None}")
+ entries: list[dict[str, object]] = []
updates = 0
- merged = False
- summary: list[str] = []
- for pr in queue:
+ landing = False
+ for pr in order:
number, branch, sha = pr["number"], pr["headRefName"], pr["headRefOid"]
- git("fetch", "--quiet", "origin", "main", branch)
- behind = git("merge-base", "--is-ancestor", "origin/main", sha, check=False).returncode != 0
- state, run_id = gate_state(repo, sha)
- action = decide(pr.get("mergeable") or "", state, behind)
- if action == "merge" and merged:
- action = "wait" # one landing per tick; the next tick sees the new main
+ git("fetch", "--quiet", "origin", branch, check=False)
+ behind = git("merge-base", "--is-ancestor", main_sha, sha, check=False).returncode != 0
+ runs = gate_runs(repo, sha)
+ state, run_id = run_state(runs)
+ mergeable = pr.get("mergeable") or ""
+ action = decide(
+ mergeable,
+ state,
+ behind,
+ queued=queued is not None and number in queued,
+ queue_failed=queue_rejected(queue_runs.get(number), runs),
+ )
+ note = f"CI {state}, {mergeable or 'unknown'}"
if action == "update":
if updates >= max_updates:
- summary.append(f"#{number}: needs an update, waits for a free slot")
- continue
- updates += 1
+ action, note = "wait", "needs an update, waits for a free slot"
+ else:
+ updates += 1
+ elif action == "merge" and queued is None:
+ if landing:
+ action, note = (
+ "wait",
+ "green; one direct landing per tick, next tick sees the new main",
+ )
+ landing = True
+ entries.append(
+ {
+ "number": number,
+ "branch": branch,
+ "head": sha,
+ "id": pr.get("id", ""),
+ "action": action,
+ "run_id": run_id,
+ "note": note,
+ }
+ )
+ return {"repo": repo, "main": main_sha, "queue": queued is not None, "entries": entries}
+
+
+# ----- integrate: merge -> resolve -> finish, one worktree per pull request
+
+
+def _updates(data: dict) -> list[dict]:
+ return [e for e in data.get("entries", []) if e.get("action") == "update"]
+
+
+def _state_file(root: Path, number: int) -> Path:
+ return root / "state" / f"pr-{number}.json"
+
+
+def _save_state(root: Path, number: int, state: dict) -> None:
+ path = _state_file(root, number)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(state, indent=2), encoding="utf-8")
+
+
+def _load_state(root: Path, number: int) -> dict | None:
+ path = _state_file(root, number)
+ if not path.exists():
+ return None
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _worktree(root: Path, number: int) -> Path:
+ return root / "wt" / f"pr-{number}"
+
+
+def merge_main_into(
+ wt: Path, head: str, main_sha: str, branch: str, checkout: Path = REPO_ROOT
+) -> dict[str, object]:
+ """Merge main into ``head`` in a new worktree; resolve what needs no AI.
+
+ ``status``: up-to-date | merged | pending (semantic conflicts left in the
+ worktree, the merge still in progress for ``resolve``).
+ """
+ wt.parent.mkdir(parents=True, exist_ok=True)
+ git("worktree", "add", "--quiet", "--detach", str(wt), head, cwd=checkout)
+ if git("merge-base", "--is-ancestor", main_sha, "HEAD", check=False, cwd=wt).returncode == 0:
+ return {"status": "up-to-date"}
+ state: dict[str, object] = {"status": "merged", "resolved": [], "ai_resolved": [], "regen": []}
+ message = f"Merge main into {branch}"
+ result = git("merge", "--no-edit", "--no-ff", "-m", message, main_sha, check=False, cwd=wt)
+ if result.returncode != 0:
+ res = resolve_conflicts("theirs", "", wt)
+ state["resolved"] = res.resolved
+ state["regen"] = sorted(res.regenerate)
+ left = conflicted_files(wt)
+ if left:
+ state["status"] = "pending"
+ state["unresolved"] = left
+ return state
+ git("commit", "--no-edit", check=False, cwd=wt)
+ return state
+
+
+def integrate_merge(root: Path, data: dict, checkout: Path = REPO_ROOT) -> int:
+ """Phase 1 (no secrets, no PR code). Returns how many still conflict."""
+ pending = 0
+ for entry in _updates(data):
+ number = entry["number"]
+ try:
+ state = merge_main_into(
+ _worktree(root, number), entry["head"], data["main"], entry["branch"], checkout
+ )
+ except (subprocess.CalledProcessError, OSError) as exc:
+ # One broken branch must never stop the train for the others.
+ print(f"[train] #{number}: merge crashed: {exc}", flush=True)
+ state = {"status": "crashed", "error": type(exc).__name__}
+ pending += state["status"] == "pending"
+ _save_state(root, number, state)
+ return pending
+
+
+def integrate_resolve(root: Path, data: dict, resolver_cmd: str) -> None:
+ """Phase 2 (API keys; runs before any PR code on this machine)."""
+ for entry in _updates(data):
+ number = entry["number"]
+ state = _load_state(root, number)
+ if not state or state.get("status") != "pending":
+ continue
+ wt = _worktree(root, number)
+ res = resolve_conflicts("theirs", resolver_cmd, wt)
+ state["resolved"] = sorted({*state.get("resolved", []), *res.resolved})
+ state["ai_resolved"] = res.ai_resolved
+ state["regen"] = sorted({*state.get("regen", []), *res.regenerate})
+ state["unresolved"] = conflicted_files(wt)
+ _save_state(root, number, state)
+
+
+def integrate_finish(root: Path, data: dict) -> None:
+ """Phase 3 (no secrets; regeneration runs PR code). Bundles each result."""
+ for entry in _updates(data):
+ number = entry["number"]
+ state = _load_state(root, number)
+ if not state:
+ continue
+ wt = _worktree(root, number)
+ try:
+ state = _finish_one(root, wt, number, state, (entry["head"], data["main"]))
+ except (subprocess.CalledProcessError, OSError) as exc:
+ print(f"[train] #{number}: finish crashed: {exc}", flush=True)
+ state = {"status": "crashed", "error": type(exc).__name__}
+ _save_state(root, number, state)
+
+
+def _finish_one(root: Path, wt: Path, number: int, state: dict, known: tuple[str, str]) -> dict:
+ """Conclude one merge, regenerate, and bundle only the new commits
+ (``known`` = the PR head and main, which the apply job already has)."""
+ if state.get("status") == "pending":
+ left = conflicted_files(wt)
+ if left:
+ git("merge", "--abort", check=False, cwd=wt)
+ return {**state, "status": "conflict", "unresolved": left}
+ git("commit", "--no-edit", check=False, cwd=wt)
+ state = {**state, "status": "merged"}
+ if state.get("status") != "merged":
+ return state
+ if state.get("regen"):
+ outcome = regenerate_and_commit(set(state["regen"]), wt)
+ if outcome is None:
+ return {**state, "status": "conflict", "unresolved": ["<regenerated files rejected>"]}
+ state = {**state, **outcome}
+ ref = f"refs/train/pr-{number}"
+ git("update-ref", ref, "HEAD", cwd=wt)
+ bundle = root / "bundles" / f"pr-{number}.bundle"
+ bundle.parent.mkdir(parents=True, exist_ok=True)
+ git("bundle", "create", str(bundle), ref, "--not", *known, cwd=wt)
+ sha = git("rev-parse", "HEAD", cwd=wt).stdout.strip()
+ return {**state, "status": "ready", "sha": sha}
+
+
+def cleanup_worktrees(root: Path, checkout: Path = REPO_ROOT) -> None:
+ for wt in sorted((root / "wt").glob("pr-*")):
+ git("worktree", "remove", "--force", str(wt), check=False, cwd=checkout)
+ git("worktree", "prune", check=False, cwd=checkout)
+
+
+# ----- apply: the only phase with a write token; it runs no PR code
+
+
+def enqueue(entry: dict) -> int:
+ """Add a pull request to main's merge queue, pinned to the tested head."""
+ return gh(
+ "api",
+ "graphql",
+ "-f",
+ f"query={_ENQUEUE}",
+ "-f",
+ f"id={entry['id']}",
+ "-f",
+ f"head={entry['head']}",
+ )
+
+
+def dispatch_ci(ref: str) -> None:
+ gh("workflow", "run", "ci.yml", "--ref", ref, "-f", "full=false")
+
+
+def _bundle_is_safe(sha: str, entry: dict, main_sha: str, checkout: Path) -> bool:
+ """The integrate job ran PR code, so treat its bundle as data: it must
+ build on both the PR's planned head and the planned main. Its content is
+ no more trusted than any push to the branch: CI and the queue test it."""
+ for ancestor in (entry["head"], main_sha):
+ if (
+ git("merge-base", "--is-ancestor", ancestor, sha, check=False, cwd=checkout).returncode
+ != 0
+ ):
+ return False
+ return True
+
+
+def apply_update(
+ root: Path, data: dict, entry: dict, dry_run: bool, checkout: Path = REPO_ROOT
+) -> str:
+ number, branch, repo = entry["number"], entry["branch"], data["repo"]
+ state = _load_state(root, number)
+ if state is None:
+ return "update was not prepared (integrate job failed or skipped); next tick"
+ status = state.get("status")
+ if status == "up-to-date":
+ return "already contains main; nothing to push"
+ if status == "crashed":
+ return f"update crashed ({state.get('error')}); left for the next tick"
+ if status in ("conflict", "pending"):
+ unresolved = [str(f) for f in state.get("unresolved", [])]
+ files = "\n".join(f"- `{f}`" for f in unresolved)
+ body = (
+ "The merge train could not bring this branch up to date with `main`: "
+ f"these files conflict and could not be resolved automatically.\n\n{files}\n\n"
+ "Resolve locally with `python scripts/agent_land.py --pr` (it rebases, "
+ "resolves generated files and lists what is left). The train retries on "
+ "the next push to this branch."
+ )
+ if not dry_run:
+ gh("pr", "comment", str(number), "--repo", repo, "--body", body)
+ gh("pr", "edit", str(number), "--repo", repo, "--add-label", "needs-rebase")
+ return "conflict - " + ", ".join(unresolved)
+ if status != "ready":
+ return f"update in unexpected state {status!r}; next tick"
+ if dry_run:
+ return "would push update"
+ sha = str(state["sha"])
+ ref = f"refs/train/pr-{number}"
+ bundle = root / "bundles" / f"pr-{number}.bundle"
+ git("fetch", "--quiet", "origin", "main", branch, check=False, cwd=checkout)
+ fetch = git("fetch", "--quiet", str(bundle), f"+{ref}:{ref}", check=False, cwd=checkout)
+ if (
+ fetch.returncode != 0
+ or git("rev-parse", ref, check=False, cwd=checkout).stdout.strip() != sha
+ ):
+ return "update bundle missing or unreadable; next tick"
+ if not _bundle_is_safe(sha, entry, data["main"], checkout):
+ return "update bundle rejected (not the planned head plus main); next tick"
+ push = git("push", "origin", f"{sha}:refs/heads/{branch}", check=False, cwd=checkout)
+ if push.returncode != 0:
+ return "update rejected (the branch moved); retry next tick"
+ gh("pr", "edit", str(number), "--repo", repo, "--remove-label", "needs-rebase")
+ ai = [str(f) for f in state.get("ai_resolved") or []]
+ if ai:
+ listing = ", ".join(f"`{f}`" for f in ai)
+ gh(
+ "pr",
+ "comment",
+ str(number),
+ "--repo",
+ repo,
+ "--body",
+ f"Merge train: conflicts in {listing} were resolved by the configured AI "
+ "resolver. CI re-runs on the result before anything lands; please skim them.",
+ )
+ # A GITHUB_TOKEN push parks the pull_request run in action_required; the
+ # next tick approves it (a dispatched run would never reach the PR).
+ return f"updated with main ({len(state.get('resolved', []))} conflicts auto-resolved)"
+
+
+def apply(root: Path, data: dict, dry_run: bool, token_is_bot: bool) -> int:
+ repo = data["repo"]
+ summary: list[str] = []
+ for entry in data.get("entries", []):
+ number, action, run_id = entry["number"], entry["action"], entry.get("run_id")
+ if action == "update":
try:
- outcome = update_pr(pr, resolver_cmd, dry_run, token_is_bot)
+ outcome = apply_update(root, data, entry, dry_run)
except (subprocess.CalledProcessError, OSError) as exc:
- # One broken branch must never stop the train for the others.
- print(f"[train] #{number}: update crashed: {exc}", flush=True)
- outcome = f"update crashed ({type(exc).__name__}); left for the next tick"
- finally:
- git("merge", "--abort", check=False)
- git("rebase", "--abort", check=False)
- git("reset", "-q", "--hard", check=False)
- git("clean", "-fdq", "--", "jarvis/ui/web/dist", check=False)
+ outcome = f"update push crashed ({type(exc).__name__}); left for the next tick"
summary.append(f"#{number}: {outcome}")
+ elif action == "merge" and data.get("queue"):
+ if dry_run:
+ summary.append(f"#{number}: would join the merge queue")
+ elif enqueue(entry) == 0:
+ summary.append(f"#{number}: added to the merge queue")
+ else:
+ summary.append(f"#{number}: merge queue refused it (head moved or not mergeable)")
elif action == "merge":
if dry_run:
summary.append(f"#{number}: would merge")
continue
- if gh("pr", "merge", str(number), "--repo", repo, "--squash") == 0:
- merged = True
+ code = gh(
+ "pr", "merge", str(number), "--repo", repo, "--squash",
+ "--match-head-commit", entry["head"],
+ ) # fmt: skip
+ if code == 0:
summary.append(f"#{number}: merged")
if token_is_bot:
dispatch_ci("main") # a GITHUB_TOKEN merge fires no push event
@@ -560,8 +977,15 @@ def train(repo: str, max_updates: int, resolver_cmd: str, dry_run: bool, token_i
f"#{number}: could not {action} CI run {run_id} - approve it in the "
"Actions tab or set the INTEGRATION_TOKEN secret"
)
+ elif action == "queued":
+ summary.append(f"#{number}: in the merge queue")
+ elif action == "held":
+ summary.append(
+ f"#{number}: the merge queue failed this head; push a fix (or re-add it "
+ "by hand if the failure was a flake)"
+ )
else:
- summary.append(f"#{number}: waiting (CI {state}, {pr.get('mergeable') or 'unknown'})")
+ summary.append(f"#{number}: waiting ({entry.get('note', '')})")
lines = ["## Merge train", "", *[f"- {line}" for line in summary]]
print("\n".join(lines))
target = os.environ.get("GITHUB_STEP_SUMMARY")
@@ -571,47 +995,29 @@ def train(repo: str, max_updates: int, resolver_cmd: str, dry_run: bool, token_i
return 0
-def update_pr(pr: dict, resolver_cmd: str, dry_run: bool, token_is_bot: bool) -> str:
- number, branch = pr["number"], pr["headRefName"]
- git("checkout", "--quiet", "-B", f"train/{number}", f"origin/{branch}")
- report = update("origin/main", "merge", resolver_cmd, REPO_ROOT)
- status = report["status"]
- repo = os.environ.get("GITHUB_REPOSITORY", "")
- if status == "conflict":
- files = "\n".join(f"- `{f}`" for f in report.get("unresolved", [])) # type: ignore[union-attr]
- body = (
- "The merge train could not bring this branch up to date with `main`: "
- f"these files conflict and could not be resolved automatically.\n\n{files}\n\n"
- "Resolve locally with `python scripts/agent_land.py --pr` (it rebases, "
- "resolves generated files and lists what is left). The train retries on "
- "the next push to this branch."
- )
- if not dry_run:
- gh("pr", "comment", str(number), "--repo", repo, "--body", body)
- gh("pr", "edit", str(number), "--repo", repo, "--add-label", "needs-rebase")
- return "conflict - " + ", ".join(report.get("unresolved", [])) # type: ignore[arg-type]
- if dry_run:
- return f"would push update ({status})"
- push = git("push", "origin", f"HEAD:refs/heads/{branch}", check=False)
- if push.returncode != 0:
- return "update rejected (the branch moved); retry next tick"
- gh("pr", "edit", str(number), "--repo", repo, "--remove-label", "needs-rebase")
- ai = report.get("ai_resolved") or []
- if ai:
- listing = ", ".join(f"`{f}`" for f in ai) # type: ignore[union-attr]
- gh(
- "pr",
- "comment",
- str(number),
- "--repo",
- repo,
- "--body",
- f"Merge train: conflicts in {listing} were resolved by the configured AI "
- "resolver. CI re-runs on the result before anything lands; please skim them.",
- )
- # A GITHUB_TOKEN push parks the pull_request run in action_required; the
- # next tick approves it (a dispatched run would never reach the PR).
- return f"updated with main ({len(report.get('resolved', []))} conflicts auto-resolved)" # type: ignore[arg-type]
+def train(repo: str, max_updates: int, resolver_cmd: str, dry_run: bool, token_is_bot: bool) -> int:
+ """Every phase in one process (a local or manual run)."""
+ root = Path(tempfile.mkdtemp(prefix="merge-train-"))
+ try:
+ data = plan(repo, max_updates)
+ if integrate_merge(root, data) and resolver_cmd:
+ integrate_resolve(root, data, resolver_cmd)
+ integrate_finish(root, data)
+ return apply(root, data, dry_run, token_is_bot)
+ finally:
+ cleanup_worktrees(root)
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def _set_output(name: str, value: object) -> None:
+ target = os.environ.get("GITHUB_OUTPUT")
+ if target:
+ with open(target, "a", encoding="utf-8") as handle:
+ handle.write(f"{name}={value}\n")
+
+
+def _read_plan(root: Path) -> dict:
+ return json.loads((root / "plan.json").read_text(encoding="utf-8"))
def main(argv: list[str] | None = None) -> int:
@@ -627,6 +1033,21 @@ def main(argv: list[str] | None = None) -> int:
tr.add_argument("--resolver-cmd", default=os.environ.get("CONFLICT_RESOLVER_CMD", ""))
tr.add_argument("--dry-run", action="store_true")
tr.add_argument("--token-is-bot", action="store_true")
+ pl = sub.add_parser("plan")
+ pl.add_argument("--repo", required=True)
+ pl.add_argument("--dir", type=Path, required=True)
+ pl.add_argument("--max-updates", type=int, default=3)
+ for name in ("merge", "resolve", "finish"):
+ phase = sub.add_parser(name)
+ phase.add_argument("--dir", type=Path, required=True)
+ if name == "resolve":
+ phase.add_argument(
+ "--resolver-cmd", default=os.environ.get("CONFLICT_RESOLVER_CMD", "")
+ )
+ ap = sub.add_parser("apply")
+ ap.add_argument("--dir", type=Path, required=True)
+ ap.add_argument("--dry-run", action="store_true")
+ ap.add_argument("--token-is-bot", action="store_true")
args = parser.parse_args(argv)
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
@@ -635,7 +1056,29 @@ def main(argv: list[str] | None = None) -> int:
report = update(args.onto, args.mode, args.resolver_cmd)
print(json.dumps(report, indent=2))
return 0 if report["status"] != "conflict" else 2
- return train(args.repo, args.max_updates, args.resolver_cmd, args.dry_run, args.token_is_bot)
+ if args.cmd == "train":
+ return train(
+ args.repo, args.max_updates, args.resolver_cmd, args.dry_run, args.token_is_bot
+ )
+ if args.cmd == "plan":
+ data = plan(args.repo, args.max_updates)
+ args.dir.mkdir(parents=True, exist_ok=True)
+ (args.dir / "plan.json").write_text(json.dumps(data, indent=2), encoding="utf-8")
+ for entry in data["entries"]: # type: ignore[union-attr]
+ print(f"[train] #{entry['number']}: {entry['action']} ({entry['note']})")
+ _set_output("updates", len(_updates(data)))
+ return 0
+ data = _read_plan(args.dir)
+ if args.cmd == "merge":
+ _set_output("pending", integrate_merge(args.dir, data))
+ return 0
+ if args.cmd == "resolve":
+ integrate_resolve(args.dir, data, args.resolver_cmd)
+ return 0
+ if args.cmd == "finish":
+ integrate_finish(args.dir, data)
+ return 0
+ return apply(args.dir, data, args.dry_run, args.token_is_bot)
if __name__ == "__main__":
diff --git a/scripts/ci/required_results.py b/scripts/ci/required_results.py
index cd058faf1e..711c8f2f81 100644
--- a/scripts/ci/required_results.py
+++ b/scripts/ci/required_results.py
@@ -24,7 +24,7 @@ from typing import Any
# Jobs that only exist on some events: pull-request-only checks and manual
# soak runs. A strict run may skip these and nothing else.
-STRICT_SKIP_OK = frozenset({"pr-policy", "soak", "release-qualification"})
+STRICT_SKIP_OK = frozenset({"pr-policy", "dependency-review", "soak", "release-qualification"})
LANE_JOBS = {
"python": {"python-fast", "tests-linux", "tests-windows", "test-report"},
@@ -41,7 +41,7 @@ LANE_JOBS = {
def expected_jobs(outputs: dict[str, str]) -> set[str]:
"""Derive required evidence from detection, rather than trusting skipped jobs."""
- required = {"detect", "gates"}
+ required = {"detect", "gates", "zizmor"}
for lane, jobs in LANE_JOBS.items():
if outputs.get(lane) == "true":
required.update(jobs)
diff --git a/tests/unit/ci/test_pipeline_audit.py b/tests/unit/ci/test_pipeline_audit.py
index fc948ed229..7340684cb3 100644
--- a/tests/unit/ci/test_pipeline_audit.py
+++ b/tests/unit/ci/test_pipeline_audit.py
@@ -157,7 +157,7 @@ def pipeline_needs():
@pytest.mark.parametrize(
- "job", ["gates", "python-fast", "tests-macos", "frontend", "release-qualification"]
+ "job", ["gates", "zizmor", "python-fast", "tests-macos", "frontend", "release-qualification"]
)
@pytest.mark.parametrize("missing", [False, True])
def test_expected_lane_cannot_be_skipped_or_omitted(job, missing):
@@ -182,11 +182,44 @@ def test_unaffected_lanes_can_still_skip():
needs = {
"detect": {"result": "success", "outputs": flags},
"gates": {"result": "success"},
+ "zizmor": {"result": "success"},
"tests-macos": {"result": "skipped"},
}
assert required_results.evaluate(needs, pipeline=True)["ok"]
+def test_dependency_review_runs_only_on_pull_requests_and_may_skip_elsewhere():
+ ci = workflows()["ci.yml"]["jobs"]
+ assert ci["dependency-review"]["if"] == "github.event_name == 'pull_request'"
+ assert "if" not in ci["zizmor"] # the workflow audit runs on every event
+ needs = pipeline_needs()
+ needs["dependency-review"] = {"result": "skipped"}
+ assert required_results.evaluate(needs, pipeline=True, strict=True)["ok"]
+ needs["dependency-review"] = {"result": "failure"}
+ assert not required_results.evaluate(needs, pipeline=True)["ok"]
+
+
+def test_live_site_checks_run_only_nightly_and_never_fail_the_run():
+ job = workflows()["ci.yml"]["jobs"]["live-network"]
+ assert job["if"] == "github.event_name == 'schedule'"
+ live = next(s for s in job["steps"] if s.get("id") == "live")
+ assert live["continue-on-error"] is True
+ assert live["env"]["JARVIS_LIVE_NETWORK_TESTS"] == "1"
+ assert all(s.get("continue-on-error") for s in job["steps"] if "pytest" in s.get("run", ""))
+
+
+def test_merge_queue_runs_the_whole_suite_and_is_never_cancelled():
+ ci = workflows()["ci.yml"]
+ triggers = ci.get("on", ci.get(True))
+ assert triggers["merge_group"] == {"types": ["checks_requested"]}
+ assert "merge_group" in ci["concurrency"]["group"]
+ assert "merge_group" not in ci["concurrency"]["cancel-in-progress"]
+ mode = next(s for s in ci["jobs"]["detect"]["steps"] if s.get("id") == "mode")
+ assert "push|merge_group) tests_full=true" in mode["run"]
+ assert "merge_group.base_sha" in mode["env"]["PR_BASE"]
+ assert ci["jobs"]["gate"]["if"] == "${{ !cancelled() }}"
+
+
@pytest.mark.parametrize("payload", [{}, {"failed_ids": [], "counts": {}, "files": 0}])
def test_empty_test_evidence_fails_even_without_a_baseline(tmp_path, payload):
report = tmp_path / "report.json"
diff --git a/tests/unit/ci/test_pipeline_scripts.py b/tests/unit/ci/test_pipeline_scripts.py
index 71d9a07743..9edb7cdee8 100644
--- a/tests/unit/ci/test_pipeline_scripts.py
+++ b/tests/unit/ci/test_pipeline_scripts.py
@@ -4,8 +4,10 @@ impact selection, conflict resolution, release cut)."""
from __future__ import annotations
import json
+import shlex
import shutil
import subprocess
+import sys
from pathlib import Path
import pytest
@@ -489,6 +491,228 @@ def test_train_updates_only_conflicting_or_stale_red_branches():
assert decide("UNKNOWN", "approve", False) == "approve"
+def test_train_leaves_a_queued_pull_request_to_the_queue():
+ decide = agent_integrate.decide
+ assert decide("MERGEABLE", "success", True, queued=True) == "queued"
+ assert decide("CONFLICTING", "failure", True, queued=True) == "queued"
+
+
+def test_train_never_re_enqueues_a_head_the_queue_already_failed():
+ decide = agent_integrate.decide
+ # Behind main: a newer main may be the fix, so update and re-test.
+ assert decide("MERGEABLE", "success", True, queue_failed=True) == "update"
+ # Already contains main: re-adding it unchanged would fail the same way.
+ assert decide("MERGEABLE", "success", False, queue_failed=True) == "held"
+ assert decide("MERGEABLE", "success", False, queue_failed=False) == "merge"
+
+
+def _queue_run(number, conclusion, created, status="completed"):
+ return {
+ "event": "merge_group",
+ "head_branch": f"gh-readonly-queue/main/pr-{number}-{'b' * 40}",
+ "status": status,
+ "conclusion": conclusion,
+ "created_at": created,
+ }
+
+
+def test_queue_runs_are_mapped_to_their_pull_request():
+ runs = [
+ _queue_run(7, "failure", "2026-10-07T10:00:00Z"),
+ _queue_run(7, "success", "2026-10-07T11:00:00Z"),
+ _queue_run(9, "failure", "2026-10-07T09:00:00Z"),
+ {"event": "push", "head_branch": "main", "created_at": "2026-10-07T12:00:00Z"},
+ {"event": "merge_group", "head_branch": "gh-readonly-queue/main/odd"},
+ ]
+ newest = agent_integrate.queue_runs_by_pr(runs)
+ assert set(newest) == {7, 9}
+ assert newest[7]["conclusion"] == "success"
+
+
+def test_queue_failure_holds_only_until_a_newer_green_pull_request_run():
+ green = _run("pull_request", "completed", "success", "2026-10-07T10:00:00Z")
+ failed = _queue_run(5, "failure", "2026-10-07T10:30:00Z")
+ assert agent_integrate.queue_rejected(failed, [green])
+ newer = _run("pull_request", "completed", "success", "2026-10-07T11:00:00Z")
+ assert not agent_integrate.queue_rejected(failed, [green, newer])
+ # A cancelled or still-running queue run is not a verdict.
+ cancelled = _queue_run(5, "cancelled", "2026-10-07T10:30:00Z")
+ assert not agent_integrate.queue_rejected(cancelled, [green])
+ running = _queue_run(5, None, "2026-10-07T10:30:00Z", status="in_progress")
+ assert not agent_integrate.queue_rejected(running, [green])
+ assert not agent_integrate.queue_rejected(None, [green])
+
+
+class _FakeGh:
+ """Records gh calls instead of reaching GitHub."""
+
+ def __init__(self):
+ self.calls: list[tuple[str, ...]] = []
+
+ def __call__(self, *args: str) -> int:
+ self.calls.append(args)
+ return 0
+
+
+def _origin_with_feature(tmp_path, repo, main_edit, branch_edit):
+ _diverge(repo, main_edit, branch_edit)
+ origin = tmp_path / "origin.git"
+ _git(tmp_path, "clone", "-q", "--bare", str(repo), str(origin))
+ machines = []
+ for name in ("integrate", "apply"):
+ clone = tmp_path / name
+ _git(tmp_path, "clone", "-q", str(origin), str(clone))
+ _git(clone, "config", "user.email", "[email protected]")
+ _git(clone, "config", "user.name", "t")
+ _git(clone, "config", "core.autocrlf", "false")
+ machines.append(clone)
+ plan = {
+ "repo": "example/project",
+ "main": _git(origin, "rev-parse", "main").strip(),
+ "queue": True,
+ "entries": [
+ {
+ "number": 3,
+ "branch": "feature",
+ "head": _git(origin, "rev-parse", "feature").strip(),
+ "id": "PR_node",
+ "action": "update",
+ "run_id": None,
+ "note": "",
+ }
+ ],
+ }
+ return origin, machines[0], machines[1], plan
+
+
+def test_train_phases_update_a_branch_across_separate_machines(tmp_path, repo, monkeypatch):
+ origin, integrate, applier, plan = _origin_with_feature(
+ tmp_path,
+ repo,
+ {"CHANGELOG.md": "# Changelog\n\n- main entry\n- base\n"},
+ {"CHANGELOG.md": "# Changelog\n\n- branch entry\n- base\n"},
+ )
+ work = tmp_path / "train"
+ assert agent_integrate.integrate_merge(work, plan, integrate) == 0
+ agent_integrate.integrate_finish(work, plan)
+ agent_integrate.cleanup_worktrees(work, integrate)
+ state = json.loads((work / "state" / "pr-3.json").read_text(encoding="utf-8"))
+ assert state["status"] == "ready", state
+ assert state["resolved"] == ["CHANGELOG.md"]
+
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ outcome = agent_integrate.apply_update(work, plan, plan["entries"][0], False, applier)
+ assert outcome.startswith("updated with main"), outcome
+ pushed = _git(origin, "rev-parse", "feature").strip()
+ assert pushed == state["sha"]
+ changelog = _git(origin, "show", "feature:CHANGELOG.md")
+ assert "main entry" in changelog and "branch entry" in changelog
+ unlabel = ("pr", "edit", "3", "--repo", "example/project", "--remove-label", "needs-rebase")
+ assert unlabel in fake.calls
+
+
+def test_train_resolver_runs_between_merge_and_finish(tmp_path, repo, monkeypatch):
+ origin, integrate, applier, plan = _origin_with_feature(
+ tmp_path, repo, {"app.py": "VALUE = 2\n"}, {"app.py": "VALUE = 3\n"}
+ )
+ work = tmp_path / "train"
+ assert agent_integrate.integrate_merge(work, plan, integrate) == 1
+ resolver = tmp_path / "resolver.py"
+ resolver.write_text(
+ "from pathlib import Path\nPath('app.py').write_text('VALUE = 5\\n')\n", encoding="utf-8"
+ )
+ command = f"{shlex.quote(sys.executable)} {shlex.quote(str(resolver))}"
+ agent_integrate.integrate_resolve(work, plan, command)
+ agent_integrate.integrate_finish(work, plan)
+ agent_integrate.cleanup_worktrees(work, integrate)
+ state = json.loads((work / "state" / "pr-3.json").read_text(encoding="utf-8"))
+ assert state["status"] == "ready" and state["ai_resolved"] == ["app.py"], state
+
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ agent_integrate.apply_update(work, plan, plan["entries"][0], False, applier)
+ assert _git(origin, "show", "feature:app.py") == "VALUE = 5\n"
+ assert any(call[:2] == ("pr", "comment") for call in fake.calls)
+
+
+def test_train_reports_a_conflict_without_a_resolver(tmp_path, repo, monkeypatch):
+ origin, integrate, applier, plan = _origin_with_feature(
+ tmp_path, repo, {"app.py": "VALUE = 2\n"}, {"app.py": "VALUE = 3\n"}
+ )
+ head = plan["entries"][0]["head"]
+ work = tmp_path / "train"
+ assert agent_integrate.integrate_merge(work, plan, integrate) == 1
+ agent_integrate.integrate_finish(work, plan)
+ agent_integrate.cleanup_worktrees(work, integrate)
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ outcome = agent_integrate.apply_update(work, plan, plan["entries"][0], False, applier)
+ assert outcome == "conflict - app.py"
+ assert _git(origin, "rev-parse", "feature").strip() == head
+ label = ("pr", "edit", "3", "--repo", "example/project", "--add-label", "needs-rebase")
+ assert label in fake.calls
+
+
+def test_apply_rejects_a_bundle_not_built_on_the_planned_head(tmp_path, repo, monkeypatch):
+ origin, integrate, applier, plan = _origin_with_feature(
+ tmp_path,
+ repo,
+ {"CHANGELOG.md": "# Changelog\n\n- main entry\n- base\n"},
+ {"CHANGELOG.md": "# Changelog\n\n- branch entry\n- base\n"},
+ )
+ work = tmp_path / "train"
+ agent_integrate.integrate_merge(work, plan, integrate)
+ agent_integrate.integrate_finish(work, plan)
+ agent_integrate.cleanup_worktrees(work, integrate)
+ # A head the bundle does not build on (an unrelated commit in the applier).
+ _git(applier, "checkout", "-q", "--orphan", "elsewhere")
+ _git(applier, "commit", "-q", "--allow-empty", "-m", "unrelated")
+ forged = {**plan["entries"][0], "head": _git(applier, "rev-parse", "HEAD").strip()}
+ monkeypatch.setattr(agent_integrate, "gh", _FakeGh())
+ outcome = agent_integrate.apply_update(work, plan, forged, False, applier)
+ assert outcome.startswith("update bundle rejected"), outcome
+ assert _git(origin, "rev-parse", "feature").strip() == plan["entries"][0]["head"]
+
+
+def test_apply_enqueues_green_pull_requests_and_reports_the_rest(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ plan = {
+ "repo": "example/project",
+ "main": "m" * 40,
+ "queue": True,
+ "entries": [
+ {"number": 1, "branch": "claude/a", "head": "a" * 40, "id": "PR_a", "action": "merge"},
+ {"number": 2, "branch": "claude/b", "head": "b" * 40, "id": "PR_b", "action": "merge"},
+ {"number": 3, "branch": "claude/c", "head": "c" * 40, "id": "PR_c", "action": "queued"},
+ {"number": 4, "branch": "claude/d", "head": "d" * 40, "id": "PR_d", "action": "held"},
+ ],
+ }
+ assert agent_integrate.apply(tmp_path, plan, False, True) == 0
+ enqueued = [c for c in fake.calls if c[:2] == ("api", "graphql")]
+ assert len(enqueued) == 2 # a queue takes every green PR, not one per tick
+ assert "head=" + "a" * 40 in enqueued[0] and "id=PR_a" in enqueued[0]
+ assert not any(c[:2] == ("pr", "merge") or c[:2] == ("workflow", "run") for c in fake.calls)
+
+
+def test_apply_without_a_queue_merges_directly_and_pins_the_head(tmp_path, monkeypatch):
+ fake = _FakeGh()
+ monkeypatch.setattr(agent_integrate, "gh", fake)
+ plan = {
+ "repo": "example/project",
+ "main": "m" * 40,
+ "queue": False,
+ "entries": [
+ {"number": 1, "branch": "claude/a", "head": "a" * 40, "id": "PR_a", "action": "merge"}
+ ],
+ }
+ agent_integrate.apply(tmp_path, plan, False, True)
+ merge = next(c for c in fake.calls if c[:2] == ("pr", "merge"))
+ assert merge[-2:] == ("--match-head-commit", "a" * 40) and "--squash" in merge
+ assert ("workflow", "run", "ci.yml", "--ref", "main", "-f", "full=false") in fake.calls
+
+
# --------------------------------------------------------------------------- release