Skip to content

Local merge-train control

scripts/dev/merge_train_guard.py controls the local VMAFx queue. It accepts only open, same-repository PRs targeting master, excludes release PR #1213, and checks holds and worktree ownership before every mutation. It never edits an existing source checkout. The rationale is ADR-1244.

Inspect and configure

Use Python 3.10 or newer on POSIX, Git, authenticated GitHub CLI, and the existing full-gate toolchain. The installed gateway runs under the python3 its launcher finds, which needs PyYAML for the squash composer; check with python3 -c "import yaml". The installed GitHub CLI must support pr merge --match-head-commit and pr checks --required --json. GitHub requests name github.com/vidiko/vmafx explicitly. Both origin fetch and push URLs must identify only the canonical repository; multiple push destinations are refused.

Keep mutable operator state outside tracked source, normally in .claude/mergetrain/. A missing or malformed policy/hold file fails closed. Create policy.json with the current owners, for example:

{
  "schema": 1,
  "protected_branches": ["build/base-image-single-source", "build/version-single-source-tree"],
  "protected_worktrees": ["/home/kilian/dev/vmafx/vmafx/.claude/worktrees/agent-rc1-ffmpeg"]
}

hold.txt contains one PR number per line, optionally followed by a reason; blank lines and # comments are allowed. A PAUSED file blocks all remote mutations. Preserve current holds when creating the policy: the example is not a replacement for the live inventory.

python3 scripts/dev/merge_train_guard.py inspect 1421 \
  --repo-root /home/kilian/dev/vmafx/vmafx --state-dir /home/kilian/dev/vmafx/vmafx/.claude/mergetrain
python3 scripts/dev/merge_train_guard.py cycle \
  --repo-root /home/kilian/dev/vmafx/vmafx --state-dir /home/kilian/dev/vmafx/vmafx/.claude/mergetrain

inspect checks one candidate; cycle reports the open queue. Both are read-only without --apply. A refused candidate explains its hold, base, ownership, or missing metadata. Network errors and incomplete inventories never become an empty, apparently green queue. cycle refuses to act if an ineligible PR already has GitHub auto-merge enabled; its owner must disable that server-side state.

Fork pull requests

Train.guard and every merge-train action (inspect, cycle, promote, rebase, arm, merge) continue to refuse cross-repository pull requests. Under ADR-3610, a fork pull request may enter the master merge queue only after a read-only admit-fork check passes for the exact maintainer-reviewed head, followed by queue-audit after enqueueing.

Configure the optional fork_reviewers list in policy.json with the non-empty GitHub logins of maintainers whose approvals authorize fork admission (a non-list or empty-string login fails closed with invalid train policy: fork_reviewers; an absent or empty list refuses admit-fork):

{
  "schema": 1,
  "protected_branches": ["build/base-image-single-source"],
  "protected_worktrees": ["/home/kilian/dev/vmafx/vmafx/.claude/worktrees/agent-rc1-ffmpeg"],
  "fork_reviewers": ["lusoris"]
}

Run admit-fork before enqueueing a fork pull request, and queue-audit after enqueueing it:

python3 scripts/dev/merge_train_guard.py admit-fork 1500 \
  --reviewed-head 0123456789abcdef0123456789abcdef01234567 \
  --repo-root /home/kilian/dev/vmafx/vmafx --state-dir /home/kilian/dev/vmafx/vmafx/.claude/mergetrain

python3 scripts/dev/merge_train_guard.py queue-audit \
  --repo-root /home/kilian/dev/vmafx/vmafx --state-dir /home/kilian/dev/vmafx/vmafx/.claude/mergetrain
  • admit-fork NUMBER --reviewed-head SHA is read-only, runs outside mutation.lock, and refuses --apply (exit 1). It verifies that SHA is a 40-character lowercase hex OID, the train is neither paused nor holding NUMBER (including release PR #1213), the pull request is OPEN against master with isDraft == false and isCrossRepository == true, live headRefOid equals SHA, mergeStateStatus is CLEAN, GitHub auto-merge is not enabled on the pull request (autoMergeRequest is null), no hardware lane switch is enabled (SYCL_ARC_RUNNER_ENABLED and GPU_COVERAGE_ENABLED set to true, read from the repository variables and from the organisation variables shared with the repository; a repository variable overrides an organisation variable of the same name, as in the workflow vars context), at least one login in fork_reviewers has its latest decisive review (APPROVED, CHANGES_REQUESTED, DISMISSED; COMMENTED and PENDING ignored) as APPROVED on commit.oid == SHA while none has CHANGES_REQUESTED, required checks pass, and the squash commit message check passes with unchanged head, title, and body. A final read after the squash message check repeats the open-against-master, pause, hold, queue eligibility, maintainer approval, and required check gates using the refreshed policy. It prints a JSON receipt (number, head, reviewer, submitted_at, merge_state, checks) and exits 0 when eligible, or prints merge-train: refused: ... and exits 1.
  • Immediately before enqueueing, confirm gh pr view NUMBER --json headRefOid reports the reviewed SHA, then run gh pr checks NUMBER --required --json name,bucket. Require a nonempty list that includes Required Checks Aggregator, with every bucket equal to pass. Check the head again after reading the results. Stop if the head differs from SHA or any required result is missing or does not pass.
  • Enqueue with gh pr merge NUMBER --squash --match-head-commit SHA, without --auto. GitHub CLI can still enable auto-merge if required checks have not passed. Immediately after the enqueue attempt, run gh pr view NUMBER --json autoMergeRequest. Continue to queue-audit only after confirming autoMergeRequest is null. If there is a pending request, stop and have its owner disable auto-merge before retrying admission.
  • queue-audit takes no PR number, refuses --apply (exit 1), and queries mergeQueue(branch: "master") on vidiko/vmafx via gh api graphql. In-repository queue entries are skipped. Each cross-repository entry must satisfy the same fork_reviewers approval rule on its live headRefOid; the entry headCommit is the squash commit GitHub builds, never the pull request head, so the audit does not request it. When clean, it prints queue audit: 0 problems and exits 0; when any cross-repository entry fails, it prints one problem per line and exits 1, and the operator removes the failing entry from the merge queue immediately.

Ownership and promotion

A checked-out head branch belongs to its existing owner, even if clean. A detached agent-* checkout at the same head is also protected. List additional detached human checkouts in protected_worktrees. The operator must finish its own work and explicitly hand off ownership; creating fake PID locks or deleting another actor's checkout is not a handoff. See worktree discipline.

rebase NUMBER --apply creates a unique detached checkout under STATE/worktrees/pr-NUMBER-*/checkout, rebases onto fetched master, and pushes with a lease bound to the observed PR head. Conflicts, rejected pushes, changed PR metadata, dirty source, and cleanup failures stop that action. The failed checkout and owner.json are retained for the owner to inspect. Only a successful, clean checkout created by this invocation is removed, using non-force Git. An existing retained checkout blocks another rebase of that PR until its owner reviews and hands it off; polling does not create repeated failed worktrees.

promote NUMBER --apply performs that same rebase first, reads the resulting remote head back, then marks the PR ready. Failure never marks it ready or arms auto-merge. Promotion does not arm a PR; the resulting head needs validation.

Full local validation and merging

Validation is an explicit owner action. It may run while held or paused, because it does not mutate GitHub. Supply the exact, clean source checkout and an output state directory shared with the guarded operator:

python3 scripts/dev/merge_train_guard.py validate 1422 \
  --repo-root /home/kilian/dev/vmafx/vmafx --state-dir /home/kilian/dev/vmafx/vmafx/.claude/mergetrain \
  --checkout /path/to/explicit-validation-checkout --apply

The runner executes full make lint and make test, in that order, and records both logs. It rejects tracked or untracked source changes before/between/after the commands, ignored Makefile shadowing, and head changes. Inherited Git redirection and GNU Make recipe/dry-run overrides are removed. A failed repeat run archives the older receipt rather than leaving that old pass usable.

The validation example assumes #1422 targets master. A stacked PR such as #1421 must first be rebased/retargeted by its owner; validation refuses a non-master base.

Success creates validated-HEAD.json, with command/log hashes and an HMAC from a private local validation-key. This is an attestation by the local runner, not third-party build provenance or proof against an operator who controls the key and executable toolchain. Handwritten pass booleans, edited receipts, changed logs, other heads, and receipts from a different gateway version are refused. Retain the state directory, logs, key permissions, and source/toolchain provenance together; do not copy an unsigned assertion into a receipt file.

After the source owner has handed off, merge NUMBER --apply requires the exact-head receipt and a nonempty required-check list containing a passing Required Checks Aggregator. Every required check must pass. Pending, skipped, cancelled, failed, or absent checks block both merge and arm; GitHub CLI exit 8 (pending) is deliberately a refusal. arm NUMBER --apply applies the same strict gates before requesting GitHub auto-merge. Both use --match-head-commit, never admin bypass or branch deletion.

Both merge and arm compose the squash commit message using scripts/ci/squash_message.py (Train.merge in scripts/dev/merge_train_guard.py). Before merging, they invoke its check_message against the pinned engine (.config/lefthook/engine.sh, forge check-message); any validation failure aborts with squash message check failed: <engine output>. The composer formats line 1 as the trimmed pull request title and parenthesised PR number, while the commit body retains any breaking-change and migration footers (BREAKING CHANGE:, BREAKING-CHANGE:, or Migration:) followed by the Signed-off-by trailer of LANDING_IDENTITY. A footer is kept only when its line starts in column zero with one of those prefixes and a non-blank value (FOOTER_RE); continuation lines below it are dropped, so write each migration step as its own footer line. More than 20 footer lines (MAX_FOOTER_LINES) or a body above 65,537 lines make the composer raise an error instead of truncating the message. The DCO Sign-off job in CI runs the same check on every pull request except release pull requests.

Prefer merge in the automatic loop: future local holds cannot stop auto-merge already stored on GitHub. When imposing a hold on an armed PR, also disable its server auto-merge explicitly. GitHub remains responsible for branch protection after the final local check; local advisory locking cannot serialize unrelated GitHub writers or arbitrary Git/editor mutations.

cycle --apply --window 3 performs one bounded pass: merge or rebase eligible ready PRs, then promote at most one draft when the ready window has room. It uses ascending PR number within drafts and never launches a repair agent. A rebased head waits for a fresh full validation receipt. Repair work is an explicit isolated-owner handoff, outside the automated queue.

Migrate a running local train

The tracked gateway does not patch, restart, or stop existing services. Before enabling it, review the exact watchdog/train/operator process identities and retain their commands, start times, scripts, and hold state as evidence. Stop all legacy actors that can invoke raw gh pr ready, gh pr merge, or Git rebases. Retire an old unrestricted agent process; do not resume its in-memory prompt.

Keep PAUSED present while deploying a reviewed, committed gateway to a stable source checkout. The reproducible installer previews its exact source hash, existing file hashes, preserved holds, and merged protected-owner policy:

python3 scripts/dev/install_merge_train_guard.py \
  --repo-root /home/kilian/dev/vmafx/vmafx --state-dir /home/kilian/dev/vmafx/vmafx/.claude/mergetrain \
  --protect-branch build/base-image-single-source \
  --protect-branch build/version-single-source-tree \
  --protect-worktree /home/kilian/dev/vmafx/vmafx/.claude/worktrees/agent-rc1-ffmpeg

After reviewing the JSON plan, repeat the same command with --apply --expect-plan THE_PRINTED_SHA256. Any changed runtime target, gateway, composer or library source requires a new preview. The helper backs up originals and modes into a fresh migration-*/ directory with plan.json and receipt.json, copies the committed runtime files to releases/RELEASE_NAME/, and leaves PAUSED present. The preview records gateway_sha256, composer_sha256 and a sorted library_sha256 map from repository-relative library paths to SHA-256 digests. RELEASE_NAME hashes the canonical JSON of those three fields (sorted keys, compact separators), so a library-only change also installs into a new directory and leaves the old release intact. Installation rechecks library bytes against the preview before changing runtime state. It preserves existing hold text and unions new protected owners into the existing policy. A failure preserves the backups and pause; do not start an incomplete migration.

The release directory contains the gateway (merge_train_guard.py), the squash message composer (squash_message.py), and its imported libraries under scripts/lib/, all installed read-only (0o444). The installer walks the committed gateway's Python AST for absolute scripts.lib imports, follows their library dependencies, and includes package initializers; scripts/lib/__init__.py ships even when the gateway imports no library. Every source must match its committed blob at the preview's source_commit.

The preview refuses three import forms that the release could not satisfy, so they fail at plan time instead of as an ImportError once the train runs:

  • a relative import (from . import helper, from .module import name) in the gateway or any library it reaches;
  • a scripts.* import outside scripts.lib, such as scripts.ci or scripts.dev;
  • a dynamic __import__ or import_module call, bare or attribute-qualified, in the gateway or any library it reaches.

The refusals read:

relative import in scripts/lib/MODULE.py:LINE; use an absolute scripts.lib import
scripts/lib/MODULE.py imports scripts.ci outside scripts.lib; the release ships only scripts.lib
dynamic import in scripts/lib/MODULE.py:LINE; the release ships static scripts.lib imports only

The gateway's importlib.util.spec_from_file_location path loader remains accepted: it loads the separately shipped, hash-checked squash message composer.

Every generated launcher verifies all runtime hashes before executing the gateway. A changed or missing library refuses with refused: installed library hash changed: scripts/lib/MODULE.py. Launchers remove the caller's working directory and adapter directory from Python's import path, put the release first, and bind the scripts package to that release only. Every adapter starts Python in -I isolated mode, which Python 3.10 supports: the shell adapters run python3 -I, and the operator adapter's shebang is #!/usr/bin/env -S python3 -I. The flag has to be there at start-up, because Python imports site hooks such as sitecustomize.py while it initialises, before the first line of the script runs. When someone runs the operator as python3 merge_train_operator.py, it re-executes itself with -I before it imports anything else, but site hooks have already run by then; run it directly. Isolated mode also ignores PYTHONPATH, other PYTHON* variables and user site packages. Adapters therefore work outside a checkout and ignore a planted scripts package, standard-library module or sitecustomize.py in the caller's directory, the state directory or PYTHONPATH. The gateway's repository copy continues to import from the repository root; composer loading still uses the file beside the installed gateway.

The helper never kills or launches a process. It installs this mapping:

Legacy entry Replacement
train.sh One read-only cycle; mutations require explicit --apply
rebase-clean.sh Explicit rebase NUMBER --apply; no implicit global sweep
merge_train_operator.py Retired mutation operator; use cycle for inspection
watchdog.sh Observe the read-only cycle every 60 seconds; mutation arguments refused

Add the active session's exact branch/worktree owners to policy.json, preserve all holds, and independently confirm that held/non-master PRs have no pending server auto-merge. Run read-only inspection and the regression command below. Review the replacement scripts, backup receipt, and source hash before starting the fresh read-only observer. Keep PAUSED until promotion/merge is explicitly authorized and the required full-gate evidence exists. Replacing a file underneath a running process does not update that process's policy. A commit landing alone does not complete this runtime migration.

python3 -m unittest discover -s scripts/dev/tests -p 'test_*merge_train_guard.py'

The regressions use disposable Git repositories and Makefiles, with fixture GitHub responses. They verify control behavior; they do not constitute full VMAFx native, backend, golden-data, make lint, or make test acceptance.