# Factory files The factory is a directory of plain files on the control plane, normally `factory/` beside `config.yaml`, in the same git repository. It is read at startup and reloaded on demand with `machinist reload` — a restart is no longer needed after changing pipelines, agents, prompts, scripts, automations, or reloadable `config.yaml` settings. An invalid factory stops startup, or during `machinist reload` leaves the running control plane unchanged and reports the problem. Runs already queued or running keep the job they started with. Only `server.listen`, `server.public_url`, `server.trusted_proxy_hops`, `server.database`, `server.tls_cert`, `server.tls_key`, `auth.*`, and `notify.webhook` in `config.yaml` (plus process environment variables such as `GH_TOKEN` and `LINEAR_*`) still need a control plane restart; `machinist reload` names any of those settings when they differ and does not apply them. ```text factory/ pipelines/.yaml a list of steps agents/.md an agent: its harness, its model and its prompt prompts/.md text every agent shares, such as rules.md scripts/ shell scripts that steps run automations/.md YAML front matter and a prompt manifest.yaml hashes of the shipped files as last installed ``` Keep what an agent is told in `agents/`, shell in `scripts/`, and pipelines to a short list of steps that call them. > [!NOTE] > For backwards compatibility, Machinist still accepts legacy `factory/presets/.yaml` > alongside `factory/pipelines/.yaml` (duplicate names across both directories are rejected) > as well as `preset:` aliases in `trigger:`, `on_merge:`, and automation front matter. ## Upgrading shipped factory files `machinist init` records the SHA-256 hash of each shipped file in `factory/manifest.yaml`. When a newer Machinist binary ships updated factory files, the control plane warns at startup and on the Settings page which files are out of date. Run `machinist factory upgrade` from the configuration directory to apply them: - Unedited files that match an older shipped hash are updated in place. - Missing shipped files are created. - Files your team has edited are never overwritten; Machinist prints a diff against the shipped version instead. Pass `--force` to overwrite edited files with the shipped copies. Commit the updated files and `factory/manifest.yaml`, then run `machinist reload` (no restart needed). ## Pipelines A pipeline is a list of shell steps. A job names one pipeline, and every job of that pipeline runs the same steps in the same order. `default_pipeline` in `config.yaml` (or its legacy alias `default_preset`) picks the pipeline for jobs that do not name one. ```yaml # pipelines/default.yaml description: Clone the repository, run Claude Code on the prompt and open one pull request. timeout: 60m # all steps together; optional runs_on: [macos] # optional; require runner labels (omit to match any runner) steps: - name: checkout timeout: 5m # this step; optional run: checkout.sh - name: implement agent: implement # runs factory/agents/implement.md - name: test idle_timeout: 30m # stop it after this long with no output; optional run: go test ./... ``` `description` is required: one sentence on what a job on this pipeline does. The New job form shows it, with the steps, under the pipeline picker. A step has one of `run`, `agent`, `gate`, or `trigger`. `run` is shell; use `run: |` for more than one line. `agent` names a file in `agents/`, and the step runs `machinist agent `. `gate` pauses the job for human approval, and `trigger` starts a downstream pipeline as a linked child job. Each command step runs with `sh -e` in one workspace on one runner. The workspace starts empty, so cloning the repository is a step like any other. Steps run in order. The first command that fails ends its step and the job, and the steps after it are skipped. There are no branches, loops or parallel steps. To review and then fix, write the review step and then the fix step. Each step is a new process. Steps hand work on through files in the workspace. A step that prints nothing for its `idle_timeout`, 15 minutes unless the step sets one, is stopped and the job fails saying so. So a hung agent frees its runner slot instead of holding it until the run's deadline. An agent prints a line for each message and action, so only a single tool call that long stays quiet; give such a step a longer `idle_timeout`. A step that hits either timeout gets SIGTERM and five seconds to exit cleanly before it is killed. Usage a harness reported before then is kept; one that reports cost only when it finishes, such as Claude Code, shows none. ### Extending pipelines and overriding harness or model To run the same steps on another harness or model without copying agent prompts or scripts, set `extends`, `harness` and `model` in a pipeline: ```yaml # pipelines/neon.yaml description: Default steps on Antigravity (Gemini 4 Neon). extends: default harness: agy model: gemini-4-neon-high ``` `extends` inherits the base pipeline's steps, `timeout`, `harness`, `model`, `runs_on`, `inputs`, `on_merge` and (when omitted) `description`. Set `runs_on:` on the child pipeline to replace the inherited host labels (or `runs_on: []` to clear them and match any runner). Set `on_merge:` on the child pipeline to replace the inherited merge triggers (or `on_merge: []` to clear them). Child `inputs:` merge with inherited inputs (see [Pipeline inputs](#pipeline-inputs)). You can chain `extends` across pipelines, override individual steps by name, and insert new steps with `before:` or `after:` — for example, to add a cross-model review and revise loop using the shipped `review.sh` and `revise.sh`: ```yaml # pipelines/neon-opus-review.yaml description: Default steps on Antigravity with Claude Opus review. extends: neon steps: - name: review after: implement timeout: 15m harness: claude model: opus run: review.sh - name: revise after: implement run: revise.sh - name: merge run: machinist merge --require-gate ``` To insert new steps at a specific point in an inherited pipeline, add `before: ` or `after: ` to each new step: ```yaml # pipelines/feature.yaml description: Write a spec, wait for approval, then run the default steps. extends: default steps: - name: spec before: implement agent: spec - name: approve-spec before: implement gate: message: Build this spec? details: spec.md timeout: 72h ``` Step placement rules in `extends`: - `before:` and `after:` are mutually exclusive and only allowed on pipelines that use `extends`. - They can only be used on **new** steps (not when overriding an existing step by name) and must name a step that exists in the base pipeline. - Multiple new steps targeting the same anchor are inserted in declaration order, so `spec` and `approve-spec` above land in order directly before `implement` (and consecutive `after: checkout` steps land in order directly after `checkout`). Override precedence is **step > pipeline > `agents/.md` front matter**: - Pipeline-level `harness` and `model` apply to every agent invoked inside the pipeline, whether the step uses `agent: ` or a shell script such as `review.sh`, `revise.sh` or `publish.sh`. - Step-level `harness` and `model` override the pipeline for that step alone. The runner passes the effective values to the step as `MACHINIST_HARNESS` and `MACHINIST_MODEL`, which `machinist agent` reads. - Switching `harness` without setting `model` drops any model inherited from the previous harness (and any custom `command:` in the agent file), so a model name from one harness is never passed to another. - When extending a pipeline, a step in `steps:` whose `name` matches a base step updates that step in place: command steps keep their `run`/`agent` and timeouts unless replaced; gate overrides merge `message`, `timeout` and `details` onto an inherited gate; trigger overrides merge `vars` when keeping the same target pipeline or replace them when changing `pipeline`. A new step name must include `run`, `agent`, `gate`, or `trigger`, and is inserted at its `before:`/`after:` anchor or appended at the end. The web app, runner routing and Dashboard model metrics all resolve and report the effective `harness` and `model` for every step. ### Pipeline inputs A pipeline can declare named string parameters beyond `repo` under `inputs:`: ```yaml # pipelines/deploy.yaml description: Deploy the merged main branch to staging, then to production after approval. runs_on: [deploy] inputs: environment: description: Where to deploy first default: staging release_tag: description: Release tag to stamp ``` Rules for pipeline inputs: - **Naming:** Input names must match `^[a-z][a-z0-9_]*$` (lowercase letters, digits and underscores, starting with a letter). `repo` is reserved and cannot be declared in `inputs:`. - **Required vs optional:** An input with no `default:` is **required** — callers must supply a non-empty value, or the request fails with `400 Bad Request`. An input with `default:` (including an explicit empty string `default: ""`) is optional and falls back to its default when omitted. Passing an undeclared input name also returns `400 Bad Request`. - **Value limits:** Every default and runtime value must be valid UTF-8, contain no NUL bytes, and be at most `1024` bytes (`1 KiB`). - **Environment variables:** Each declared input is injected into every step as `MACHINIST_INPUT_` (for example `environment` becomes `MACHINIST_INPUT_ENVIRONMENT`), keeping a separate prefix from built-in `MACHINIST_*` variables. - **Inheritance:** A pipeline using `extends:` inherits its base pipeline's `inputs:` and can add new inputs or override the `description` or `default` of an inherited input. - **Non-interactive entrypoints:** Pipelines configured as `server.default_pipeline`, `linear.pipeline`, or `github_issues.pipeline` (or their legacy `preset` aliases) cannot declare required inputs (inputs without a `default:`), because issue trackers ([GitHub Issues](github-issues.md) and [Linear](linear.md)) cannot supply custom `vars`. - **Where inputs are supplied:** - **Web app:** The **New job** form renders one field per declared input on the selected pipeline (pre-filled with defaults and marking required fields). Non-empty inputs are displayed on the job page. - **Run API & MCP:** Pass pipeline inputs in `vars` on `POST /machinist/run` (alongside `repo`) or on the MCP `run_job` tool (where `repo` stays a top-level argument). - **Automations:** File automations (`factory/automations/*.md`) accept an optional `vars:` YAML map in front matter (validated at load/reload time). UI/database automations store `vars` on the automation and accept per-run `vars` overrides when triggered via the UI or `POST /api/v1/automations//run`. - **Triggers:** `trigger:` steps and `on_merge:` pass matching parent inputs and explicit `vars:` to child pipelines. ### Approval gates A `gate:` step pauses a job between steps so a person can review work (such as a spec or staging smoke test) before continuing, without holding a runner slot while waiting. Short form: ```yaml - name: approve-production gate: Promote to production? ``` Full mapping form: ```yaml - name: approve-production gate: message: Promote to production? timeout: 24h details: smoke-test.md ``` Gate fields and syntax rules: - `gate` is mutually exclusive with `run`, `agent`, and `trigger`. Gate steps cannot set step-level `timeout`, `idle_timeout`, `harness`, or `model` (put `timeout` inside `gate:`). - `message` is required: a non-empty UTF-8 string (trimmed, no NUL bytes, at most `1024` bytes). - `timeout` is optional: a positive Go duration such as `24h` or `72h`. When omitted on a manual, Run API, MCP, GitHub Issues, or Linear job, the job waits until someone approves, denies, or cancels it. - `details` is optional: a single safe filename inside `$MACHINIST_DIR` matching `^[A-Za-z0-9][A-Za-z0-9_.-]*$` (no `/`, no `..`, no symlinks), read as a regular file up to `64 KiB`. If the file was not written, `details` is empty; if it is non-regular or over `64 KiB`, the run fails. Load-time placement rules (checked after `extends` expansion): - A gate cannot be the **first** step of a pipeline. - A gate cannot be the **last** step of a pipeline. - If the pipeline has a `checkout` step, every gate must appear **after** `checkout`. How pause and resume work: 1. **Checkpoint and pause:** When a runner reaches a `gate` step, it reads any configured `details` file and captures a workspace checkpoint containing the pinned base commit SHA, commits beyond that base, uncommitted worktree changes, Machinist control files, and the `details` file. Unlike failure checkpoints, if a gate checkpoint exceeds `4 MiB` or the git snapshot fails, the run fails immediately instead of parking an unresumable job. Otherwise the runner frees its slot, deletes its workspace, and the control plane moves the job to `waiting`. 2. **Notifications and visibility:** Waiting jobs appear in the Board's **Review** column with a `Gate` badge, increment the Dashboard's waiting count, and show a **Gate** panel on the job page (displaying `message`, `details` in a safe `
` block, timeout info, and **Approve** /
   **Deny** controls with an optional reason). If `notify.webhook` is set, Machinist posts an alert
   with the static `gate.message` and job URL (never `details`). Jobs started from
   [GitHub Issues](github-issues.md) or [Linear](linear.md) also post a comment on the originating
   issue.
3. **Approve:** Approving (via the web UI, `POST /machinist/jobs/{id}/approve`, or MCP
   `approve_job`) requires `run` scope (`admin`/`member` users or `full`/`run` tokens). The control
   plane moves the job back to `working` and queues a resumed run starting at the step after the
   gate. Any online runner matching the pipeline's `runs_on` and harnesses runs `checkout`, restores
   the checkpoint against the exact pinned commit SHA so upstream pushes to `main` never swap the
   approved code, and continues from the next step. A job's overall timeout counts **running time
   only** — time spent waiting does not consume the timeout budget.
4. **Deny, timeout, or cancel:** Denying (with an optional reason), cancelling, or passing
   `gate.timeout` (swept automatically by the control plane) transitions the job from `waiting` to
   `cancelled` and queues no further runs.
5. **Automations and gates:** A job started by an automation can pause at a gate **only** when the
   gate declares a `timeout:` (so a scheduled job cannot block its schedule indefinitely). If an
   automated job reaches a gate with no `timeout:`, the control plane fails the job immediately.

### Triggers and `on_merge`

A pipeline can start downstream pipelines as independent, linked child jobs — either mid-pipeline with a
`trigger:` step, or automatically when its pull request merges with top-level `on_merge:`.

Step trigger (short and mapping forms):

```yaml
- name: start-tests
  trigger: gpu-tests

- name: start-deploy
  trigger:
    pipeline: deploy
    vars:
      environment: staging
```

Top-level `on_merge` (accepts a single mapping or a list of mappings; legacy `preset:` is also accepted as an alias for `pipeline:`):

```yaml
on_merge:
  pipeline: deploy
  vars:
    environment: staging
```

```yaml
on_merge:
  - pipeline: deploy
    vars:
      environment: staging
  - pipeline: notify-release
```

How triggers work:

- **Syntax rules:** `trigger` is mutually exclusive with `run`, `agent`, and `gate`, and cannot set
  `timeout`, `idle_timeout`, `harness`, or `model`.
- **What the child job receives:** Each triggered child job inherits the parent's `repo` and
  initial `prompt`, records `source: trigger` and `parent_id` (plus `source_url` linking to the
  parent job when `server.public_url` is set), and receives any parent `vars` whose names are
  declared in the child pipeline's `inputs:`, overlaid with the trigger's explicit `vars:`. Steps in
  the child job receive:
  - `MACHINIST_PARENT_JOB_ID`: the parent job's ID.
  - `MACHINIST_MERGE_SHA` (for `on_merge` triggers): the merge commit SHA landed on the base
    branch (works for merge commits, squash merges, and rebase merges).
- **Independent execution & credential isolation:** The child runs with its own `runs_on`,
  `timeout`, `harness`/`model`, and `steps` (for example, keeping deploy credentials only on
  `runs_on: [deploy]` runners). It can be inspected, rerun, or cancelled independently; cancelling
  a parent does not cancel already-started children.
- **Sandbox-safe execution:** `trigger` steps do not call back to the control plane mid-run, so
  they work identically on local, Docker, and Kubernetes runners with no network access inside
  sandboxes. The runner records triggered pipelines and reports them to the control plane when the
  run finishes or pauses at a gate, and the control plane creates each child idempotently.
- **When `on_merge` fires:** Fires once idempotently when the parent job's pull request transitions
  to merged (whether auto-merged by Machinist, merged by a person, or already merged when a run
  completes). It does not fire if the pull request stays open, closes without merging, was never
  opened, or if the parent job was `cancelled`.
- **Load-time checks and cycle detection:** Checked at factory load and reload after `extends`
  expansion: every target pipeline must exist, `vars` cannot set reserved `repo` or undeclared child
  inputs, every required child input must be supplied via `vars:` or declared on the parent pipeline,
  and the combined graph of `trigger` steps and `on_merge` edges must contain no cycles (a cycle
  such as `A -> B -> A` fails factory load/reload).
- **Parent/child links and reruns:** The parent's job page lists its direct children (ID, pipeline,
  state, link), the child's job page links back to its parent, and Board cards display each job's
  pipeline badge. Rerunning a parent from scratch can fire its `trigger` steps again; resuming after
  a gate skips earlier steps and does not re-fire pre-gate triggers.

### Worked example: Issue to production

`machinist init` continues to install only the `default` pipeline. To build an end-to-end
issue-to-production workflow with spec approval, PR auto-merge, and staged deploys on dedicated
deploy runners, add two pipelines to `factory/pipelines/` (plus `factory/agents/spec.md` and deploy
scripts in `factory/scripts/`):

#### `factory/pipelines/feature.yaml`

```yaml
description: Write a spec and wait for approval, then build it with the default steps and deploy once it merges.
extends: default
on_merge:
  pipeline: deploy

steps:
  - name: spec
    before: implement
    agent: spec            # factory/agents/spec.md writes $MACHINIST_DIR/spec.md
  - name: approve-spec
    before: implement
    gate:
      message: Build this spec?
      details: spec.md
      timeout: 72h
```

#### `factory/pipelines/deploy.yaml`

```yaml
description: Deploy a merged commit to staging, test it, and promote it to production after approval.
runs_on: [deploy]
inputs:
  environment:
    description: Initial deployment environment
    default: staging

steps:
  - name: checkout
    run: |
      checkout.sh
      git checkout --detach "${MACHINIST_MERGE_SHA:-origin/HEAD}"
  - name: deploy-staging
    run: deploy.sh "$MACHINIST_INPUT_ENVIRONMENT"
  - name: smoke-staging
    run: smoke-test.sh "$MACHINIST_INPUT_ENVIRONMENT" > "$MACHINIST_DIR/smoke.md"
  - name: approve-production
    gate:
      message: Promote to production?
      details: smoke.md
      timeout: 24h
  - name: deploy-production
    run: deploy.sh production
  - name: smoke-production
    run: smoke-test.sh production
```

How a job flows through these two pipelines:

1. Start a `feature` job from [GitHub Issues](github-issues.md), [Linear](linear.md), the web
   app, Run API, or MCP. It checks out the repo, runs
   `spec` to write `$MACHINIST_DIR/spec.md`, saves a checkpoint, frees its runner slot, and pauses
   at `approve-spec`.
2. A reviewer reads `spec.md` in the job's Gate panel and clicks **Approve**. Machinist resumes on
   any matching runner at `implement`, runs `publish`, `merge-gate`, and `merge`, and opens (or
   auto-merges) the pull request.
3. Once the pull request merges, `on_merge` starts a linked `deploy` child job with
   `MACHINIST_PARENT_JOB_ID` and `MACHINIST_MERGE_SHA` set. Only a runner advertising the `deploy`
   label claims it.
4. `deploy` checks out the exact merged commit, deploys and smoke-tests `staging`, writes
   `$MACHINIST_DIR/smoke.md`, and pauses at `approve-production`. Approving promotes that exact
   pinned commit to `production` and runs production smoke tests.

### Agents

An agent file says which harness runs it, which model to ask for, and what to tell it:

```markdown
---
harness: codex        # agy, claude, codex or pi
model: gpt-5-codex    # optional; the harness's default otherwise
command: /opt/codex   # optional; the program to run, if it is not on PATH
---
Review the change on this branch...
```

`machinist agent ` gives the agent a system prompt in three parts: where it is
working (the repository, the branch and the control directory), then `prompts/rules.md`
if there is one, then the agent file's prompt. The job's prompt is the work. It runs the
harness headless with every permission, prints its progress as it goes, and records the
tokens and cost the harness reports. The step fails when the agent exits non-zero.

| Harness | Runs |
| --- | --- |
| `claude` | `claude --print --output-format stream-json` with the system prompt appended to Claude Code's own |
| `codex` | `codex exec --json`, with the system prompt first in the message, since Codex takes no separate one |
| `pi` | `pi --print --mode json --no-session` with the system prompt appended to Pi's own |
| `agy` | Google's Antigravity CLI: `agy --print  --output-format stream-json --dangerously-skip-permissions`, with the system prompt first in the prompt, since agy takes no separate one. Gemini models such as `gemini-4-neon-high`. agy reports tokens but no cost |

The web app shows which agent runs each step, on which harness and model: on the New job
form, on the job page, and on running jobs on the board and the Runners page.
Machinist reads this from the step's `agent:` or from `machinist agent ` in its command
or in a script from `scripts/` that it runs. Once a step has run, it shows what actually ran,
which `machinist agent` records.

Each harness must be installed and signed in on the runner. To use a different agent for a
step, change `harness` in its file. To change what a step asks for, edit its prompt.

The shipped agents:

| Agent | Step |
| --- | --- |
| `implement` | Inspect relevant code and outline a brief plan, make the change with tests (a failing test first for a bug), run the repository's own checks without claiming a check passed unless it ran, self-review the diff before finishing, and commit. Never push, open a pull request or merge |
| `review` | Shipped for opt-in review pipelines (such as `cross-model-review.yaml`): review the branch without changing it, run the checks, and write `review.json`: a verdict of `accepted`, `revision_needed` or `human_decision_needed`, and findings marked unambiguous or not |
| `revise` | Shipped for opt-in review pipelines: fix the unambiguous findings and mark them addressed. `scripts/revise.sh` runs it only when the verdict is `revision_needed`, then runs `review` again |
| `publish` | Open one ready pull request with a summary, testing, optional review (only when `review.json` exists), and assumptions. It never pushes or merges. `scripts/publish.sh` pushes the branch first with `machinist push`, and runs it only when the branch has commits |
| `merge-gate` | Judge the final diff against `.machinist/merge-policy.md` from `origin/HEAD` (or `prompts/merge-policy.md`), without changing files or GitHub credentials, and write `merge-gate.json` (`approve` + `low` risk, or `human_review`). `scripts/merge-gate.sh` skips branches with no commits or unaccepted reviews |

When you opt into a separate review step (see [`cross-model-review.yaml`](../examples/pipelines/cross-model-review.yaml)),
it is worth most from a different model family than the one that wrote the change. If Codex or agy
is on your runners, set `harness: codex` or `harness: agy` on the `review` step or in `agents/review.md`.

The last step, `machinist merge`, is code, not an agent. The default pipeline runs
`machinist merge --without-review --require-gate`. It reads `review.json` (when present) and
`merge-gate.json`, posts the merge gate judgment as a comment on the pull request, hands the
pull request to the control plane and ends at once, so the run is over and its runner slot is
free while CI runs. The result says whether the pull request will merge or stays open, and
why. The job is `pr_ready` while the control plane watches the checks, about once a minute.
It merges the pull request with `gh pr merge` when all of these hold, and otherwise leaves it
open for a person:

- `github.auto_merge` is on. The control plane checks its own setting, whatever a step says.
- When a pipeline requires a review step (`machinist merge --require-gate`, without
  `--without-review`), `review.json` must be valid with verdict `accepted` (a missing review
  leaves the pull request open). The default single-agent pipeline passes `--without-review`,
  so no `review.json` is required.
- `merge-gate.json` (required by `--require-gate` in the default pipeline, and enforced whenever present) is valid with `decision: "approve"` and `risk: "low"`. Medium- or high-risk changes stay open for human review with the judgment commented on the pull request.
- Every check on the pull request passed. The control plane waits for them, and for checks
  to start, up to two and a half minutes, before it treats the repository as having none. A
  failed check fails the job, even when the pull request would have stayed open anyway.

- The pull request's head is still the commit the merge step saw, or the one
  the control plane's own branch update made from it. A commit pushed after the run
  leaves the pull request open for a person.

The merge names the head commit whose checks passed, so GitHub refuses any other. A branch
that fell behind its base is updated, up to three times, and every check must pass again on
the new head. It merges with the first of a merge commit, a squash and a rebase that the
repository allows, so squash-only and rebase-only repositories work without a setting. With a
GitHub App the control plane merges with the app's token, and otherwise with its own
`GH_TOKEN`, so that token needs to be able to merge.

### PR Steward

When a watched pull request fails a CI check (for example, a compile or test failure after a
parallel pull request merged) or hits a merge conflict (`DIRTY` merge state or a conflicting
branch update), **PR Steward** automatically shepherds the pull request back to green instead
of immediately failing or abandoning it:

- Up to `github.steward_retries` times per job (default `2`, `0` disables, max `5`, persisted
  in SQLite across control-plane restarts), the control plane clears the old check watch,
  records a timeline entry naming the failed check or conflict, and requeues a follow-up run on
  the **same branch**.
- The follow-up prompt tells the agent to fetch `origin`, merge the job's target base ref (`origin/` when `base_branch` is set, or `origin/HEAD` otherwise), resolve any
  conflicts, inspect and fix the failing check, run local checks, and commit on the branch so
  the run pushes the update and re-runs `merge-gate` (and `review`, when configured).
- **Safety guardrails:** PR Steward never runs if a person pushed commits to the branch after
  the last run's head commit, or if the pull request was already merged or closed.
- **Metrics:** Automatic steward retries are not counted as human `reruns` touches in Dashboard
  metrics. Once `github.steward_retries` is exhausted, Machinist falls back to marking the job
  `failed` (on CI failure) or leaving the pull request open (on merge conflict) and notifies
  a person.

In opt-in review pipelines (such as [`cross-model-review.yaml`](../examples/pipelines/cross-model-review.yaml)),
the reviser does not judge its own fixes. `scripts/review.sh` removes any `review.json`
before the review runs, and fails the step if the review writes none. `scripts/revise.sh`
keeps the first review as `first-review.json` and runs the review again on the fixed branch,
and only that verdict counts. When the first review accepted the change, no revise agent
runs.

`machinist verdict` prints the verdict, for scripts like these. `machinist gate` validates and prints `merge-gate.json`.

### Merge gate and policy

The default pipeline runs a read-only `merge-gate` step (`scripts/merge-gate.sh`) after `publish` and before `merge`:

- **Blast-radius judgment:** Code quality and tests are verified in `implement` (and any opt-in `review` step), and CI runs before merge. `agents/merge-gate.md` (pinned to `haiku` by default for low cost and latency) inspects `git diff "${MACHINIST_BASE_REF:-origin/HEAD}...HEAD"` and decides whether the change is reversible, low-risk work (`decision: "approve"`, `risk: "low"`) or needs a person (`decision: "human_review"`, `risk: "medium"` or `"high"`).
- **Default policy:** `prompts/merge-policy.md` approves normal, reversible engineering work (features, UI updates, bug fixes, refactors, tests, documentation) and requires human review for high-blast-radius or hard-to-revert changes (database migrations/schema changes, auth/session/token/secrets logic, billing or breaking public APIs, CI/deployment/dependency upgrades, or weakening tests/safety checks).
- **Per-repository override (security invariant):** Commit `.machinist/merge-policy.md` to a repository's default branch to override `prompts/merge-policy.md` for that repository. The agent **always** reads it from the repository's default branch via `git show origin/HEAD:.machinist/merge-policy.md` — never from the working tree, the PR branch, or a custom target `base_branch` (`$MACHINIST_BASE_REF`) — so neither a pull request nor a target feature branch can weaken its own merge policy. See [Merge policies](merge-policies.md) for copy-paste starter policies (`conservative`, `balanced`, `fast-startup`, `strict-fintech`).
- **Credential isolation & deterministic tripwire:** `scripts/merge-gate.sh` unsets `GH_TOKEN` and `GITHUB_TOKEN` before running the judge agent, skips branches with no commits or unaccepted reviews, and runs `machinist gate --tripwire` so plain Go code forces `human_review` (`high` risk) for workflow files (`.github/workflows/`), merge-policy edits, SQL migrations, or newly skipped tests — regardless of what the model returned.
- **PR comments, outcome labels & observe mode:** `machinist merge` posts the Merge Gate judgment as a comment on the pull request via `gh pr comment` and applies an outcome label (`merge-gate:auto-merge`, `merge-gate:human-review`, `merge-gate:tripwire`, or `merge-gate:observe`). Setting `github.auto_merge: false` acts as **observe mode**: the gate still evaluates every pull request and comments its judgment without merging anything.
- **Opting out:** In a custom pipeline without a `merge-gate` step, use `machinist merge --without-review` (or `machinist merge` if you include a `review` step), without `--require-gate`.

`machinist push` pushes the job's branch. When GitHub rejects the push, for example because
the token cannot change workflow files, the step fails with GitHub's answer. The job fails,
says why, and the merge step never runs. A job whose branch has no commits pushes nothing
and is done without a pull request.

The runner removes the workspace when the run ends, so a rejected push first saves the
change: `git format-patch` of the commits beyond `$MACHINIST_BASE_REF` (defaulting to `origin/HEAD`), written to `change.patch` in
the control directory. `format-patch` skips merge commits, so when the branch has one, for
example where the job merged the base branch in to resolve a conflict, the patch is one commit
of everything the branch changed since it forked from `$MACHINIST_BASE_REF`, resolution included.
The control plane keeps it with the run, and the job page links to it. Download it and apply
it with `git am`, then push it yourself, without running the agent again. Any step can leave `change.patch` the same way. A patch over 4 MiB is not kept.

When any step fails, the job's result is the step's error and the last line the step wrote
to stderr.

### Prompts and scripts

Every run carries the factory's `agents/`, `prompts/` and `scripts/` to the runner, so they
work on any runner, local or Kubernetes. They are written under `$MACHINIST_DIR`, and
`$MACHINIST_DIR/scripts` is first on `PATH`, so a step runs a script by its file name.
Together they must be under 4 MiB.

`prompts/rules.md` holds the rules for every agent: run headless, record guesses in
`assumptions.md`, follow the repository's instructions. `scripts/checkout.sh` clones the
repository and switches to the job's branch.

### Live output from an agent

`machinist agent` turns each harness's event stream into one line per message or action
as it happens:

```
Claude Code started with 
▸ Read internal/server.go
▸ Run go test ./...
Finished after 12 turns in 3m10s, $0.42
```

Lines that start with `▸` are actions. The job page shows the latest one as what a running
job is doing. `machinist agent` also records the tokens and cost the agent reports, so the
job page and the dashboard can count them. Codex and agy report tokens but no cost, so their
steps show the cost as not reported, and a total that leaves them out ends in `+`. An agent
with no `model:` shows the model its harness said it started with. To run some other command from
a `run` step with the same live lines, wrap it: `machinist agent-log -- `. Output
that is not Claude Code's stream passes through unchanged.

Step names are letters, digits, hyphens and underscores, and are unique in a pipeline.

### What a step gets

| Variable | Value |
| --- | --- |
| `MACHINIST_REPO` | The job's repository, as `owner/name` |
| `MACHINIST_BRANCH` | `machinist/`, the branch for the job's work |
| `MACHINIST_BASE_BRANCH` | The job's optional target base branch (e.g. `develop`, `release/1.2`), or empty when targeting the repository's default branch |
| `MACHINIST_BASE_REF` | `origin/` when `base_branch` is set, otherwise `origin/HEAD` |
| `MACHINIST_JOB_ID` | The job's ID |
| `MACHINIST_PRESET` | The pipeline's name |
| `MACHINIST_DIR` | The control directory, outside the workspace |
| `MACHINIST_INPUT_` | Value of each declared pipeline input (`` upper-cased), such as `MACHINIST_INPUT_ENVIRONMENT` |
| `MACHINIST_PARENT_JOB_ID` | The parent job's ID, when the job was started by a `trigger` step or `on_merge` |
| `MACHINIST_MERGE_SHA` | The merge commit SHA landed on the base branch, when the job was started by `on_merge` |
| `MACHINIST_HARNESS` | Effective harness override for the step, when set by the pipeline or step; read by `machinist agent` |
| `MACHINIST_MODEL` | Effective model override for the step, when set by the pipeline or step; read by `machinist agent` |
| `MACHINIST_AUTO_MERGE` | `"true"` or `"false"`, from `github.auto_merge` in `config.yaml` |
| `GH_TOKEN` | The runner's GitHub token, for `gh` and `git` |
| `GIT_AUTHOR_*`, `GIT_COMMITTER_*` | The bot's name and email |

A step also gets the variables in the runner's `env` list. See
[Runners](runners.md#what-steps-can-use).

The prompt is the job's request. It is on stdin and
in `$MACHINIST_DIR/prompt.md`. A step need not read it.

### Control files

Steps talk to Machinist through files in `$MACHINIST_DIR`. It is outside the workspace,
so a commit never picks them up. Each file must be a regular file of at most 64 KiB.

| File | Effect |
| --- | --- |
| `result.md` | When every step passes, its text is the job's result. Without it the result is "Every step passed." |

Steps run headless and nothing can answer a question mid-step (use a [`gate:` step](#approval-gates)
when a job should pause between steps for human approval). `prompts/rules.md` tells the agent to
make the smallest reasonable choice and list each one in `assumptions.md` in the control directory.
The publish step adds that list to the pull request under **Assumptions**.

After a job ends, Machinist looks for an open pull request on `MACHINIST_BRANCH` and records
its number on the job.

`init` installs one pipeline, `default`: `checkout`, `implement`, `publish`, `merge-gate`, and
`merge`. A job that names no pipeline uses it. Add a pipeline only when a job needs different
steps, such as a cross-model review step, separate test, approval gate, or deploy step. See
[Pipeline recipes](pipelines.md) for copy-paste starter pipelines.

## Automations

Automations can be created directly on the **Automations** page in the web app (stored in the control plane database) or checked into `factory/automations/.md`:

```markdown
---
schedule: "0 9 * * 1-5"   # optional; omit for manual-only
timezone: UTC
repo: owner/name
base_branch: develop      # optional; defaults to the repository's default branch
pipeline: default         # legacy alias: preset
harness: codex            # optional; agy, claude, codex or pi
model: gpt-5-codex        # optional
runs_on: [linux, gpu]     # optional; overrides the pipeline's runs_on
vars:                     # optional; pipeline input values (validated against pipeline inputs)
  environment: staging
---
The prompt goes here.
```

Quote `schedule`, because a cron line can start with `*`. Omit `schedule` (and `timezone`) for a manual automation that runs only when triggered by hand or via API.

`repo` must be in `github.repositories` (or added in Settings → Projects for UI-managed automations), `pipeline` (or its legacy alias `preset`) must name a pipeline, and `vars` (when present) must satisfy that pipeline's declared `inputs:`. Missed scheduled runs collapse into one, and no job starts while the automation's last one is active (including while `waiting` at a gate). An automated job can pause at a `gate:` step only if that gate sets a `timeout:` so it cannot stall its schedule indefinitely; reaching a gate with no `timeout:` fails the automated job immediately. To run one now, open **Automations** in the web app, or call `POST /api/v1/automations//run` with a token and an optional JSON body (`prompt`, `repo`, `pipeline`, `harness`, `model`, `runs_on`, `vars`) to override fields for that run only. Every run appears as a normal job on the **Jobs** page.