Default config file name:
.mergetrain.yaml
mergetrain init writes only the policy a new project must choose:
version: 2
project:
name: example-app
gates: []Add at least one meaningful gate before production deployment. Everything else
on this page is optional. Omitted values use safe code defaults: origin,
main, local .mergetrain/ state, sequential gates, ephemeral validation,
no notifications, no reuse, and no verify hooks.
PyYAML is a required dependency, and mergetrain always uses safe_load for
.mergetrain.yaml. Existing block-style files remain unchanged, while standard
flow-style collections such as [main, release] and {name: tests} now work
consistently on every installation. Legacy YAML booleans (yes, no, on,
off), prefixed or leading-zero integers (0x1F, 010, 0_600), base-60
integers (1:30), and tab indentation are rejected so operator policy cannot
change meaning through implicit scalar conversion. So is a key repeated in one
mapping, such as a second run: in a gate, which the parser would otherwise
let replace the first.
Invalid mapping, list, string, boolean, path, and positive-integer values also
fail closed during typed config validation.
YAML remains the primary format to preserve committed project configuration and
the existing init/documentation contract. Moving new files to TOML would not
remove YAML loading for existing repositories, and Python 3.10 would require a
second parser dependency because tomllib arrived in Python 3.11. Requiring one
standards-based YAML implementation removes the custom-parser burden without
introducing dual-format discovery, precedence, or migration rules.
version: 2The config schema version. mergetrain init writes the current version (2);
an omitted version: is treated as version 1 and migrated in memory. Version-1
files may still contain the removed no-op agent block or presentation-only
terminology block; both are ignored during migration. A version-2 file that
declares either removed key is rejected so stale policy cannot appear active.
A file whose version: is newer
than this binary understands is recorded — not rejected — at load, so recovery
still works on an older binary. Command-scoped enforcement surfaces the mismatch
instead: status --diagnose reports the supported version and a next_action
of upgrade_mergetrain. Upgrade
mergetrain before deploying.
project:
name: example-appproject.name is used in JSON output and temporary worktree names.
state:
db: .mergetrain/queue.sqlite
logs: .mergetrain/logs
worktree_root: .mergetrain/worktrees
validation_workspace:
mode: ephemeral
cache_key: ""
cache_paths: []Relative runtime-state paths are resolved from one shared control root. In a
standard Git linked worktree, mergetrain follows Git's .git/commondir
metadata to the control checkout, so the control checkout and all task
worktrees use the same queue DB, logs, runner lock, and integration-worktree
directory. The configuration is read from the control checkout's
.mergetrain.yaml too, unless --config names another file, and
init --write writes the file that is read. A task branch's own copy,
committed or not, never becomes the policy for the shared queue: a
configuration change takes effect once it has landed and the control checkout
has it.
Run from a subdirectory of a configured checkout, mergetrain uses the top of
that checkout, so status there reports the real queue and init --write
refuses to start a second one. A directory with its own .git or
.mergetrain.yaml is used as given, and so is a directory inside a checkout
that has no mergetrain configuration. In an ordinary checkout, a non-Git directory, a submodule, or
malformed/nonstandard worktree metadata, mergetrain keeps the historical
repository-root resolution. Absolute paths remain unchanged, and a relative
global --db override remains relative to the explicitly selected --repo.
validation_workspace.cache_paths are different: they name directories inside
the validation checkout and therefore remain normalized repository-relative
paths rather than runtime-state locations.
Validation worktrees are disposable by default. Projects with path-sensitive generated caches may opt into one runner-owned stable validation path:
state:
validation_workspace:
mode: persistent
cache_key: unity-library-v1
cache_paths:
- unity/Teratorn/LibraryPersistent mode derives
{worktree_root}/{project.name}-validation-workspace; it does not accept an
arbitrary path. Only validate runs use that path. Deploy reassembly and bisect
probes remain in isolated, disposable worktrees, and the existing runner lock
serializes all access.
Each cache_paths entry must name a normalized, repository-relative directory
that is ignored by Git and contains no tracked files. Globs, absolute paths,
backslashes, .git, and ./.. segments are rejected. Before every validation,
mergetrain hard-resets tracked inputs to the fetched integration ref and removes
all ignored and untracked content except those declared directories. A symlink,
foreign worktree, tracked cache path, non-ignored cache path, or workspace that
cannot be restored cleanly blocks validation. So does a workspace directory that
is not itself a registered linked worktree of the repository, such as one a
failed cleanup left behind without its .git: Git would otherwise run the reset
in the checkout that contains it. Move such a directory aside or delete it.
The cache is retained only while cache_key, the gate/fingerprint policy, and
the configured environment fingerprint outputs match its marker. Change
cache_key whenever the build cache schema or an un-fingerprinted toolchain
changes. Marker corruption or an identity mismatch clears only the declared
cache directories before gates run. Gate tree-integrity checks, SHA-pinned train
identity, and push behavior are unchanged; generated cache files are never added
or pushed by mergetrain.
status --diagnose --json reports the mode, derived path, existence, initialization state,
key, and declared cache paths. gc protects the workspace while persistent mode
is configured. To remove it, switch back to mode: ephemeral, inspect
gc --json, then explicitly run gc --apply.
Keep ephemeral mode unless measurements show that a project-local cold build is the dominant gate cost. The efficient-operation guide explains the cache decision, rollout measurements, and project-specific tradeoffs.
git:
remote: origin
integration_branch: main
push_refs:
- mainintegration_ref is derived as:
{remote}/{integration_branch}
That short name is what status output and the ${integration_ref} placeholder
show. mergetrain itself resolves the integration base through the full
remote-tracking ref, refs/remotes/{remote}/{integration_branch}, because Git
resolves a short name to a tag or local branch called origin/main before the
remote-tracking ref. A gate that hands ${integration_ref} to Git keeps that
short-name lookup; write refs/remotes/${integration_ref} where a gate must not
be redirected.
remote names the fetch remote used to assemble the train. Before approval,
mergetrain separately resolves its effective push endpoint with
git remote get-url --push --all from the control checkout. A split setup such
as origin.url = fetch-A plus origin.pushurl = push-B is supported and binds
approval to push-B. Exactly one effective push URL is required: multiple
pushurl values fail closed because they cannot be one remote atomic
transaction.
Relative filesystem push URLs (for example ../remote.git) are rejected;
their meaning changes with the integration worktree's current directory. Use
an absolute path or a file:// URL. Absolute local paths and local file URLs
are resolved to their canonical target before approval, so changing a symlink
later cannot redirect the push. Network URLs and Git's SCP-like SSH form remain
supported.
Deploy mode pushes the verified commit and its content-addressed recovery audit ref atomically:
git push --atomic origin \
<sha>:main \
<sha>:refs/mergetrain/deploys/<sha>Multiple refs are allowed:
git:
remote: platform
integration_branch: develop
push_refs:
- develop
- mainThis produces:
git push --atomic platform \
<sha>:develop \
<sha>:main \
<sha>:refs/mergetrain/deploys/<sha>The actual command also protects the audit ref with --force-with-lease so it
can only be created or retain the identical value, and passes
--no-follow-tags --recurse-submodules=no so push.followTags,
push.recurseSubmodules, and submodule.recurse cannot add a tag or another
repository's commits to the push. The configured remote must
permit creation under refs/mergetrain/deploys/; these refs are permanent
recovery evidence and are not payload targets configurable through
push_refs.
Approval summary, destination hash, audit lookup, pending marker, atomic push, and reconcile all use the same resolved push endpoint identity. The live raw URL is held only in memory and supplied to Git through a fresh random sentinel and transient remote alias; endpoint-matching URL rewrite rules are not re-applied. Credentials are not written to the queue database or command line. If the endpoint changes after gates or after an ambiguous push, mergetrain blocks instead of consulting a different repository.
If push_refs is omitted it defaults to integration_branch. An explicitly
empty list, null value, blank ref, or duplicate ref is a configuration error;
deploy targets never fail open to main.
queue:
lock_ttl_minutes: 30
daemon_interval_seconds: 15
heartbeat_interval_seconds: 10
command_timeout_seconds: 3600lock_ttl_minutes controls runner lock expiry. Managed Git, gate, and verify
commands renew the lease every heartbeat_interval_seconds, and right after
the machine wakes from sleep; the heartbeat must be shorter than the TTL.
command_timeout_seconds terminates a command and marks the affected job
failed. All queue timing values must be positive.
processing is a repository-wide setting. Keep the default batch for
ordinary parallel agent work. It combines eligible queued jobs available
when a runner claims work and does not wait for other agents to finish.
For example, a login fix, a search filter, and an admin-screen change can share
checks. If one fails, compatible work can land after failure isolation and
checks on the remaining combination. A repaired job joins the back on retry.
Choose ordered only when each submission needs a separate landing and must
keep its original position through repair. For example, compiler agents can
measure each optimization against the preceding landed result. If the middle
submission fails, later landings wait for its repair or explicit cancellation.
See the agent work examples.
Release availability: ordered requires 3.6.0 or newer. Keep the default
batch for ordinary parallel work and follow the upgrade procedure
before enabling ordered processing.
To select ordered processing in a version that supports it:
queue:
processing: orderedordered admits only the earliest submission not yet landed, including its
replacement after retry. A blocked/failed head and a manual head waiting for
approval hold later work. A successful Git push completes that position.
Post-push verification failures or unknown results remain in Attention and
history while later submissions can land, as in batch mode. An uncertain push
still blocks progress until reconciliation determines what landed.
Cancellation or dismissal explicitly resolves a position. Task agents can
continue submitting finished work; they use the same commands and MCP tools.
This can increase gate/verify runs compared with batching. It provides no
dependency scheduling or reservation before work starts.
Before changing processing, finish in-flight work and deploy or dismiss any Ready train. The change is part of execution-policy approval; existing auto jobs from the other policy block rather than silently gaining new behavior. Follow the upgrade procedure when older runners are installed.
notify:
webhook_url: "https://notify.example.invalid/hook/secret-token"
transitions:
- landed
- blocked
- needs_reconcile
- daemon_paused
timeout_seconds: 10daemon --notify and hub daemon --notify send transition-deduplicated
notifications through the provider-neutral JSON webhook. The webhook receives an HTTP POST with
{"title":"...","message":"..."} and Content-Type: application/json.
Slack/Discord-specific message shaping belongs in an adapter or relay; core does
not embed provider credentials or schemas.
When a delivery fails, a landing or a batch that did not land is sent again by later ticks until it is delivered (at most the newest 20 wait), and a reconcile or error pause is sent again while it lasts.
If --notify is supplied without webhook_url, the single-repo daemon warns at
startup and Hub warns once per affected repository when a transition needs
delivery. This avoids treating --notify without a webhook as a successful
headless notification.
For webhook delivery, transitions selects landed,
blocked/partial, needs_reconcile, and daemon error/pause messages. A disabled
transition is recorded as settled so enabling it later does not replay old
history. timeout_seconds must be positive, and the URL must use HTTP(S).
The webhook is sent without HTTP authentication, so a URL with
user:password@ before the host is rejected; put a token the endpoint expects
in its path or query instead. Treat webhook_url as a secret: diagnostic config JSON reports only
webhook_configured, never the URL. Delivery errors likewise omit the
credential-bearing URL, and a YAML syntax error names the line and column of
the problem without quoting the text there.
mergetrain reads webhook_url only from this file; there is no environment
variable for it. .mergetrain.yaml is normally committed, so everyone who can
read the repository can read the URL and post to the webhook. When that is
wider than the webhook's audience, point webhook_url at a relay you control,
such as one on the runner host, that holds the provider's credentials. See
Secrets.
gate_parallelism:
# The default is 1, which preserves strictly sequential execution.
max_workers: 4
# Optional wall-clock ceiling for the complete configured gate plan.
timeout_seconds: 1800
gates:
- name: tests
run: python -m unittest discover -s tests
paths:
- src/**
- tests/**
- pyproject.toml
- name: deploy-policy
run: ./scripts/check-deploy-policy
always_rerun_on_deploy: true
- name: ruff
run: ruff check .
parallel_group: quality
needs:
- tests
workers: 1
timeout_seconds: 120
- name: mypy
run: mypy
parallel_group: quality
needs:
- tests
workers: 2Gates run before push in the temporary integration worktree. The optional
always_rerun_on_deploy flag matters only when validated-gate reuse is accepted;
that gate still runs against the exact restored validation commit.
mergetrain always runs one built-in diff-check before configured gates. Older
generated configs may still contain the same gate explicitly; that exact
default is ignored at runtime and status --diagnose recommends removing it. A customized
gate is never discarded merely because it uses the same name.
An optional paths list runs a gate only when the train changes a path that
can affect it; see gates[].paths.
Configured gates remain sequential unless they share the same non-empty,
contiguous parallel_group. gate_parallelism.max_workers is a resource-token
ceiling: a running gate consumes its positive workers value, and mergetrain
starts only a set whose total fits the ceiling. The weight describes the
command's expected CPU/worker cost; it does not rewrite an internal flag such as
pytest -n, so keep the declared weight consistent with the command.
Omitted needs preserves declaration order. A contiguous parallel group
defaults to the complete preceding stage; the following gate waits for every
member of that group. An explicit non-empty needs list may name only the
built-in diff-check or earlier configured gates. Group names cannot be
reopened later in the list, which makes the dependency graph acyclic and
unambiguous at load time.
timeout_seconds on a gate overrides queue.command_timeout_seconds for that
gate. gate_parallelism.timeout_seconds optionally bounds the whole configured
gate plan. The built-in integrity diff-check always completes before any
parallel group. If one parallel gate fails, times out, or the train is canceled,
mergetrain terminates every peer subprocess group. Per-gate logs and terminal
events are then committed in declaration order, so concurrent completion cannot
make JSON or logs nondeterministic. The same POSIX-shell resolution and process
tree cleanup apply on Linux, macOS, and Git for Windows. On Windows each command
runs in a Job Object, so cleanup also reaches descendants whose parent already
exited, such as the processes that MSYS programs re-parent.
Every run string is executed by a POSIX sh, on every platform — mergetrain
never falls back to cmd.exe. On Windows it uses sh from PATH or the one Git
for Windows ships (sh.exe under the Git installation), and refuses to run gates
at all when no POSIX shell can be found, rather than running them under a shell
with different quoting rules. So one gate command works everywhere: write POSIX
shell syntax, not cmd syntax, and expect POSIX quoting and expansion.
A non-empty paths list runs a top-level pre-push gate only when the train
changes a listed path. Use it to keep a heavy suite off trains that cannot
break it:
gates:
- name: unit
run: python -B -m pytest -q -p no:cacheprovider tests/unit
- name: render
run: python -B -m pytest -q -p no:cacheprovider -n 4 tests/render
paths:
- src/example_app/render/**
- tests/render/**
- tests/conftest.py
- pyproject.tomlunit runs for every train. render runs only when a train changes the
renderer, its tests, the shared pytest configuration in tests/conftest.py, or
pyproject.toml, which holds the dependencies and pytest settings. A
documentation-only train skips it. List every input that can change the
gate's result: shared code it imports, fixtures, build scripts, manifests,
lockfiles, and generated inputs. Leave cross-cutting security, policy, and
repository-integrity checks unscoped.
Matching. mergetrain computes the changed paths once per train, from the
captured integration-base commit to the exact assembled train commit. A scoped
gate runs when any changed path matches any pattern, so in a batch one member's
change runs the gate for the whole train. Rename and copy records include both
the old and the new path: moving a file out of src/example_app/render/ still
runs render. Deletions count too. A gate without a match records a
skipped gate event, no changed paths matched configured paths, and keeps
its normal gate index. Gates without paths always run, as does the built-in
diff-check.
Fail closed. If Git cannot produce the path set or mergetrain cannot parse it, every scoped gate runs. A path-selection failure can therefore cost time but can never silently weaken validation.
Patterns. Patterns are repository-relative POSIX globs on every platform.
*, ?, and character classes match within one path segment; a segment
containing only ** matches zero or more complete segments. A class that
starts with ! or ^, such as [!_] or [^_], is negated, as in Git and the
shells. Absolute paths, ./.. segments, backslashes, empty segments,
duplicate patterns, and ** embedded inside another segment are rejected.
paths is supported only for top-level pre-push gates, not deploy.verify
or reuse fingerprints.
Policy. paths is part of the gate policy that the control checkout's
configuration supplies, so a change takes effect once it has landed there. It is
also part of the execution policy that unattended approval binds: changing it
blocks queued --auto jobs, as described in
Deploy authorization changed.
The one-laptop guide combines
this gate with parallel quick checks.
deploy:
reuse:
enabled: false
max_age_minutes: 60
on_mismatch: rerun # rerun | fail
fingerprints:
- name: toolchain
run: ./scripts/toolchain-fingerprintValidated-gate reuse is opt-in. Set enabled: true for configuration-level
authorization. There is no per-deploy reuse switch in v3.
Reuse requires the recorded integration base, task heads, train membership,
validation commit/tree, gate policy, environment fingerprints, and validation
age to match. on_mismatch: rerun performs the normal full reassembly and gate
run; fail blocks before push. The default remains full gate rerun.
deploy --json and hub status --json expose the same
structured reuse explanation: authorization, exact identity checks and mismatch
facts, the action for each gate (reuse, rerun, skip, or a conditional
preview state), and estimated_savings. Savings use up to 20 successful timing
samples per gate and report sample count, history coverage, and confidence.
They are an advisory sum of per-gate medians, not a promise of wall-clock time;
estimated_savings.authorizes_reuse is always false. Only the committed reuse
policy, followed by a matching exact identity check, can authorize reuse.
always_rerun_on_deploy, path-scoped skips, and fail-closed path
discovery are represented separately rather than counted as reused work.
Each fingerprint command must print one stable, opaque, non-empty line of at
most 512 characters. mergetrain hashes the values instead of storing them.
Adapters can use these commands to identify a compiler, SDK, container image,
or other environment-sensitive input. Post-push deploy.verify hooks always
run, including after gate reuse.
deploy:
verify:
- name: live-health
run: curl -fsS https://example.invalid/healthVerify hooks run after push. A verify failure means the remote ref was already
updated, so mergetrain keeps status=deployed while recording
push_status=succeeded, verify_status=failed, and a warning note. Runs with no
hooks record verify_status=not_configured; configured hooks that all pass record
verify_status=succeeded. A later verify --job re-run is allowed only while
the current hook policy matches the identity recorded at deployment, and it
updates that deployment's train members together. Removing or changing hooks
requires explicit --ack succeeded|failed; an empty current list is never an
implicit successful verification.
Placeholders available in gates, deploy.reuse.fingerprints, and
deploy.verify:
${integration_ref}
${project}
${repo}
${worktree}
${repo} and ${worktree} are escaped for their surrounding shell quote
context, so each expands to exactly one path argument even when the path contains
spaces or shell metacharacters. They may be used unquoted, inside matching single
or double quotes, in # comments, and inside $(...). mergetrain reads the
command the way /bin/sh does, so a quote character inside a comment does not
change how a later placeholder is escaped.
Some places have no escaping mergetrain can prove correct: backquotes, ${...},
$((...)), and $'...'. The same holds for everything after a construct that
shells parse differently: a here-document or here-string (<<, <<<, and a
bash arithmetic shift look alike), bash $[...] arithmetic or a name[...]
array subscript, a comment or case statement inside $(...), or $$(,
$${, or $$[ inside double quotes, where bash's parser opens a $(, ${,
or $[ that other shells read as the process ID and text. A path made only of letters, digits, and _@%+=:,./- needs no
escaping and expands there as-is. Any other path fails the gate with an error
before the command runs; use "$MERGETRAIN_REPO" or "$MERGETRAIN_WORKTREE" in
those places instead. A verify hook with this problem blocks the deploy before
the push.
That escaping is POSIX, on every platform, because the shell always is —
including for Windows paths, whose backslashes survive the expansion. A gate that
embeds a path inside a Python string literal is a separate concern: python -c "...'${worktree}'..." would read C:\Users as an escape sequence, so pass such
paths as arguments (python script.py "${worktree}") or read them from
MERGETRAIN_WORKTREE instead.
Equivalent environment variables:
MERGETRAIN_PROJECT
MERGETRAIN_INTEGRATION_REF
MERGETRAIN_REPO
MERGETRAIN_RUNNER_PYTHON
MERGETRAIN_WORKTREE
mergetrain prepends the directory containing MERGETRAIN_RUNNER_PYTHON to
PATH for gates, reuse fingerprints, and verify hooks. Invoking mergetrain
through a virtualenv or pipx interpreter therefore makes sibling tools such as
ruff, mypy, and versioned Python launchers available without activating that
environment in the parent shell. Existing PATH entries retain their order
after the runner's tool directory.
Commands are executed through /bin/sh; treat config files as trusted code.