# forge.yaml Configuration Reference

`forge.yaml` is placed at your project root and tells ForgeDock commands how to interact with your specific project. Without it, commands cannot resolve your GitHub repository, paths, or branches.

## Quick Start

```bash
cp forge.yaml.example forge.yaml
# Edit forge.yaml with your project details
echo "forge.yaml" >> .gitignore  # if your credentials path is sensitive
```

---

## CLI Flags

`--verbose` and `--fast` apply to both `npx forgedock` (the full install journey) and `npx forgedock init` (config-only regeneration); `--manual` and `--minimal` apply to `init` only:

| Flag | Behavior |
|------|----------|
| `--manual` | `npx forgedock init` only. Skips the annotated review screen and asks plain, one-field-at-a-time prompts instead, pre-filled with the detected values as defaults. |
| `--minimal` | `npx forgedock init` only. Skips detection enrichment and the review screen entirely, and writes a short `forge.yaml` containing only the three required sections (`project`, `paths`, `branches`) with detected values. |
| `--verbose` | Shows each field's detection source and confidence rationale on the review screen (e.g. `git remote`, `package.json`, `gh api`), instead of only flagging low-confidence fields. |
| `--fast` | Skips the animation/motion frames and jumps straight to the static screens. |

**Environment variables:**

| Variable | Behavior |
|----------|----------|
| `FORGE_NO_MOTION=1` | Same effect as `--fast` — disables animation frames. Color is unaffected. |
| `NO_COLOR=1` | Disables ANSI color output only. Motion is unaffected (monochrome choreography). |
| `FORGEDOCK_INIT_BACKEND=cli\|api\|none\|auto` | Overrides AI-enrichment backend selection for `init` (see below). Default `auto` (or unset) preserves the CLI-first ladder. |
| Non-TTY / piped output (or `CI=1`) | Plain sequential log: no color **and** no animation. |

The default (no flags) is the annotated review screen: detection runs, AI enrichment fills in what it can — using a local, authenticated `claude` CLI when available, otherwise falling back to the Anthropic API when `ANTHROPIC_API_KEY` is set, otherwise skipped — and you review the result on a single screen — Enter accepts everything, low-confidence fields are flagged with a `# TODO(forgedock:<field>)` comment if left unedited.

If you have both a local `claude` CLI and `ANTHROPIC_API_KEY` set and want to pin one explicitly instead of letting `init` prefer the CLI, set `FORGEDOCK_INIT_BACKEND=api` (or `=cli`, or `=none` to skip enrichment entirely). This is independent of `FORGEDOCK_BACKEND`, which controls the separate `forgedock run` engine backend.

---

## Schema Overview

| Section | Required | Purpose |
|---------|----------|---------|
| [`project`](#project-required) | **Yes** | GitHub identity (owner, repo, name) |
| [`paths`](#paths-required) | **Yes** | Local filesystem locations |
| [`branches`](#branches-required) | **Yes** | Branch naming conventions |
| [`agents`](#agents-optional) | No | Default model for pipeline agents |
| [`repos`](#repos-optional) | No | Multi-repository routing |
| [`project_board`](#project_board-optional) | No | GitHub Projects v2 integration |
| [`orchestration`](#orchestration-optional) | No | `/orchestrate` concurrency and cascade admission policy |
| [`hygiene`](#hygiene-optional) | No | Automatic reclaim of ForgeDock-owned leftovers: TTLs, branch deletion, near-ceiling GC, `auto_gc` |
| [`pipeline`](#pipeline-optional) | No | `/orchestrate` batch-engine tuning (stall detection, token budget, narration) |
| [`build`](#build-optional) | No | `/work-on` build-phase scope check (`build.scope.*`) and review depth (`review.depth.*`) |
| [`services`](#services-optional) | No | External service URLs and IDs |
| [`review`](#review-optional) | No | Context injected into review agents |
| [`devdocs`](#devdocs-optional) | No | Devdocs knowledge tree path |
| [`verification`](#verification-optional) | No | Health-check patterns |
| [`execution`](#execution-optional) | No | `forgedock orchestrate`: run lanes in sandboxes instead of host processes (`mode: local\|remote\|hybrid`, `max_remote`) |
| [`verify`](#verify-optional) | No | Core work-on: run lane verification on CI runners instead of the host (`mode: local\|ci\|hybrid`) |
| [`selftest`](#selftest-optional) | No | `forgedock selftest --live`: the disposable sandbox repo and fixture language of the live contract harness |
| [`billing`](#billing-optional) | No | Enable financial integrity audit phase |
| [`adaptive_scripts`](#adaptive_scripts-optional) | No | Per-repo script override configuration |

---

## `project` (REQUIRED)

Core identity fields. Used by every command that calls `gh issue`, `gh pr`, or `gh project`.

```yaml
project:
  name: "Acme Platform"
  owner: "acme-org"
  repo: "acme-platform"
  description: "SaaS platform for automated data processing"
  # forge_repo: "acme-org/acme-forge"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **Yes** | Human-readable name used in pipeline reports and issue comments |
| `owner` | string | **Yes** | GitHub org or username. Used as `GH_REPO` prefix and `--owner` flag |
| `repo` | string | **Yes** | Repository name. Combined: `owner/repo` = the `GH_REPO` value in all commands |
| `description` | string | No | One-line description used in issue templates |
| `forge_repo` | string | No | Pipeline repository in `owner/repo` format. Set this when your ForgeDock pipeline lives in a different repo than the project being developed. Used by `audit.md`, `audit-agents.md`, and `security-audit.md` to resolve `{FORGE_REPO}` when looking up pipeline issues and commands. Defaults to `project.owner/project.repo` if omitted. |

**Commands that use this section**: `work-on`, `review-pr`, `orchestrate`, `issue`, `milestone`, `cleanup`, `audit`, `audit-agents`, `security-audit`, `pipeline-health`

---

## `paths` (REQUIRED)

Local filesystem paths. Commands use these to locate the project, create git worktrees, and read credential files.

```yaml
paths:
  root: "/home/youruser/projects/acme-platform"
  worktree_base: "/home/youruser/projects/acme-platform/.claude/worktrees"
  # credentials:
  #   file: "/home/youruser/credentials.yaml"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `root` | string (absolute path) | **Yes** | Absolute path to the project root. Used as the base for `git worktree add` |
| `worktree_base` | string (absolute path) | **Yes** | Directory where per-branch git worktrees are created. Default: `{root}/.claude/worktrees` |
| `credentials.file` | string (absolute path) | No | Path to a YAML credentials file for analytics/monitoring tools. **Do not commit.** |

**Commands that use this section**: `work-on` (Phase 3E), `quality-gate`, `deploy-info`

---

## `branches` (REQUIRED)

Branch naming conventions that control PR targeting and source branch selection.

```yaml
branches:
  default: "main"
  staging: "staging"
  feature_pattern: "milestone/{slug}"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `default` | string | **Yes** | Default branch (`main` or `master`). Used as fallback PR base |
| `staging` | string | **Yes** | Staging branch for fast-lane PRs (issues without a milestone). Set to `main` if you have no staging branch |
| `feature_pattern` | string | **Yes** | Pattern for feature branches. `{slug}` is the milestone title in kebab-case. Example: `milestone/{slug}` → `milestone/user-auth-v2` |

**Lane routing logic** (from `work-on.md`):
- Issue has no milestone → fast lane → PR targets `branches.staging`
- Issue has milestone → feature lane → PR targets branch matching `branches.feature_pattern`

**Commands that use this section**: `work-on`, `review-pr`, `cleanup`

---

## `agents` (OPTIONAL)

Model configuration for pipeline agents. `default_model` governs the main agent — the one you invoke directly (`work-on`, `orchestrate`, `review-pr`, etc.), referenced by every command spec's "Agent model policy" line. `subagent_model` governs the **child** sub-agents that a top-level command spawns internally — e.g. `/orchestrate`'s per-issue `/work-on` agents, `/review-pr`'s domain persona reviewers, `/analytics`'s parallel data-collection agents, `/incident-response`'s validation/root-cause agents.

```yaml
agents:
  default_model: "sonnet"
  subagent_model: "sonnet"
```

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `default_model` | string | No | `"sonnet"` | Short alias — `"sonnet"`, `"opus"`, or `"haiku"` — the same values the Agent/Task tool's `model` parameter accepts. This is the only form that works for interactive command-spec sub-agent spawning. |
| `subagent_model` | string | No | `default_model`, else `"sonnet"` | Short alias, same accepted values as `default_model`. Overrides the model used for child agents spawned internally by a top-level command (see above). Omit to inherit `default_model`. In engine lanes (core work-on), only this field is read, with no `default_model` fallback. When set, it is the default model of subagents that have no model of their own. When unset, the operator's own `CLAUDE_CODE_SUBAGENT_MODEL` (if any) stays in effect. In every lane session, ForgeDock-defined agents such as the explorer keep their own model: an ambient `CLAUDE_CODE_SUBAGENT_MODEL_FORCE` in the operator's settings is turned off (#4843, #4849). **Upgrade note (1.38.1):** a `_FORCE=1` cap in your settings.json no longer applies to ForgeDock-defined agents in lanes. To pin model-less subagents, set this field. |

**Resolution order** (highest precedence first):
1. `--model <id>` — CLI flag, `npx forgedock run` only (headless; main agent only).
2. `FORGEDOCK_MODEL` env var — headless runner only (main agent only).
3. `agents.default_model` — this field. Governs the main agent.
4. Hardcoded default — `"sonnet"` for interactive agents, `"claude-sonnet-5"` for the headless runner (`bin/runner.mjs`'s `DEFAULT_MODEL`).

**Sub-agent resolution order** (highest precedence first):
1. `agents.subagent_model` — this field. Governs child agents spawned by a top-level command.
2. `agents.default_model` — falls back here when `subagent_model` is unset.
3. Hardcoded default — `"sonnet"`.

**Headless runner note**: `bin/runner.mjs` (`npx forgedock run`, used for CI/headless invocations) calls the Anthropic SDK directly and also accepts a full Anthropic model ID here as a pass-through escape hatch (e.g. `"claude-opus-4-6"`). A full model ID does **not** work for interactive Agent/Task tool calls in command specs — those only accept the short-alias enum (`sonnet`/`opus`/`haiku`/`fable`). Prefer the short alias unless you specifically need a headless-only override. `subagent_model` is interactive-only — it has no headless-runner equivalent, since the headless runner does not spawn child sub-agents.

Projects without this section see no behavior change — everything defaults exactly as it did before these fields existed.

**Commands that use this section**: all commands with an "Agent model policy" line (`default_model`, nearly every command spec) and all commands that spawn internal sub-agents — `orchestrate`, `review-pr`, `analytics`, `incident-response` (`subagent_model`).

---

## `repos` (OPTIONAL)

Multi-repository routing. Use this when your project spans multiple GitHub repositories and you want to route issues to satellite repos by prefix.

Without this section, all issues route to `project.owner/project.repo`.

```yaml
repos:
  default:
    repo: "acme-org/acme-platform"
    staging_branch: "staging"

  satellites:
    - prefix: "mcp"
      repo: "acme-org/acme-mcp-server"
      staging_branch: "main"
      local_path: "/home/youruser/projects/acme-mcp-server"

    - prefix: "sdk"
      repo: "acme-org/acme-python-sdk"
      staging_branch: "main"
      local_path: "/home/youruser/projects/acme-python-sdk"
      # billing_enabled: false  # set true to run /security-audit Phase 4 on this repo

    # Monorepo satellite: multiple packages in one repo.
    # subpaths maps named identifiers to per-package root directories
    # relative to local_path. Used by /sync-ecosystem when the repo
    # contains multiple independently published packages.
    - prefix: "mono"
      repo: "acme-org/acme-sdks"
      staging_branch: "main"
      local_path: "/home/youruser/projects/acme-sdks"
      subpaths:
        python_sdk: "sdk/python"
        node_sdk: "sdk/node"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `default.repo` | string | No | Full `owner/repo` of the primary repo. Should match `project.owner/project.repo` |
| `default.staging_branch` | string | No | Staging branch for the default repo |
| `satellites[].prefix` | string | **Yes (per entry)** | Short prefix used in issue routing (e.g., `mcp:5` routes issue 5 to the MCP server repo) |
| `satellites[].repo` | string | **Yes (per entry)** | Full `owner/repo` of the satellite repository |
| `satellites[].staging_branch` | string | **Yes (per entry)** | Target branch for fast-lane PRs in this repo |
| `satellites[].local_path` | string | No | Absolute local path to the satellite repo's checkout |
| `satellites[].subpaths` | map(string→string) | No | Named sub-directory paths within `local_path`, for monorepo satellites that publish multiple packages. Each key is a logical name; the value is the relative path to that package's root. Used by `/sync-ecosystem` to locate per-package version files and publish workflows. |
| `satellites[].billing_enabled` | boolean | No | Set to `true` to run Phase 4 (Financial Integrity) of `/security-audit` against this satellite repo. Mirrors the top-level [`billing.enabled`](#billing-optional) flag but scoped per-satellite. Defaults to `false` when absent. |
| `satellites[].trigger_on_merge` | boolean | No | When `true`, fires a cross-repo trigger when a PR merges in the parent repo and touches paths matching `trigger_paths`. Set to `false` to disable triggering for this satellite. Defaults to `true` when `trigger_paths` is present; otherwise has no effect until runtime trigger support is configured. |
| `satellites[].trigger_paths` | list of strings | No | Path glob patterns that constrain when the trigger fires. Uses GitHub Actions glob syntax (same as `on: push: paths:`). The trigger fires only when at least one changed file matches a pattern in this list. When omitted, the trigger fires on every merge (if `trigger_on_merge: true`). |
| `satellites[].auto_run` | boolean | No | When `true`, automatically invokes `/work-on` on the satellite issue when the cross-repo trigger fires. Requires a running Claude Code session with ForgeDock installed in the satellite repo. Advanced opt-in — defaults to `false`. Do not set to `true` unless a persistent Claude Code session is available in the satellite repo. |

**Routing syntax in commands**: `<prefix>:<issue_number>` — e.g., `mcp:5`, `sdk:12`

**Commands that use this section**: `work-on` (multi-repo prefix table), `sync-ecosystem`, `security-audit` (satellite billing audit)

---

## `project_board` (OPTIONAL)

GitHub Projects v2 integration. When configured, ForgeDock automatically adds issues to the project board and updates Status, Lane, Component, Priority, and Workflow fields as issues progress through the pipeline.

`/forgedock-init` fills this section for you: it links an existing board or creates a new one, links it to the repo, adds any missing Lane/Priority/Workflow/Component fields (Status is built in), and writes the IDs below. Projects v2 needs the `read:project`/`project` token scope, which `gh auth login` does not grant by default. If the scope is missing, `/forgedock-init` prints the fix:

```bash
gh auth refresh -h github.com -s read:project,project
```

```yaml
project_board:
  owner: "acme-org"
  project_number: 1
  project_id: "PVT_kwHOxxxxxxxxxxxxxxxx"

  field_ids:
    status: "PVTSSF_xxxxxxxxxxxxxxxxxxxxxxxx"
    lane: "PVTSSF_xxxxxxxxxxxxxxxxxxxxxxxx"
    component: "PVTSSF_xxxxxxxxxxxxxxxxxxxxxxxx"
    priority: "PVTSSF_xxxxxxxxxxxxxxxxxxxxxxxx"
    workflow: "PVTSSF_xxxxxxxxxxxxxxxxxxxxxxxx"

  option_ids:
    status:
      todo: "xxxxxxxx"
      in_progress: "xxxxxxxx"
      done: "xxxxxxxx"
    lane:
      fast: "xxxxxxxx"
      feature: "xxxxxxxx"
      sync: "xxxxxxxx"
    priority:
      p0: "xxxxxxxx"
      p1: "xxxxxxxx"
      p2: "xxxxxxxx"
      p3: "xxxxxxxx"
    workflow:
      investigating: "xxxxxxxx"
      building: "xxxxxxxx"
      in_review: "xxxxxxxx"
      merged: "xxxxxxxx"

  components:
    - repo: "acme-org/acme-platform"
      option_id: "xxxxxxxx"
      label: "Platform"
```

### Finding Your IDs

```bash
# List projects and their numbers/IDs
gh project list --owner <owner> --format json | jq '.projects[] | {number, id, title}'

# List field IDs for a project
gh project field-list <project_number> --owner <owner> --format json | jq '.fields[]'

# List option IDs for a single-select field
gh project field-list <project_number> --owner <owner> --format json \
  | jq '.fields[] | select(.name == "Status") | .options[]'
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `owner` | string | **Yes** | GitHub org/user that owns the project board |
| `project_number` | integer | **Yes** | Project number visible in the URL (`/projects/1`) |
| `project_id` | string | **Yes** | GraphQL node ID (`PVT_...`) returned by `gh project list` |
| `field_ids.*` | string | **Yes (per field)** | `PVTSSF_...` IDs for each custom field |
| `option_ids.*.*` | string | **Yes (per option)** | 8-char hex IDs for each single-select option |
| `components` | array | No | Maps `owner/repo` values to Component field option IDs |

**Commands that use this section**: `work-on` (Phase 0C, Phase 6B), `orchestrate`

---

## `orchestration` (OPTIONAL)

Concurrency limits and cascade admission policy for `/orchestrate`'s batch engine. Previously read at runtime (`orchestration.max_concurrent`) but undocumented; this section is the first place it — and the newer `cascade` sub-section (forge#2234) — are formally specified.

```yaml
orchestration:
  # Maximum number of top-level /work-on agents dispatched concurrently. Each
  # worker normally fans out to about 8 total subagent spawns (build, quality
  # gate, and review included), so set this to no more than session_budget / 8.
  # Default: 12; use 25 or fewer for a 200-spawn session budget. This limits
  # in-flight workers only: under cascade.policy: all, raising it increases
  # both completion and finding-spawn throughput and does not itself bound or
  # shrink cascade queue growth.
  max_concurrent: 12

  # Stacked lanes, phase 1 (#5831). off (default): a dependent waits for its dependency to
  # merge before any work. plan: while a dependency is still pending or running, a dependent
  # is planned in an idle slot (after every ready issue): one plan lane per issue per batch
  # investigates and freezes the contract, never builds, commits or pushes, and ends `planned`.
  # Its build lane starts after the dependency merged and reuses that contract unless it is
  # stale (changed scope or lane, or the dependency's merged diff touches a deliverable path).
  # full = plan plus stacked builds (#5832): a dependent whose one unmerged in-batch dependency
  # is PR-ready (review passed, precheck green) builds on that lane head and opens a stacked PR
  # on the dependency's branch. The merge step (guard merge.stacked_base) refuses while the PR
  # base is not the lane or the dependency is unmerged; after it merged the PR moves onto the lane.
  # Cascades (#5833): while it waits, a moved dependency head is rebased onto and re-verified (a conflict
  # restarts the dependent from its frozen contract), a dependency closed without merging drops the
  # stacked PR/branch and re-plans the dependent on the lane base, and after the merge only the checks
  # the dependency's diff touches re-run. Rows carry `cascade`; the batch report counts cascades per dependent.
  # A plan lane's other ends do not count toward the breaker, relaunch or requeue budgets.
  stacking: off

  # Age (hours since the issue last updated) after which a predecessor still at
  # `workflow:remediating` or `workflow:engine-error` is classified GATED
  # (stalled, needs a human) instead of IN_PROGRESS. Default: 48.
  in_progress_max_hours: 48

  # Extra env var names (comma-separated) a batch pins for its lanes in plan.json,
  # beyond the built-in allowlist (PATH, HOME, USER, SHELL, LANG, LC_*, TMPDIR,
  # CLAUDE_CONFIG_DIR, CLAUDE_CODE_USE_*, ANTHROPIC_BASE_URL, ANTHROPIC_MODEL,
  # ANTHROPIC_SMALL_FAST_MODEL, ANTHROPIC_DEFAULT_*_MODEL, FORGEDOCK_*, GH_*, GITHUB_*;
  # secret-looking names and the launching session's other CLAUDE_CODE_*, CLAUDE_PID,
  # ANTHROPIC_* are never pinned unless listed here; the configured execution.token_env
  # name is also kept). Submit prints one line naming the CLAUDE_*/ANTHROPIC_*/GH_*/
  # GITHUB_*/FORGEDOCK_* keys left out (names only).
  # Inspect or edit the pinned env with `forgedock orchestrate --show-env <id>`,
  # `--set-env <id> KEY=VAL`, `--unset-env <id> KEY` (applies to newly launched lanes).
  env_passthrough: ANTHROPIC_BASE_URL

  # Globs (comma-separated) of PATH directories removed from the pinned PATH. Non-existent
  # dirs and per-session temp dirs (an arg0 or claude* dir under a temp root) are always dropped.
  path_exclude: /opt/wrappers/*

  cascade:
    # Named preset expanding to the granular keys below. Any granular key set
    # explicitly overrides just that field — the preset supplies defaults, not
    # hard values. Default: "balanced".
    #   all          — admit everything: no generation cap, no token cap, every
    #                  heuristic-based defer disabled. For a maintainer draining
    #                  a backlog who wants /orchestrate to "pick up everything."
    #   balanced     — the pre-#2234 hardcoded behavior, unchanged: generation
    #                  cap at 1 (i.e. cascade-spawned findings deferred),
    #                  900000-token per-batch ceiling, idle/keyword/same-file
    #                  heuristics all active.
    #   conservative — same admission shape as balanced, with a lower
    #                  (450000) token ceiling for cost-sensitive or noisy repos.
    policy: "balanced"

    # Maximum cascade generation depth admitted. Generation 1 = an original
    # issue (not spawned from a review-finding). Generation 2 = spawned from a
    # review-finding. Generation 3 = spawned from a finding that was itself
    # spawned from a review-finding. Accepts a positive integer or the literal
    # string "unlimited". Governs Phase 1 resolve-time admission only (the
    # `cascade`/`review-findings`/`findings` resolution in phase-1-resolve.md)
    # — it does NOT individually dispatch deferred generation-2+ findings in
    # Step 4C. Bounded P3 batching is the sole automated exception: it may
    # aggregate a finite generation-2 member set under batch_max_generation,
    # as implemented by #2849. This is what makes "admit gen-2, stop at gen-3"
    # expressible, which the pre-#2234 --allow-gen2 flag could not say.
    # Default: 1 (from the "balanced" preset); "unlimited" under "all".
    max_generation: 1

    # Maximum generation a P3 batch may aggregate. Batching is a sanctioned,
    # auditable exception to Step 4C's autonomous cascade cap: it can fold
    # several deferred low-priority findings into one reviewed unit, but it
    # must never make recursion unbounded. Every batch records the maximum
    # member generation in FORGE:BATCH_MAX_GENERATION. This value is always
    # finite, even under policy: all. Default: 2.
    batch_max_generation: 2

    # Permit closure only of mechanically identical bot/app alerts: same
    # normalized title, generator, and trigger condition, while retaining one
    # canonical issue. Human reports are never included. Default: false.
    dedup_automated: false
    # Per-batch token ceiling for Step 4C's review-finding cascade dispatch.
    # New home for the same lever previously read only as
    # `pipeline.token_budget_per_batch` (kept working as a deprecated alias —
    # see the `pipeline` section below). Accepts a positive integer or
    # "unlimited". Default: 900000 (from "balanced"); 450000 under
    # "conservative"; "unlimited" under "all".
    token_budget: 900000

    # Whether a fully human-gated original batch (forge#1814's
    # BATCH_FULLY_GATED — every original-batch issue DONE/FAILED/GATED with at
    # least one GATED) suppresses further cascade-finding dispatch. Default:
    # true (from "balanced"); false under "all".
    defer_on_batch_gated: true

    # Whether the comment/typo title-keyword heuristic defers P3-and-below
    # cascade findings. Default: true (from "balanced"); false under "all".
    keyword_heuristic: true

    # Whether a P3 finding sharing a file with the active batch is deferred
    # (avoids serializing agents on same-file predecessor edges). Default:
    # true (from "balanced"); false under "all".
    p3_same_file_defer: true

    # Running findings-spawned / merged-units ceiling. "off" (the default)
    # only reports amplification; a positive decimal defers further
    # same-lineage refinements to the completion sweep once exceeded.
    max_amplification: "off"

    # Number of consecutive merged-unit observations at ratio >= 1.0 before
    # printing a convergence warning. Default: 3.
    convergence_window: 3

    # On-by-default amplification circuit breaker (forge#3060). Counts ALL
    # cascade findings (new surface as well as same-lineage refinements). When
    # the ratio stays >= 1.0 for convergence_window merged units, P3-and-below
    # admission pauses, the operator gets a report (ratio + queue size), and the
    # paused P3s wait for bounded P3 batches. P1/P2 are never affected, and
    # `policy: all` / unlimited overrides do not disable it. "on" (default) | "off".
    amplification_breaker: on

  # In-batch recovery (#4267): recovery lanes `forgedock orchestrate` launches
  # per issue for a mechanical needs-human (ci.red, base.conflict, ...).
  # Default 1; 0 disables in-batch recovery.
  recovery:
    max_attempts: 1

  # Parked-PR base sync (#4525): while a batch runs, a needs-human PR whose base moved
  # is merged with the base. Default on; `enabled: false` opts out.
  base_sync:
    enabled: true
    union_globs: "CHANGELOG.md, src/registry/*.ts"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `max_concurrent` | integer | No | Max concurrent top-level `/work-on` dispatches. It does not bound cascade growth; under `policy: all` it raises drain and spawn throughput together. Default: 12. |
| `breaker.errors` / `breaker.window_min` | integer | No | `forgedock orchestrate` circuit breaker (#4121): after `errors` engine-errors within `window_min` minutes the batch stops admitting lanes, lets running lanes finish, and keeps the rest pending for `--resume`. `errors: 0` turns it off. Default: 3 in 30 |
| `max_deferrals` | integer | No | `forgedock orchestrate`: requeues of one issue after a non-host `deferred` (usage limit, merge/push transient, CLI idle, lease held, gh unavailable) before its row is final. `host.busy` and `sandbox.capacity` (sandbox pool full) deferrals are not capped. Default: 3 |
| `transient_retries` | integer | No | `forgedock orchestrate` (#5161): backoff retries of an issue whose lane ended `engine-error` with a transport or gateway failure in its detail (curl `returned error: 5xx`, `HTTP/1.1 5xx`, `Bad Gateway`, `Service Unavailable`, `overloaded`, connection reset/refused/timeout). Delays 30s, 2m, 8m, then 15m each; dependents stay pending meanwhile. Not counted against the single engine-error relaunch; once spent, the row ends `engine-error`. Every such error still counts toward the breaker. `0` turns transient retries off. Default: 4 |
| `blocked_label` | string | No | `forgedock orchestrate` (#4773): an open issue carrying this label is admitted to the batch but not dispatched; removing the label releases it on the next scheduler pass. A `Blocked by #N` / `Depends on #N` line in the body of a trusted author (OWNER, MEMBER, COLLABORATOR or a bot) is a DAG edge to #N, and `--add` prints the edges it created. Empty turns the label off. Default: `blocked` |
| `auto_add_children` | string | No | `forgedock orchestrate` (#4965): which children a running batch adds by itself. `off` (no auto-adds; a decomposed lane's sub-issues stay out too), `decomposed` (a decomposed lane's sub-issues join, as before), `epic` (also the open children of every batch issue and of each `--epic N`, found by a `**Parent**: #P` line, the `parent` field or GitHub sub-issues, including children filed after the batch started) or `all`. Only children whose author is trusted (an owner, member or collaborator, or a bot, the `Blocked by` rule) are auto-added; any other is skipped with a logged row. Children labelled `needs-human` and children another live batch of the repo still holds are not added. Each pass that adds posts one batch decision and one `added` row listing the children and edges. `forgedock orchestrate --auto-children <mode>` overrides it per batch and `--resume` keeps it. Default: `decomposed` |
| `auto_add_children_poll_s` | integer | No | Seconds between child scans for `epic`/`all` (one `gh issue list` per scan). Default: `120` |
| `global_parallel` | integer | No | `forgedock orchestrate` (#4191): host-wide cap on running lanes across every batch and repo on the host, enforced through the host lane registry (`~/.forge/sched/`, or `FORGEDOCK_SCHED_DIR`). A freed slot goes to the highest-priority queued issue (`priority:P<n>` / `P<n>` labels, unlabelled P2); within a priority, slots are shared across repos by weight (#4193: `forgedock sched weight <owner/repo> N`, `--clear` resets; default equal, FIFO inside a repo), and priority always dominates weights; running lanes are never preempted and `--parallel` K still bounds each batch. `forgedock sched cap N` overrides it live for the whole host (`--clear` reverts); `forgedock sched show` lists the weights, slots and the queue. Default: unset (no global cap) |
| `recovery.max_attempts` | integer | No | `forgedock orchestrate` in-batch recovery (#4267): how many recovery lanes the batch launches per issue for a `needs-human` with a mechanical code (`ci.red`, `base.conflict`, `ci-pending` on a conflicting PR, `contract.invalid` after a mid-run issue edit, `builder.block_untyped`, the `env.*` codes, `contract.invalid_command`, `budget.exceeded`, and since #5035 `conformance.unimplemented`, `conformance.omission` and `conformance.unjustified_deferral`; the full list is in docs/OUTCOME-CODES.md). A recovery lane (`run-issue --recover <code>`) removes `needs-human`, posts a `FORGE:DECISION`, resumes the open PR and re-queues the issue with its dependents. If it ends anything but `merged`, the issue is labelled `needs-human` again with a recovery-evidence `FORGE:NEEDS_HUMAN` comment. Human codes are never recovered. Flat form: `recovery_max_attempts`. Default: 1; `0` disables in-batch recovery (a mechanical `needs-human` is final, as before). |
| `recovery.mechanical_max_attempts` | integer | No | `forgedock orchestrate` (#4725): the separate recovery budget of mechanical `needs-human` rows (`env.*`, `base.conflict`, a conflicting PR); never below `recovery.max_attempts`. Flat form: `recovery_mechanical_max_attempts`. Default: 2, so with the default config such a row gets 2 recovery lanes, not 1. |
| `base_sync.enabled` | boolean | No | `forgedock orchestrate` parked-PR base sync (#4525): every 10 min while the batch runs, an open PR of a `needs-human` row is merged with its moved base in a throwaway worktree. A clean merge, or one whose only conflicts are hunks where both sides purely added lines in a `union_globs` file, is pushed as a plain merge commit (never forced). Any other conflict is aborted, the branch left alone, and its paths are posted once per base sha as a `FORGE:DECISION` on the issue. Sequence/`_journal.json` files are never resolved here. Flat form: `base_sync_enabled`. Default: `true`; `false` opts out. |
| `base_sync.union_globs` | string | No | Comma-separated globs (`*` within a segment, `**` across; no `/` matches the file name anywhere) of well-known append-only files (registries, changelogs) whose two-sided line additions the base sync keeps both of. Flat form: `base_sync_union_globs`. Default: none (every conflict is reported). |
| `cascade.policy` | string | No | `all` \| `balanced` \| `conservative`. Default: `balanced` |
| `cascade.max_generation` | integer or `"unlimited"` | No | Max cascade generation admitted at Phase 1 resolve time. Default: 1 |
| `cascade.batch_max_generation` | integer | No | Finite maximum member generation that an automated P3 batch may aggregate. Default: 2 |
| `cascade.dedup_automated` | boolean | No | Allow only mechanically identical bot/app alerts to be closed with a retained canonical issue. Default: `false` |
| `cascade.token_budget` | integer or `"unlimited"` | No | Per-batch token ceiling for Step 4C cascade dispatch. Default: 900000 (deprecated alias: `pipeline.token_budget_per_batch`) |
| `cascade.defer_on_batch_gated` | boolean | No | Suppress cascade dispatch when the original batch is fully human-gated. Default: `true` |
| `cascade.keyword_heuristic` | boolean | No | Defer P3-and-below comment/typo-titled findings. Default: `true` |
| `cascade.p3_same_file_defer` | boolean | No | Defer P3 findings sharing a file with the active batch. Default: `true` |
| `cascade.max_amplification` | positive number or `"off"` | No | Opt-in ceiling for same-lineage refinement dispatch. Default: `"off"` |
| `cascade.convergence_window` | positive integer | No | Consecutive ratio observations at or above 1.0 before warning. Default: 3 |
| `cascade.amplification_breaker` | `on` \| `off` | No | Pause P3-and-below cascade admission while the findings-spawned / merged-units ratio stays at or above 1.0 for `convergence_window` units. Counts all cascade findings (not only same-lineage); P1/P2 unaffected; independent of `cascade.policy`, so `policy: all` does not disable it. Paused P3s route to bounded P3 batches. Default: `on`. Opt out with `off` (boolean `false` is accepted as `off`, `true` as `on`). |

**Upgrade note — in-batch recovery is on by default** (1.29.0): without `orchestration.recovery.max_attempts`, `forgedock orchestrate` launches one recovery lane per issue for a mechanical `needs-human` before reporting it. To keep the previous behavior (every `needs-human` final), set `orchestration.recovery.max_attempts: 0`. The budget of mechanical rows (`env.*`, `base.conflict`, conflicting PR) is `orchestration.recovery.mechanical_max_attempts` (default 2, #4725); set it to `0` as well to turn those off.

**Upgrade note — `cascade.amplification_breaker` is on by default**: existing configs that do not set this key now get the breaker automatically. During a batch, once the findings-spawned / merged-units ratio stays at or above 1.0 for `convergence_window` units (it can trip at exactly 1.0 over 3 units), P3-and-below cascade admission pauses; paused P3s are routed to bounded P3 batches rather than dispatched individually. P1/P2 are unaffected. To keep the previous behavior, set `orchestration.cascade.amplification_breaker: off` (or `false`). See [RELEASE-NOTES.md](RELEASE-NOTES.md) for the release that introduced this default.

**Hard invariant — not configurable**: safety exclusions (findings whose `## Problem` section indicates security/billing/anti-bot/auth concerns) are never batched and never auto-admitted by any `cascade.policy`, including `all`. That exclusion is enforced upstream of this section (the P3 batching eligibility check) and has no corresponding key here by design.

**CLI overrides**: `--policy`, `--max-generation`, `--token-budget` on `/orchestrate` take precedence over these keys for a single invocation — see `commands/orchestrate/config.md` → "Cascade Policy CLI Flags".

**Commands that use this section**: `orchestrate`

---

## `orchestrate.lane_audit` (OPTIONAL)

Engine-gap filing of the lane audit (#6078). When a lane ends needs-human or engine-error on an active pipeline/env/pool signature, the audit can file an issue in the engine repo.

```yaml
orchestrate:
  lane_audit:
    file_gaps: false              # default false; only the string true enables
    repo: RapierCraftStudios/ForgeDock   # optional: engine repo to file in
    label: engine-gap             # optional
```

One issue per signature: it is found by the `<!-- forge-gap: SIGNATURE -->` marker among open issues with the label; a further lane with the same signature updates its occurrence count and affected-lane list (`#N`, a lane is counted once). Nothing is filed for `fixed_in_later` signatures or genuine/spec classes. Redaction: the body holds only the signature, class, owner, action, engine version, count and lane issue numbers; any text in it has the lane's repo name, `owner/name` patterns and absolute paths replaced by `<repo>`/`<path>`. Filing failures are ignored and never change how the lane ends.

---

## `orchestrate.health` and `notify` (OPTIONAL)

Early batch health (#5167). `forgedock orchestrate` checks each batch at T+15 and T+60 minutes after it was created (`plan.json` `created`), and once more when the batch ends. When the batch starts, it prints the schedule: `health checks: T+15 14:05Z, T+60 14:50Z, and at batch end; forgedock status --batch <id>`. The first unhealthy check raises one `BATCH UNHEALTHY <id>` alert, which lists the top causes and the exact recovery commands (`--requeue`, a relaunch, `--resume`, `--cancel`). `health.json` in the batch dir records the checkpoints already done and the alert, so a daemon restart arms only the remaining checks and a batch never alerts twice. Checks and alerts never fail, delay or change the batch.

Causes: `root-failed` (a root issue, meaning one with no dependency inside the batch, ended non-merged); `terminal-share` (the share of rows ended `skipped`/`held`/`engine-error`/`needs-human` or another non-merged outcome except `invalid`/`decomposed` is at or above the threshold, with nothing merged); `stalled` (0 lanes running while issues are pending, operator-held issues excepted); `refused` (the launch was refused).

```yaml
orchestrate:
  health:
    root_failed: true      # any root ended non-merged is unhealthy (default true)
    terminal_share: 0.5    # 0..1, terminal-non-merged share with 0 merged (default 0.5)
    stalled: true          # 0 running while pending > 0 (default true)
    issue: 123             # comment target; default: the batch's --epic issue(s); a milestone gets no comment
    checks_min: [15, 60]   # minutes after launch (default [15, 60])
notify:
  command: "curl -fsS -H 'content-type: application/json' -d @- https://hooks.example/forge"
```

| Key | Default | Meaning |
|---|---|---|
| `orchestrate.health.root_failed` | `true` | Raise `root-failed`. |
| `orchestrate.health.terminal_share` | `0.5` | Threshold for `terminal-share`. |
| `orchestrate.health.stalled` | `true` | Raise `stalled`. |
| `orchestrate.health.issue` | none | Issue to comment on. When unset, the alert comments on each `--epic` issue. |
| `orchestrate.health.checks_min` | `[15, 60]` | Timed checkpoints, in minutes after launch. |
| `notify.command` | none | Shell command run once per alert. It gets the alert JSON (`{alert, batch, repo, text, causes, recovery}`) on stdin and `FORGEDOCK_ALERT=BATCH_UNHEALTHY`, `FORGEDOCK_ALERT_BATCH` and `FORGEDOCK_ALERT_TEXT` in its env. It is killed after 30 s. A failure only prints a `health: notify.command failed` line. |

The keys are flattened one level by the parser, the same as `orchestrate.drift.*`. Health keys alone do not turn drift on.

Every channel is best effort: the runner line, the GitHub comment (marker `FORGE:BATCH-HEALTH`), `notify.command`, and the `forgedock status` line. `forgedock status` lists the unhealthy batches that are unresolved (no report yet, or alerted within the last day) and the launch refusals from the last day. `forgedock status --batch <id>` shows that batch's health (healthy, or unhealthy with causes and recovery) and its pending checkpoints.

A refused milestone start (#4659, `parallel milestone start refused: …`) still exits 1 with the error on stderr and creates no batch dir. It is also recorded in `<batch root>/refusals.json` (the newest 20 are kept) and sends the same alert, with the merge-the-dependency or `--force "<reason>"` relaunch.

**Commands that use this section**: `forgedock orchestrate`, `forgedock status`

---

## `decisions` (OPTIONAL)

Decision engine (#4766, see [DECISIONS.md](DECISIONS.md)). The issue-watch stage (#4793) calls `settle` for the open `needs-human` issues a watch selects: it runs when `mode: live` (a repo setting: every watch of the repo runs the stage), or when the watch sets `sweep_needs_human: true`; `policy` and `human_only` are also read by prodwatch (`loadPolicy`). The parser has one nesting level and no arrays, so lists are comma-separated.

| Key | Type | Description |
|---|---|---|
| `policy` | string | The repo's north-star file. Default `NORTHSTAR.md`, falling back to `CLAUDE.md`, then `AGENTS.md`. |
| `mode` | string | `shadow` (default: post `FORGE:DECISION (shadow)`, keep the label) or `live` (clear `needs-human`, requeue). |
| `human_only` | list | Authority-matrix classes that always stay human. Default `spend,credentials,external-publish,customer-send,prod-write,promotion,legal`. |
| `hint_<class>` | list | Match words for a class; replaces the built-in hints, and is required for a class that is not built in. |
| `veto_hours` | number | Owner veto window after a live decision (default 24). |
| `reversal_max` | number | Reversal rate (0-1) above which live falls back to shadow (default 0.2, minimum sample 5). |

## `hygiene` (OPTIONAL)

Automatic reclaim of what ForgeDock leaves behind (#4183), using the `forgedock gc` reaper. Only resources ForgeDock provably owns are reclaimed: entries of a stale lane ledger, Docker containers and volumes labelled `forgedock.owner=1`, `lean-*`/`agent-*` dirs under `.claude/worktrees`, `feat/issue-<n>-lean` branches of closed issues, and ForgeDock scratch under `~/.forge/tmp`. Everything else is reported, never touched, and so are unpushed or uncommitted work, live lanes, protected branches and branches with an open PR. Block form only.

```yaml
hygiene:
  container_ttl_hours: 6
  worktree_ttl_hours: 24
  tmp_ttl_hours: 6
  delete_merged_branches: true
  max_host_load_ratio: 0.8
  auto_gc: true
  schedule: 6h
  min_free_gb: 5
```

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `container_ttl_hours` | number | `6` | Age after which owned Docker containers and volumes are reclaimed (an expired `forgedock.expires` label reclaims earlier). |
| `worktree_ttl_hours` | number | `24` | Age after which owned worktrees (clean and pushed) and abandoned lane branches are reclaimed. |
| `tmp_ttl_hours` | number | `6` | Age after which `~/.forge/tmp` run dirs (owner dead) and runner scratch (no live process) are reclaimed. |
| `delete_merged_branches` | boolean | `true` | `false`: lane branches of closed issues are reported, never deleted. |
| `max_host_load_ratio` | number in (0,1] | `0.8` | Near-ceiling trigger relative to the `engine` admission thresholds: load/core at or above ratio × `max_load_per_core`, or free memory/tmp at or below the minimum ÷ ratio. |
| `auto_gc` | boolean | `true` | `false` disables GC in `forgedock orchestrate`; `forgedock gc` and `forgedock doctor --fix` still work. |
| `schedule` | duration | unset | e.g. `6h`, `30m`, `2d`. `doctor --fix` and `init` install a systemd user timer (cron fallback) that runs `forgedock gc --apply` (owned scope only) with no batch running. Unset or `auto_gc: false`: no timer. |
| `min_free_gb` | number | `5` | Free disk (GB) on the worktree root and `~/.forge` below which orchestrate runs GC before an admission and refuses heavy steps (image builds) if GC cannot free enough. `0` = off. Doctor warns below it. |

Invalid values fall back to the default. `forgedock gc --older-than <d>` overrides every TTL for that run. Resources of a live lane (its ledger owner is alive) are always skipped.

**Where it runs**: `forgedock orchestrate` applies GC once before admitting lanes, and again before an admission when the host is near the ceiling (at most every 5 minutes). The batch report ends with `reclaimed: N item(s), SIZE (preflight A, admissions B)`, or `reclaimed: off (hygiene.auto_gc: false)`. `forgedock doctor` shows a **Resource hygiene** check (owned counts and sizes, reclaimable count, unowned stale items as warnings), and `doctor --fix` runs the reaper. `/cleanup branches` calls `forgedock gc`.

**Commands that use this section**: `orchestrate`, `doctor`, `gc`, `cleanup`

---

## `pipeline` (OPTIONAL)

Tuning knobs for the CLI backend and `/orchestrate`'s batch engine — invocation and stall timeouts, narration verbosity, and (deprecated alias only, see `orchestration.cascade` above) the review-finding cascade token budget. All keys optional; sane defaults apply when omitted.

```yaml
pipeline:
  # Wall-clock limit for one CLI backend invocation. The environment variable
  # FORGEDOCK_CLI_TIMEOUT_MS (milliseconds) takes precedence. Default: 60.
  cli_timeout_minutes: 60

  # Minutes an agent may sit idle (no FORGE:HEARTBEAT / label change) before
  # /orchestrate's stall detector treats it as stuck and attempts an
  # auto-resume. Default: 15.
  stall_timeout_minutes: 15

  # Deprecated alias for orchestration.cascade.token_budget (forge#2234) — kept
  # working so existing configs are unaffected. When both are set,
  # orchestration.cascade.token_budget wins. Default: 900000.
  token_budget_per_batch: 900000

  # Estimated token cost of a single P3-or-lower review-finding /work-on
  # pipeline, used to decrement the token budget above. Default: 150000.
  token_estimate_per_finding: 150000

  # Narration verbosity for /orchestrate's per-completion status updates.
  # "terse" (default): one line per completion. "verbose": adds a running
  # per-completion recap table. Cosmetic only — never changes which phases run.
  narration: "terse"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `cli_timeout_minutes` | integer | No | Wall-clock minutes for one CLI backend invocation. Default: 60. `FORGEDOCK_CLI_TIMEOUT_MS` (milliseconds) takes precedence. |
| `stall_timeout_minutes` | integer | No | Idle minutes before the stall detector attempts auto-resume. Default: 15 |
| `token_budget_per_batch` | integer | No | **Deprecated** — use `orchestration.cascade.token_budget`. Default: 900000 |
| `token_estimate_per_finding` | integer | No | Estimated tokens per P3-or-lower cascade finding. Default: 150000 |
| `narration` | string | No | `terse` \| `verbose`. Default: `terse` |

**Commands that use this section**: CLI backend (`cli_timeout_minutes`); `orchestrate` (remaining keys)

---

### `ci` budget and placement (forge#5278)

Actions-minutes awareness and where CI runs. Keys are flat under `ci:` (the parser is one level deep; they coexist with the `milestone_integration` keys above).

```yaml
ci:
  mode: auto               # remote | local-first | local-attested | auto (default)
  monthly_minutes: 40000   # budget; default: the plan's included minutes
  reserve_pct: 10          # headroom under the budget before auto switches (0-90, default 10)
  # included_minutes: 50000  # override the built-in plan table (free 2000, pro/team 3000, enterprise 50000)
  # plan: enterprise         # override the detected plan
```

| `mode` | Behaviour |
|---|---|
| `remote` | Current behaviour: `verify.mode` ci/hybrid push and wait for Actions. |
| `local-first` | Host checks must pass before anything is pushed that triggers paid CI; `verify.mode` ci/hybrid run as `local`. Paid CI runs once on the release head. |
| `local-attested` | As `local-first`, and the host result is posted as a `forgedock/ci-local` commit status; paid CI only for release/nightly. Trust trade-off: the status is attested by ForgeDock, not run by Actions, the same trust as a self-hosted runner. |
| `auto` | `remote` while the projected month stays under `monthly_minutes` less `reserve_pct`; otherwise `local-first`, announced in the next batch/release report. A public repo (free hosted minutes) is never switched; an unreadable billing API stays `remote`. |

`forgedock ci budget [--repo owner/repo] [--json] [--digest] [--propose [--base REF]]` prints the plan, included minutes, month-to-date usage across the account (billing usage API: needs a token that can read the org or user billing), the projection, the active mode, alerts (projected overage, a new burn source such as a repo flipped private) and the parity hit rate (local green -> remote red, per suite). `--digest` adds the per-repo and per-workflow month digest; `--propose` lists the runnable local jobs derived from the repo's workflow files (same tool pins). `--set-mode`, `--budget`, `--reserve`, `--plan` write the `ci` block (see `/forgedock-ci-setup`). Runner minutes are weighted by OS (Linux 1, Windows 2, macOS 10). Caches live in `~/.forge/ci-budget/` (`FORGEDOCK_CI_BUDGET_DIR`).

### `ci.tests` test engine (forge#5710)

Affected-test selection, shard planning and flaky quarantine for `forgedock tests select|shard|recall` (see [test-engine.md](test-engine.md)). Off by default. Block style; the parser flattens these keys under `ci`, so their names are unique within `ci`.

```yaml
ci:
  tests:
    selection: shadow        # off (default) | shadow | enforce (refused until the recall ledger graduated)
    suites:                  # "<path glob> ... => <test-file glob | @suite | *> ..."
      - "migrations/** => tests/integration/**"
    # run_all: ["infra/**"]          # extra globs that select everything (lockfiles, manifests and CI files always do)
    # ignore: ["**/*.md"]            # changed files that select nothing
    # test_globs: ["tests/**/*.py"]  # replaces the *.test.* / *.spec.* / __tests__ / test_*.py / *_test.py convention
    # full_branches: [main, "release/**"]  # head or PR-base branches that always run the full suite
    graduate_after: 50       # consecutive full runs with 100% failure recall before enforce may skip
    graduate_min_failing: 1  # of those, subset selections that contained a real failure
    shards: 4                # default shard count of `tests shard`
    # shard_target_s: 240    # or derive the count from a per-shard time target
    quarantine: report       # off | report (default) | non-blocking (opt-in; never for an unskippable class)
    quarantine_after: 3      # same-commit fail -> pass flips ...
    quarantine_window_days: 14   # ... inside this window
    # recall_ledger: /var/lib/forge/recall.jsonl  # default ~/.forge/tests/<owner>__<repo>/recall.jsonl
```

| Key | Type | Default | Description |
|---|---|---|---|
| `selection` | string | `off` | `off`: nothing is computed. `shadow`: the selection is recorded and the full suite runs. `enforce`: only the selection runs, once the ledger graduated; before that it behaves as `shadow` and says so. |
| `suites` | list | none | Declared path -> suite map, the fallback for what the import graph cannot see. |
| `run_all`, `ignore`, `test_globs`, `full_branches` | list | see above | Selection inputs. Changing `suites`, `run_all`, `ignore` or `test_globs` restarts graduation. |
| `graduate_after`, `graduate_min_failing` | number | 50, 1 | Graduation criterion. |
| `shards`, `shard_target_s` | number | none | Shard count, or a time target to derive it from. |
| `quarantine`, `quarantine_after`, `quarantine_window_days` | string, number, number | `report`, 3, 14 | Flaky-test report. Quarantined tests always run. |
| `recall_ledger` | string | per-repo file under `~/.forge/tests/` | Where the recall ledger lives. |

Scheduled runs and `full_branches` always run the full suite, whatever the mode. **Commands that use this section**: `forgedock tests select`, `forgedock tests shard`, `forgedock tests recall`.

## `execution` (OPTIONAL)

Owner opt-in for the paid API agent backend (#4257). The API backend is **never the default**: under `--backend auto` (the default) ForgeDock uses the `claude` CLI, and when no CLI is available it fails with `CLI_BACKEND_UNAVAILABLE` instead of billing `ANTHROPIC_API_KEY`.

```yaml
execution:
  # Use the API backend when `auto` finds no usable claude CLI. Takes effect only
  # together with the env var FORGEDOCK_ALLOW_API_BACKEND=1 on the host.
  agent_backend: api
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `agent_backend` | string | No | `api` approves the API backend as the `auto` fallback, only when `FORGEDOCK_ALLOW_API_BACKEND=1` is also set. Any other value, or no value, means `auto` never selects `api`. |

An explicit `--backend api` / `FORGEDOCK_BACKEND=api` still selects the API backend without this section; that flag is itself the explicit choice.

**Commands that use this section**: `forgedock run`, `forgedock run-issue`, `forgedock backend-check`

---

## `engine` (OPTIONAL)

Per-command `--model` and `--max-turns` for the CLI backend (`forgedock run-issue` phases and `forgedock run <command>`). Opt-in: with no keys set, the `claude` invocation is unchanged and uses the CLI's own default model with no turn bound. `forge.yaml` is parsed one level deep, so settings are **flat** keys under `engine:`, named `<key>_model` and `<key>_max_turns`, where `<key>` is the command name with every non-alphanumeric character replaced by `_`.

```yaml
engine:
  # work-on/review -> work_on_review (the review phase is the most expensive).
  work_on_review_model: sonnet
  work_on_review_max_turns: 120

  # review-pr-staging -> review_pr_staging (non-work-on commands work the same way).
  review_pr_staging_max_turns: 80
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `<key>_model` | string | No | Model alias (`sonnet`, `opus`, `haiku`) or full model id passed as `--model`. Invalid values are ignored. |
| `<key>_max_turns` | integer | No | Positive integer passed as `--max-turns`. Invalid values are ignored. |

| `path` | string | No | `core` (default), `full`, `lean` or `auto`. `core` is the lean work-on (`bin/lean/`): a planning call that writes a frozen contract, an implement call in the same session, one read-only conformance reviewer, GitHub as the register (see `conformance`). `lean` and `auto` are aliases of `core`; `full` runs the legacy multi-phase pipeline and is required for `--retry` and `--wait-lease`. The `--path` flag overrides. `lean_reviewer_model` sets the reviewer model (default `claude-sonnet-5-5`); the builder uses `--model` or the CLI default. `forgedock orchestrate <issues...> [--parallel K] [--lane L]` runs the core per issue (K default 3, lane default `staging`) and honours `**Depends on**` ordering among the given issues. A lane that reports an open dependency pulls it into the batch, unless that dependency is labelled `needs-human` or already ended `needs-human` in the batch: then the issue and its dependents end `skipped (dependency #N needs-human)` without a lane for it (forge#4387). |
| `conformance` | string | No | Core work-on conformance gate. The builder first writes a contract (requirements quoted verbatim from the issue and maintainers' comments, deliverables, preserve constraints, validate commands), which the engine freezes and posts as `FORGE:CONTRACT`; changes go only through typed amendments (`FORGE:AMENDMENT`). A deterministic precheck (scope, validation, deferrals) and a row-based conformance review follow, and the engine computes the verdict. `shadow` (default): the verdict is posted in `FORGE:REVIEW` and logged (`CONFORMANCE_SHADOW` event) but only what the previous reviewer blocked on still blocks (a requirement found not implemented, a regression), plus the precheck's equivalent: any `conformance.unimplemented` precheck or amendment failure (a validate command that failed or has no recorded result, a deliver requirement the builder reported as not implemented, an invalid amendment; #4160). These block before any reviewer run. Scope creep and omissions are recorded only. A review still incomplete or inconsistent after one targeted re-ask (only the missing ids) ends `needs-human`, or with `review_incomplete: degraded` merges with a `review-degraded` PR label and a tracked follow-up. Accepted deferrals are filed and linked, as in enforce. `scripts/calibration.mjs --shadow` reports the per-repo shadow verdict mix and when to switch to enforce. `enforce`: every failure blocks (one same-session builder resume, then `needs-human` with a `conformance.*`/`review.*` code, see docs/OUTCOME-CODES.md); deferrals the reviewer accepts are filed in one batched follow-up issue (`scripts/file-deferred-followups.sh`) and linked in the PR body and a `FORGE:TRACKED` comment before merge. |
| `conformance_kinds` | string | No | Per-check-kind gate modes. A flat list `"code=mode, code=mode"`, for example `"conformance.omission=enforce, conformance.guard_broken=shadow"`; mode is `enforce` (blocks) or `shadow` (recorded in `FORGE:REVIEW` and the run log, never blocks). A kind listed here follows its own mode in a shadow and in an enforce lane; every other kind follows `conformance`. A `review.risk_paths` hit still enforces the whole lane. Invalid entries are dropped; absent changes nothing. **Enforcement rule:** enforce a kind only when its measured false-block rate is ~0 over enough blocks; keep the rest in shadow. Measure with `node scripts/conformance-calibrate.mjs --labels docs/eval/conformance-labels-v1.json [--replay <corpus.json>]`, which scores labelled lane verdicts (and an optional replay corpus) and prints precision, recall and false-block rate (false blocks / blocks) per kind, plus the `conformance_kinds` value the data supports (default: at least 3 blocks and 0 false blocks; `--min-blocks`, `--max-false-rate`). A deliver requirement whose test deliverable no executed passing validate runs is listed as unverified with its id (decision line, `REQUIREMENT_UNVERIFIED` event; report only). With `conformance_kinds` set, the lane row carries the failure codes seen (`kinds`) and the batch report adds per-kind would-block shares. |
| `conformance_mutation` | string | No | `off` (default) or `report` (#4913). `report` reruns each deliver requirement's executed evidence test with the diff's non-test files reverted to the merge base (`git apply -R`, restored from HEAD afterwards, even on error); a test that still passes is vacuous and raises `conformance.mutation_survived` (`REQUIREMENT_MUTATION_SURVIVED` event, decision line). The kind is shadow (recorded only) unless `conformance_kinds` sets `conformance.mutation_survived=enforce`. A dirty tree, failed revert, timeout (124) or missing runner skips the check, never fails it. Capped at 120 s per gate. Judge promotion with `node scripts/conformance-calibrate.mjs --labels <labels.json> --events <run-log>`: it prints the survived-mutation share and the false-survived rate (#4929). |
| `cli_idle_minutes` | number | No | Core builder idle timeout (#4112): the builder CLI runs with `--output-format stream-json` and is killed (code `cli.idle`) when it shows no stream activity for this many minutes. The run log records the last tool call and the live child processes. Default 15. |
| `cli_busy_minutes` | number | No | Extended idle window for a core builder (#4405). When the idle timeout is reached but the session has a live heavy step (a heavy-shim step, test runner, linter or type checker child) or a queued or running heavy-queue entry of its own processes, the kill waits until `cli_idle_minutes` + this many minutes of silence. The run log records `CLI_IDLE_EXTENDED` once per silent stretch, and a later `CLI_IDLE_KILL` carries `heavyQueue` ({queued, running}) and `extended: true`. A silent session with no such child is still killed at `cli_idle_minutes`. Default 45 (the heavy queue's 30-minute maximum wait plus the 15-minute idle default). |
| `cli_max_minutes` | number | No | Absolute ceiling for a core builder session (code `cli.timeout`), replacing the fixed 60-minute kill. A session that keeps making progress is never idle-killed. Default 180. On either kill, uncommitted work is committed as `wip(forge): checkpoint after <reason>` and the lane branch is pushed (with the push retry), the builder retries once from the checkpoint, and a second kill ends `deferred`; a rerun resumes from the branch. |
| `split_plan` | boolean | No | `false` (default, #6207): one builder session. The plan, contract and implement calls resume the same CLI session, so the code the plan read is reused and the build never restarts cold from a digest (an explicit `route_handoff_tokens` still applies). `true` restores the two-session path (a plan above `route_handoff_tokens`, default 40000, hands the build a digest). |
| `builder_model_tier` | string | No | `auto` (default, #6207): today's size/risk routing (`lean.builder_routing`). `mid` or `top` pins the builder tier so an A/B can compare them on the #6203 scorecard (`builder_tier_setting` on RUN_TERMINAL). A pinned `mid` still sends risk-class lanes to the top model, and a failed validate round still escalates a mid lane. |
| `turn_budget_s` / `turn_budget_m` / `turn_budget_l` | number | No | Core implement turn budget per lane size (#4392). Size comes from a `size:S|M|L` issue label, else the frozen contract's distinct deliverable paths (S ≤ 2, M ≤ 5, else L). The build call and its context/timeout restarts share the budget; at the limit the session is stopped, checkpointed, and one fresh wrap-up session of max(5, budget/5) turns either finishes or writes `status: budget-exceeded` with a digest. A stop or overrun ends with the non-human `budget-exceeded` reason and code `budget.exceeded` (no `needs-human` label, forge#4505), which `forgedock orchestrate` recovers once (continue from the checkpoint or split); a batch that does not recover it labels it `needs-human` once. Lane results carry `turns: {size, budget, build, total, exceeded}`, and the batch report prints `turns by size`. Defaults 25 / 60 / 100; 0 disables that size. An L lane's budget scales with the contract: +10 turns per distinct deliverable path above 5 (capped at +2x `turn_budget_l`), and a `budget.exceeded` recovery of an L lane gets a further +50% of `turn_budget_l` (#4587). |
| `lane_limits` | map | No | Cap each core lane's whole process tree (#4115, #4690), under `pipeline:` or `engine:`: `tasks_max` (default `1024`; `0`/`off` disables), `memory_max` (for example `3G`) and `cpu_quota` (for example `150%`). Where `systemd-run --user --scope` works (probed once) every lane's builder CLI is spawned as `systemd-run --user --scope -q --unit=forgedock-lane-... -p TasksMax=... -p MemoryMax=... -p CPUQuota=... -- claude ...` by default. `memory_max` has no default: lanes get no `MemoryMax` unless it is set (`off` also disables; #4740). A lane that hits `TasksMax` or `MemoryMax` is stopped and ends `needs-human` with `env.lane_limit` (not an engine-error, so the breaker ignores it). Where scopes are unavailable the run logs one line saying lanes are uncapped and the limits are ignored. Write it nested or flat (`lane_limits_tasks_max`, `lane_limits_memory_max`, `lane_limits_cpu_quota`). While a builder runs the engine polls host load and memory every 15 s against the `admission` thresholds: over them it SIGSTOPs the lane's process group, under them SIGCONT, and never pauses longer than 10 minutes. |
| `admission` | map | No | Host-resource admission for the core work-on (#4105), checked before the lease, worktree or any GitHub call. When a check fails the run ends `deferred` (code `host.busy`, exit 75) with a last line such as `issue #N → deferred (host busy: mem 1.2G < 2G; retry in 60s)`; no lease is taken and nothing is posted. Keys: `enabled` (default `true`; `false` disables admission), `min_free_mem_mb` (default 2048; `MemAvailable` from `/proc/meminfo`, else `os.freemem()`), `min_free_tmp_mb` (default 1024; free space of the run TMPDIR filesystem, `~/.forge/tmp`, and of `/tmp`, via `statfs`), `max_load_per_core` (default 4; 1-minute load average divided by cores), `lane_cpu_reservation` (default 1) and `lane_mem_mb` (default 2048). The last two feed the live local lane cap (#4777), on by default: `min(--parallel / global_parallel, max(1, min(floor(cores / lane_cpu_reservation), floor((MemAvailable - min_free_mem_mb) / lane_mem_mb))))`, re-probed at every admission attempt, so `--parallel 12` on a 4-core / 8 GB host runs fewer concurrent local lanes. Remote sandbox lanes are exempt; `enabled: false` removes the cap. The cap reads the `forge.yaml` of the batch's repo, also when the batch runs under the schedd daemon. Write it nested (`engine:` then `admission:` with the keys indented) or flat as `admission_enabled`, `admission_min_free_mem_mb`, `admission_min_free_tmp_mb`, `admission_max_load_per_core`, `admission_lane_cpu_reservation`, `admission_lane_mem_mb`; the parser reads one nested level into `engine`. `/orchestrate` requeues a host-busy lane and lowers K by 1 for 5 minutes. Host overload hold (#5174): `overload_load_per_core` (flat `admission_overload_load_per_core`; default 2, `0` disables) holds every new local lane admission of a host-wide batch while the 1-minute load average divided by cores is above it; the issue stays queued and is retried on the next poll, and remote sandbox placements are never held. While it holds, the batch log has one `host-overloaded` row per episode, and `forgedock status` (`host` row) and `forgedock schedd status` print `host_overloaded (load X.X/core > T): new local admissions held` (otherwise `load X.X/core (threshold T)`). Unlike `max_load_per_core` it never defers a running lane. The env `FORGEDOCK_OVERLOAD_LOAD_PER_CORE` (same values) overrides it for every batch on the host. Local heavy steps (the heavy-shim semaphore path) run at nice 10 and, on Linux with `ionice` on PATH, in the idle IO class, so test runners and installs do not starve the schedd daemon. |
| `merge_wait` | string | No | Core work-on merge gate. `required` (default): wait only for the status checks the base branch requires: the union of classic branch protection (`gh api repos/{o}/{r}/branches/{base}/protection/required_status_checks`, contexts and checks) and repository rulesets (`gh api repos/{o}/{r}/rules/branches/{base}`, `required_status_checks` rules); with neither (404 or empty) merge right after review PASS. A merge rejected by base branch policy (PR `MERGEABLE` but `BLOCKED`) is waited on and retried within the CI budget, then left `ci-pending`; it is never base-synced and never `base.conflict`. A failing required check is `needs-human`; a pending one is polled with backoff and never `needs-human`. `all`: wait for every check (`scripts/wait-ci-green.sh`). `none`: merge right after review. Always `--match-head-commit` at the reviewed head. The policy used is recorded in the `FORGE:WORK-ON` comment. |
| `context_pack` | string | No | Context pack (#4275). Before the plan call the core compiles the issue's GitHub/git neighbourhood into a small, budgeted pack: linked issues and PRs (parent, `Depends on`, body links, same-repo cross-references, siblings), prior attempts, merged PRs on the issue's files that were reverted or whose decisions/findings name a symbol from the issue, structured `FORGE:FACTS` records of earlier lanes on the issue's files (rejected approaches with why, hot spots, decisions, conventions, baselines; #4401), and repo-fact file pointers (found in the lane worktree or, for untracked caches, the main checkout; #4400). `shadow` (default): the pack is compiled, posted on the issue as a collapsed `FORGE:CONTEXT` comment and logged as a `CONTEXT_PACK` event; the builder prompt is unchanged. `on`: it is also appended to the plan prompt as hints. `off`: nothing is gathered, posted or logged. `ab` (#4444): the A/B experiment. Each issue gets a stable arm, `on` or `shadow`, from a hash of `repo#issue`, logged as that mode with `context_ab: true`; the default stays `shadow`. The pack never enters the text contract quotes are checked against. Values read from linked issues' `FORGE:STATE` are kept only when they are outcome codes. Compare with `forgedock stats --context-ab` (per lane type and mode: first-pass yield, turns and cache-read per merge, rework rate, and recovery lanes' implement attempt against the first run on the same issue). Unless `off`, a resumed or recovery lane also gets a bounded resume digest of its last run in the builder prompt (end reason, validate results per command, deliver requirements, files changed; logged as `RESUME_DIGEST`; #4400), whatever the mode. |
| `context_pack_sources` | string | No | Comma list of the pack sources to use: `graph`, `attempts`, `pitfalls`, `ledger`, `facts` (earlier lanes' `FORGE:FACTS` on the issue's files plus repo-fact file pointers). Default: all five. |
| `context_pack_bytes` | integer | No | Hard byte cap of the pack; items that do not fit are dropped whole and counted. Default: 6144. |
| `context_pack_days` | integer | No | Window of the merged-PR ledger, in days. Default: 30. |
| `lane_instructions` | string | No | Lane profile (#4395). Core lane sessions always run with Claude Code auto-memory off (`CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`). Set this to a repo-relative file, for example `devdocs/lane-instructions.md`, that holds only the hard rules plus pointers into docs. It is read from the lane worktree, so it is versioned with the repo. Lanes then also skip CLAUDE.md discovery (`CLAUDE_CODE_DISABLE_CLAUDE_MDS=1`), and the file text is appended to the system prompt of every fresh builder, reviewer and verifier session. An absolute path, a `..` path, or a missing, empty or over-16 KB file is a trajectory anomaly; lanes then keep CLAUDE.md. Settings and hooks always load (no `--setting-sources`). `FORGEDOCK_FULL_SESSION=1` keeps a full session. Each `phase_attempt` telemetry record carries `lane_profile` (`full`, `memory-off` or `lane`) and `baseline_tokens`, the first turn's context of a fresh session, so baseline growth is visible. `forgedock stats --lane-profile [--issues <list>]` compares `baseline_tokens` per phase and the conformance rate per profile from local run logs, for the before/after check on the same issue set. |
| `ci_pending_max_minutes` | integer | No | Minutes the engine waits for CI when the review phase ends BLOCKED with "checks still pending", or the remediate phase holds at its M7 re-gate on "CI pending" (the merge gate's wait window ended while CI was still running). Default: 90. Invalid values are ignored. This key is flat like the others but is not part of the `<key>_model` / `<key>_max_turns` pattern. |

**CI still pending**: the engine polls `scripts/wait-ci-green.sh` (no model calls) one read per poll on a 60 s, 2 min, 4 min, 5 min (cap) backoff with +/-20% jitter, while the lease keeps renewing, then re-dispatches the phase that was waiting, review or remediate (idempotent at an unchanged head: review re-runs the merge gate and merges; remediate resumes at its M7 re-gate). Before each poll it reads `gh api rate_limit` (not itself rate-limited) and, below 10% of the REST budget, sleeps until the window resets instead of polling; a rate-limited or transient (5xx, network) poll is retried and never re-dispatches the phase. Red CI takes the normal ci-gate path. When the budget is exhausted the run ends `needs-human` with outcome code `review.ci_pending_timeout`; `--retry` resumes. Each wait emits a `ci_pending_wait` telemetry event (`docs/TELEMETRY.md`) with the minutes waited, polls made and rate-limit sleeps.

**Precedence** (model): `engine.<key>_model`, then the run-level model the caller passed explicitly, then omitted. `max_turns` comes only from this section. No defaults ship.

**Version gate**: the flags are added only when the installed `claude --version` supports them (`--max-turns` is hidden from `claude --help`, so help text is never scraped); an unparseable version omits both flags.

**Turn exhaustion**: when `--max-turns` is exhausted the run ends `engine-error` (detail `max-turns`) and the phase is never committed, so `forgedock run-issue --retry` re-enters the same phase. Raise `<key>_max_turns` before retrying. Phase runlog events record `model` and `turns` next to `usage` so a limit can be sized from measured turn counts.

**Per-run scratch dir** (`tmp_root`): every engine child runs with `TMPDIR` and `CLAUDE_CODE_TMPDIR` set to `<tmp_root>/<repo-key>/<issue>` so venvs and Claude session data stay off a size-limited `/tmp`. `engine.tmp_root` is an absolute or `~`-prefixed path; default `~/.forge/tmp`. The `<repo-key>` is the checkout's directory name plus 8 hex characters of a hash of its real path, so the same issue number in two repos never shares a dir; the dir is created `0700` and an existing symlink or dir owned by another user is not used (the child keeps the inherited tmp). Old `<tmp_root>/<issue>` dirs from earlier versions are not migrated. When `tmp_root` is unset and the operator already exported `TMPDIR` or `CLAUDE_CODE_TMPDIR`, that choice is respected and never cleaned. The dir is removed on a terminal outcome and kept on `engine-error` so `--retry` resumes. A disk-full/quota failure (EDQUOT, ENOSPC, errno -28/-122) ends a retryable `engine-error` (outcome code `infra.disk_quota`), never `needs-human`.

**Minimal phase sessions** (forge#4065): on a supported CLI (`claude --version` >= 2.1.296, probed once and cached like the flags above) every engine phase (`work-on/*`) runs with `--strict-mcp-config --mcp-config '{"mcpServers":{}}'`, so operator MCP servers and connectors are not loaded. Phases whose spec never calls `Skill(...)` (`work-on/investigate`, `work-on/close`) also get `--disable-slash-commands`; skill-using phases keep skills. Operator settings are intentionally not skipped (no `--setting-sources`), because ForgeDock's user-scope PreToolUse/SubagentStop hooks must keep running. Set `FORGEDOCK_FULL_SESSION=1` to restore the previous full session (no flags). Other `forgedock run` commands (qa-sweep, analytics, geo-audit, autopilot) keep the full session because they may need MCP servers. An old or unparseable CLI version also omits the flags.

**Commands that use this section**: CLI backend (`runCommand` in `bin/runner.mjs`)

---

## `prod_watch` (OPTIONAL)

Settings for `forgedock prod-watch` (see [PROD-WATCH.md](PROD-WATCH.md)): read-only production signal sources triaged, rate-limited and filed as issues.

```yaml
prod_watch:
  poll_minutes: 10
  deployed_probe: "curl -fsS https://example.com/health"
  target_watch: prod
  alert_channel: "notify-oncall"
  governor:
    max_issues_per_hour: 5
    max_open_prod_issues: 20
    max_cost_usd_per_round: 1
  sources:
    alerts: {kind: alertmanager, run: "curl -fsS http://alertmanager/api/v2/alerts"}
```

| Key | Type | Required | Description |
|---|---|---|---|
| `poll_minutes` | number | No | Minutes between rounds. Default 5. |
| `sources` | map | Yes | `name: {kind, list, read, run, close, queries}` flow map per source (memo, alertmanager, sql, prometheus). Only `list`/`read`/`run` run in the loop. |
| `deployed_probe` | command | No | Exits 0 when the fix is deployed; enables the verify step. |
| `governor` | map | No | `max_issues_per_hour`, `max_open_prod_issues`, `max_cost_usd_per_round`, `cost_per_issue_usd`. Missing = unlimited. With a cost cap set, an LLM call that reports no cost is charged `cost_per_issue_usd`, or the whole cap when that is unset. |
| `target_watch` | string | No | An `issue_watch` watch name; filed issues get its first `labels` entry. Otherwise the value is the label. Default label `prod-watch`. |
| `kill_switch` | path | No | While this file exists, rounds do nothing. Default `.forge/prod-watch.off`. Relative paths resolve under the working directory; absolute paths are used as given. |
| `alert_channel` | command | No | Receives title and body on stdin for a P0 incident; nothing else pages. |

**Commands that use this section**: `forgedock prod-watch`

---

## `selftest` (OPTIONAL)

Settings for `forgedock selftest --live` (see [SELFTEST.md](SELFTEST.md)): a harness that drives the real `gh`, git and `orchestrate` against a disposable sandbox repo, and the `FORGE:SELFTEST` result the staging->main review requires.

```yaml
selftest:
  sandbox_repo: acme/forgedock-sandbox   # disposable repo; the harness creates and closes issues, PRs and branches in it
  fixture: node                          # node (default) | python
  nightly_interval_hours: 24             # opt-in: schedd runs `selftest --live` this often (default off)
```

| Key | Type | Required | Description |
|-----|------|----------|-------------|
| `sandbox_repo` | string | No | `owner/repo` the live harness runs in. `--repo` overrides it; with neither the command stops. Never point it at a real project. Setting it also turns on the release gate: `forgedock review-staging` then requires a passing `FORGE:SELFTEST` marker for the release PR head; unset, the gate is skipped. |
| `fixture` | string | No | Toolchain of the two trivial fixture issues: `node` (default) or `python`. `--lang` overrides it. |
| `nightly_interval_hours` | number | No | Off when unset or 0. When positive, the schedd daemon (host, never GitHub Actions) starts a detached `selftest --live` against `sandbox_repo` once this many hours have passed since the last run of that repo. On failure, including a run that cannot start, it files or edits one issue naming the failed step, in the repo schedd resolves for its working directory. See [SELFTEST.md](SELFTEST.md#nightly-run). |

**Commands that use this section**: `forgedock selftest`, `forgedock review-staging` (release gate, only when `sandbox_repo` is set)

---

## `gate` (OPTIONAL)

```yaml
gate:
  required_checks: ["CI"]   # extra checks the staging review treats as required
```

`forgedock review-staging --summary` blocks only on the required checks of the target branch (branch protection and rulesets, read from the GitHub API) plus this explicit list; the list is never inferred. Other red checks are reported as non-blocking warnings. When no required checks can be read, every red check blocks.

## `release` (OPTIONAL)

Settings for `forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>]` (#5208), which runs the `branches.staging` → `branches.default` release as one resumable job. State is kept in `~/.forge/releases/<id>/` (or `FORGEDOCK_RELEASE_DIR`); `--resume <id>` continues from the last completed step (preflight, release-pr, review, fixes, promotion, post-merge). Preflight refuses while lanes of the repo run or PRs to the staging branch are open, and sets the repo's batches to K=1 until the job ends. Post-merge is automated (#5213): it confirms a publish run for the merge commit (dispatching one when none appears), waits for `artifact_check`, then opens and merges the version-sync PR; a bound that runs out stops the job as blocked and `--resume <id>` retries. `forgedock release status [<id>] [--watch] [--interval s] [--json]` (bare `forgedock release --watch` runs the same loop) and `forgedock release explain <id | #issue | PR> [--json]` (#5554) are read-only: status reads the ledger (when `release.managed`) or the local cache plus the release PR's gate; `--watch` polls until the release is done, refused or blocked. `explain #N` prints the ordered rule trace (skip labels, priority, theme_map, `Depends on`, recorded release set, each with its config key), the lane and what would change it; `explain <PR>` prints the gate decision. `--json` output has schema `forgedock.release.status/v1` or `forgedock.release.explain/v1` and `next_actions[]`, the exact commands an agent may run; output carries no host name, so another host prints the same text. `status --watch [--interval s]` prints only when the output changes and stops at a terminal state; `forgedock release --watch` runs the same loop. Status prints `unknown` for any field the ledger does not hold. `explain #N` also reads the `FORGE:CLASSIFY` record (else `classification: absent`), `plan.skip_labels`, `classify.min_confidence`, `risk.rules[i]`, `forces[i]`, prints `planner: not installed` until the planner registers, and takes the lane from the latest `lane` entry in `controls.jsonl`; `explain <PR>` lists each required check with its outcome and any demotion (actor, expiry, reason, issue). `next_actions[]` carries `hold|resume|cancel` and `lane #N --force <lane>` commands (the `release-control.mjs` verbs) with `--reason <reason>` placeholders; `rollback` and the other control verbs exist (see the CLI reference) but `next_actions[]` does not emit them. `explain <PR>` reads the live `_active.exemptions` records (`release exempt`), `explain #N` the `_active.lanes` records.

```yaml
release:
  auto_merge: false
  artifact_check: ""
  version_sync: false
  publish_workflow: publish.yml
  preflight_command: ""
  preflight_timeout: 1200
  preflight_blocking: true
  rehearsal_command: ""
  rehearsal_timeout: 1200
  rehearsal_blocking: true
  mode: freeze
  branch_pattern: "release/{date}-{n}"
  fix_mode: cherry-pick
```

`forgedock release verify <sha> [--repo owner/repo]` reads the `FORGE:RELEASE` record from the PR that contains `<sha>` and exits 0 only when `<sha>` is the snapshot plus recorded picks, each a clean cherry-pick of a `branches.staging` commit (same tree as `git cherry-pick`), so a repo workflow that trusted `head.ref == staging` can call it instead.

`forgedock release verify <release id>` (#5562) re-runs the deploy verification of a release that passed LIVE_CHECK; a release id (`rYYYYMMDD-HHMMSS-N`) is never mistaken for a sha. Policy `verify` block (default branch, `.forge/release.yaml`): `results` (list of `{workflow, kind: smoke|edge|convergence}`, layer 1), `workflow` (verification workflow dispatched through the epoch fence, layer 2), `slis` (layer 3, entries `{name, tolerance, worse: higher|lower, abs}` read through an injected read-only metric source; without one the layer reports `sli: skipped (no host)`), `post_deploy_checks_file` (layer 4, each issue's `[check:id]` runs once; entries with `for` are windowed and become rollup follow-ups), `flags` (layer 5, `{flag, off_command}` verified in the off state, never activated) and `close_requires: verified|deployed`. With `verified` (default once the block is set) an issue is closed only after a `FORGE:VERIFIED <deploy sha>` comment; `deployed` closes without it. Soak minutes by risk class: low 10, medium 20, full 30, p0 15, overridden by `lanes.<lane>.soak_min` (a number or a map by class). An empty `verify` block leaves VERIFYING a bare transition to LIVE.

### Default release flow: the v1.0 contract (#6164)

`forgedock release` and `forgedock review-staging` follow the original release contract of `commands/review-pr-staging.md` (commit dcfb86bf, 2026-06-05), restored as the default for every repo. There is no switch to turn it off.

1. **Open-finding gate first**: an open `review-finding` issue blocks the release before CI or any reviewer.
2. **`ci-green` step** before `review`: waits for every required check on the release PR head (protection, rulesets and `gate.required_checks`; `forgedock/verify`, `forge/deploy-gate` and the gate-marker check excluded). A failed check is rerun once; a pass on the rerun counts as green and files a `flaky-test` issue naming the test when the log shows it. A check still red after its rerun gets one CI fix round in the release PR, then CI is awaited again. A draft release PR (host preflight mode) has no Actions CI yet, so the step skips it.
3. **One review pass** on the green head. Every finding is filed as an issue (Phase 7). Nothing the review finds is fixed inside the release PR: no review fix lanes and no review-driven delta passes. A head that moves during review stops the job; re-run it.
4. **Verdict**: a CONFIRMED CRITICAL/HIGH finding (or a failed guard) means BLOCK. The job stops with `blocked: review blockers #A #B`, the release PR is closed, the blocker issues are added to the repo's open orchestrate batch (`orchestrate --add`) when one exists, and the next release starts fresh after they merge (the open-finding gate enforces it). Without blockers the release merges on GATE_PASS and everything else stays filed for later.
5. `forgedock review-staging <PR>` pre-dispatch (also `--delta`) runs the gate, then refuses while a required check is pending or failing (`CI not green on <sha> (pending: ..., failing: ...)`); `--allow-ci-pending` overrides and is recorded in the route marker. `--gate-only` runs just the open-finding gate.
6. `release status` prints `timing`: `ci_green_min`, `review_min`, `fix_rounds`, `review_passes`; the release ledger mirrors them.

Drift this removes: #4358 and #4360 (pre-dispatch and delta passes in the review loop), #5212 (review step fix lanes and delta passes), #5567 (CI and panel started on the same head, `ci.fix.co_start`, now ignored).

```yaml
release:
  block_severity: high        # lowest blocking severity: critical | high | medium (default high)
  ci_green_max_wait_min: 40   # how long ci-green waits for pending checks before it blocks (max 240)
  review_fixes: false         # compatibility only: true restores the #5212 review fix lanes and delta passes
```

### `.forge/release.yaml` (#5551)

Nested release policy (`schema: 1`) lives in a committed `.forge/release.yaml`, not in the host-local forge.yaml. It is read from the default branch with `git show origin/<default>:.forge/release.yaml`, never from the PR head or the worktree, so a PR cannot weaken its own gates. The flat `release.*` keys above stay the fallback when the file is absent there. Sections: `branches`, `trust`, `state`, `units`, `couplings`, `contracts`, `forces`, `classify`, `risk`, `plan`, `lanes`, `merge`, `ci`, `preflight`, `deploy`, `verify`, `rollback`, `controls`.

- `forgedock release check-config [--ref <git ref>]` parses it with the vendored, pinned YAML parser and fails (exit 1) on unknown keys, wrong types, duplicate keys, unreachable lanes (unknown pipeline, `base: integration` with no `branches.integration`, `ci_tier` not in `ci.tiers`) and keys deferred to a later phase (`plan.auto_if`, `retention_days`, `ci.forbid_per_issue_steps`, `couplings[].refine`, `ci.provider: command`, `risk.weights`).
- `forgedock release init` writes the zero-config profile (`schema: 1`, `branches.default: main`, `plan.approval: wait`, `lanes.release.pipeline: existing`, `merge.approval: confirm`) to `.forge/release.yaml` and nothing else; it never overwrites.

The forge.yaml reader handles two levels, so the rehearsal block is written as the flat keys `rehearsal_command`, `rehearsal_timeout` and `rehearsal_blocking`.

| Key | Type | Required | Description |
|-----|------|----------|-------------|
| `auto_merge` | boolean | No | `true` merges the release PR with `--match-head-commit` once `FORGE:GATE_PASS` is posted and `forge/deploy-gate` is success, as `--merge` does. Default: `false` (the job stops at GATE_PASS and prints the merge command). |
| `artifact_check` | string | No | Shell command that confirms the published artifact (e.g. `npm view pkg@1.2.3 version`). Post-merge retries it with a bounded exponential backoff (npm propagation delay) and blocks when it keeps failing. Default: none. |
| `version_sync` | boolean | No | The repo pushes a `chore/sync-version-<VERSION>` branch after a release. Post-merge opens its PR to `branches.staging` if missing and merges it with `--match-head-commit` once its checks are green (no checks, or a red one, blocks the job). Default: `false`. |
| `publish_workflow` | string | No | Workflow file post-merge looks for (and dispatches when no run appears) for the merge commit. Default: `publish.yml`. |

| `preflight_command` | string | No | Shell command run on the host (not as Actions minutes) in the repo checkout on the staging head **before** the release PR is opened (#5277), again after each fix round, and once more on the final head before the PR is marked ready. Put the repo's own suites here, e.g. `preflight_command: npm test`. Setting it also opens the release PR as a **draft** and marks it ready only after review and a passing preflight, so Actions CI runs once on the final head. Unset: no preflight, the PR is opened ready as before. |
| `allow_red_staging` | bool | No | Staging-health gate (#6013): before a release is cut, every check-run of the staging head must be finished and green; otherwise the preflight step refuses and names **all** failed checks (classified regression or runner) and pending ones, so the fixes go out together and the next snapshot is cut once. `allow_red_staging: true` proceeds with a recorded warning. Default `false`. The ledger records each round (`rounds`: pr, head, outcome, cause, times) and `forgedock stats --release-ledger` trends snapshot rounds per release. |
| `preflight_timeout` | integer | No | Seconds before the command is killed (counts as a failure). Default: `1200`. |
| `preflight_blocking` | boolean | No | `true` (default): a failure files one `release-blocker` issue per head (a re-run comments on it) and stops the job before the PR is opened or marked ready; fix it and `--resume <id>`. `false`: the failure is recorded and the release goes on. |
| `rehearsal_command` | string | No | Shell command run on the host (not as Actions minutes) in the repo checkout, on the release-PR head after review and before promotion (#5253). Wire the project's deploy dry-run here: bundle build, env load and the trusted-runtime closure check, e.g. `rehearsal_command: ./scripts/deploy-dry-run.sh` where the script builds the release bundle, loads the production env file in check mode and verifies the trusted-runtime closure, exiting non-zero on the first failure. Unset: no rehearsal, release behavior is unchanged. |
| `rehearsal_timeout` | integer | No | Seconds before the command is killed (counts as a failure). Default: `1200`. |
| `rehearsal_blocking` | boolean | No | `true` (default): a failure files one `release-blocker` issue per release head (a re-run at the same head comments on it) with the output tail and the head SHA, and stops the job before promotion; fix it and `--resume <id>`. `false`: the failure is recorded and promotion goes on. |
| `mode` | `snapshot` \| `freeze` | No | `freeze` (default) is the original behaviour: the release PR head is `branches.staging`, preflight refuses while a lane runs or a PR targets staging, and every batch is held at K=1 until the job ends. `snapshot` (#5276) cuts `release/<id>` from a staging SHA and opens `release/<id>` → `branches.default`; lanes keep merging to staging and no batch K is touched. A `FORGE:RELEASE` record (snapshot SHA, base/head range, bundle PRs, issues, cherry-picks) is kept in the job state and as a hidden marker in the PR body. Only one release branch may exist at a time. Promotion is unchanged (merge commit, `--match-head-commit`) but is stopped unless the head is the snapshot plus exactly the recorded cherry-picks. The branch is deleted after post-merge; fixes are already on staging, so nothing is back-merged. |
| `branch_pattern` | string | No | Snapshot branch name; `{date}` is `YYYYMMDD`, `{n}` counts the day's release PRs. Default `release/{date}-{n}`. Everything under the pattern's prefix before `{` counts as a release in flight. |
| `fix_mode` | `cherry-pick` \| `recut` | No | Snapshot mode only. `cherry-pick` (default): after a fix lane merges to staging, the merged commits of PRs labelled `release-blocker`, or closing a `release-blocker` issue or the blocking issue the job filed, are cherry-picked onto `release/<id>` (a clean pick only; a conflict blocks the job) and appended to `FORGE:RELEASE`. `recut`: the branch is moved to the current staging tip and the picks start over. |

### Managed release: nightly and budget (#5569)

Both blocks are read only when `release.managed` is on; otherwise no nightly, minutes or budget call is made. Before the first step `forgedock release [--lane release|train|p0]` (default `release`) reads the latest nightly run and applies the budget.

```yaml
nightly:
  workflow: nightly.yml      # workflow file of the nightly run
  branch: staging            # integration branch
  block_release: true
  t0_t2_hours: 24            # T0-T2 cadence; results older than twice this are stale and never block
  t3_t4_hours: 168           # T3-T4 cadence (weekly)
  t3_jobs: "hands e2e"       # comma list of job-name substrings that are T3 (a leading "T<n>" in a job name wins)
  t4_jobs: "trivy"
  unskippable: "migration"   # job-name substrings that block a release whatever their tier
budget:
  on_exceed: local-first     # local-first | hold | proceed
  ignore: false              # true: budget never blocks this repo
```

| Key | Description |
|-----|-------------|
| `nightly.block_release` | Default `true`. A red T0-T2 job (an unclassified job counts as T2) or an `unskippable` job blocks `lane: release` with status blocked at step `gate`. T3/T4 reds never block; `train` and `p0` are never blocked. Any red files one open `nightly-red` issue (an existing one has its body edited). |
| `budget.on_exceed` | Applied at the gate when the forecast (median of the lane's last 5 recorded releases) exceeds the month's remaining minutes (`ci.monthly_minutes` less the reserve, less month-to-date). `local-first` records `ciMode` in the release state, `hold` blocks, `proceed` continues. `p0` always proceeds. Unknown forecast or usage proceeds. |

`forgedock release report` prints the model (`budget.model_release_minutes`, default 500, per release) against the measured minutes of the first 3 recorded releases and says whether they are within 25%; outside it, `budget.on_exceed` and the nightly cadence are the levers.

The release state (and so the ledger) records `lane` and `minutes: {runs, total}`, where total is the sum of ceil(job minutes) of the Actions runs created since the release started, read from the jobs API.


### Deploy gate catalogue and false-block telemetry (#5583)

Optional; with no `.forge/gates.yaml` (on the ref) every command below is a no-op with zero writes. `forgedock release check-config` validates the file when present. Fields per gate under `gates:` (`schema: 1`): `id`, `protects_against` (origin issue), `where`, `determinism`, `pre_merge_artifact` (fixture), `version`, `mode` (`block|skip|rollback|freeze|warn|red`), `owner`, `review_by` (`YYYY-MM-DD`); admission also needs `on_uncertainty: inconclusive`, `failure_triggers` and `proportionality`. Optional `evidence_check: <required check name>` marks a gate that re-runs work a required check already did; see [`deploy.promote`](#deploypromote-optional) for when that evidence lets the gate be skipped (a safety gate never is).

`.forge/release.yaml` `gates:`: `demote_fb_rate` (percent, default 5), `demote_window` (runs, default 20), `safety` (never demoted; default `migration-immutability`, `identity-preflight`, `backup-freshness`, `health-auto-restore`, plus the unskippable classes).

A `deploy-telemetry` job prints one JSON line per gate per run: `{"schema":"forgedock.release.gate/v1","gate":"<id>","outcome":"pass|fail|inconclusive|skip","class":"TP|FB|unknown","minutes":<n>,"evidence":"<text>"}`. A `TP`/`FB` class without `evidence` is stored as `unknown`. `forgedock release gates record <release-id> --file <jsonl>` stores the lines in the release state (`gates`). When `FORGE_GATE_TELEMETRY` names such a JSON-lines file and a catalogue exists, the release run stores its lines in `state.gates` next to `state.minutes` automatically; `historyFromRoot` exposes them as its `gates` property.

| Command | Description |
|---------|-------------|
| `release gates [--since 30d] [--json]` | Per gate: `runs`, `fails`, `fb`, `fb_share` (FB runs / runs, in percent), `minutes`. Text: a tab-separated header `gate runs fails fb fb_share minutes` and one row per gate. JSON: one line `{"schema":"forgedock.release.gates/v1","gates":[{gate,runs,fails,fb,minutes,fb_share}]}`. |
| `release gates check [--base <ref>]` | Fails for a gate added or changed against the base ref (default `origin/<default>`) that lacks the fixture, version, `on_uncertainty: inconclusive`, failure trigger with proportionality, or owner and `review_by`. |
| `release gates demote` | A gate whose FB rate over the last `demote_window` runs (a full window) exceeds `demote_fb_rate` is demoted to `warn` for 14 days via the audited `release demote` control, and an issue is filed. Safety gates are never demoted. |
| `release promote <gate> --fixture <ref> --reason <text>` | Re-promotes a demoted gate; refused without a fixture reference. |

The result (pass or fail, head SHA, blocker issue) is recorded in the release state (`steps.rehearsal`) and in a `FORGE:REHEARSAL` section of the release PR body next to the gate result.

Repos that set `preflight_command` should skip their Actions CI while the release PR is a draft, so the paid run happens once, on the final head:

```yaml
on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]
jobs:
  test:
    if: ${{ !github.event.pull_request.draft }}
```

**Commands that use this section**: `forgedock release`

### Gate-only fix lane: `release control regate` (#5584)

`forgedock release control regate <release id> --ref <fix branch|sha> --reason "..." [--gate-fix-ref <hotfix branch>]` re-evaluates the gates of the same release sha (same image digests, no rebuild, no migration rerun) with the gate code of `--ref`, so a fix limited to gate artifacts does not need a new merge cycle. Nothing runs unless the verb is called. The fix still goes through CI and review once; it never skips the merge cycle for code that ships in images.

- **Classifier**: the diff between the release's merged sha and `--ref` is gate-only only when every path matches `gates.paths` (default `scripts/deploy/**`, `scripts/lib/**`, `scripts/prod-smoke-test.sh`, `**/gate-fixtures/**`, `tests/gates/**`). A `.github/workflows/*.yml` file qualifies only when every changed hunk lies in a step named in `gates.workflow_steps` (default none). A migration path (`**/migrations/**`, `**/migrate/**`, `*.sql`), an image path (`Dockerfile*`, `docker-compose*.yml`) or any other app path sends the fix to the normal lane.
- **Dispatch**: one `gh workflow run` of `verify.workflow` at `--ref` through the epoch fence, inputs `sha` (the release sha), `regate=true`, `gate_sha` and `forge_epoch`. The engine never sets `override_freeze` (I26); LIVE_CHECK (I28) still applies to the result.
- **`gate_fix_ref`** (hotfix same-release gate fix): with `--gate-fix-ref`, the dispatch also carries `gate_fix_ref=<branch>`, which lets a hotfix-branch gate fix replace the default-branch preflight copy. It is recorded in the audit line and in `state.regates`.
- **Refusals** (nothing is written or dispatched): no recorded live record/rollback target (`state.deploy.target`); `deploy.freeze_variable` set by the run (not set before the deploy) while migration files lie between the rollback target and the release sha; a fix that is not gate-only; a ref already re-evaluated.
- **Audit**: every use appends a `controls.jsonl` line (`verb: regate`) with the actor, the fix sha, the release sha and `gate_sha` (sha1 over the changed gate paths and their blobs at `--ref`); the release state keeps `regates[]`, and gate telemetry recorded afterwards carries that `gate_sha`.

### Policy reference (`.forge/release.yaml`, #5572)

One row per key path of `POLICY_SCHEMA` (`bin/lean/release-config.mjs`). `<name>` is a map key you choose and `[]` a list item. A default of "none" means the key is unset and its feature is off. `bin/lean/release-docs.test.mjs` fails when a schema key is missing here or a key listed here is not in the schema, so a phase that adds a key documents it in the same change.

| Key | Type | Default | Meaning |
|-----|------|---------|---------|
| `schema` | 1 | required | Policy file version; must be `1`. |
| `branches` | object | - | Branch names the release lanes use. |
| `branches.default` | string | `main` (init profile) | The branch releases land on; the policy file is read only from here (I13). |
| `branches.integration` | string | null | Integration branch for lanes with `base: integration`; unset makes such a lane unreachable. |
| `branches.train` | string | none | Branch prefix or name for train waves. |
| `branches.release` | string | none | Branch prefix or name for release waves. |
| `branches.hotfix` | string | none | Branch prefix or name for hotfix (P0) branches. |
| `release` | object | - | Release-merge settings. |
| `release.hold_merges_during_release_ci` | boolean | `true` | While a release PR (head = the integration branch, base = the default branch) has CI running, lane merges into the integration branch wait (`merge.held_release`) so they do not restart that CI; `false` disables the hold. |
| `trust` | object | - | Who the pipeline believes. |
| `trust.actors` | array | none | Logins whose control comments and commits are trusted. |
| `trust.require_verified_commits` | boolean | off | Refuse release commits that are not verified. |
| `state` | object | - | Where release state lives and how leases behave. |
| `state.ledger_prefix` | string | built-in prefix | Name prefix of the ledger entries kept on GitHub. |
| `state.lease_ttl_s` | number | built-in | Seconds a run lease stays valid without a heartbeat. |
| `state.heartbeat_s` | number | built-in | Seconds between lease heartbeats. |
| `units` | map | none | Deployable units, keyed by name; each is mapped to code paths. |
| `units.<name>.paths` | array | none | Globs of files that belong to the unit. |
| `units.<name>.image` | string | null | Image name the unit ships as, when it has one. |
| `units.<name>.criticality` | low\|medium\|high | none | `low`, `medium` or `high`; feeds risk. |
| `units.<name>.tests` | array | none | Test commands or names that cover the unit. |
| `units.<name>.verify` | array | none | Post-deploy checks that cover the unit. |
| `units.<name>.service_pipeline` | boolean | off | The unit deploys through its own service pipeline. |
| `units.<name>.single_host_ok` | boolean | off | The unit may run on one host. |
| `units.<name>.dockerfile` | string | null | Dockerfile checked by `release check-config --coverage`. |
| `units.<name>.surface` | service\|web\|edge | none | `service`, `web` or `edge`. |
| `couplings` | array | none | Paths that force other units to roll when they change. |
| `couplings[].paths` | array | none | Globs whose change couples units. |
| `couplings[].affects` | array | none | Unit names rolled by that change; each must exist in `units`. |
| `contracts` | array | none | Producer/consumer interfaces between units. |
| `contracts[].producer` | string | none | Unit that owns the contract. |
| `contracts[].consumers` | array | none | Units that depend on it. |
| `contracts[].paths` | array | none | Globs of the contract files. |
| `contracts[].additive_only` | boolean | off | Only additive changes are allowed. |
| `contracts[].regenerate` | string | null | Command that regenerates generated contract files. |
| `forces` | array | none | Rules that force a pipeline for matching paths. |
| `forces[].paths` | array | none | Globs the rule matches. |
| `forces[].pipeline` | full\|service\|hotfix | none | `full`, `service` or `hotfix`. |
| `forces[].reason` | string | none | Text shown in `release explain`. |
| `classify` | object | - | Issue classification (the `FORGE:CLASSIFY` record). |
| `classify.min_confidence` | number | none | Records below this confidence are not trusted for lane choice. |
| `classify.text_only_cap` | number | 0.5 | Confidence cap for a record built from issue text alone. |
| `classify.triage_max_per_hour` | number | 10 | Triage classify calls per rolling hour. |
| `classify.exists_in_evidence` | mechanical\|llm | none | `mechanical` or `llm`: how cited evidence paths are checked. |
| `risk` | object | - | Risk rules. |
| `risk.rules` | array | none | Ordered rules; the matching rule sets risk and may force a pipeline. |
| `risk.rules[].when` | object | none | Conditions, all of which must hold. |
| `risk.rules[].when.migration` | boolean | none | The change touches migrations. |
| `risk.rules[].when.paths` | array | none | Globs the change touches. |
| `risk.rules[].when.contract` | boolean | none | The change touches a contract. |
| `risk.rules[].when.rolled_units_gt` | number | none | More than this many units roll. |
| `risk.rules[].when.diff_lines_gt` | number | none | More than this many changed lines. |
| `risk.rules[].risk` | low\|medium\|high | none | `low`, `medium` or `high`. |
| `risk.rules[].forces` | string | none | Pipeline the rule forces. |
| `risk.rules[].requires` | string | none | Named requirement (for example `rollout-declaration`) reported with the risk when the rule matches. |
| `features` | object | - | Feature wave policy (#5571). |
| `features.flag_policy` | require\|warn\|off | none | `require` refuses a feature wave that adds no rollout key, `warn` warns, `off` does nothing; `lanes.<name>.flag_policy` wins. |
| `plan` | object | - | The release plan. |
| `plan.approval` | wait\|auto\|auto-if | `wait` (init profile) | `wait`, `auto` or `auto-if`; `auto-if` is rejected until its phase. |
| `plan.skip_labels` | array | built-in labels | Issue labels kept out of a plan. |
| `plan.require_design_gate` | boolean | off | Plan needs the design gate to pass. |
| `plan.max_issues` | number | none | Issue cap for one plan. |
| `plan.stale_snapshot_s` | number | none | Seconds after which a plan snapshot is stale. |
| `lanes` | map | none | Named lanes (for example `release`, `train`, `p0`). |
| `lanes.<name>.pipeline` | string | `existing` (init profile) | Deploy pipeline the lane runs; `existing` keeps the repo's own. |
| `lanes.<name>.ci_tier` | string | none | CI tier; must exist in `ci.tiers` when tiers are set. |
| `lanes.<name>.approval` | string | none | Approval mode for the lane. |
| `lanes.<name>.budget` | string | none | Budget class for the lane. |
| `lanes.<name>.base` | live\|integration\|default | none | `live`, `integration` or `default`. |
| `lanes.<name>.units_max` | number | none | Maximum units per wave. |
| `lanes.<name>.max_risk` | low\|medium\|high | none | Highest risk the lane accepts. |
| `lanes.<name>.train_max_issues` | number | none | Issue cap per train wave. |
| `lanes.<name>.train_max_units` | number | none | Unit cap per train wave. |
| `lanes.<name>.soak_min` | any | none | Soak time, in minutes, before the next wave. |
| `lanes.<name>.flag_policy` | require\|warn\|off | none | `require`, `warn` or `off`; overrides `features.flag_policy`. |
| `lanes.<name>.requires` | array | none | Lanes or checks that must pass first. |
| `credentials` | object | - | Credentials the gates use. |
| `credentials.gate_app` | string | null | App identity that posts gate results. |
| `credentials.lane_env_strip` | array | none | Environment variables removed from lane processes. |
| `merge` | object | - | How the release PR merges. |
| `merge.approval` | confirm\|with-plan\|auto | `confirm` (init profile) | `confirm`, `with-plan` or `auto`. |
| `merge.method` | merge-commit\|squash\|rebase | none | `merge-commit`, `squash` or `rebase`. |
| `merge.trailers` | array | none | Commit trailers added to the merge. |
| `ci` | object | - | CI policy for releases. |
| `ci.provider` | github-actions\|command | `github-actions` | `github-actions`; `command` is rejected until its phase. |
| `ci.required_checks` | any | none | Checks required on the release PR. |
| `ci.selection` | any | none | How CI jobs are chosen for a diff. |
| `ci.rerun_budget_min` | number | none | Minutes of reruns the flake classifier may spend. |
| `ci.fix` | object | - | Gate-failure fix loop. |
| `ci.fix.max_rounds` | integer | none | Fix rounds before the release stops. |
| `ci.fix.co_start` | boolean | none | Start the fix lane while checks still run. |
| `ci.fix.full_run_workflow` | string | none | Workflow that runs the full suite on a fix. |
| `ci.flake` | object | - | Flake handling (#5568). |
| `ci.flake.quarantine_after` | number | none | Flakes of one test before it is quarantined. |
| `ci.flake.window_days` | number | none | Days over which flakes are counted. |
| `ci.unskippable` | array | none | Job-name substrings that can never be skipped or waived. |
| `ci.tiers` | map | none | Named CI tiers, each a job list. |
| `ci.tiers.<name>.jobs` | array | none | Job names in the tier. |
| `ci.nightly` | any | none | Nightly block (#5569): `workflow`, `branch`, `block_release`, `t0_t2_hours`, `t3_t4_hours`, `t3_jobs`, `t4_jobs`, `unskippable`; see Managed release: nightly and budget. |
| `ci.budget` | any | none | Budget block (#5569): `on_exceed` (`local-first`, `hold`, `proceed`), `ignore`, `model_release_minutes`; see Managed release: nightly and budget. |
| `preflight` | object | - | Checks run before release. |
| `preflight.commands` | array | none | Commands run on the host. |
| `preflight.timeout_s` | number | none | Seconds before a command is killed. |
| `preflight.blocking` | boolean | none | A failure stops the release. |
| `deploy` | object | - | Deploy stage. |
| `deploy.live_release_command` | string | none | Command that reads the live release. |
| `deploy.freeze_variable` | string | none | Repository variable that freezes deploys. |
| `deploy.concurrency_group` | string | none | Concurrency group of the deploy workflows. |
| `deploy.start_timeout_s` | number | 60 | Seconds to wait for a deploy run to start. |
| `deploy.stage_timeout_s` | number | built-in | Seconds a deploy stage may run. |
| `deploy.expected_digests_command` | string | none | Command printing the image digests a deploy should end with. |
| `deploy.recovery` | object | - | Deploy recovery. |
| `deploy.recovery.rerun_max` | integer | built-in | Reruns of a failed stage. |
| `deploy.recovery.max_attempts` | integer | built-in | Total attempts. |
| `deploy.recovery.signatures` | array | none | Failure signatures that may be rerun. |
| `deploy.pipelines` | map | none | Named deploy pipelines. |
| `deploy.pipelines.<name>.workflow` | string | none | Workflow file. |
| `deploy.pipelines.<name>.trigger` | push\|dispatch | none | `push` or `dispatch`. |
| `deploy.pipelines.<name>.inputs` | map | none | String inputs passed on dispatch. |
| `deploy.pipelines.<name>.wait` | boolean | none | Wait for the run to finish. |
| `verify` | object | - | Deploy verification (#5562). |
| `verify.workflow` | string | none | Verification workflow. |
| `verify.results` | array | none | Result workflows to read. |
| `verify.results[].workflow` | string | none | Workflow file. |
| `verify.results[].kind` | smoke\|edge\|convergence | none | `smoke`, `edge` or `convergence`. |
| `verify.flags` | array | none | Flags the verification can turn off. |
| `verify.flags[].flag` | string | none | Flag name. |
| `verify.flags[].off_command` | string | none | Command that turns it off. |
| `verify.slis` | array | none | SLI checks; free-form entries. |
| `verify.post_deploy_checks_file` | string | none | File of post-deploy checks. |
| `verify.close_requires` | verified\|deployed | none | `verified` or `deployed`: what closes an issue. |
| `rollback` | object | - | Rollback ladder (#5563). |
| `rollback.triggers` | array | none | `smoke`, `health`, `livecheck`, `sli`, `crashloop` or `human`. |
| `rollback.ladder` | array | none | Steps in order: `flag`, `unit`, `full`, `stop`. |
| `rollback.refuse_across` | array | none | Changes a rollback must not cross (`destructive_migration`). |
| `rollback.open_revert_pr` | boolean | none | Open a revert PR after a rollback. |
| `rollback.flags` | array | none | Kill switches. |
| `rollback.flags[].flag` | string | none | Flag name. |
| `rollback.flags[].kill_command` | string | none | Command that kills it. |
| `rollback.unit_workflow` | string | none | Workflow that rolls one unit back. |
| `rollback.unit_action` | string | none | Action name passed to it. |
| `rollback.full_workflow` | string | none | Workflow that rolls everything back. |
| `rollback.health_command` | string | none | Command that reports health. |
| `rollback.result_command` | string | none | Command that reports the rollback result. |
| `events` | object | - | Event sinks. |
| `events.webhook_url` | string | none | Webhook that receives release events. |
| `quarantine` | object | - | Quarantine limits. |
| `quarantine.days` | number | none | Days a quarantine lasts. |
| `quarantine.max` | number | none | Maximum quarantined tests. |
| `gates` | object | - | Deploy gate catalogue settings (#5583). |
| `gates.demote_fb_rate` | number | 5 | False-block percent above which a gate is demoted. |
| `gates.demote_window` | integer | 20 | Runs in the demotion window. |
| `gates.safety` | array | built-in list | Gates never demoted. |
| `gates.paths` | array | built-in globs | Paths a gate-only fix may touch (regate). |
| `gates.workflow_steps` | array | none | Workflow steps that count as gate code. |
| `controls` | object | - | Operator controls (#5555, #5556, #5564). |
| `controls.intake` | any | none | Intake pause settings. |
| `controls.conductor` | any | none | Conductor workflow settings. |
| `controls.exempt` | any | none | Exemption settings. |

#### Zero-config profile

`forgedock release init` writes exactly this to `.forge/release.yaml` and never overwrites an existing file; `release init --conductor` also installs the conductor workflow.

```yaml
schema: 1
branches: {default: main}
plan: {approval: wait}
lanes: {release: {pipeline: existing}}
merge: {approval: confirm}
```

#### Deferred keys

These keys are rejected by `release check-config` until their phase ships:

- `plan.auto_if`
- `retention_days`
- `ci.forbid_per_issue_steps`
- `couplings[].refine`
- `ci.provider=command`
- `risk.weights`

#### CLI reference

| Command | Purpose |
|---------|---------|
| `forgedock release` | Run the staging to default release as one resumable job (`--merge`, `--watch`, `--resume <id>`). |
| `forgedock release p0` | Hotfix lane for an issue or branch (`--units`, `--preempt`, `--yes`). |
| `forgedock release verify` | Verify a release sha, or re-run deploy verification of a release id. |
| `forgedock release recover` | Recover a release that stopped mid-deploy. |
| `forgedock release deploy` | Deploy stage engine (`deploy.engine`): `--plan [<id>] [--sha]` lists the stages that would run and why; `--resume <id> [--sha]` continues from the first failed or incomplete stage. |
| `forgedock release rollback` | Roll a release back (`--reason`, `--to flag\|unit\|full`, `--later`). |
| `forgedock release plan` | Build the release plan for a lane. |
| `forgedock release start` | Start a planned release (`--plan`, `--approve`, `--wave`). |
| `forgedock release go` | Advance a started release (`--plan`, `--merge`, `--activate <key>`). |
| `forgedock release status` | Read-only state of a release (`--watch`, `--json`). |
| `forgedock release explain` | Rule trace for an id, issue or PR. |
| `forgedock release check-config` | Validate the policy file (`--ref`, `--coverage`). |
| `forgedock release init` | Write the zero-config profile. |
| `forgedock release control` | Audited controls: `hold`, `resume`, `cancel`, `lane`, `exempt`, `freeze`, `unfreeze`; each also runs as `forgedock release <verb>` and needs `--reason`. `demote`, `promote`, `rollback` and `regate` are control verbs too. |
| `forgedock release gates` | Gate telemetry (`check`, `demote`, `record`). |
| `forgedock release promote` | With `--check`, `--gate`, `--attest`, `--observed`, `--report` or `--images`: build once, promote (`deploy.promote` in forge.yaml, #5711). With a gate id and `--fixture`: the control verb. |
| `forgedock release report` | Model vs measured Actions minutes. |
| `forgedock intake` | `pause`, `resume` or `status` of issue intake (`_active.intake`). |
| `forgedock ci budget` | Actions-minute budget and CI placement (#5278). |
| `controls log` | The `controls.jsonl` audit line every control verb appends; read it through `release status` and `release explain`. |
| `ci flakes`, `ci nightly` | Records, not commands: the flake ledger (`_active.flakes`) and the nightly result, read through `release status`, `release explain` and `release report`. |

## `deploy.promote` (OPTIONAL)

Build once, promote (#5711). The release commit's CI result is recorded as evidence bound to the commit, its tree and the image digests; the deploy side checks that evidence instead of re-running tests, builds and rehearsals that already passed on the same tree. **Default off.** Once enabled it starts in shadow: it records what it would have skipped while the full pre-gate still runs.

```yaml
deploy:
  promote:
    enabled: true                 # default false: nothing is read or written
    shadow: true                  # default true: record only. false = act on the evidence
    required_checks: [unit, build]            # default: gate.required_checks, then .forge/release.yaml ci.required_checks
    evidence_app: github-actions  # the only app whose evidence check run is trusted (default github-actions)
    cache_ref: registry.example/acme/buildcache   # registry layer cache, one tag per service
    cache_mode: max               # min | max (default max)
    builder: ""                   # buildx builder name (a persistent builder keeps cache mounts)
    rebuild_all: ["docker/base/**"]           # a change here rebuilds every image
    services:
      web:
        image: registry.example/acme/web
        context: web              # default "."
        dockerfile: web/Dockerfile            # default <context>/Dockerfile
        paths: ["packages/ui/**"] # build inputs outside the context
        cache_paths: ["/app/.next/cache"]     # build cache mounts the Dockerfile declares
      api:
        image: registry.example/acme/api
        context: services/api
        paths: ["libs/shared/**", "uv.lock"]
        cache_paths: ["/root/.cache/uv"]
```

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `deploy.promote.enabled` | boolean | `false` | Master switch. Anything but `true` is off. |
| `deploy.promote.shadow` | boolean | `true` | `true`: the decision is recorded and the pre-gate still runs. `false`: accepted evidence skips the pre-gate. |
| `deploy.promote.required_checks` | list | `gate.required_checks`, then the policy's `ci.required_checks` | Check runs that must be `success` on the attested commit. With none, nothing is attested or skipped. |
| `deploy.promote.evidence_app` | string | `github-actions` | App slug whose `forge/promote-evidence` and `forge/promote-decision` check runs are read. |
| `deploy.promote.cache_ref` | string | none | Registry repository for the layer cache; each service uses the tag `<cache_ref>:<service>`. Without it no cache flags are emitted. |
| `deploy.promote.cache_mode` | `min`\|`max` | `max` | `mode=` of `--cache-to`. |
| `deploy.promote.builder` | string | none | `--builder` for every build. |
| `deploy.promote.rebuild_all` | list of globs | none | A changed path matching one rebuilds every image. |
| `deploy.promote.services.<name>.image` | string | required | Image repository; the build is tagged `<image>:<sha>`. |
| `deploy.promote.services.<name>.context` | string | `.` | Build context. Every path under it is a build input. |
| `deploy.promote.services.<name>.dockerfile` | string | `<context>/Dockerfile` | Dockerfile path; also a build input. |
| `deploy.promote.services.<name>.paths` | list of globs | none | Build inputs outside the context. A service with context `.` and no `paths` is rebuilt on every change. |
| `deploy.promote.services.<name>.cache_paths` | list | none | Targets of `RUN --mount=type=cache` mounts (a framework build cache, a package-manager cache). |
| `deploy.promote.services.<name>.cache_ref` | string | `<cache_ref>:<name>` | Layer-cache reference of this service. |

Without `services`, the `units` of `.forge/release.yaml` that name an `image` are used (`paths`, `dockerfile`).

**Evidence.** `forgedock release promote --attest --sha <sha> --digests <file|json>` reads the check runs of the commit and, only when every required check concluded `success` on exactly that commit, writes the attestation `{commit, tree, images, checks: [{name, conclusion, id, run_id}], config_hash}` as the output of a `forge/promote-evidence` check run on the commit. The token must belong to an app with `checks: write` (the workflow `GITHUB_TOKEN` does). A failed, missing, skipped or unfinished required check, a malformed digest, or a configured service without a digest: exit 1, nothing written.

**Decision.** `forgedock release promote --gate --sha <sha> --digests <file|json>` is the deploy-side call. Evidence is looked up on the commit, its parents (a merge commit of the attested head) and the heads of pull requests merged as it (squash). The pre-gate is skipped only when all of these hold; anything else runs the full pre-gate:

- the evidence check run was posted by `evidence_app` and names the commit it is on;
- the tree to deploy equals the attested tree;
- every currently required check is in the attestation as `success`, and still is `success` on the attested commit when read again now;
- every digest to deploy equals the attested digest of that service (`--digests`, else the policy's `deploy.expected_digests_command`);
- the config hash (required checks and service build inputs) equals the attested one;
- the block has no finding (an unknown key, a missing image, no required checks).

It prints the decision (`--json`: `{"schema":"forgedock.release.promote/v1","mode","would_skip","skip_pre_gate","reasons","skips","gates"}`), appends `skip_pre_gate=` and `would_skip=` to `$GITHUB_OUTPUT`, and records the decision as a `forge/promote-decision` check run on the commit. In enforce mode a decision that cannot be recorded does not skip. `--check` prints the same explanation and writes nothing.

When `.forge/gates.yaml` exists, each gate with an `evidence_check` is listed as skipped or kept. A gate on the safety allowlist (`gates.safety` and the unskippable classes) is always kept.

**Shadow.** With `shadow: true`, `skip_pre_gate` is always `false`. After the pre-gate, `forgedock release promote --observed pass|fail --sha <sha> [--minutes N]` records its outcome next to the decision. `forgedock release promote --report [--last 30]` counts, over the last commits of the default branch: decisions, would-skips, observed outcomes, agreements, **disagreements** (promote would have skipped a pre-gate that failed) and the pre-gate minutes it would have saved; it exits 1 on any disagreement. Exit criterion for the owner's decision to set `shadow: false`: at least 10 observed would-skip decisions and 0 disagreements.

**Image plan.** `forgedock release promote --images --base <ref> [--sha <sha>] [--json]` plans without running docker. A service is reused (previous digest, no build) only when the changed paths are known, a well-formed previous digest exists (`--previous`, else the attestation of the base commit), no `rebuild_all` path changed and no changed path matches its context, `paths` or Dockerfile. Each service to build gets `docker buildx build` arguments with `--cache-from type=registry,ref=…` and `--cache-to type=registry,ref=…,mode=…`, `--metadata-file .forge/build/<service>.json` (its `containerimage.digest` is the digest to attest) and `--push`. The plan lists each `cache_paths` mount with the id the Dockerfile gives it and warns when the Dockerfile declares no such mount. BuildKit keeps cache mounts in the builder and does not export them with `--cache-to`: use a persistent builder (`builder`) or restore them in the workflow.

```yaml
# CI on the release commit, after tests and image builds:
- run: forgedock release promote --attest --sha "$GITHUB_SHA" --digests digests.json
# Deploy workflow:
- id: promote
  run: forgedock release promote --gate --sha "$GITHUB_SHA" --digests digests.json
- if: steps.promote.outputs.skip_pre_gate != 'true'
  run: ./scripts/pre-gate.sh        # today's full pre-gate, unchanged
- if: always() && steps.promote.outputs.skip_pre_gate != 'true'
  run: forgedock release promote --observed "${{ job.status == 'success' && 'pass' || 'fail' }}" --sha "$GITHUB_SHA"
```

**Commands that use this section**: `forgedock release promote`

---

## `issue_watch` (OPTIONAL)

Named, scoped, capped watches for `forgedock issue-watch` (see [ISSUE-WATCH.md](ISSUE-WATCH.md)). Write `issue_watch:`, then `watches:`, then one block per watch name. The release keys need `mode: release` and at least a `threshold` or `immediate`.

```yaml
issue_watch:
  watches:
    nomilestone:
      milestone: none
      exclude_labels: [epic, post-deploy]
      include_followups: defer-only
      mode: batch
      parallel: 12
    release-1-4:
      version: "1.4"
      max_issues: 300
      until: 2026-11-15T00:00:00Z
```

| Key | Type | Required | Description |
|---|---|---|---|
| `milestone` | string | No | Milestone title or slug, or `none`. |
| `labels`, `exclude_labels` | list | No | Labels that must / must not be present. |
| `search` | string | No | `gh search` query. |
| `title_regex` | string | No | Regex tested against the title. |
| `since` | ISO time | No | Only issues created at or after it. |
| `version` | `x.y` | No | Target version from the milestone title or a `version:x.y` label. |
| `lane` | string | No | Pin the lane; never a default branch. Default: the issue's own lane. |
| `max_issues` | integer | No | Total claims; at N the watch drains and exits. Default: none (forever). |
| `max_inflight` | integer | No | Claims in flight at once. Default 4; in `batch` mode, `parallel`. |
| `until` | ISO time | No | Stop claiming at this time, drain and exit. |
| `mode` | string | No | `per-issue` (default), `batch` or `release` (pool, then cut themed releases). |
| `parallel` | integer | No | K of the batch in `batch` mode. Default 4. |
| `include_followups` | string | No | `none` (default) or `defer-only`. |
| `trust_app` | boolean | No | Claim issues authored by this repo's ForgeDock App. Other bots and `NONE`-association authors stay untrusted. Default false. |
| `trust_app_labels` | list | No | Needs `trust_app`: an App-authored issue must carry one of these labels. |
| `skip_labels` | list | No | Issues carrying any of these labels are skipped. Default for `mode: batch`: `epic, needs-human, post-deploy, workflow:merged, awaiting-promotion, host-task`; `[]` for the other modes and to switch it off. |
| `release_pause` | boolean | No | Pause the watch while a `forgedock release` job is in flight; it resumes by itself. Default true in `mode: batch`. |
| `freeze.intake_auto_resume` / `release.tracker` | boolean / issue number | No | With `release.managed` (#5555): `freeze.intake_auto_resume: true` lets the issue watch clear a `forgedock intake pause --release <id>` once release `<id>` has ended in the ledger; `release.tracker` is the issue that gets the `forge:intake-paused` label. Default off. |
| `postdeploy_rollup` | issue number | No | Release issue that collects post-deploy-only follow-ups as checklist lines. |
| `sweep_needs_human` | boolean | No | Also settle `needs-human` escalations that predate the watch (the backlog). Default false; `forgedock issue-watch run --dry-run` classifies them first and writes nothing. |
| `max_launches` | integer | No | Total lane launches (claims plus requeues by the decision engine); at N the watch drains. Default: none. Decision-stage issues also count against `max_issues`. |
| `threshold` | map | release | `{ min_issues, min_score, max_age_days }`; any one fires a release. |
| `immediate` | list | release | `label:<name>` or `priority:P0..P3` entries that cut a release now with only their theme. |
| `max_release_issues` | integer | release | Cap on a release set, closure included. Default 40. |
| `theme_map` | block | release | `<theme>: [label:<x>, scope:<x>, path:<glob>]` rules, one theme per line. |
| `tracker` | issue number | release | Issue that gets the `FORGE:RELEASE_PLAN` comment. Default: the first issue of the release. |

---

## `followups` (OPTIONAL)

Deferred follow-ups (`scripts/file-deferred-followups.sh`) are routed by kind (#5078):

| Kind | Where it goes |
|---|---|
| Post-promotion, production-verify, rollout-promote (`post-deploy`, `owner:orchestrator`, `owner:promote:<flag>`, or an owner why such as "after release", "rollout", "purge") | A checklist line in the repo's ONE open post-deploy rollup (`FORGE:POSTDEPLOY_ROLLUP`, else the lowest open issue labelled `followups.rollup_issue_label`). Never a new issue when one is open. |
| Read-only production data or capture (bucket `host`, or an owner why naming obs-psql, a `*-monitor` or a read-only prod query) | ONE host aggregate per batch (`FORGE:HOST_BATCH: <batch id>`) holding every item under a `### #<parent>` heading. Labels `followup:host` and `host-task`, never `needs-human` (#5207). |
| Truly external, and `ops` (credentials, spend, an account, a third party, a customer) | ONE issue per batch (`FORGE:EXTERNAL_BATCH: <batch id>`) holding every item under a `### #<parent>` heading, labelled `followup:external`, `external-prerequisite` and `needs-human`. |
| `verify-now` | The release rollup, like `post-deploy` (#5207). |
| Engineering (bucket `new-issue`, class `engineering`, or no class) | Never filed (#5207): the conformance review rejects the deferral and the builder delivers it in the same lane; the script exits 2. No per-parent follow-up issue is filed for any class. |

Each issue carries the label `followup:<class>` and inherits the parent's milestone. A requirement may set an optional `class` in the contract. Otherwise `post-deploy` items are `post-deploy` and the rest `engineering` (rejected). A parent milestone that has shipped (closed) is replaced by the next open milestone by due date, else `followups.default_milestone`. The batch report lists `follow-ups appended: #N (<class>: k item(s) from #a,#b)` per issue, not "issues filed".

```yaml
followups:
  default_milestone: "Backlog"     # optional: milestone title used when the parent's milestone has shipped and no later one is open
  rollup_issue_label: post-deploy  # optional: a repo's own open issue with this label is the post-deploy rollup when no marked one is open
```

## `rollouts` (OPTIONAL)

```yaml
rollouts:
  files: "config/rollouts.json,src/flags.py"   # comma-separated rollout registry / env flag list paths
  dormant_days: 14                            # dormancy report threshold (default 14)
```

A diff that adds a key to one of these files with a default of `false`, `0`, `off` or `null` (#4769) must be covered by an activation row in the contract: a `defer` requirement with bucket `owner:promote:<flag>` (a trailing `*` matches a prefix) or a `deliver` row whose why names the flag. Without one conformance fails with `activation_missing`, and an acceptance criterion naming `shadow`, `cohort` or `treated` fails with `mode_unreachable`. Without `rollouts` nothing changes.

A post-deploy check whose output has a line `BLOCKED: <flag> = off ...` is not a failure: it posts one `FORGE:ROLLOUT_ASK` owner ask per flag on the rollup and parks `awaiting-measurement`; the ask is posted again only when the output (the evidence) changes. `dormancyReport` (`bin/lean/activation.mjs`) lists introduced flags still `off` after `dormant_days`, with days dormant and the parent issue, through an injected read-only `flagState(flag)` hook; a `keep-off` decision for a flag (or `PREFIX*`) silences it.

## `deploy` (OPTIONAL)

`deploy.engine` (#5712) turns the deploy of a release into a resumable stage machine (`bin/lean/deploy-stages.mjs`). Default off: without `enabled: true` the deploy step is unchanged. Your repo keeps its own tooling (ssh, compose, k8s): a stage is a host command (`run`) or a dispatched workflow (`workflow`).

```yaml
deploy:
  engine:
    enabled: true
    live_release_command: "ops/live-release"      # prints the live sha, or JSON {sha, images}; used when .forge/release.yaml has no deploy.live_release_command
    stage_timeout_s: 1800                         # default per stage (3600); a stage may set timeout_s
    colour:
      active_command: "ops/active-colour"         # prints the colour serving traffic
      names: [blue, green]                        # default
    services:
      mode: shadow                                # off | shadow | enforce (shadow when desired_command is set)
      desired_command: "ops/digests --sha $FORGE_SHA"   # JSON {service: {digest, config}}
      live_command: "ops/digests --live"                # same shape, what is running
    canary:
      health_command: "ops/health"                # run after each step
      medium: {steps: [10, 100], wait_s: 120}     # defaults: low [100]; medium [10, 100] 120 s; high [10, 50, 100] 300 s
    rollback:
      budget_s: 60                                # timeout of the two commands below
      shift_back_command: "ops/shift 0"           # traffic back to the old colour
      abort_command: "ops/down $FORGE_COLOUR"     # optional: stop the idle colour after a pre-traffic failure
    stages:
      - {id: build, kind: build, run: "ops/build", inputs: ["services/**"], services: true}
      - {id: expand, kind: migrate, run: "ops/migrate expand", inputs: ["db/expand/**"]}
      - {id: deploy-new, kind: deploy, run: "ops/up $FORGE_COLOUR", inputs: ["ops/**"], services: true, check: "ops/is-up $FORGE_COLOUR"}
      - {id: smoke-new, kind: smoke, run: "tests/smoke/run $FORGE_COLOUR", inputs: ["tests/smoke/**"]}
      - {id: shift, kind: shift, run: "ops/shift $FORGE_TRAFFIC_PCT", inputs: ["ops/router/**"]}
      - {id: verify, kind: verify}
      - {id: retire-old, kind: retire, run: "ops/down $FORGE_OLD_COLOUR", inputs: ["ops/**"]}
      - {id: contract, kind: contract, run: "ops/migrate contract", inputs: ["db/contract/**"]}
```

| Stage key | Meaning |
|-----------|---------|
| `id` | Unique name. |
| `kind` | `build`, `migrate`, `deploy`, `smoke`, `shift`, `verify`, `retire`, `contract` or `run` (default). Each kind has an idempotency contract (the engine may run a stage twice): see `devdocs/decisions/5712-deploy-stage-engine.md`. |
| `run` / `workflow` | Exactly one (a `verify` stage may have neither). A workflow receives the inputs `stage`, `sha`, `release`, `colour`, `old_colour`, `services`, `traffic_pct`, `forge_epoch`. |
| `inputs` | Path globs. A change to a matching file at the deploy sha re-runs the stage. Default `**` (any commit). |
| `needs` | Earlier stages this stage depends on. Default: all earlier stages. It re-runs when a needed stage's outputs change, or, for a needed stage without outputs, when that stage's inputs change. |
| `services` | `true`: the stage works per service; its key includes the service digests, and in `enforce` mode it is skipped when no service changed. |
| `check` | Read-only probe that the stage's effect still holds. A done stage is skipped only when it passes; a failure re-runs this stage and all later ones. |
| `outputs_command` | Prints a JSON object recorded as the stage's outputs. Without it, a `run` stage's last stdout line is used when it is a JSON object. |
| `timeout_s` | Stage timeout. |

Commands get `FORGE_SHA`, `FORGE_TARGET_SHA` (what was live before), `FORGE_RELEASE`, `FORGE_STAGE`, `FORGE_COLOUR` (new), `FORGE_OLD_COLOUR`, `FORGE_RISK`, `FORGE_SERVICES` (comma list to act on; empty means the engine has no service list), `FORGE_SERVICES_SKIPPED` and, for `shift`, `FORGE_TRAFFIC_PCT`.

Rules the engine enforces:

- **Resume.** Each stage has a checkpoint (inputs hash, outputs, status) in the release state and, for a managed release, on the ledger. A stage is skipped when its checkpoint is done and its inputs are unchanged; so a resume starts at the first failed or incomplete stage, and a fix commit re-runs only the stages whose `inputs` it touches (or whose needed outputs changed).
- **Smoke before traffic.** A `smoke` stage must come before the first `shift`. A failure before the shift moves no traffic: the old colour keeps serving, and there is no hold, freeze or rollback trigger.
- **Rollback.** A failure from the shift up to `retire` runs `rollback.shift_back_command` within `rollback.budget_s`. If that fails, the rollback ladder is triggered as before. After `retire` the engine holds for a roll-forward.
- **Changed services only.** A service is unchanged only when its image digest and config hash both match what is running. `shadow` deploys everything and records what would have been skipped and whether that agreed; `enforce` skips.
- **Canary by risk class.** The risk class comes from the release risk rules (`risk.rules` of `.forge/release.yaml`, else the defaults) over the files changed since the live sha.
- **Verification.** A `verify` stage is required. It checks the live record against the deployed sha, runs its own command if it has one, then the `verify` layers of `.forge/release.yaml`.

```bash
forgedock release deploy --plan <release id>            # which stages would run, and why
forgedock release deploy --plan --sha <sha> --json      # plan for a commit, as JSON
forgedock release deploy --resume <release id>          # continue from the first failed or incomplete stage
forgedock release deploy --resume <release id> --sha <sha>   # same, deploying a later default-branch commit that contains the release merge (a fix)
```

To turn it off, set `enabled: false` or remove the block. A release already started by the engine must be finished (or rolled back) with the engine on.

## `post_deploy` (OPTIONAL)

Deferred follow-ups whose items are all post-deploy checks are parked (`awaiting-promotion`, no lane) until the parent's fix is on `branches.default`. Keys: `precondition_cmd` (exit 0 ready, 1 parked) and `min_age` (soak window, e.g. `24h`).

A post-deploy item may carry `due:YYYY-MM-DD` (`- [ ] \`R2: …\` — post-deploy: [check:id] due:2026-11-03 why`): it parks `awaiting-due` (with a `due:<date>` label) until that UTC date. A `decision:` item parks with one typed `FORGE:OWNER_ASK` comment and no lane. The daemon timer (and `forgedock probe --due`) re-evaluates parked follow-ups (`awaiting-promotion`, `awaiting-due`, `awaiting-measurement`) and removes the wait labels when the parent's fix is on the default branch, the date has passed or the check is defined. The only production access a check has is the checks file's command and the `acceptance_probe.env` allowlist; a pass ticks the items, a fail files one `followup:engineering` issue per failing check, and an item with no runnable check gets the owner ask. The batch report lists `due date:` and `owner ask:` apart from failures.

### Named checks (#4626)

A post-deploy requirement carries a check id (`[check:<id>]` in the follow-up item). The command is read from `.forge/post-deploy-checks.json` on the default branch (`git show origin/<default>:...`), never from an issue body or comment:

```json
{ "login-smoke": { "run": "scripts/smoke.sh", "pass": "exit 0", "timeout": 120 } }
```

`pass` is `exit 0` (default) or a `/regex/flags` over the output; `timeout` is seconds. When the gate reports the follow-up ready, the check runs with no model call: pass closes the follow-up with a `FORGE:PROBE` record, fail reopens the parent with the output. An item with no check id, or an id the default branch does not define, gets the `awaiting-measurement` label and never a lane. A contract's check id must be on the default branch or added by the same PR.

### Experiment arm overrides (#5206)

An `experiment:` arm can carry config overrides that apply only to the lanes hashed to that arm, so one batch, one checkout and the normal issue flow run both arms. A key is `<arm>.<key>: <value>`, where `<arm>` is a declared arm:

```yaml
experiment:
  id: explore-ab
  arms: on,off
  on.lean.explore: on
  off.lean.explore: off
  min_n: 20
```

| Override key | Values | Overrides |
|---|---|---|
| `lean.explore` | `on`, `off` | `lean.explore` |
| `lean.explore_model` | a model id | `lean.explore_model` |
| `lean.light_mode` | `off`, `shadow`, `on` | `lean.light_mode` |
| `context_pack` | `shadow`, `on`, `off` (not `ab`) | `engine.context_pack` |
| `review.verifier` | `off`, `shadow`, `enforce` | `review.verifier` |

Any other dotted key, a key for an undeclared arm, or an invalid value makes the whole `experiment:` declaration invalid. The experiment is then ignored, with the reason printed to stderr, and no override is ever partly applied. The lane applies its arm's overrides before it reads any of these settings. `RUN_TERMINAL` (and `phase_attempt` telemetry) records `arm_overrides`: the applied overrides as a sorted `key=value` list, or `none`. `forgedock stats --experiment <id>` adds an `applied` column per arm: the runs whose recorded overrides match the arm's. A count below `n` means the toggle did not apply on some runs.

Closing an experiment follow-up (#4634): add a check that runs `forgedock stats --experiment <id> --require-met` (exit 0 only when every target of the forge.yaml `experiment:` is met; n/a below min n is not met), and put `[check:<check id>]` in the follow-up item:

```json
{ "exp-light-vs-full": { "run": "forgedock stats --experiment light-vs-full --require-met" } }
```

Met targets pass the check and close the follow-up; with `for`/`every` it is re-measured through the window. The probe env is minimal: list the GitHub token variable in the forge.yaml `acceptance_probe.env` allowlist so stats can read telemetry.

### Windowed monitoring (#4627)

A check may declare `for` (the window, `30m`/`24h`/`7d`/`2w`) and `every` (the cadence, default `6h`; needs `for`); an entry with an invalid duration, or `every` without `for`, is ignored:

```json
{ "login-smoke": { "run": "scripts/smoke.sh", "for": "7d", "every": "6h" } }
```

When every item's check is windowed, the first pass records the release (the `origin/<default>` sha) and the window end in a `FORGE:PROBE` record, labels the follow-up `post-deploy-monitoring` and leaves it open (no lane, no second measurement by the pre-filter). It re-runs, with the command read from the default branch each time, when `every` has elapsed or `origin/<default>` moved (a later release). At the window end it closes. A fail after a pass opens a regression issue (`FORGE:REGRESSION`) naming the fix commit, the last passing release and the breaking release, and closes the follow-up; the parent is not reopened. A fail on the first run behaves as above (the parent reopens). No model call.

Triggers: `forgedock probe --due [--dry-run] [--repo owner/repo]` runs the due ones once; the `forgedock schedd` daemon runs them on a timer while it is up (`FORGEDOCK_SCHEDD_DUE_MS`, default 15 minutes).


## `events` (OPTIONAL)

Outbound lifecycle events (#4630). The local JSONL sink is always on; the webhook needs both keys. See [EVENTS.md](EVENTS.md) for the schema and signature.

```yaml
events:
  webhook_url: https://hooks.example.com/forgedock   # https, or http on localhost; unset = no webhook
  webhook_secret_env: FORGE_EVENTS_SECRET            # NAME of the env var holding the HMAC secret (default shown); never put the secret here
  dir: ~/.forge/events                               # local JSONL directory
```

## `lean` (OPTIONAL)

Settings of the core work-on (`bin/lean/`) that change its contract.

```yaml
lean:
  repro_test: prefer   # off | prefer (default)
  repro_quality: shadow   # off | shadow (default) | enforce
  precheck:
    max_minutes: 10    # optional pre-PR check round budget in minutes (1-120)
  ci_precheck: on               # on (default) | off: run the PR's required CI jobs in the lane before the PR opens (#5820)
  ci_precheck_include: [e2e]     # optional: heavy kinds (e2e, visual, lighthouse, docker, build) or job ids/names to run locally too
  ci_precheck_exclude: ["gha:ci:slow-*"]   # optional: job ids/names/kinds never run locally (wins over include)
  ci_precheck_max_jobs: 8        # optional cap on locally run CI jobs per round (default 8)
  fix_model: claude-sonnet-5-5   # optional model of fresh fix-round sessions (default: the reviewer model)
  builder_routing: on            # on (default) | off: route the build to a mid-tier model by the frozen contract
  builder_mid_model: claude-sonnet-5-5   # optional mid-tier builder model (default claude-sonnet-5-5)
  contract_max_corrections: 3   # #5623: builder correction rounds for a builder-correctable invalid contract before it ends contract.invalid (which a batch then requeues once with a fresh plan)
  review_max_resumes: 3         # #5644: builder resume rounds, each with only the open findings, for builder-fixable review/conformance failures (regression, unimplemented, omission, deferral, scope) before needs-human; stops early when a round changes nothing
  light:
    mode: shadow     # off | shadow (default) | on: light-lane eligibility (#4448; lane wiring #4450)
    max_lines: 40    # upgrade to the full lane above this many non-test diff lines
    max_files: 2     # max predicted / changed non-test files
    source: investigation   # investigation (default) | text: eligibility from the investigation's predicted files and size, or (kill-switch) from the issue text (#5426)
  sequence:
    regenerate: pnpm --filter @x/db db:generate   # optional snapshot generator after a deterministic renumber
  base_merge_union_globs: "src/index.ts, **/messages.ts"   # optional #4588: append-only files, both sides' added lines kept
  base_merge_json_globs: "i18n/translation-status.json"     # optional #4588: JSON maps, 3-way key union
  base_merge_generated_globs: "i18n/generated/**"           # optional #4588: base side taken, then regenerated
  base_merge_generated_command: "pnpm i18n:generate"        # optional #4588: the regenerate command
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `repro_test` | string | No | `prefer` (default): on an issue labelled `bug` or `type:bug`, the plan step must freeze a `repro_test` in the contract (`{"path","id","command"}`) when the bug is testable. Before review, the engine runs `scripts/acceptance-red-green.sh` for that command on the host in every verify mode: one targeted test, red on the base (head's changed test files overlaid) and green on head. A test that ran but is not red on the base and green on head fails the precheck as `conformance.unimplemented` (it blocks in shadow too) and goes back to the builder for one in-session fix round. A head the harness could not run at all (timeout, missing runner or dependencies) ends `needs-human` with the recoverable code `env.repro_unrunnable`, not a builder round: the batch runner's recovery lane reruns it through the repo's own toolchain (see docs/OUTCOME-CODES.md). The harness runs with the lane env (`TMPDIR`, toolchain) and the workspace dependency trees, and a repro test file that is new on head is run against the base sources. A bug that is not testable (specs, docs, workflows, environment) records `"repro_test":"none"` with a one-line `repro_test_reason` and the lane continues as before. `off` gives exactly the previous contract and precheck. Each proof emits a `REPRO_RED_GREEN` run-log event (`base`, `head`) and adds a trajectory decision. |
| `repro_quality` | string | No | `shadow` (default): after a repro_test is red on the base and green on head, the engine checks it deterministically (0 LLM calls) and records `repro_quality` on the run's `RUN_TERMINAL` event (`behavioural`, `patch_echo`, `mutation_survivor`, `none`) plus a `REPRO_QUALITY` run-log event. `patch_echo`: every assertion only compares literals the same diff introduced; the reviewer prompt then asks for an explicit accept or reject. `mutation_survivor`: 1-3 targeted mutations of the fix's added lines (flipped condition, early return, dropped call) all left the repro green; the tree is restored after each. `enforce` blocks a `mutation_survivor` (`conformance.mutation_survived`, kind `repro_mutation_survivor`); `off` skips the check. Flip to `enforce` only after the false-positive rate is under 5% on a replay of recent lanes. |
| `precheck.max_minutes` | number | No | Total budget in minutes (1–120) of one round of pre-PR check commands (#4331). The flat form `lean.precheck_max_minutes` also works and wins. When unset, `verify.precheck_total_seconds` applies (default 600 s). Check commands run change-scoped (a learned command with a test-map entry runs only when its globs match the changed files; unmapped commands always run), concurrently up to the host worker cap under one heavy slot, each timed (`ms` in the `PRECHECK_COMMANDS` run-log event). Commands not started when the budget runs out are recorded `deferred-to-ci` (an anomaly, not a failure) and left to CI. |
| `ci_precheck` | string | No | `on` (default) or `off` (#5820). In the pre-PR check round (after the build, before review and `PR_OPENED`) the lane runs the CI jobs the PR must pass, locally and scoped to the change. The check set is the `scripts/ci-local` plan of the change (CI definitions from the base ref plus the lane's edits, path filters, change-scoped commands; see `verification.ci_local`), narrowed to the jobs whose name or id is a required status check on the lane base (classic branch protection plus rulesets) and the jobs a required aggregator job `needs`. When no required check maps to a job (none configured or unreadable), a conservative set runs: the lint, typecheck and unit-test jobs. Heavy jobs (e2e, visual/Storybook, Lighthouse, app builds, docker images) stay CI-only unless `ci_precheck_include` names them. Each job runs as one pre-PR check command (`ci-local.sh run` with a one-job plan) under the round's budget, per-command timeout and heavy slot. A failing job goes to the builder in the precheck fix round with its log tail, like a failed declared check; a job that cannot run locally (ci-local degraded or deferred, timeout, no `yq`) is recorded with its reason as an anomaly, is not rerun in later rounds and never blocks the PR. Run-log events: `CI_PRECHECK_PLAN` (`source` required/fallback, `commands` with `job`, `why`, `steps`, `command`; `skipped` and `unrunnable` with reasons) and `CI_PRECHECK_RESULT` (`round`, `green`, per-job `status` pass/fail/unrunnable/deferred/deferred-to-ci). |
| `ci_precheck_include` | list | No | Heavy kinds (`e2e`, `visual`, `lighthouse`, `docker`, `build`) or job ids/names (`gha:<workflow>:<job>`, `*` globs) to run locally as well; a named job also runs when it is not a required check. |
| `ci_precheck_exclude` | list | No | Kinds or job ids/names never run locally; wins over `ci_precheck_include`. |
| `ci_precheck_max_jobs` | integer | No | At most this many CI jobs per round (default 8); the rest are left to CI and listed in `skipped`. |
| `fix_model` | string | No | Model of fresh fix-round sessions (#4363; `engine.lean_fix_model` is also read). Default: the reviewer model (`engine.lean_reviewer_model`, else Sonnet). Fix rounds for precheck, CI, docs, structure, enumerating-test and sequence-number failures, and conformance or review FAILs whose failures all cite a `file:line`, run in a fresh session (no resume of the builder's transcript) whose prompt carries only the round's failure output, the capped `git diff <base>...HEAD`, the frozen contract and the issue title and summary (under 60K characters). A fresh session that makes no commit gets one resume of the original builder session in the same round. Other rounds (block or contract corrections, CI unavailable, base-sync conflicts, failures without a file:line) resume the builder as before; round limits (`verify.max_rounds`, the one review retry) are unchanged. The run log's `PHASE_ATTEMPT_USAGE` records `mode: "fresh"\|"resume"` on each fix-round attempt. Plan and build sessions keep the builder model. |
| `builder_routing` | string | No | `on` (default) or `off` (#4394). After the contract is frozen, the lane is classed from its deliverable paths only: `risk` (any path with a built-in risk word such as auth, billing, payments, session, secret or migration, or matching a `review.risk_paths` glob), `docs-config-test` (every path is a test, doc or config file; lockfiles count as code), `small` (at most 2 non-test deliverables) or `large` (more, or none). `docs-config-test` and `small` build on the mid tier (`builder_mid_model`); `risk` and `large` build on the top model (`--model`, else the CLI default). Before the contract exists, the pre-contract calls (investigation, plan, contract corrections, light build) run on a provisional route from the issue alone (#5810): top for a risk word in the title (bar session/token), a label or a named path, a `size:L` label, more than 2 named code files, or a resumed, salvaged or recovery lane; else the mid tier (class `unscoped` when the issue names no files). The run log gets `BUILDER_PREROUTE {mode, class, tier, model, reason, risk}`. The contract route may then upgrade the tier without rerunning the plan, and a provisional `risk` class floors the build at top. A failed validate round on the mid tier (`precheck`, `ci_red`, `merge_ci`) escalates the lane once: that fix round and every later builder call, fresh fix sessions included, run on the top model. Escalation adds no round. Conformance or review fix rounds do not escalate and keep `fix_model`. `off` keeps every builder call on the top model, as before, and still records the class. The run log gets `BUILDER_ROUTE {mode, class, tier, model, risk}` and `BUILDER_ESCALATED {from, to, trigger}`, and `RUN_TERMINAL` gets `builder_tier`, `builder_class`, `builder_escalated` and `builder_model`. `forgedock stats --tiers` reports merge, conformance and post-merge-rework rates, first-pass yield and cost per tier (`mid`, `mid->top`, `top`) and class, from local run logs. Target-repo risk areas (for example detection code) belong in `review.risk_paths`. A diff that relaxes a rule in a declared `review.risk_paths` path (a new accept/rescue/allow branch or a removed deny) must add a negative test (`conformance.unimplemented` `relaxation_untested` otherwise) and always gets the independent verifier, even with `review.verifier: off` (#5237). |
| `builder_mid_model` | string | No | Mid-tier builder model for `builder_routing` (#4394; `engine.lean_builder_mid_model` is also read). Default `claude-sonnet-5-5`. An invalid id is ignored. |
| `light.mode` | string | No | `off`, `shadow` (default) or `on` (#4448). `bin/lean/light.mjs` decides whether an issue qualifies for the light lane: a repro, steps to reproduce, expected or actual behaviour or a code block in the body; 1 to `max_files` predicted non-test files; no `size:M`/`size:L` label; no predicted path with a built-in risk word or matching `review.risk_paths`; not an `investigate(` issue, a post-deploy issue (`post-deploy`/`awaiting-promotion` label, or only post-deploy checklist items) or a decision issue (`decision`, `needs-decision`, `product-decision`, `rfc` or `adr` label, or a `decision(`/`rfc(`/`adr(` title). A missing repro or file prediction is `ambiguous`, left to a cheap classifier. `off` is never eligible; `shadow` reports the verdict without changing the lane; `on` lets an eligible issue run light. The lane wiring is #4450. A light lane posts a `FORGE:LITE` receipt on the issue (outcome light or upgraded, diff stat, red/green repro, gates, true cost from the #4407 per-session deltas, eligibility reason, upgrade reasons), and the batch efficiency report ends with a `lanes:` line: the light/upgraded/full split with cost and the upgrade rate, upgraded ÷ (light + upgraded) (#4452). A predicted file over `maintenance.hotspot.file_lines` is a hard `hotspot` reason, and every evaluated signal (repro, named files, churn, hotspot, risk path, `docs`/`config`/`chore` labels, size) is recorded in the `LIGHT_ELIGIBILITY` event's `signals` without changing the verdict (#5209). `forgedock stats --depth` reports outcomes per verdict and signal and whether the #5052 promotion criterion is met; flipping `mode: on` stays a config decision. The flat form `lean.light_mode` also works and wins. |
| `light.max_lines` | number | No | Upgrade trigger (#4448): a light lane whose non-test diff (added + deleted lines) exceeds this moves to the full lane. Default 40. The other triggers: more than `max_files` non-test changed files, a repro that is not red on the base, two failed test runs, a touched risk path, or a public-API-shape change (#4449). Flat `lean.light_max_lines` wins. |
| `light.max_files` | number | No | Max predicted non-test files for eligibility and max changed non-test files before an upgrade (#4448). Default 2. Flat `lean.light_max_files` wins. |
| `light.source` | string | No | `investigation` (default) or `text` (#5426; the kill-switch, today's text heuristic). With `investigation`, eligibility is computed from what the investigator predicts, not from `namedPaths(body)`: the first builder call is investigation-only and writes `investigation.md` and `.forge-lean/triage.json` (`files`, `size`, `risk`, `decision_needed`; the `### Affected Files` section is the fallback). `bin/lean/fastforward.mjs` feeds those into the same `light.mjs` rules (at most `max_files` non-test files, size S, no risk path, no hotspot, no flagged risk or decision; the investigator's confirmation replaces the text repro requirement) and the text verdict stays only as a `pre_text_*` shadow signal. Invalid, already-fixed and blocked verdicts close as before. With `mode: on`, an eligible issue fast-forwards: the investigation session resumes for one implement session, then the deterministic light gates run, then merge; the trajectory and the `FORGE:LITE` receipt name the skipped stages (plan, contract freeze, multi-session review) and why. A gate failure upgrades to the full lane (#4450), and an ineligible issue continues in the same session with the contract step. With `mode: shadow`, the lane is unchanged and a `FASTFORWARD_ELIGIBILITY` event (`shadow: true`) is logged after the plan session. `forgedock stats --depth` reports the fast-forward eligibility rate and the merge, defect and revert rates of fast-forwarded, upgraded and full lanes. Promotion stays a config decision. |
| `sequence.regenerate` | string | No | Command run in the lane worktree (`sh -c`) after the engine renumbers a schema-changing sequence-numbered migration (#4386), to regenerate its snapshot, e.g. `pnpm --filter @x/db db:generate`. The flat form `lean.sequence_regenerate` also works and wins. When a lane-added numbered file (`NNNN_*.sql`, a drizzle `meta/_journal.json` + `meta/NNNN_snapshot.json`, a numbered ADR) shares its number with the base, the engine renumbers it without a builder session: `git mv` to max(base)+1…, the document's own number in its heading, references to the old name repo-wide, the base journal plus the lane's entries, and a data-only migration's snapshot cloned from the base tip with a new `id`/`prevId`. A schema-changing migration without this command, or a migration in another language (`.py`, `.ts`), falls back to the builder renumber, and the trajectory records why. When the generator writes no snapshot for a hand-written migration (no schema diff), the engine reruns it with ` --custom` appended (drizzle-kit's empty migration), keeps its snapshot and restores the lane's SQL byte-identical, so the command must forward trailing args (a pnpm/yarn script, or `npm run x --`). A base-sync whose conflicts are only in such files is resolved the same way, with no re-review. At the merge gate a lane with numbered files holds a host sequence lease per (repo, lane branch, directory) from its last renumber check through the merge, so only one numbered-file PR is in the renumber→CI→merge window at a time. |
| `sequence.versioned` | string | No | Versioned-directory sequence classes (#5235), `<dir>/v{N} -> companion[, companion]; ...`, e.g. `scripts/backup-contracts/v{N} -> src/version.ts=VERSION = {N}`. A companion is a file that references the version, as `path` (it holds the class name, `v{N}`) or `path=template` (`{N}` is the version). When a lane-added `<dir>/vN` collides with a version the base has, the engine renumbers it (`git mv`, then rewrites each companion from the old to the new version) without a builder. The flat form `lean.sequence_versioned` also works and wins. Build-start reservation: before the build the engine reserves, through the host sequence lease, one number per numbered series dir (and one version per configured class) the frozen contract's deliverables touch, above the base and the other open PRs, and tells the builder which to use, so concurrent lanes on one branch get distinct numbers. A renumber after a base-sync reruns the frozen validate commands before the merge (one fix round, then an anomaly). Fail-open: errors mean no reservation. Default: none, so nothing changes. |
| `base_merge_union_globs` / `base_merge_json_globs` / `base_merge_generated_globs` / `base_merge_generated_command` | string | No | Deterministic resolution of sibling-lane conflicts when the lane merges its base (#4588, `bin/lean/conflictres.mjs`; flat keys only). Comma-separated globs (`*` within a segment, `**` across; no `/` matches the file name anywhere). `union_globs`: hunks where both sides only added lines keep both. `json_globs`: a 3-way key union of a JSON object (a key both sides changed differently is refused). `generated_globs` + `generated_command`: the base side is taken, then the command runs once in the lane worktree (`sh -c`) and the files are re-added. A file that cannot be fully resolved, and every sequence/migration file, goes on as before (sequence resolver, then the builder). Default: none, so nothing changes. The same keys apply to milestone branch syncs (`forgedock milestone-sync`, #4663). |
| `milestones.sync_debounce` | string | No | Debounce window of the milestone sync PR (#4663, `bin/lean/milestonesync.mjs`): on a protected milestone branch `forgedock milestone-sync` keeps ONE `sync/milestone-{slug}` PR and force-pushes its head in place; a base that moved again inside the window reports `debounced` (a `ship` sync ignores the window). `10m`, `1h`, `1d`. Default: `10m`. |

## `stats` (OPTIONAL)

Thresholds of the fail-soft alerts (#4354). `forgedock stats` prints them as an `ALERTS` section, and the `forgedock orchestrate` batch report ends with the alerts for the batch's repo. Steps that never fail a run (shared dependency cache, pre-PR check budget, toolchain detection) can degrade silently. The alerts compare their rates in the local run logs (`~/.forge/runs`, or `FORGE_RUNS_DIR` for `forgedock stats`) against these thresholds. They read no network source and use no model.

```yaml
stats:
  alerts:
    window: 50                # last N lanes per repo
    min_lanes: 10             # fewer lanes in the window: nothing is printed
    deps_failed_pct: 20       # DEPS_PREPARED status failed, and status materialize-fallback, per ecosystem
    deferred_to_ci_pct: 30    # lanes with a deferred-to-ci pre-PR check
    toolchain_warning_pct: 50 # lanes repeating the same TOOLCHAIN_WARNING
    outcome_share_factor: 2   # outcome code share vs the previous window
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `alerts.window` | number | No | Rolling window: the last N lanes of the repo, ordered by `RUN_START`. Each run in a run log is one lane. Default 50. |
| `alerts.min_lanes` | number | No | With fewer lanes in the window, or no run logs, nothing is printed. Default 10. |
| `alerts.deps_failed_pct` | number | No | Alert when `DEPS_PREPARED` status `failed` is above this percentage of the lanes that prepared that ecosystem. A separate alert uses the same threshold for status `materialize-fallback`: a cached snapshot failed to link or repair, and the lane installed fresh. Default 20. |
| `alerts.deferred_to_ci_pct` | number | No | Alert when more than this percentage of lanes left a pre-PR check `deferred-to-ci`. Default 30. |
| `alerts.toolchain_warning_pct` | number | No | Alert when one `TOOLCHAIN_WARNING` text is repeated on more than this percentage of lanes. Default 50. |
| `alerts.outcome_share_factor` | number | No | Alert when an outcome code other than `completed` has at least this factor of its share in the previous window. The code must be on at least 2 lanes, and the previous window must have at least `min_lanes` lanes. A code new in this window counts. Default 2. |

Release ledger keys (#5718, `forgedock stats --release-ledger`, all optional; see [STATS.md](STATS.md)):

```yaml
stats:
  ledger_release_base: main            # default: the repo's default branch
  ledger_release_head: staging         # default: branches.staging, else any head
  ledger_ci_workflows: [CI, images.yml]  # names or file names; default: every workflow
  ledger_deploy_workflow: deploy.yml   # name or file; default: detected
  ledger_deploy_job: "^deploy"         # regex on the job name; default: detected
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `ledger_release_base` | string | No | Branch a release PR targets. Default: the repository's default branch. |
| `ledger_release_head` | string | No | Head branch of a release PR. Default: `branches.staging` when set, else every PR into the base counts. |
| `ledger_ci_workflows` | list | No | Workflows (name or file name) counted as release-PR CI. Default: all. |
| `ledger_deploy_workflow` | string | No | The deploy workflow (name or file). Default: the push/dispatch workflow on the base whose name says deploy, publish or release with the most runs; the report names what it picked. |
| `ledger_deploy_job` | string | No | Regex for the job that rolls out. Default: the longest job whose name says deploy, else the longest job. |

Each alert line names the event, the rate, the sample size (`count/sample` lanes) and one example reason. When no alert fires, nothing is printed. The flat form `stats.alerts_<key>` also works and wins. `forgedock stats --no-local` skips the alerts.

### Phase ledger (#4908)

Setup overlaps the plan session (#5434): deps install, heavy shims and `env.setup` run in the background and are awaited before implement, so `deps_install` is only the residual wait. The run log gets `LANE_SETUP_TIMING` (`step`, `ms`) per sub-step (including the pack-to-session gap: `pack_pitfalls`, `pack_gh_reads`, `pack_compile`, `prompt_assembly`, `cli_init`) and `FIRST_SESSION` (`ms` from lane start to the first model session). The runner option `contextWaitSeconds` (default 5, 0 = wait without bound) caps how long the plan waits for hotspots and the context pack.

No configuration. Every lane records start and end of the engine phases it reaches, so a lane's wall time is attributed instead of guessed: `queue_wait`, `sandbox_start` (claim, worktree, toolchain), `deps_install`, `validate`, `plan`, `implement`, `precheck`, `review`, `ci_wait`, `base_sync`, `merge`, each with `model_ms` and `usd` where model calls ran in it. A lane's phases sum to its `wall_ms`; `queue_wait` precedes the lane clock and is added by the batch runner. The ledger is the `phases` object on each `log.jsonl` outcome row and on `RUN_TERMINAL`, and `phase_<id>_ms|_model_ms|_usd` fields in `FORGE:TELEMETRY`. The batch report prints a `phases` line (p50/p90 per phase, largest share of wall time, `n/a` without ledger data) and `forgedock stats` prints a `Lane wall time by phase` table. The efficiency lines also list merged issues with no acceptance probe declared (`unprobed merged issues`).

Inside `sandbox_start` (#5435) each step (`fetch`, `claim`, `resume_probe`, `salvage_cleanup`, `warm_claim`, `scratch_setup`, and inside the cold add `sparse_plan`, `git_worktree_add` (add + checkout, including any post-checkout hook) and `sparse_checkout`, `worktree_add`, `toolchain`) is timed: a `SANDBOX_STEP` event per step (the lane fetch overlaps the claim's GitHub writes and the resume probe's `gh pr list` and `git ls-remote` run in parallel, so the steps need not sum to the phase) in the run log and a `steps` object (ms) on the `sandbox_start` entry of the ledger, so the dominant startup cost is measured. Without the pool, the cold add no longer runs the repo's post-checkout hook (hooks are disabled for the lane's `git worktree add`, sparse checkout and read-tree calls only; commits keep their hooks). The budget is `sandbox_start` p50 ≤ 3 s (`sandboxStartBudget` in `phaseledger.mjs`); `bin/lean/sandbox-budget.test.mjs` asserts it over a bench run's `log.jsonl` when `FORGE_BENCH_LOG` points at one. Local lanes can keep warm worktrees: set `FORGE_LOCAL_WARM_TREES=N` (1 to 4, default off) and a fresh lane claims a pooled worktree under `<worktree root>/warm/` instead of a cold `git worktree add`. The claim moves the tree to the lane branch at the base sha and verifies `HEAD` against that sha, so a stale pool is never handed out; any failure falls back to the cold add, and the pool is refilled after each claim.

## `verify` (OPTIONAL)

Verify-by-CI for the core work-on path (forge#4167). It moves a lane's heavy verification (type-checks, test suites, docker test containers) off the host and onto CI runners, and it catches CI-class failures (lock files, suite wiring, hangs, formatting) before the lane merges into staging. Write it as a block-style section: `parseForgeYaml` does not read inline `{ ... }` maps.

```yaml
verify:
  mode: ci                      # local (default) | ci | hybrid
  workflow: forgedock-verify.yml  # optional; needs an `on: workflow_dispatch` trigger
  paths_input: changed_paths    # optional workflow_dispatch input that receives the changed paths (newline-separated)
  skip_paths: "*.md,docs/**"    # optional, comma-separated; default *.md,*.mdx,*.rst,*.txt,docs/**,devdocs/**
  max_rounds: 2                 # optional CI fix rounds before needs-human (default 2)
  precheck_timeout_seconds: 300 # optional per-command timeout of the declared pre-PR checks (default 300)
  precheck_total_seconds: 600   # optional total budget of one pre-PR check round (default 600)
  check_run: true               # optional; post the forgedock/verify check run (default false)
  checks: "lint,test"           # optional; the check names that gate CI verification (default: the required checks)
  flaky: "memory-erasure,e2e-pdf"  # optional; known-flaky CI job names: reported, never block or feed the builder
  post_merge: pnpm -r typecheck # optional; run on the merged tree at base-sync before the push (default: the lane's scoped typecheck)
  duplicate_exports: false      # optional; turn off the same-app duplicate-export check (default true)
  settle: condition             # optional; fixed (default) | shadow | condition: wait for unreported gate checks
  cancel_superseded: own        # optional; off (default) | own | all: cancel runs of the head a push replaced

lean:
  enumerating:
    mechanical: false          # optional; kill switch for the engine's own enumerating-test edits (default true; #5480): a model session fixes them instead
  invariants:                   # optional block list; repo-wide check commands that always run before the PR
    - pnpm check:registry
  guard_command:                # optional; per-extension command for the guard gate's base test files
    ".py": "scripts/pytest {path}"
  e2e: auto                     # optional e2e merge gate: auto (default) | always | never
  precheck_block: false         # optional (#5079); true: a declared pre-PR check still failing after the fix round (or a round with no commit) ends the lane needs-human ci.red (recoverable) instead of opening the PR with an anomaly
  guard_block: true             # optional (#5239); default true: verify.invariants (the pre-merge guard set) block the merge; false keeps a failing invariant advisory
  e2e_label: full-ci            # PR label that makes the repo's CI run e2e (label path)
  e2e_checks: "e2e"             # check names of the e2e jobs the label path waits on
  # e2e_workflow: e2e.yml       # or: a workflow_dispatch workflow that runs e2e (wins over the label)
  # e2e_paths_input: specs      # its input that receives the changed spec paths
  # e2e_paths: "e2e/**,tests/e2e/**"  # globs of e2e specs (default below)
  # e2e_blocking: changed       # changed (default) | all
```

| Key | Type | Required | Description |
|-----|------|----------|-------------|
| `mode` | string | No | `local` (default): today's behaviour; the builder runs every validate command on the host and no CI is started before review. `ci`: the builder runs only formatters and linters on the files it changed (no type-checks, test suites or test containers) and records validate ids it left to CI as `{"id","command","ci":true}`; the engine verifies on CI. `hybrid`: the builder runs the targeted validate commands too, and CI also verifies. |
| `workflow` | string | No | Workflow file name or id dispatched on the lane branch (`gh workflow run <workflow> --ref <branch>`). The engine waits for the `workflow_dispatch` run of the lane's head commit. Without it, the engine waits on the head commit's check runs. Under `engine.merge_wait: required` only the base branch's required checks gate (other checks are reported, not gating), and each check name counts at its latest attempt (the newest check run, so a green rerun or a later green run of the same job wins). With no required checks configured, or none of them reported within 5 minutes, every check gates as before. |
| `paths_input` | string | No | Name of a `workflow_dispatch` input that receives the changed paths, so the workflow can scope its jobs to the change. |
| `skip_paths` | string | No | Comma-separated globs. A glob without `/` matches the basename anywhere; `**` spans directories. When every changed file matches, the lane skips CI verification (a docs-only lane runs no CI matrix). |
| `max_rounds` | integer | No | Builder fix rounds for red CI (0–10, default 2). Also bounds the merge-time fix rounds and the declared-check fix rounds below, in every mode. |
| `precheck_timeout_seconds` | integer | No | Timeout of each declared check command (1–3600, default 300); a command that hits its own timeout is retried once with a load-scaled timeout (#4589) when the total budget leaves room, else it is deferred to CI. |
| `precheck_total_seconds` | integer | No | Total budget of one round of pre-PR check commands (1–7200, default 600; it was 1800 before 1.30.0). `lean.precheck.max_minutes` takes precedence. Commands not started within the budget are deferred to CI, not failed. |
| `checks` | string | No | Comma-separated check names that gate CI verification without `workflow` (forge#4387). Overrides the required-check set; other checks are reported, not gating. |
| `invariants` | list | No | Block list of cheap repo-wide check commands (#4585), e.g. the suites that list every table, export, key or namespace (cross-tenant registry, export and purge coverage, i18n status, boundary tests). They run in the pre-PR check round in every verify mode, whichever tests the test map selected: never scoped away by `.forge/test-map.json`, deduplicated against the learned commands, and subject to the same round budget and per-command timeout. A failure goes to the builder in the precheck fix round like a failed declared check. The plan and implement prompts also carry an invariants checklist built from the list (a new table, export or key must join every registry that enumerates its kind). `forgedock check` and the light lane run them too. Absent: nothing changes. |
| `guard_block` | boolean | No | Default `true` (#5239). `invariants` are the repo's pre-merge guard set: they also run on the merged tree after a base-sync (before the push), and one still failing after the fix rounds ends the lane needs-human `ci.red` instead of opening or merging the PR. Before spending a builder round, a failing invariant is run once on the merge base: if it fails there too the base is already red, so the lane ends `deferred` with `base.red` (never needs-human, retried after 900 s), the commit that last changed the files the failure names is found with `git log`, and the issue it belongs to (closing keyword, `issue-N` branch, or last `(#N)` in the message) gets a `FORGE:BASE_RED` comment and is reopened if closed; with no issue number a tracking issue is filed. `false`: failing invariants stay advisory as before. No effect without `invariants`. |
| `guard_command` | map | No | Guard gate (#4693) test-file command per extension (#4792), e.g. `".py": "scripts/pytest {path}"` for a repo whose tests need a managed environment. Consulted before the contract's validate commands and the hard-coded `node --test` / `python -m pytest -q` fallbacks. `{path}` is replaced by the repo-relative path of the guard's base copy (`<name>__guardbase.<ext>`); a template without `{path}` gets it appended. Runs from the worktree root. Keys may be written with or without the leading dot. Absent: unchanged. Weak guards (#5752): a base test that reads file text, imports no local non-test module, runs no process and only asserts that literals exist (`assert.match`, `assert.ok(x.includes(...))`, `expect(...).toContain/toMatch`, Python `assert "lit" in s`, `re.search`) breaking is a review note (`guard_weak` event, trajectory decision), not `conformance.guard_broken`; any other assertion keeps it a strong guard. `{"kind":"supersedes","mechanism":"<name>","why":"..."}` in result.json amendments removes a named mechanism in one decision: it retires every broken guard whose test files the lane deleted; a surviving strong guard still needs its own `{"kind":"supersedes","guard":"#N"}`. |
| `sandboxes` | map | No | Test sandboxes (#5450): throwaway services a lane's validate commands need. One entry per name, written on one line: `postgres: { image: postgres:16, init: "make migrate DB_URL=$SANDBOX_URL", ttl: 30m }`, `redis: { image: redis:7 }`, `api: { compose: docker-compose.test.yml, service: api, needs: [postgres, redis] }`, `http-replay: { fixtures: tests/fixtures/http/, for: integration }`. Optional `port` and `ready` (a command run in the container until it exits 0) override the postgres/redis defaults. A frozen contract validate entry declares `env: ["postgres"]`; only then is a sandbox created, once per lane, with unique container names (`forge-sbx-<lane>-<name>`), ephemeral loopback ports and `forgedock.*` labels, registered in the lane ledger so teardown and `forgedock gc` reclaim it. Validate commands get `SANDBOX_<NAME>_URL` (a `fixtures` entry: `SANDBOX_<NAME>_DIR`, an absolute path); `init` runs on the host with `SANDBOX_URL`. A name with no entry, or a host without Docker, ends the lane `needs-human` (never a skip; no-Docker uses `env.tool_missing` so the lane is placed where Docker runs). A `fixtures` entry also exports `SANDBOX_<NAME>_MODE` (`replay`, or `record` with `record: true` or `FORGE_SANDBOX_RECORD=1`); an `http*` entry also exports `SANDBOX_HTTP_REPLAY_DIR`/`_MODE`. Each lane's image sandboxes join their own network `forge-sbx-<lane>-net`. `forgedock init --minimal` writes a commented proposal detected from compose files, migrations and test markers. Images are checked or pulled once per batch process (lanes share the cache). Each sandbox adds a `FORGE:SANDBOX {name, kind, ms, cost_usd}` line to the lane decisions. Operators: `forgedock sandbox up <name>... | down | ls`. Absent: no sandbox is ever created. |
| `check_run` | boolean | No | Default `false` (no Checks API call, behaviour unchanged). `true`: after each push of a reviewed head (PR open, base-sync, merge-time fix round) the engine posts one completed `forgedock/verify` check run on that head (forge#4270), `success` iff every deterministic gate the lane already ran passed: declared check commands, undeclared package edges, docs freshness, contract scope, validate ids, requirement status, hotspot growth, amendments. The output carries each gate's id, pass/fail and evidence as JSON; the run log records a `VERIFY` event. Report only: ForgeDock never makes it required and never waits on it (it is ignored by its own CI waits); requiring it is the repository's branch-protection choice. Creating check runs needs a token that may (a GitHub App with `checks: write`); a Checks API failure is logged as an anomaly and never fails the lane. |
| `settle` | string | No | How long CI verification waits for a gating check name that has not reported (forge#5718). `fixed` (default): the whole 5-minute grace period, unchanged. `condition`: until the head's check suites show nothing more can report (every suite completed, the same suites on two consecutive polls, at least 20 s after the push), never longer than the grace period; an unreadable suite list keeps the fixed wait. `shadow`: waits as `fixed` and logs a `CI_SETTLE` run-log event with when the condition held (`known_at_ms`) and whether the gating set was the same (`agreed`). Turn `condition` on after shadow agrees on your repo: a workflow that registers after every suite completed (a chained `workflow_run`) is the one case the condition cannot see. The set of gating checks and their verdicts is the same in every mode. |
| `cancel_superseded` | string | No | Default `off`. `own`: after the lane pushes a new head, cancel the queued and running `pull_request` / `pull_request_target` runs of its branch for an older head that this actor triggered (forge#5718). `all`: whoever triggered them. Push and dispatch runs are never cancelled (they may deploy), and a run of the current head never is. Logged as `CI_SUPERSEDED_CANCEL`. A GitHub App token has no user: set `FORGE_BOT_LOGIN` for `own`. The same check by hand: `forgedock ci cancel-superseded (--pr N \| --branch B) [--mode own\|all] [--dry-run]`. Prefer the workflow `concurrency` block ([CI.md](CI.md#superseded-runs)) where you can edit the workflow. |
| `post_merge` | string | No | Command run in the lane worktree on the merged tree after each base-sync merge, before the push (forge#4406). Default: the typecheck rows of the lane's change-scoped checks (`bin/lean/checks.mjs`), in `local` and `hybrid` mode only; `ci` mode runs no host typecheck unless `post_merge` is set. A failure resumes the builder with the output, up to `max_rounds` rounds, and the fixed head is re-reviewed; still failing is a trajectory anomaly and CI stays the gate. |
| `duplicate_exports` | boolean | No | Default `true`: at hand-off and after each base-sync merge, names the lane newly exports that another non-test module of the same app or package (nearest `package.json`/`pyproject.toml`/`setup.py`/`go.mod`/`Cargo.toml`) already declares go back to the builder once ("rename or reuse", both paths); one left over is an anomaly (forge#4406). Re-exports, default exports and names 3+ other modules declare (framework conventions) are ignored. `false` turns the check off. |
| `e2e` | string | No | e2e merge gate (forge#4403). `auto` (default): run e2e when the diff touches `e2e_paths` or a contract requirement quote has `[type:e2e]`. `always`: on every lane except docs-only ones. `never`: today's behaviour. Without `e2e_label` or `e2e_workflow` no e2e can run, so every mode keeps today's behaviour (a lane that changed specs records a decision saying so). |
| `e2e_label` | string | No | Label added to the PR (`gh pr edit --add-label`) so tiered CI runs its e2e jobs. The label must already exist in the repo. |
| `flaky` | list | No | Comma-separated string, flow list (`[a, b]`) or block list of CI job names (#4586). A failed CI job whose name equals an id is reported (never matched by log text: a log naming a flaky test can also hold a real failure) (anomaly, `CI_FLAKY_REPORTED`) and never blocks the lane or reaches the builder; the engine's CI verification and e2e gate honour it. A check that is required by branch protection still blocks the merge. Independently of this list, the failed jobs of a red CI verification or required check are rerun once per head before a fix round (`max_rounds`) is counted; only a failure that repeats counts. |
| `e2e_checks` | string | No | Comma-separated check-run names of the e2e jobs the label path waits on. Default: every check on the head except `forgedock/verify`. A check run concluded `skipped` (the unlabelled tier) counts as not run. |
| `e2e_workflow` | string | No | Workflow file name or id dispatched on the lane branch instead of the label (`workflow_dispatch`); the engine waits for its run of the reviewed head. Wins over `e2e_label`. |
| `e2e_paths_input` | string | No | `workflow_dispatch` input of `e2e_workflow` that receives the changed spec paths (newline-separated). |
| `e2e_paths` | string | No | Comma-separated globs of e2e specs (same glob rules as `skip_paths`). Default `e2e/**,**/e2e/**,*.e2e.*,*.e2e-spec.*,cypress/**,playwright/**`. |
| `e2e_blocking` | string | No | `changed` (default): only failures of the lane's own specs block the merge; other e2e failures are reported as an anomaly. `all`: every e2e failure blocks. |

**English-copy check (forge#4596).** At hand-off and after each base-sync merge, keys the lane added to a non-`en` JSON locale catalog (`messages/ta.json`, `locales/ta/common.json`) whose value equals the same key in the `en` counterpart go back to the builder once to translate (placeholders kept, status entries inserted in place, never re-sorted); a copy left over is an anomaly. Always on, deterministic, no cost without catalogs. The repo's own `i18n:check` is not run by the engine: list it in `lean.precheck.commands` to run it before the PR.

**Flow** (`ci`/`hybrid`, `bin/lean/verify.mjs` `runCiVerify`):

1. After the build and before every conformance review, the engine pushes the lane branch (a plain push, never forced) and runs CI on the head. A base-sync that moves the head is verified again.
2. Green (or skipped by `skip_paths`): the review runs. The precheck accepts validate ids left to CI for that head, but a recorded non-zero exit still fails.
3. Red: the failed jobs' logs (`gh run view --log-failed`, tails capped at about 12 KB) go back to the builder session. The builder fixes and commits, and the engine pushes and verifies again. Still red after `max_rounds` ends as `needs-human` (`ci.red`) and nothing merges. A fix round with no new commit (the builder's signal that the failure is not the change's) reruns the failed jobs once (`gh run rerun <id> --failed`) and verifies again: green continues to review, still red ends `ci.red`. Each rerun emits a `CI_FLAKE_RERUN` run-log event (`trigger`, `head`, `runs`, `jobs`, `result`).
4. Slow CI: once the core CI wait budget (360 min, the same budget the merge wait uses) is used up, the lane ends `ci-pending` and can be resumed. Slow CI is never `needs-human`.
5. CI unavailable (dispatch refused, or no run or check for the head within 5 minutes): one local fallback. The builder runs every validate command on the host and records real exit codes.

Each verification emits a `CI_VERIFY` run-log/telemetry event (`mode`, `round`, `result`, `skipped`, `run_url`) and adds a **Verify** row to the trajectory.

**Every mode, including the default `local` (forge#4240):**

- **Declared check commands before the PR.** Each `learned.test_commands` entry (a block list under `learned:`) runs with `bash -c` in the lane worktree after the build commit, before review and before the PR, with the per-command timeout above. These run on the host and use no Actions minutes. If they all pass, there is no extra builder turn. A failure resumes the builder in its session with the command, its exit code and the output tail, then the commands run again, up to `max_rounds`. A round with no new commit, or exhausted rounds, is recorded as an anomaly and the lane continues, because CI stays the gate. The engine has no built-in command list: to run `scripts/ci-local.sh`, list it here. Each round emits a `PRECHECK_COMMANDS` run-log event (`round`, `results: [{command, rc}]`).
- **The same checks in the builder's session (#4364).** The builder runs `forgedock check` in the lane worktree before it writes its result: the contract's validate commands plus the same change-scoped pre-PR commands, budget and worker cap, locally (no GitHub, no Actions minutes). The engine hands it the settings above in `.forge-lean/check-plan.json`; outside a lane, `forgedock check --base REF` reads this file's `learned.test_commands`, `lean.precheck.max_minutes` and `verify:`. A builder result of `fixed` without a passing run on its final tree logs a `SELF_CHECK_MISSING` run-log event (`state`: `skipped`, `stale` or `red`), and a failed pre-PR round's `PRECHECK_COMMANDS` event carries `self_check`. Neither fails the lane: the engine's own checks and CI stay authoritative.
- **Fix rounds at merge.** When a required check fails on the PR (`engine.merge_wait: required`), the failed jobs' logs (`gh run view --log-failed`, capped) go back to the builder session. The fixed head is re-reviewed and pushed, then the wait starts again. Still red after `max_rounds` (one budget shared with the `ci`/`hybrid` rounds above), or a round with no new commit, ends `needs-human` (`ci.red`). `max_rounds: 0` ends `ci.red` on the first failure. Each round emits a `CI_FIX_ROUND` run-log event (`trigger`, `round`, `jobs`). `merge_wait: all` is unchanged.

**e2e merge gate (forge#4403, every verify mode).** Tiered CI usually skips e2e on lane PRs, so required checks alone let a lane merge with its own e2e specs failing. When the gate runs (see `e2e` above), after the merge wait and before `gh pr merge`, once per reviewed head, the engine labels the PR with `e2e_label` and waits on the head's `e2e_checks` (or dispatches `e2e_workflow` and waits on its run), with the same CI wait budget.
- Green: the PR merges.
- Red: a failure is the lane's when its failed-job log names one of the spec files the lane changed (path or basename), when the log is empty, or when the lane changed no spec (a `[type:e2e]` contract). The lane's failures (all failures with `e2e_blocking: all`) go back to the builder like a failed required check: one fix round from the shared `max_rounds` budget, re-review, push, then the wait and the e2e run start again; `ci.red` when the rounds are spent. Other failures are recorded as an anomaly and the PR merges.
- Still pending at the budget: `ci-pending` (resumable). Label refused, dispatch refused, or no e2e run within 5 minutes: `needs-human`, nothing merged.

Each run emits an `E2E_VERIFY` run-log/telemetry event (`pr`, `head`, `reason`, `result`, `specs`, `failures`, `own`, `blocking`). It spends Actions minutes only after review, on lanes that touch e2e.

**Cost:** `ci`/`hybrid` spend GitHub Actions minutes before review, so they are opt-in per repo. On the green path they add no LLM calls; each red CI round adds one builder resume. The merge gate (`engine.merge_wait`) is unchanged.

**Commands that use this section**: core work-on (`forgedock run-issue`, `forgedock orchestrate`; `bin/engine-cli.mjs` `readVerify`)

## `ci` (OPTIONAL)

Scheduled full-suite integration runs on active milestone branches (forge#4667), report-only. Under the fast-lane/heavy-ship-gate model the whole e2e suite otherwise runs only at the ship PR. Write it as a block-style section; the parser flattens the keys of `milestone_integration:` under `ci`. Off unless `workflow` is set.

```yaml
ci:
  milestone_integration:
    workflow: e2e.yml            # workflow_dispatch workflow that runs the full suite
    # project: web-e2e           # optional project passed to the workflow
    # project_input: project     # its input name (default project)
    interval_hours: 24           # run when this old (default 24, nightly)
    every_merges: 10             # optional: also run after N lane merges into the milestone
    block_admission_after: 2     # optional: hold new lanes after N consecutive red runs, until green
    max_minutes: 360             # optional wait budget per run (default 360)
```

| Key | Type | Required | Description |
|---|---|---|---|
| `workflow` | string | Yes | Workflow file dispatched on `milestone/<slug>` (needs `on: workflow_dispatch`). |
| `project` / `project_input` | string | No | Value and input name passed to the workflow. |
| `interval_hours` | number | No | Hours between runs of a milestone. Default 24. |
| `every_merges` | integer | No | Also run once this many lane merges happened since the last run (checked by `forgedock orchestrate`). |
| `block_admission_after` | integer | No | After this many consecutive red runs, `forgedock orchestrate` admits no new lane of that milestone (ends `held`) until a run is green. |
| `max_minutes` | integer | No | Wait budget of one run. Default 360. |

State lives in a `FORGE:INTEGRATION` block in the milestone description. A red run files or updates one `integration-red` issue on the milestone (failing specs, merge range); the next green run closes it. `/deploy-info` shows open ones as a ship-gate risk and `/pipeline-status` shows each milestone's last green run. Schedule it with cron or a scheduled workflow: `forgedock integration run [--repo owner/repo] [--milestone TITLE] [--force]` (exit 1 when a run is red; `forgedock integration status` prints each last green run); `forgedock orchestrate` also runs it every `every_merges` merges.


### `ci.budget` CI budget gate (forge#5760)

The lane check (`bin/lean/ci-gate.mjs`, wired into the lean precheck) runs on every lane whose diff changes `.github/workflows/*.yml|yaml`; it needs no config. A lane that adds a workflow file, adds a job, or adds a step that runs a single test file must either fold it into `shared_regression_job` or carry a comment in the workflow YAML:

```yaml
# FORGE:CI_BUDGET trigger=pull_request:src/gpu/** minutes=120/month why=needs a GPU runner the shared job lacks
```

On a new workflow the comment can sit anywhere in the file; on a new job or step it goes inside the job or on the comment lines directly above its id. `trigger=`, `minutes=` and `why=` are all required.

```yaml
ci:
  budget:
    max_workflows: 15
    max_ci_jobs: 40
    monthly_minutes: 50000
    shared_regression_job: regression   # a job id, or a test dir (contains "/") one-file checks must live under
```

| Key | Type | Default | Description |
|---|---|---|---|
| `max_workflows` | number | unset (no cap) | Workflow files allowed; a lane over it fails unless it removes as many as it adds. |
| `max_ci_jobs` | number | unset (no cap) | Jobs across all workflows; same rule. |
| `monthly_minutes` | number | unset | Actions minutes per month, shown in the release-bundle `CI_NET:` line. The forge.yaml parser flattens `ci`, so this is the same key as `ci.monthly_minutes` (#5278). Keep the other `ci.budget` names unique within `ci`. |
| `shared_regression_job` | string | unset | Where new one-file checks belong; a step added to this job (or running a file under this dir) needs no annotation. |

Failure kinds (`conformance.unimplemented`): `ci_budget_unannotated`, `ci_budget_annotation_invalid`, `ci_budget_exceeded`, and `ci_hygiene`. `ci_hygiene` covers a new workflow or job with no `concurrency`, no job-level `timeout-minutes`, no `paths`/`paths-ignore` on `push`/`pull_request`, or no job-level `if:` on `issues`/`issue_comment`/`pull_request_review_comment`/`discussion_comment` events. The staging review prints the bundle's net change (`CI_NET: workflows ±N, jobs ±M, est. minutes/month ±K`). This block is separate from the `.forge/release.yaml` `ci.budget` (`on_exceed`) block.

## `execution` (OPTIONAL)

Where `forgedock orchestrate` runs its lanes (forge#4253). Block style only.

```yaml
execution:
  mode: remote          # local (default) | remote | hybrid
  max_remote: 4         # remote lanes running at once (default 0 = remote off)
  provider: container   # default container when mode is not local
  image: my/lane-image:1  # container provider: an image with git and forgedock; never pulled
  secrets: GH_TOKEN,ANTHROPIC_API_KEY  # env var NAMES forwarded to the sandbox; nothing else is
  # provider: pool (forge#4546): remote with endpoint and token defaulted to the local router (below); no keys needed
  # provider: remote (forge#4254), only when named explicitly:
  # endpoint: https://runner-pool.example/v1  # sandbox HTTP API (protocol below)
  # token_env: FORGEDOCK_SANDBOX_TOKEN        # credential NAME: read from the env, else the OS keychain
  # cache_store: s3://lane-cache               # shared cache store the sandbox mounts
  # allow_actions: false                       # true only to accept a GitHub Actions endpoint
  # execution budget (forge#4255): flat keys, forge.yaml is parsed one level deep
  budget_minutes: 600      # hard cap on sandbox-minutes per batch
  budget_usd: 25           # hard cap on estimated sandbox USD per batch
  day_budget_minutes: 2000 # hard cap on sandbox-minutes per host UTC day (all batches, schedd or not)
  day_budget_usd: 80       # hard cap on estimated sandbox USD per host UTC day
  # heavy: true          # hybrid placement only: true = lanes go remote, false = ignore detected weight; adds no commands, no admission change
  on_budget: stop          # stop (default) | local: what the queue does once a cap is reached
  cost_per_minute: 0.04    # USD per sandbox-minute when the provider reports no cost (default 0)
```

| Key | Type | Required | Description |
|-----|------|----------|-------------|
| `mode` | string | No | `local` (default): lanes are detached host processes, as before. `remote`: lanes run in sandboxes of `provider`. `hybrid`: each lane is placed from facts (forge#4256, below). |
| `max_remote` | integer | No | Remote lanes of the batch that may run at once. They take no slot of the host lane cap (`orchestration.global_parallel`, `forgedock sched cap`); the batch `--parallel` still applies. `0` (default) keeps lanes local. The pool router's per-agent lane ceiling (`forgedock pool limit <agent> --lanes N`) caps lane sandboxes on a host across all batches and defers the rest. |
| `heavy` | boolean | No | Hybrid placement override (forge#4523). `true`: every lane that passes rules 1-3 is placed remote. `false`: the detected validation weight is ignored (rule 5 still applies). Unset: detect. It changes placement only: no pre-PR commands run, and host admission (`max_load_per_core`) is unchanged. |
| `provider` | string | No | `container` (reference: an ephemeral local container), `remote` (a runner pool or remote session over HTTP, forge#4254), `pool` (the built-in pool router on this host, forge#4546: `remote` with `endpoint` and `token_env` defaulted from the router config, `COMPUTESHARE_CONFIG` or `~/.config/computeshare/router.json`, and its `forgedock.token`; the repo's `forge.yaml` is sent to every sandbox, so no router `repos` map is needed; missing router config and no `endpoint` fails with `execution.provider.misconfigured`) or `local`. The default is `container` off `local` mode; `remote` and `pool` are used only when named. Unknown names fail the batch start. |
| `image` | string | No | Container provider image; it must provide `git` and `forgedock`. Started with `--pull never`. |
| `secrets` | string | No | Comma-separated env var names copied from the dispatcher's env into the sandbox. The sandbox also gets `GH_REPO` (the target repo) and `FORGEDOCK_BATCH_ID`, and nothing else from the host. |
| `endpoint` | string | `remote` | Base URL of the sandbox API (`pool`: defaults to the local router). A GitHub Actions API (`api.github.com`, or any `/actions/` path) is refused unless `allow_actions: true`, so pre-review Actions minutes are never spent implicitly. Missing: the batch start fails (`execution.provider.misconfigured`). |
| `token_env` | string | No | Name of the API credential, sent as `Authorization: Bearer`. Read from the env, else the OS keychain (service `forgedock`, account = the name: `secret-tool store --label forgedock service forgedock account NAME` on Linux, `security add-generic-password -s forgedock -a NAME -w` on macOS). Never written to the ledger, the batch state, logs or GitHub. |
| `cache_store` | string | No | Shared cache store the remote sandbox mounts (sent as `cache.store` with `cache.key` = the repo). |
| `allow_actions` | boolean | No | `true` accepts a GitHub Actions endpoint. Default `false`. |
| `public_default` | string | No | `actions`: a **public** repo with no `mode` runs lanes on GitHub-hosted runners (`provider: actions`, forge#5748). Off by default (forge#5900): without it nothing changes on upgrade. Needs owner setup first: `.github/workflows/forgedock-lane.yml`, the `forgedock-lane` environment with its `CLAUDE_CODE_OAUTH_TOKEN` secret, and server-side protection on the default and base lane branches (the lane refuses to run without it, forge#5899). |
| `budget_minutes`, `budget_usd` | number | No | The `execution.budget` per batch: once the batch's sandbox minutes / estimated USD (settled lanes plus the running ones' elapsed time) reach the cap, no new remote lane is admitted. Missing, non-numeric or negative means no cap. |
| `day_budget_minutes`, `day_budget_usd` | number | No | The same cap per host UTC day, summed over every batch on the host from the host-day store (`execution-budget.json` in `~/.forge/sched/`, or `FORGEDOCK_EXECUTION_BUDGET_FILE`). A corrupt or unreadable store refuses remote lanes while a day cap is set; remove the file to reset it. |
| `fallback_local` | boolean | No | `true`: a remote-placed lane runs on the host while the provider reports no agent online (`GET {endpoint}/status -> {"online": N}`, the built-in router answers it with `online`, `total` and per-agent `ok`/`paused`), so a batch completes locally with every pool agent offline or asleep (forge#4547). Default `false`: such lanes defer (`sandbox.capacity`). A missing or failing `/status` is unknown and never triggers it. It also covers a sustained `sandbox.capacity`: an issue the pool refused `capacity_fallback_after` times (default 3) for capacity runs on the host when the host has headroom (the host-busy guard; a busy host or a failing probe keeps it waiting remote) (forge#5112). |
| `capacity_fallback_after` | integer | No | With `fallback_local: true`: how many `sandbox.capacity` deferrals of one issue make it run on the host, subject to the host-busy guard (forge#5112). Default: 3. A missing, non-integer or non-positive value uses the default. |
| `account_rotator` | string | No | `tokenbaton`: the `claude` on PATH is the tokenbaton shim, which runs each call on the logged-in account with the most room (`CLAUDE_CONFIG_DIR=~/.claude-<n>`) (forge#5094). Unset: detected (forge#5205) when `TOKENBATON_HOME` is set or the first `claude` on PATH resolves to `tokenbaton-exec` / a `.tokenbaton/shim/claude`; `off` (also `none`, `false`) or env `FORGEDOCK_ACCOUNT_ROTATOR=off` disables it. forgedock reads `$TOKENBATON_HOME` (as-is, else `~/.tokenbaton`): `current` (the account number) and `live.<n>` (`<5h used %> <5h reset s> <weekly used %> <weekly reset s> <updated s>`), re-read on every check and never written. An account has headroom when its 5-hour use is under 95% and its weekly use under 100%; a sample whose reset has passed is stale: unknown, never 0%, worth one try but ranked after fresh samples. While any account has headroom no host-wide usage hold is recorded and admissions continue. A lane whose call hits a usage limit records that account (from the run's `/proc/<pid>/environ`), excludes it until its reset, and relaunches the same call (same session) at once pinned to the account tokenbaton picks (the real `claude` past the shim, `CLAUDE_CONFIG_DIR=~/.claude-<n>`), at most once per account; the lane result reports `rotations` and `limited`, and the batch keeps excluding those accounts until their reset. Only when no account has room does the lane pause or defer, and the batch holds until tokenbaton's earliest reset over every account. When the installed tokenbaton has the tokenbaton#3 API, forgedock uses `tokenbaton --pick --json --exclude <n,..>` (exit 2 = none with room, `earliest_reset`) and `tokenbaton-ctl mark-limited <n> --until <s>`; otherwise it computes the same from `live.<n>`. `forgedock limits show` lists each account's 5-hour use, `(stale)` for a passed reset. Any other value, or unreadable files: off (per-account holds as before). |
| `warm_sandboxes` | integer | No | Warm sandboxes per repo the pool agent keeps ready (checkout at the base ref, dependency cache primed). When `N > 0` the launch spec carries `warm: N` and the lane first calls `POST {endpoint}/sandboxes/claim`; a ready warm sandbox takes the lane (refreshed to the lane's base ref with an incremental fetch before work starts), and when none is ready, the claim fails or the endpoint lacks the route the lane starts cold. Default `0` (off): no claim call and the launch spec is unchanged (forge#4912). |
| `unreachable_window_min` | number | No | Remote providers: how long a lane keeps polling (with backoff, up to 30s) after the provider's transport fails (connection refused/reset, `fetch failed`, timeout, 502/503/504) before it ends `deferred` with `sandbox.unreachable` (forge#4672). Inside the window the lane never ends and the sandbox is never torn down; after it the sandbox is kept and adopted on the next attempt or `--resume`; the engine-error breaker does not count it. `adopt` applies the same window. Default: 5 |
| `on_budget` | string | No | `stop` (default): running lanes finish and the rest end `held` (`execution budget: ...`) for a later `--resume`. `local`: the rest run as detached host lanes. |
| `min_lane_engine` | string | No | Lowest lane-engine version (e.g. `1.67`) a pool agent may run this batch's lanes on (forge#6091). Placement always prefers agents on the orchestrator's engine version; unset (default), a lower-version agent is still used as a fallback when it is the only one free. Set, agents below it are skipped and, when none qualifies, the launch is deferred (`pool.engine_old`) until an agent upgrades. |
| `host_capabilities` | list | No | Host-only capabilities the dispatching host has and a sandbox does not relay (forge#4542): names such as `sops`, `prod_monitor`, `ops_credentials`. A lane whose issue text names one (built-in signals: `.secrets/*.enc.yaml`, `sops`, `ssh *-monitor`, `obs-psql`, `credentials.yaml`; a declared name written out; `host_capability_patterns`) is placed `local` in `remote` and `hybrid` mode with the reason `host capability: <name>`, unless the provider relays it (`relay_commands`, forge#4778; otherwise remote providers relay none). A remote lane that still blocks as `credentials` naming only a declared capability ends `env.capability_remote` (recoverable) and is rerun locally once. |
| `host_capability_patterns` | list | No | `name:regex` entries (case-insensitive) that also mean the lane needs capability `name`, e.g. `vault:vault\s+kv`. An invalid entry is ignored. |
| `relay_commands` | list | No | Read-only capability relay (forge#4778): `capability:command` entries, e.g. `prod_monitor:obs-psql` or `prod_monitor:obs-*` (exact name, or a prefix glob with one trailing `*`; no `/`, whitespace or other glob characters). A `remote`/`pool` lane needing a listed capability is placed remote: the sandbox runs the command unchanged (a `cs-relay` shim), the request goes sandbox -> pool agent -> router queue, and the dispatching host picks it up on its status poll, gates it against this list and runs it with no shell, a 120 s timeout and a 1 MB output cap, redacting known secrets; a refused command gets rc 126 and the key never leaves the host. List only read-only wrappers, never `sops` or `ops_credentials`. The frozen contract's simple validate / repro_test commands that pass the gate are pre-fetched at dispatch and shipped with the lane (96 KB cap). An older router or agent without the relay makes `cs-relay` exit 125, the lane blocks as `credentials` and is recovered locally once, as before. |
| `cost_per_minute` | number | No | USD per sandbox-minute, used when the provider reports no cost of its own (the `container` provider never does). Default `0`. |

**Lifecycle:** each sandbox is listed in the lane ledger (`~/.forge/ledger/<batch>/sandbox-<n>.json`, kind `sandbox`) before it starts and removed from it only after teardown succeeded: on success, failure, a lane that exits without a result, and adopt after `--resume`. A sandbox left by a killed dispatcher is reaped by `forgedock gc --apply` (scope `--sandboxes`). The container provider mounts the checkout's git dir read-only at `/src` (cloned to the container's own `/work`), `~/.forge/verify-cache` read-only at `/cache`, and the batch `lanes/` dir at `/result`.

**Pool agent image hygiene** (forge#5758, keys in the pool agent config, not `forge.yaml`): after a self-update or start builds the lane image, the agent removes superseded `forgedock-lane:<version>` images and their per-repo `-t<hash>` tools variants. `keep_lane_images` (default `2`) is the number of newest versions kept, always including the running one; a tag any container (running or exited-but-kept) uses is never removed, and images outside the `forgedock-lane:` prefix (`image` overrides) are never touched. Every `build_cache_interval_s` seconds (default `21600`, 6 h) `reap()` also runs `docker builder prune --keep-storage <build_cache_keep_gb>gb` (`build_cache_keep_gb`, default `20`) and removes dangling anonymous volumes (64-hex names no container references; named `cs-work-`/`cs-cache-` volumes are not touched). Failures are logged and never fail an update or a reap.

**Remote provider** (`bin/lean/sandbox-remote.mjs`, forge#4254). The sandbox is addressed by the id ForgeDock picks (`fdrsbx-<batch>-<issue>`), JSON over HTTP:

| Request | Response |
|---------|----------|
| `POST /sandboxes` | Launch spec `{id, issue, batch, image, repo: {slug, url, ref}, cache: {store, key} \| null, env, command, result_file}`. The sandbox clones `repo.url` at `repo.ref`, mounts the cache, runs `command` (`forgedock run-issue ...`) with exactly `env` (the `secrets` names, resolved from the env or keychain, plus `GH_REPO` and `FORGEDOCK_BATCH_ID`). `429`/`503` = no capacity (`Retry-After` honoured). |
| `GET /sandboxes/:id` | `{state}`: `pending`/`starting`/`running`, `exited`, or `404` = gone |
| `GET /sandboxes/:id/logs?cursor=N` | `{text, cursor}`: lane log since `cursor`; appended to the batch lane log with secret values redacted |
| `GET /sandboxes/:id/result` | The lane's result file (`404` until written) |
| `GET /sandboxes/:id/usage` | `{minutes}`: billable sandbox minutes, set on the handle and the lane result (`sandbox.minutes`); without it, wall-clock minutes |
| `DELETE /sandboxes/:id` | Teardown; `404` counts as torn down |

**Start failures** (every provider): a sandbox that cannot start ends the lane `needs-human` with code `sandbox.start_failed`, not relaunched and not counted by the engine-error breaker; a capacity error ends it `deferred` (`sandbox.capacity`), requeued after the provider's retry-in (else 60s) and not counted toward `orchestration.max_deferrals`, so a queue deeper than the pool waits instead of being skipped (forge#4528). A pool that serves `GET {endpoint}/status -> {"free": N}` (integer, optional) also caps remote admissions to N per sample, so the extra lanes queue inside the batch instead of bouncing on a 503 (forge#4540); a missing, failing or malformed `/status` is unknown and never blocks admission. See docs/OUTCOME-CODES.md. `forgedock gc --apply --sandboxes` tears a stale remote sandbox down through the same API (the checkout's forge.yaml `execution`).

**Cold start** (forge#4909): the dependency cache (`FORGE_DEPCACHE_ROOT`, default `~/.forge/depcache`, keyed by lockfile hash) is hardlinked into lane worktrees; when it sits on another filesystem than the worktree (EXDEV) files are copied instead, so a second lane with the same lockfile hash still records `deps: hit` rather than reinstalling. A lane refused for capacity (`sandbox.capacity`) on a pool that serves `/status -> {"free": N}` is relaunched only once a slot is free, not on the retry-in timer; the wait is recorded as the lane's queue time (`waits.queue`).

**Warm start** (forge#4912): with `warm_sandboxes: N > 0` the lane asks `POST {endpoint}/sandboxes/claim` (same body as the launch spec; `200`/`201` = claimed, `204`/`404`/`405` = none ready) before a cold `POST /sandboxes`. The built-in router forwards the claim to a pool agent holding a ready warm sandbox of the same repo and size; the agent (`GET /warm` lists them, `POST /warm` sets a repo's size, `POST /warm/claim`) starts `N` sandboxes per repo from the `warm` of the launch specs it sees, hands the lane over through a mode-0600 claim file, and refills the pool. The claimed sandbox runs `git fetch` for the lane's ref and resets to it, so installed dependencies stay. Warm sandboxes count against the agent's reservation, are renewed by the agent itself and replaced at the agent's max lifetime. Capped at 8 per repo.

**Hybrid placement** (`mode: hybrid`, forge#4256, `bin/lean/execution.mjs` `placeLane`, no model call). Each lane is placed when it is admitted. The first matching rule wins:

1. `max_remote: 0` → local.
2. `verify.mode: ci` → local. Heavy validation already runs, and is billed, on CI, so the lane is not billed twice.
3. A docs-only lane (issue label `docs`, `documentation` or `type:docs`) → local.
4. Heavy expected validation → remote (`execution.heavy: true` forces this, `false` ignores the detected weight). This means a declared check command (`learned.test_commands`) is a type check, linter, test runner or build, or the repo has a heavy toolchain marker, at the root or one or two directory levels down (`web/tsconfig.json`, `services/x/pyproject.toml`; `node_modules`, `vendor`, `dist`, `build`, `target` and dot-directories are skipped): `tsconfig.json`, an eslint config, a package.json `test`/`lint`/`typecheck`/`build` script (also in those subdirectories), `Cargo.toml`, `go.mod`, `pyproject.toml`/`setup.cfg`/`pytest.ini`, `pom.xml` or `build.gradle`.
5. A host without headroom → remote. "Without headroom" means MemAvailable is below `engine.min_free_mem_mb` + `engine.heavy_step_mem_mb`, or the load per core is above `engine.max_load_per_core` when that is set.
6. Otherwise → local.

A lane placed remote runs on the host instead when `max_remote` remote lanes are already running, or when the execution budget refuses it. In hybrid mode this happens whatever `on_budget` says. The decision `{where, reason}` (for example `fallback to local: max_remote 4 reached (heavy validation: tsc)`) is recorded:

- in the batch row (`placement`);
- in the trajectory (`Placement: ...`);
- in the lane's FORGE:STATE as `placement: {where, reason, mode}`. The lane gets it as `run-issue --placement <local|remote> --placement-reason <text>`.

**Cost and budget:** every remote lane's sandbox minutes and estimated cost (the provider's own usage report, e.g. the remote provider's `/usage` minutes, else wall-clock minutes × `cost_per_minute`) land in its row (`sandbox: {minutes, cost_usd, attempts}`, summed over relaunches), in `report.json`, in the printed table (`sbx-min`, `sbx-$` next to the token `cost`, shown only when a lane used a sandbox), in a `sandbox:` summary line with the budget state, and in FORGE:TELEMETRY as one `sandbox_usage` event per lane. The caps are plain arithmetic, no model call. The batch total is kept in the batch `state.json` and the day total in the host-day store, so both survive `--resume` and a schedd restart.

**Commands that use this section**: `forgedock orchestrate` (`bin/engine-cli.mjs` `readExecution`), `forgedock gc`

## `env` (OPTIONAL)

Lane environment for the core work-on (#4163). With no keys set, lanes still pin the target repo's own toolchain:

- **Package manager**: `package.json` `packageManager` (`pnpm|yarn|npm@x.y.z`, a `+sha…` suffix is ignored), else a `pnpm`/`yarn` line in `.tool-versions`. After the worktree is added the engine writes shims for it (`pnpm`+`pnpx`, `yarn`, or `npm`+`npx`) to `<run tmp>/toolchain/bin`. Each shim runs `corepack <pm>@<version>` (npm always via `npx -y`), or `npx -y` when corepack is not on PATH (yarn ≥ 2 via `@yarnpkg/cli-dist`). The shim dir goes first on the PATH of every runner call (builder and reviewer), so the builder's shell, its validate commands and git hooks (lefthook, husky) resolve the pinned version. `COREPACK_ENABLE_DOWNLOAD_PROMPT=0` and `COREPACK_ENABLE_STRICT=0` are set. The builder prompt says the toolchain is pinned and not to install global shims.
- **Node**: `.nvmrc`, else `.node-version`, else `.tool-versions` `nodejs`, else `package.json` `engines.node`. When the host `node` does not satisfy it, the run's trajectory shows a warning under **Anomalies**. Node is not switched.

A repo with no pins and no `env` keys runs exactly as before: no shim dir, no env change, no prompt change.

```yaml
env:
  toolchain: "pnpm@10.4.1"              # optional: overrides the detected package manager; "off" disables detection
  setup: "bash scripts/reconcile-dev-db.sh"   # optional: run once per fresh lane worktree, before the builder
  sparse_max_kb: 1024                   # optional: tracked files this size or larger stay out of lane worktrees; 0 = full checkout
  snapshots:                            # optional: environment library (#5714), off unless enabled
    enabled: false
    store: local                        # local | oci
    keep: 3
    max_age_days: 14
    ready: 2
    base_image: ghcr.io/acme/ci-base:1  # oci store: the image installs run in
    image: ghcr.io/acme/shop-env        # oci store: repository snapshots are pushed to (tag = key)
  proxies:                              # optional: caching proxies lanes use (pool/services); each key independent
    npm: http://proxy-host:4873
    pypi: http://proxy-host:3141/index
    apt: http://proxy-host:3142
    git: git://proxy-host:9418
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `toolchain` | string | No | `<pnpm\|yarn\|npm>@<x.y.z>` replaces the detected package-manager pin; `off` disables all toolchain detection. An invalid value is ignored and recorded as an anomaly. |
| `setup` | string | No | Shell command (`bash -c`) run once in each fresh lane worktree before the builder starts, with the lane's PATH and `TMPDIR`. Use it for environment drift the repo's migrations don't cover, for example a dev-database reconcile script. Timeout 15 min. A non-zero exit ends the lane `needs-human` with code `env.setup_failed`: an environment error, not a build failure. The builder never runs. |
| `sparse_max_kb` | integer | No | Default `1024`. Lane worktrees are sparse checkouts: tracked files of this many KB or more (generated JSON, screenshots, PDFs, media) are not written to disk, which cuts per-lane disk in repos that track large assets (#4221). Lockfiles, manifests (`package.json`, `pyproject.toml`, `requirements*.txt`, ...), toolchain pins, `tsconfig*.json`, `forge.yaml`, `.gitattributes` and `.gitignore` are always checked out. A repo with no such file gets a plain checkout. The builder prompt names the absent files; `git sparse-checkout add /<path>` brings one back. `0` disables it. Git sets `extensions.worktreeConfig=true` in the repo's shared config; the sparse setting itself is per lane worktree, so the main checkout is unchanged. If the sparse setup fails, the lane uses a full checkout. |

| `snapshots.enabled` | boolean | No | Default `false`. Environment library (#5714, [ENV-LIBRARY.md](ENV-LIBRARY.md)): dependency trees are installed once per environment key (lockfiles + manifests + toolchain pin files + `execution.lane_tools` + image) outside any job and reused. With a pool provider, each launch asks the pool agent to keep the repo's snapshot built and staged in the cache volume; a lane whose lockfiles match claims a staged copy by directory rename (`Dependencies (...): hit (env snapshot (rename))`), and any other lane installs as before. Absent or `false`: no launch field, no lane env, no helper container. |
| `snapshots.store` | `local` \| `oci` | No | Default `local` (directory store: the pool cache volume, or `FORGE_ENV_ROOT`, default `~/.forge/env`). `oci`: `forgedock env build` writes a `Dockerfile.env` for `<image>:<key>`, used as a CI job container and a deploy base layer. |
| `snapshots.keep` | integer | No | Default `3`. Snapshots kept per repo, newest by last use. |
| `snapshots.max_age_days` | integer | No | Default `14`. Snapshots unused this long are removed; a repo's newest always stays. |
| `snapshots.ready` | integer | No | Default `2`. Staged hardlink copies the pool keeps ready per snapshot; one is consumed per claiming lane. `0`: lanes hardlink from the snapshot instead. |
| `snapshots.base_image` | string | `oci` only | The image the frozen installs run in (your CI base image with the toolchain installed). Part of the key. |
| `snapshots.image` | string | `oci` only | Image repository without a tag; snapshots are `<image>:<key>`. |
| `proxies.npm` / `pypi` / `apt` / `git` | URL | No | `http(s)://` or `git://` URLs of the opt-in caching services in `pool/services/docker-compose.yml`. Pool lanes get the matching package-manager variables (`npm_config_registry`, `PIP_INDEX_URL`, `UV_DEFAULT_INDEX`, `FORGE_APT_PROXY`, ...; full table in [ENV-LIBRARY.md](ENV-LIBRARY.md)). Absent keys change nothing. A value that is not such a URL is ignored. |

**Commands that use this section**: `forgedock run-issue`, `forgedock orchestrate` (core path; `bin/engine-cli.mjs` `readEnvConfig`); `forgedock env key|build|status|gc|stage` and pool launches read `snapshots` and `proxies` (`bin/env/env.mjs` `readEnvSnapshots`)

---

## `build` (OPTIONAL)

Tuning for the `/work-on` build phase. Today it holds the **scope check** (forge#3862, replacing the diff-size gate): after the implement phase stages its changes and before validation commits them, the build compares the staged diff with the architect plan (the `PLANNED_FILES:` list and `ESTIMATED_DIFF_LINES` in the plan's `### Scope Baseline`), measures a deterministic `review_weight` with `scripts/diff-size.sh`, and records the outcome in `FORGE:DIFF_SIZE`. **Size never blocks, a finished build is never discarded, and a completed build is never routed to decompose.**

```yaml
build:
  scope:
    test_weight: 50          # percent weight of test lines in review_weight (default 50)
    module_depth: 2          # path segments that define a module (default 2)
    overrun_pct: 200         # whitespace-insensitive lines over the plan estimate, in percent, that count as scope creep (default 200)
    trim_out_of_plan: false  # move out-of-plan hunks into the batched follow-up checklist (default false: flag only)
    trim_max_files: 3        # trim only when at most this many files are out of plan (default 3)
    # Extra exclusion globs, ADDITIVE to the built-in defaults below.
    exclude_globs:
      - "docs/api/*"
      - "*.pb.go"

review:
  depth:
    extended_weight: 1500    # review_weight at or above which review is EXTENDED (default 1500)
    extended_modules: 6      # modules touched at or above which review is EXTENDED (default 6)
    slice_files: 12          # changed files per slice in extended review (default 12)
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `build.scope.test_weight` | integer | No | Percent of a test file's changed lines counted in `review_weight` (tests are easier to review). Default: 50 |
| `build.scope.module_depth` | integer | No | Leading path segments of a file's directory that identify a module for the `modules` count. Default: 2 |
| `build.scope.overrun_pct` | integer | No | The scope is flagged when whitespace-insensitive changed lines exceed the plan's estimate by more than this percent (200 = more than twice the estimate). Default: 200 |
| `build.scope.trim_out_of_plan` | boolean | No | Opt-in. Moves each out-of-plan file's hunks out of the PR into the batched follow-up issue (forge#3843); the hunks are saved in a patch file next to the git dir, so nothing is lost. Never triggered by an overrun alone. Default: `false` (flag only) |
| `build.scope.trim_max_files` | integer | No | Trim only when at most this many files are out of plan; more is flagged, not trimmed. Default: 3 |
| `build.scope.exclude_globs` | list of strings | No | Globs excluded from the measurement, in addition to the built-in defaults. Default: `[]` |
| `review.depth.extended_weight` | integer | No | `review_weight` at or above which the build records `review_depth: EXTENDED`. Default: 1500 |
| `review.depth.extended_modules` | integer | No | Modules touched at or above which the build records `review_depth: EXTENDED`. Default: 6 |
| `review.depth.slice_files` | integer | No | In extended review, each domain agent reviews slices of at most this many changed files. Default: 12 |

All thresholds are config values with generous defaults, to be calibrated from telemetry (`diff_size` events carry the plan estimate, the actual, `review_weight`, the scope outcome and the review depth; see `docs/TELEMETRY.md`).

**`review_weight`** (computed by `scripts/diff-size.sh`): changed lines with whitespace ignored (`git diff -w`, so a pure re-indent counts about 0), over the counted files only (generated and vendored code excluded), where test files count `test_weight` percent. `modules` counts the distinct directories (first `module_depth` segments) holding at least one non-whitespace change. It drives review depth, never blocking.

**Built-in default exclusions** (always applied, defined once in `scripts/diff-size.sh`): lockfiles (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `Cargo.lock`, `poetry.lock`, `uv.lock`, `go.sum`, `Gemfile.lock`, `composer.lock`), `*.min.*`, `*.snap`, and the directories `dist/`, `build/`, `generated/`, `fixtures/`, `vendor/` (anchored to the repo root, so first-party directories such as `commands/work-on/build/` are counted) plus `__generated__/` and `__snapshots__/` (any depth). The diff is measured against the merge base of `HEAD` and `origin/<base>`, so commits that landed on the base after the branch point are not counted. A configured glob ending in `/` matches that directory at any depth; any other glob is matched against the file basename and the full path. Globs are treated as data, never evaluated.

**Scope-check outcomes** (`result:` in `FORGE:DIFF_SIZE`): `OK` (in plan, standard depth); `EXTENDED_REVIEW` (in plan, `review_weight` or `modules` at the extended threshold: review adds reviewers and per-file slices); `SCOPE_FLAGGED` (files outside the plan, or an estimate overrun: listed in the comment for review, review extended, optionally trimmed); `OVERRIDDEN` (scope flagged but a justified `FORGE:SIZE_OVERRIDE` is present). An architect skip marker (empty plan) means no plan baseline: the out-of-plan check is skipped, never blocking. A `FORGE:SIZE_OVERRIDE` comment (trusted author, non-empty justification on the line after the marker) suppresses the scope flag and the decompose loop guard. The measured `diff_lines` is still recorded in the `FORGE:TRAJECTORY` comment.

**Decomposition is a planning decision**: `work-on:investigate` answers `**YES**` only when the work is separable (independent modules or services, no shared files, no ordering dependency, each piece independently testable), with the reason recorded; a cohesive change stays one unit at any size. It emits `ESTIMATED_DIFF_LINES` (the scope baseline) and `INDEPENDENT_SEAMS` inside `### Decomposition Assessment`. The engine downgrades a `**YES**` to NO unless `INDEPENDENT_SEAMS` is at least 2 with an own-line `DECOMPOSE_JUSTIFICATION:`; it has no line-count rule. A sub-issue, an issue with a trusted `FORGE:DECOMPOSED` comment, or one with a justified `FORGE:SIZE_OVERRIDE` is never decomposed (decompose Guard 1).

**Migration from `build.diff_size.*`** (deprecated; read as aliases for one release, then removed):

| Old key | New behaviour |
|---------|---------------|
| `build.diff_size.threshold` | No longer a gate. A positive value is read as `review.depth.extended_weight` (extended review instead of a block or split); `0` (gate disabled) now just means the defaults. The build records `deprecated_config` in `FORGE:DIFF_SIZE` when an alias supplied a value |
| `build.diff_size.exclude_globs` | Read as an alias of `build.scope.exclude_globs` (additive) |
| `build.diff_size.estimate_factor`, `build.diff_size.batch_seam_min` | Ignored. The investigator's decomposition rule is separability, not a line count |

`BUILD_RESULT: status: NEEDS_DECOMPOSE`, the `forge/wip/{NUMBER}` ref, the cohesive-overage path and the outcome code `build.size_over_gate` are retired. An old run whose build was handed to decompose can be resumed at build with `run-issue --retry` once a trusted `FORGE:DECOMPOSED:REVOKED` comment (newer than the `FORGE:DECOMPOSED` comment) and a justified `FORGE:SIZE_OVERRIDE` are on the issue; untrusted comments never reopen a run.

**Commands that use this section**: `work-on` (build phase B5.5, `close`), `review-pr` (Phase 3 review depth)

---

## `decomposition` (OPTIONAL)

Controls what happens to a decomposed parent issue. A parent is only a tracker for its sub-issues, but while it is open it inflates GitHub's open-issue count and every backlog view.

```yaml
decomposition:
  # Close the parent at decomposition. Default: false (parent stays open until its last child closes).
  close_parent: true
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `close_parent` | boolean | No | When `true`, `work-on:decompose` (Phase D6.5) closes the parent after the sub-issues exist, `FORGE:DECOMPOSED:COMPLETE` is posted and `workflow:decomposed` is set, with the comment "Decomposed into #a #b #c; tracked here until all complete". The label is kept. Every child body is also checked for the `**Parent**: #N` reference. Default: `false`. Any value other than `true`, or an unreadable config, leaves the parent open |

**Batch members**: when the parent carries a `FORGE:BATCH_MEMBERS` block, `work-on:decompose` (Phase D2.7) reopens and reuses a closed member that matches a planned sub-issue one to one, instead of filing a duplicate. Members with a merged PR or a `false-positive`, `needs-human` or `operator-only` label are never reopened, and any ambiguity falls back to creating a new issue. There is no config key for this.

**With `close_parent: true`**: `work-on:close` Phase C3 keeps checking children off the closed parent's checklist. When the last child closes, the parent gets an "All sub-issues complete" comment and `workflow:merged`; it is not closed a second time and never reopened. `/pipeline-status` and `/pipeline-health` exclude `workflow:decomposed` from work counts and report them separately as `trackers (N)`. `/orchestrate` expands an explicitly requested closed decomposed parent to its open children.

**With `close_parent: false`** (default): unchanged. The parent stays open and is closed by C3 when the last child closes.

The lean (core) path reads the same key (#4337): with `close_parent: true` it closes the parent at decomposition as `completed` (#5152; scope moved to the sub-issues, not dropped), keeps `workflow:decomposed` and lists the sub-issues in the closing comment; dependents still wait on the sub-issues, and a trusted `FORGE:DECOMPOSED:REVOKED` reopens it. With the default `false` the lean parent stays open.

**Limitation**: `--retry` and engine resume refuse closed issues, so a closed decomposed parent cannot be re-run. It has nothing left to run; work on its open children instead.

**Commands that use this section**: `work-on` (`decompose` D6.5, `close` C3), `orchestrate`

---

## `services` (OPTIONAL)

External service endpoints and identifiers. Used by analytics and monitoring commands.

```yaml
services:
  domain: "acme.io"
  gsc_property: "https://acme.io"

  analytics:
    umami:
      url: "https://umami.acme.io"
      website_id: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    clarity:
      project_id: "xxxxxxxxxx"
    history_file: "/home/youruser/analytics-history.yaml"
    ga4:
      property_id: "000000000"
      service_account_key: "/home/youruser/credentials/ga4-service-account.json"

  app_url: "https://acme.io"
  api_url: "https://api.acme.io"

  # server_ssh: "ubuntu@203.0.113.42"
  # ememo_path: "/home/ubuntu/ememo"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `domain` | string | No | Primary public domain. Used in GEO and SEO checks |
| `gsc_property` | string | No | Google Search Console property URL or `domain:` prefix |
| `analytics.umami.url` | string | No | Base URL for Umami self-hosted analytics instance |
| `analytics.umami.website_id` | string | No | Umami website UUID for metric queries |
| `analytics.clarity.project_id` | string | No | Microsoft Clarity project identifier |
| `analytics.history_file` | string (absolute path) | No | Path to the persistent audit history YAML file. Written after each `/analytics` run; provides trend baselines. Do not commit. |
| `analytics.ga4.property_id` | string | No | Numeric Google Analytics 4 property ID (from GA4 Admin → Property Details) |
| `analytics.ga4.service_account_key` | string (absolute path) | No | Path to a GA4 service account JSON key file. Grant the account Viewer access in GA4. Do not commit. |
| `app_url` | string | No | Frontend app URL used by `qa-sweep` for page accessibility testing. Default: `http://localhost:3000` |
| `api_url` | string | No | Base URL for the project's API. Used in health checks |
| `server_ssh` | string | No | SSH target for production server health checks. Format: `user@host` (e.g., `ubuntu@203.0.113.42`). Used by `/autopilot` Phase 1 to run server-level checks over SSH. |
| `ememo_path` | string | No | Absolute path on the production server to open eMemo files. Used by `/autopilot` to surface in-progress work notes. Only relevant if your team uses eMemo. |

**Commands that use this section**: `analytics`, `geo-audit`, `autopilot` (analytics snapshot, SSH health check)

---

## `design` (OPTIONAL)

UI lanes and the visual gate (forge#5330, forge#5369). Everything is opt-in: a repo with no `design.routes` is never routed or gated and behaves as before. `design.system` is read independently by every UI lane.

| Key | Meaning | Default |
| --- | --- | --- |
| `system` | design-system docs, token files or component dirs (list or comma-separated). A UI lane reads them first, reuses their components, tokens, spacing and type, and gives a new surface its empty, loading and error states | `[]` |
| `routes` | globs of user-visible route files, e.g. `web/src/app/(site)/**/page.tsx`. **Setting it turns the design gate on** | unset = off |
| `exclude` | globs removed from `routes` (e.g. `web/src/app/(site)/api/**`) | `[]` |
| `gate` | `blocking` or `advisory`. Blocking turns a finding into a failed lane precheck (`conformance.unimplemented`) and a `GATE_FAILURE` at `review-pr-staging`; advisory reports the same findings and never fails | `advisory` |
| `spec_label` | the label that counts as an approved design (besides a non-draft `FORGE:DESIGN_SPEC` comment) | `design:approved` |
| `needed_label` | the label that marks an issue waiting for `/design` | `design:needed` |
| `directions_param` | query parameter that selects a design direction when `/design` renders variants of a route | unset |
| `viewports` | widths (px) every route is rendered at | `[390, 1440]` |
| `require_visual_check` | the staging visual gate requires a screenshot at every viewport and a render-critique verdict per route | `true` |

What the keys drive:

- **Routing (lane time).** When the frozen contract's deliverables include a page entry (`page.tsx|jsx`, `.vue`, `.svelte`) under `routes` and the issue has neither a `FORGE:DESIGN_SPEC` comment nor the `spec_label` label, the lane is routed to `/design` instead of being built from a functional spec. With `gate: blocking` the lane stops before the implement call (`needs-human`, outcome code `design.spec_required`) until a spec exists; with `advisory` the implement prompt tells the builder to reference a `/design` spec.
- **Lane precheck (blocking only).** The same visual gate that runs at staging runs over the lane's diff with the deterministic source critique and the spec check, so a plain-text hero page with empty boxes fails before it reaches a PR. Rendered screenshots are not required here: lanes never install a browser and record `not rendered: <reason>` under `### Visual Check`.
- **`review-pr-staging` Phase 1I.** `scripts/visual-gate.mjs` lists every new or changed route (`--list`), the reviewer renders each at every viewport, runs `design-render-critique-loop` against the route's spec, and the script judges the evidence, posts a `FORGE:VISUAL_GATE` comment (routes, screenshot paths, critique verdict) and exits 1 on a blocking finding. A changed route also adds the Frontend review persona (`review-roster.sh --design-routes true`).
- **Deterministic critique floor** (`critiqueMarkup`, 0 LLM calls): empty or label-only boxes, placeholder copy or null samples, and a text-only page (an `h1` with no component, media or background) block; a page whose only calls to action are bare links warns.

```yaml
design:
  system: [docs/design-system.md, web/styles/tokens.css]
  routes: ["web/app/**/page.tsx", "web/app/**/layout.tsx"]   # opt-in: setting this turns the design gate on
  exclude: ["web/app/api/**"]
  gate: blocking            # blocking | advisory (default advisory)
  spec_label: design:approved
  needed_label: design:needed
  viewports: [390, 1440]
  require_visual_check: true
```

---

## `review` (OPTIONAL)

Context injected into review agent prompts. Helps the 9-agent review system give relevant, project-specific feedback.

```yaml
review:
  tech_stack: "Next.js 15 App Router, FastAPI, PostgreSQL 16, Docker, Traefik"

  context: |
    Multi-service monorepo: services/api (Python/FastAPI), web/ (Next.js).
    Deploy: blue/green via Docker Compose on a single VPS behind Traefik.
    Database: PostgreSQL with async SQLAlchemy. No ORM migrations — raw SQL.

  domains:
    billing: "Stripe webhooks; idempotency keys required on all handlers"
    auth: "JWT + refresh token rotation; sessions stored in Redis"
    database: "Always use docker exec <container> for psql/migrations"

  # max_parallel: 2         # release review: reviewers running at once (default max(2, cores/2)); the rest queue. Reviewers run at nice 19 / ionice idle (#6098)
  # max_filed_findings: 2   # per-review cap on filed findings (default 2; 1 on review-finding lineage)

  # key_paths:
  #   auth: ["services/api/auth/**", "web/src/lib/auth/**"]
  #   billing: ["services/api/billing/**", "web/src/app/billing/**"]
  #   database: ["services/api/db/**", "migrations/**"]
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `tech_stack` | string | No | One-line tech stack summary. Injected into all review agent prompts |
| `context` | string (multiline) | No | Freeform context about architecture, deploy model, and known pitfalls |
| `domains.*` | string | No | Domain-specific notes keyed by review agent name (`billing`, `auth`, `database`, `frontend`, `api`, `infra`, `security`) |
| `max_filed_findings` | integer >= 0 | No | Per-review cap on ISSUE dispositions (`scripts/cap-findings.sh`, applied by `review-pr` §6B.5 and `review-pr-staging` §7B (via `review-finalize.sh classify`) after classification). Default `2`; `1` when the reviewed PR is itself a fix for a `review-finding` issue, where every filed HIGH/CRITICAL consumes that budget. ISSUE findings are ranked by severity, then confidence, then safety-domain agent (security, auth, billing, concurrency, database), then input order; an unparseable severity or confidence ranks as MEDIUM/LIKELY. The overflow becomes `NOTE capped`: listed in the PR body and counted as `notes_capped` in `FORGE:NOTE_DISPOSITION`, never filed and never dropped. **HIGH/CRITICAL findings are never capped** and still block; `ISSUE fix-efficacy-*` findings (the linked issue is not fixed, or the PR re-introduces its defect) are never capped either and count against the review-finding budget like HIGH. `0` is valid (cap every MEDIUM/LOW finding); a non-numeric or negative value falls back to the default with a warning. An explicit value overrides both defaults. |
| `key_paths` | map(string→list of strings) | No | Domain-to-file mapping used by `/work-on` investigation and `/review-pr` agents to quickly locate relevant files. Keys are domain names matching issue labels; values are lists of file path patterns (glob-style, relative to repo root). When present, agents use this table instead of inferring files from labels and issue body. |
| `enforce_domains` | string or list | No | Lean lanes (#5099). Review domains whose touch makes the conformance gate enforce for the whole lane (sticky, like a `risk_paths` hit): any of `frontend`, `auth`, `infra`, `database`, `api`, as a comma-separated string or a block list. Unknown names are dropped. Default empty: lanes stay in shadow (ADR `devdocs/decisions/4398-risk-path-enforce.md`: enforce a domain only once its shadow false-block rate is near 0). Independently of this key, the lean reviewer always gets a `<domain_checks>` block naming the domains the diff touches, using `scripts/review-roster.sh` path triggers (for example `web/`, `app/`, `*.tsx`, `next.config.*` → frontend, with the dynamic-API-in-static/ISR-tree check). It reports domain findings as `regressions` rows, which block even in shadow. The run log gets `REVIEW_DOMAINS {domains, enforced}`. |

**Commands that use this section**: `review-pr`, `review-pr-agents` (all domain agents), `work-on` (Phase 1B investigation)

---

## `devdocs` (OPTIONAL)

Path configuration for the devdocs knowledge tree. Pipeline agents (work-on, review-pr, etc.) read these files as **authoritative project knowledge** before acting.

Create the devdocs tree by copying the seed templates from `devdocs/templates/` (in this repo) into your configured path, or scaffold it manually by creating `devdocs/project/architecture.md`, `devdocs/agent/using-forgedock.md`, and an optional `devdocs/index.yaml`.

```yaml
devdocs:
  path: "devdocs"
  # index_path: "devdocs/index.yaml"   # optional; defaults to {path}/index.yaml
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `path` | string (relative path) | No | Path to the devdocs tree, relative to project root. Default: `devdocs`. |
| `index_path` | string (relative or absolute path) | No | Path to the selective loading index file. Default: `{path}/index.yaml`. When the index file exists at this path, agents read it first (~400 tokens) and load only docs whose domain matches the current issue's labels. When absent, agents fall back to loading all docs with `applies_to: work-on` (backward compatible). Create the index manually or copy the seed template from `devdocs/templates/`. |

**Commands that use this section**: `work-on/build/context` (Phase C-1), `work-on/build/architect` (Phase A0)

### Selective Loading (index.yaml)

When `devdocs/index.yaml` exists, agents use **domain-filtered selective loading** instead of reading all applicable devdocs:

1. Read `index.yaml` (~400 tokens)
2. Extract issue labels (e.g. `billing`, `infra`, `auth`)
3. Load only docs in matching domains + all `always_load` entries
4. When no labels match any domain key: load only `always_load` entries

**Domain matching**: GitHub issue labels map directly to domain keys in `index.yaml`. For example, a label `billing` matches `domains.billing`. Prefixes like `workflow:`, `priority:`, and `review-finding` are stripped before matching.

**`always_load` entries** are loaded for every task regardless of domain. Use for `project/custom-instructions.md` and other files every agent must read.

**Token savings**: A typical task loads 1-3 docs (~1,500-3,000 tokens) instead of all docs (~8,000-12,000 tokens). The index itself costs ~400 tokens — break-even at 1 file avoided.

**Backward compatibility**: If `index.yaml` is absent, behavior is unchanged — all docs with `applies_to: work-on` are loaded. No migration required for existing devdocs trees.

Scaffold the index manually by creating `devdocs/index.yaml` (or copy the seed template from `devdocs/templates/` in the ForgeDock repo).

### Migration from `review.context`

If you previously stored project context in `forge.yaml → review.context`, move that content into the appropriate devdocs file:

| `review.context` content | Target devdocs file |
|--------------------------|---------------------|
| Architecture decisions | `devdocs/project/architecture.md` |
| Tech stack details | `devdocs/project/stack.md` |
| Coding conventions | `devdocs/project/conventions.md` |
| Project terminology | `devdocs/project/glossary.md` |
| ForgeDock usage notes | `devdocs/agent/using-forgedock.md` |

Agents read devdocs files as binding source-of-truth, so they receive richer context than the single `review.context` string.

---

## `verification` (OPTIONAL)

Service health-check patterns for the quality gate and validate commands.

```yaml
verification:
  health_endpoint: "https://api.acme.io/health"

  health_patterns:
    - '"status": "ok"'
    - '"database": "connected"'

  services:
    - name: "api"
      container: "acme-api-blue"
      health_url: "http://localhost:8000/health"
    - name: "web"
      container: "acme-web-blue"
      health_url: "http://localhost:3000"

  consumer_sweep:
    mode: advisory         # advisory (default) | blocking
    budget_seconds: 60     # wall-clock budget for the sweep

  test_runners:            # path prefix -> runner command prefix (block-style map)
    services/worker: "poetry -C services/worker run"
    web: "pnpm --filter web exec"

topology:
  route_reachability: "bash scripts/check-ingress.sh"   # optional; blocking when declared
  prod_parity:                                         # optional; block map {path glob: command | "note: how to verify"}
    "db/migrations/**": "bash scripts/check-migration-role.sh"
    "web/app/**": "note: run under the production ISR runtime"
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `health_endpoint` | string | No | Primary health-check URL that should return HTTP 200 |
| `health_patterns` | array of strings | No | Strings that must appear in the health endpoint response body |
| `services` | array | No | Named services to verify as part of deployment validation |
| `services[].name` | string | **Yes (per entry)** | Human-readable service name |
| `services[].container` | string | No | Docker container name for `docker exec` verification |
| `services[].health_url` | string | No | Local URL for container-level health checks |
| `ci_local` | object | No | Local CI gate settings (see below) |
| `commands.<lang>.<step>` | string | No | Toolchain commands (`format`, `lint`, `typecheck`, `test`, `build`) per language key (`python`, `typescript`, ...); see `forge.yaml.example`. An absent key logs `SKIPPED — not configured` |
| `commands.typescript.lint` | string | No | TypeScript lint. Validate runs it like `typescript.typecheck` (bounded by `FORGEDOCK_VERIFICATION_TIMEOUT_SECONDS`, default 120 s; a failure blocks). The core engine reads it from the trusted `forge.yaml` (main checkout or base ref, never the PR's tree), and `bin/lean/checks.mjs` prints it in place of the discovered lint. Without it, a turbo lint is scoped to the changed packages (`--filter=[base]`), not their dependents. Prefer a changed-files, cached lint |
| `commands.typescript.test_changed`, `commands.typescript.typecheck_changed`, `commands.python.test_changed` | string | No | Changed-file scoped steps for `/review-pr` Phase 2 (repos where the full typecheck or suite is too slow or heavy). They run in the per-PR worktree and read the PR's changed files that still exist from `$FORGE_CHANGED_FILES` (newline-separated environment variable; never spliced into the command string). Reported as Phase 2 evidence with `EXIT <lang>.<step>=<code>` like the full-repo steps; a non-zero `typecheck_changed` blocks, a failing `test_changed` follows the REAL/flaky rule of `test`. Examples: `vitest related $FORGE_CHANGED_FILES --run`; `pytest -q $(printf '%s\n' $FORGE_CHANGED_FILES \| grep 'test_.*\.py$')`. For `typecheck_changed`, filter the compiler output to the changed files so pre-existing errors elsewhere do not block. `forgedock init` suggests them when vitest or pytest is detected |
| `consumer_sweep.mode` | string | No | `advisory` (default): the validate consumer sweep (`scripts/consumer-sweep.sh`, V4.6) records unaddressed referencing sites and never fails. `blocking`: unaddressed sites fail validate with `consumer_unaddressed`, build runs one repair round, and sites still unaddressed are recorded as `CONSUMERS: unresolved` and passed to review as known risk (never `needs-human`). Flip to `blocking` only after `bash scripts/consumer-sweep.sh --eval-history 20` shows a mean of at most 2 flagged sites per merge and none above 10 on your repo |
| `consumer_sweep.budget_seconds` | integer | No | Wall-clock budget for the sweep (default `60`). When it runs out the sweep stops with `BUDGET_EXCEEDED`, reports the partial result, and never fails, in either mode |
| `test_runners` | map (path prefix → runner) | No | Default unset (no runner enforced). For repos whose validate commands need a managed runner (uv, poetry, pnpm workspace). The lean engine checks it at contract freeze (`testRunnerProblems`, `bin/lean/preflight.mjs`): a validate command that touches a configured path prefix without containing that prefix's runner string is reported as a contract problem, instead of failing later as `contract.invalid_command` / `env.tool_missing`. Paths in the command are relative to the runner's cwd. Write it as a block-style map: `parseForgeYaml` does not read inline `{ ... }` maps. |
| `coupled_files` | map (glob → glob list) | No | Default unset (#5079). "If file A changes, file B must change": a block map `{when glob: required glob[, glob]}`, e.g. `"infra/guard/bootstrap.sh": "infra/guard/MANIFEST.sha256"`. A key prefixed `added:` fires only for files the lane adds (`"added:scripts/tests/test_*.py": ".github/workflows/ci.yml"`). A lane that changes a `when` file without a matching required file fails precheck with `coupled_file_missing` (`conformance.unimplemented`, builder resumed once). Quote keys that contain `*`, and list alternatives as separate keys: brace globs (`*.{ts,tsx}`) are not expanded. |
| `verify.baselines` | map (glob → command) | No | Default unset (#5448). Baseline suites validate runs whenever a changed path matches the glob, e.g. `baselines:` with `"shared/content/**": make stealth-baseline`; each distinct command runs once, a non-zero exit fails the gate (`conformance.regression`). The contract's `regression` set (existing tests of callers, shared modules, sibling configs) is folded into `validate` at freeze. A post-deploy requirement needs a registered check id and `local_infeasible_why`; a check-less one is rejected at freeze unless it needs an owner or read-only prod data, and development work is never deferrable as prod-only. |
| `validate.recipes` | map (regex → replacement) | No | Default unset. A top-level `validate:` block with a block-style `recipes:` map, e.g. `"poetry run pytest": "uv run --with-requirements r.txt pytest"`. Each key is a regex source; the first recipe that matches a frozen validate or `repro_test` command rewrites it at contract freeze (`applyValidateRecipes`), recorded as a decision. Use it for commands whose environment is not installed in lane sandboxes. |
| `validate.catalog` | comma list | No | Default `.github/workflows/ci.yml, scripts/ci-local.sh`. CI files from which the engine derives rewrite entries (the repo's own pytest or JS runner) for validate commands freeze preflight finds unrunnable; `validate.recipes` entries take precedence (#5653). |
| `validate.regenerate` | string | No | Default unset. Command that regenerates generated artifacts. When a validate failure reads as a stale artifact, it runs once and the validate is rerun; it counts only if regeneration changes no tracked file (#5653). |
| `topology.route_reachability` | string (command) | No | Default unset (no check, no behaviour change). A repo-supplied command that takes the route paths a diff adds (Next.js `app/**/route.*`, `pages/api/**`; URL form, route groups removed) as arguments and exits non-zero when the production ingress does not deliver them to the service that implements them. Runs in the lean lane after validate and in `review-pr-staging`; a non-zero exit blocks (`conformance.unimplemented`, kind `route_unreachable`). Read by `readEnvConfig` (`bin/engine-cli.mjs`), run by `bin/lean/routecheck.mjs`. |
| `pages.enabled` / `pages.routes` | bool / list | No | Page gate (#5428). Default on only when the repo tracks Next `app/**/page.*` files; `enabled: false` turns it off, and `routes` globs add non-Next page files. A diff touching a public page needs `page_gate` {design_spec, seo, geo} in the contract (checked by `validateContract`), and `page_missing`-class precheck rows (`page_design_missing`, `page_visual_missing`, `page_metadata_missing`, `page_canonical_missing`, `page_structured_data_missing`, `page_sitemap_missing`, `page_forbidden_pattern`, `page_link_broken`, `page_lint_failed`) fail as `conformance.unimplemented`. Read by `readEnvConfig`, checked by `bin/lean/pagegate.mjs`. |
| `pages.exclude` / `pages.design_only` | lists | No | Globs (#5585). `exclude` drops internal, auth-gated or admin routes from the page gate entirely (no `page_gate` brief, no `page_*` rows). `design_only` keeps the `design` requirement (`page_gate.design_spec`, an approved spec, 390/1440 screenshots) but skips SEO/GEO. A page whose own file or an ancestor `layout.*` declares `robots: { index: false }` or `noindex` is excluded automatically (needs the file to exist in the worktree). Default empty. |
| `pages.require` / `pages.icp_doc` | list / path | No | Default `[design, seo_intent, geo]`. `icp_doc` names the repo's ICP doc the SEO brief must cite. `design` also needs a 390 and 1440 screenshot in the result's `page_gate.screenshots`; `design` and `seo-geo` become review domains and `/review-pr-staging` Phase 1H blocks. |
| `pages.sitemap` / `pages.metadata_patterns` / `pages.canonical_patterns` / `pages.structured_data_patterns` / `pages.forbid_patterns` / `pages.lint` | lists / command | No | Regex and glob overrides of the built-in Next defaults (sitemap files, `metadata`/`generateMetadata`, `canonical`, JSON-LD, `[[null]]`/raw-JSON/dead-end patterns on added page lines). A generated sitemap is justified in the result as `page_gate.sitemap_justification`. `lint` is a repo command given the page files; non-zero fails. |
| `docs.required_for` | string or list | No | Default unset (#5419): the docs gate is off, so library/CLI repos are unchanged. Kinds of user-facing surface that need user docs: `api`, `mcp`, `dashboard`, `cli`, `sdk`. Built in: Next route handlers (`api`) and `app/**/page.*` under a `dashboard` path (`dashboard`); other kinds need `docs.surfaces`. Read by `readEnvConfig`, checked by `bin/lean/docsgate.mjs`. |
| `docs.paths` / `docs.registries` | list | No | Globs of the docs pages and of their registration files (nav, sitemap, `llms.txt`). A diff touching a surface with no changed file under either, and no `docs: [{surface, justification}]` in the result file, fails `docs_missing` (`conformance.unimplemented`). `paths` defaults to `docs/**`. The planner is told to add an R-docs requirement naming them. |
| `docs.surfaces` | map (kind → globs) | No | Repo globs for each kind's surface files. |
| `docs.link_prefixes` / `docs.link_check` | list / command | No | Default prefix `/docs`. Each internal `href="/docs/..."` or `docsHref` link the diff adds must resolve: `link_check` gets the links as arguments and a non-zero exit fails `docs_link_broken`; without it a docs file under `paths` must serve the link. With `docs.required_for` set, `docs` is also a review domain (reviewer check for undocumented or contradicting docs), `forgedock docs gate --milestone T --repo o/r` blocks closing a milestone with user-facing children and no merged `docs` child, and `/review-pr-staging` Phase 1G blocks undocumented user-facing changes. |
| `outcome_evidence.paths` | map (area → globs) | No | Default unset (#5752): no check. Declares areas whose changes must show a before/after measurement on recorded real inputs (a replay corpus, production samples), not only mocks. A lane whose non-test changed files match an area fails precheck (`conformance.unimplemented`, kind `outcome_evidence_missing`) unless its result.json carries `"outcome_evidence": [{"area": "<area>", "metric": "<name>", "corpus": "<path>", "before": <number>, "after": <number>, "better": "higher\|lower"}]`. A row with no metric, a missing or undeclared corpus or non-numeric values is `outcome_evidence_invalid`; an `after` worse than `before` is `outcome_evidence_regressed`. Each failure names the area, the files and the required row shape. |
| `outcome_evidence.corpus` | map (area → globs) | No | Where each area's recorded real inputs live; a row's `corpus` must match them and exist in the tree. Corpus files themselves do not trigger the area. A `post-deploy` requirement of a lane touching an area needs a metric baseline on its `.forge/post-deploy-checks.json` entry, `"baseline": {"metric": "<name>", "value": <number>, "better": "higher\|lower"}`, not a string match (`outcome_evidence_baseline_missing`). |
| `topology.prod_parity` | block map | No | Default unset (no check, no behaviour change; #5284). Production-only facts the lane tests cannot exercise (runtime build mode, migration role vs app role, env-file scope, ingress). Key: path glob; value: a check command, run once with the matching changed paths as arguments (non-zero or cannot-start blocks, `conformance.unimplemented` kind `prod_parity_failed`), or `note: <how to verify>`, which blocks (kind `prod_parity_unjustified`) until `.forge-lean/result.json` carries `parity: [{surface: <glob>, justification}]`. Read by `readEnvConfig`, run by `bin/lean/prodparity.mjs`. |

**Commands that use this section**: `quality-gate`, `validate` (V2 runs `verification.commands`; V4.8 runs the local CI gate; health checks and `consumer_sweep`), `work-on`

### `verification.ci_local` (OPTIONAL)

Validate Phase V4.8 runs `scripts/ci-local.sh` before review: it derives the repo's pull-request checks from its own CI
definitions and runs them locally in the build worktree, so deterministic CI failures are fixed in build (at most 2 fix
iterations; a failure still unfixable after that is DEGRADED by default, see `mode`). It never contacts GitHub and never triggers a remote
workflow; remote CI still runs once, at merge. Everything works with no configuration.

```yaml
verification:
  ci_local:
    mode: advisory
    exclude_jobs: ["gha:ci:e2e-*"]
    include_jobs: []
    extra_commands:
      - "make lint-docs"
    services: auto
    budget_minutes: 15
    max_parallel: 4
```

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `mode` | `advisory` \| `blocking` | `advisory` | `advisory`: a runnable job still failing after the 2 fix iterations is DEGRADED (`DEGRADED_CHECKS+=ci-local`), recorded in `FORGE:BUILDER` under `### Local CI unresolved` and surfaced to review; the build is not blocked. `blocking` (opt-in): the build is blocked with `ci-local: <jobs>`. Flip to `blocking` only once telemetry (`ci_local` events) shows a low false-fail rate on your repo |
| `exclude_jobs` | array of globs | `[]` | Job ids or names to drop from the plan (matched against `gha:<workflow>:<job>`, `gitlab:<job>`, and the job name) |
| `include_jobs` | array of globs | `[]` | When non-empty, only matching CI jobs run (an allowlist); `extra_commands` and the portability checks (when they apply) always run |
| `extra_commands` | array of strings or `{name, command}` | `[]` | Extra commands always added to the plan. `verification.commands` is not repeated here: V2 already runs it as the fast pre-step |
| `services` | `auto` \| `off` | `auto` | `auto` starts a job's service containers with docker (same image, env, ports), tearing them down afterwards; without docker, or with `off`, such jobs are deferred |
| `budget_minutes` | number | `15` | Overall wall-time budget; jobs not finished or started within it leave the run DEGRADED (never PASS, never FAIL). One invocation is capped at 9 minutes whatever this says (the Bash tool limit is 10): beyond that the run is a partial DEGRADED result and re-running resumes from the result cache (`FORGE_CI_LOCAL_MAX_INVOCATION_SECONDS`, default 540) |
| `max_parallel` | number | `4` | Jobs run in parallel by one run (also bounded machine-wide, see below) |

**Trusted config**: every field above is read from the main checkout's `forge.yaml` (for a plain checkout, the base ref's
copy), never from the PR's own tree, so a PR cannot exclude jobs from the gate that checks it.

**Where checks come from**: GitHub Actions (`.github/workflows`), GitLab CI, CircleCI, Azure Pipelines, Bitbucket Pipelines
and Buildkite definitions, read from the trusted base ref plus the PR's own edits (a PR can add a check but cannot delete
one). Only when the repo has NO CI definitions are its task runners used; when CI exists but its path filters leave no job
applicable the run executes nothing and records `no_applicable_jobs` (a docs-only change never triggers a full suite) (`package.json` scripts, Makefile, justfile,
Taskfile, tox/nox, pre-commit, pyproject tools, Cargo, Go, Maven, Gradle). Deterministic portability checks (Windows-invalid
filenames, case collisions, CRLF in scripts, bash 3.2 constructs and GNU-only flags on added lines, plus the repo's
`scripts/check-shell-portability.sh` when present) run only when the repo's CI definitions target macOS or Windows (a
`macos-*`/`windows-*` runner, matrix entry or executor); for a Linux-only repo they are skipped with a note, so correct
Linux-only code is never blocked on bash 3.2 rules.

**Deferred to CI** (listed in the `FORGE:BUILDER` comment under `### Deferred to CI`, never guessed): jobs that reference
`secrets.` or `environment:`, deploy/publish jobs, `pull_request_target`, schedule/dispatch-only workflows, unknown `uses:`
actions, orbs, plugins and templates, service containers without docker, macOS/Windows variants on another host, matrix
variants beyond the first host-compatible one, and jobs whose tools are not installed locally. A failed dependency install
(for example offline) defers the job instead of failing it, and so does a failure of a job whose pinned toolchain differs
from the host by a major version (`setup-node` 18 vs host 26: version drift, listed with its reason). A job timeout is
DEGRADED, never FAIL, and its clock starts when the job starts executing, not while it waits for a machine slot.

**Exact scoping** (runs only what the change can affect): job-level path filters from the CI definition (including
`dorny/paths-filter` outputs) gate whole jobs (generate such a filter step in git mode: `actions/checkout` with `fetch-depth: 0`, and `token: ''` with `base:` set on `dorny/paths-filter`, because the default PR files API times out on large diffs and every gated suite is then skipped, #5592); per-file linters (shellcheck, eslint, prettier, ruff, black, flake8, ...) run
on the changed files only; tests use the ecosystem selector (`jest --findRelatedTests`, `vitest related`, `go` affected
packages with reverse dependencies, `cargo test -p` affected crates, Maven `-pl ... -amd`, `nx affected`, `turbo --filter`) or a
git-grep reference graph for file-list runners (pytest, mocha, `node --test`, bats, rspec, direct `*.test.*` invocations);
changed test files always run. **Fail-safe widening**: a lockfile, build or lint config, CI definition, unreferenced shared
fixture, an unknown file type, or an empty test selection for a changed source file widens the step to the full command (the
reason is reported, never silently narrowed). Short module names (`app/db.py`, `__init__.py`) are matched by their qualified
import forms. `${{ github.* }}` expressions in `run:` scripts are passed to the script as environment variables, never
substituted into the script text. CircleCI secondary containers run on a per-job docker network and publish only declared
(or well-known default) ports on 127.0.0.1, never `--network host`.
Passing results are cached by input hash under `~/.forge/ci-local/results` and reused across build iterations, lanes and
issues on the same base. An identical check (command, cwd, shell, env, input hash) that appears in several jobs of one invocation
runs once; the later jobs reuse its result (`cache=dedup`, a failure is shared). Machine slots are granted in FIFO ticket order
across invocations (`~/.forge/ci-local.lock/queue`; tickets of dead processes are reaped), and a slot is taken only right before a
step really executes. Job lines, `CI_LOCAL_CHECK`, `CI_LOCAL_RESULT` and the `ci_local` telemetry report `wait_ms` (time queued
for a slot) separately from `duration_ms` (execution). Ready jobs run narrow/scoped first, then cheapest first (cached durations).

**Environment** (all optional): `FORGE_CI_LOCAL_SLOTS` (machine-wide concurrent jobs across all runs, default
`max(2, min(8, cpus/2))`; slots live under `~/.forge/ci-local.lock` and stale ones are reclaimed), `FORGE_CI_LOCAL_BUDGET_MINUTES`,
`FORGE_CI_LOCAL_MAX_PARALLEL`, `FORGE_CI_LOCAL_JOB_TIMEOUT` (seconds, default min(900, budget)), `FORGE_CI_LOCAL_SERVICES=off`,
`FORGE_CI_LOCAL_MAX_INVOCATION_SECONDS` (default 540), `FORGE_CI_LOCAL_HOME` (default `~/.forge`), `FORGE_CI_LOCAL_NO_CACHE=1`. Jobs run in a runner-like environment: an allowlist of
system and toolchain variables (PATH, HOME, locale, XDG_*, CARGO_*, GOPATH, JAVA_HOME, proxies, ...) plus `CI=true`; credentials and
ambient operator state (agent tokens, `FORGE_*`/`CLAUDE_*` settings, git hook variables) never reach them. Extra names can be
listed in `FORGE_CI_LOCAL_PASSTHROUGH` (comma separated). Requires `node`, `git`, and mikefarah `yq` v4 for YAML CI definitions (without `yq`
the gate is DEGRADED and reported in `verification_skipped`, never a silent pass).

**Commands that use this section**: `work-on` (validate V4.8)

---

## Schema check and config history (#5315)

forge.yaml is parsed tolerantly, so a setting nobody reads used to be silent. `bin/config-schema.mjs` now checks it:

| Finding | Level | Meaning |
|---------|-------|---------|
| `unknown-key` | error | A top-level key outside the sections in this document, or an unknown child of a closed section (`verification.ci_local`) |
| `ignored-on-path` | error | The key is set, but the active `engine.path` never reads it (the legacy `full` path ignores `env`, `verify`, `lean`, `engine.conformance`, `engine.conformance_kinds`) |
| `wrong-type` | error | A typed key has the wrong shape (for example `verification.ci_local.extra_commands` that is not a list, `engine.path` outside `core\|full\|lean\|auto`) |
| `deprecated-alias` | warning | `pipeline.token_budget_per_batch`, `build.diff_size.threshold` |

`npx forgedock doctor` reports errors as failures and aliases as warnings; `orchestrate` prints one `config: ...` line per finding at batch start, naming the key.

### Config history

Every setup or agent edit of forge.yaml records a version under `~/.forge/config-history/<owner>__<repo>/` (override the root with `FORGE_CONFIG_HISTORY_DIR`), never a `forge.yaml.bak-*` file in the repo.

| Command | Does |
|---------|------|
| `forgedock config history` | Lists versions with date and reason |
| `forgedock config diff <n>` | Diffs version `n` against the current forge.yaml |
| `forgedock config rollback <n>` | Restores version `n`; the current content is recorded first, so a rollback can be undone |
| `forgedock config record [reason]` | Records the current forge.yaml as a version |
| `forgedock config import-bak [--delete]` | One-time import of `forge.yaml.bak*` files in the repo into the history (idempotent); `--delete` removes them |

## Credentials File Format

If `paths.credentials.file` is set, the file at that path is expected to be a YAML file with this structure:

```yaml
# credentials.yaml — DO NOT COMMIT
umami:
  username: "admin"
  password: "your-password"

cloudflare:
  api_token: "your-cf-token"
  zone_id: "your-zone-id"

# QA test user credentials — read by /qa-sweep for browser-based authentication
qa:
  username: "test@example.com"
  password: "your-test-password"

# Add other service credentials as needed
```

The credentials file is read directly by analytics and monitoring commands. It is never committed — add it to `.gitignore`.

---

## `billing` (OPTIONAL)

Controls whether financial integrity checks run in `/security-audit`. Only relevant for projects with Stripe or similar billing infrastructure. When omitted or set to `false`, Phase 4 (Financial Integrity) of the security audit is skipped.

```yaml
billing:
  enabled: false
```

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `enabled` | boolean | No | `false` | Set to `true` to enable Phase 4 (Financial Integrity) in `/security-audit`. When `false`, the billing audit phase is skipped — appropriate for projects that do not process payments or have no Stripe integration. |

**Commands that use this section**: `security-audit` (Phase 4 — Financial Integrity)

---

## `adaptive_scripts` (OPTIONAL)

Per-repo script override configuration. Controls whether ForgeDock looks for project-specific scripts in `.forgedock/scripts/` before falling back to universal scripts.

```yaml
adaptive_scripts:
  enabled: true
  directory: ".forgedock/scripts"
  commit: false
```

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `enabled` | boolean | No | `true` | When `true`, pipeline agents check `.forgedock/scripts/` for a per-repo script before using the universal one. Set to `false` to disable per-repo overrides entirely and always use universal scripts. |
| `directory` | string (relative path) | No | `".forgedock/scripts"` | Directory where per-repo adaptive scripts live, relative to the project root. Scaffolded by `npx forgedock init`. |
| `commit` | boolean | No | `false` | When `false`, `.forgedock/scripts/` is `.gitignore`d — scripts are local-only and not shared with the team. Set to `true` (and remove the `.gitignore` entry) to commit per-repo scripts to version control. |

**Commands that use this section**: `work-on` (Phase 0B script resolution), any pipeline command that calls a deterministic script

### Script Precedence

ForgeDock resolves which script handles each operation using a strict 4-level hierarchy (highest to lowest authority):

```
1. forge.yaml → learned: (machine-captured corrections)        ← highest
2. .forgedock/scripts/{operation}.sh  (per-repo adaptive)
3. scripts/{operation}.sh             (universal, ships with npm)
4. Prose instructions in command specs (fallback)              ← lowest
```

### Override Semantics

- **Per-repo scripts completely replace** the universal script for that operation — there is no partial inheritance or merging.
- **Per-repo scripts may call universal scripts** via the `$FORGEDOCK_SCRIPTS/{operation}.sh` path. Every universal script exports `FORGEDOCK_SCRIPTS` (absolute path to the universal scripts directory) and `FORGEDOCK_HOME` (absolute path to the ForgeDock installation root) so that per-repo scripts can delegate back to them.
- **No circular dependencies**: per-repo scripts may call universal scripts but must NOT call other per-repo scripts. One level of delegation only.
- **`forge.yaml → learned:`** overrides take precedence over everything. They represent explicit user corrections captured by the pipeline.

### Example: per-repo script that delegates to universal

```bash
#!/usr/bin/env bash
# .forgedock/scripts/classify-lane.sh
# Override: this repo uses 'develop' instead of 'staging' for the fast lane.

set -euo pipefail

# Delegate to universal classify-lane.sh to get the standard result
UNIVERSAL_RESULT=$(bash "$FORGEDOCK_SCRIPTS/classify-lane.sh" "$@")

# Override only the fast-lane output for this project
if [ "$UNIVERSAL_RESULT" = "staging" ]; then
  echo "develop"
else
  echo "$UNIVERSAL_RESULT"
fi
```

### Logging

When a pipeline agent resolves a script tier, it logs the result in the FORGE annotation:

```
Script tier: adaptive (.forgedock/scripts/classify-lane.sh)
Script tier: universal (scripts/classify-lane.sh)
Script tier: prose (no script found — using spec instructions)
```

---

## Label Bootstrap

ForgeDock manages a canonical set of GitHub labels for use across all pipeline commands. Labels cover workflow state, priority, review findings, audit findings, and category classification.

### Bootstrap command

```bash
# Create/update all ForgeDock-managed labels on the repo defined in forge.yaml:
npx forgedock labels setup

# Or target a specific repo explicitly:
npx forgedock labels setup --repo owner/repo

# Also create per-repo domain labels (comma-separated):
npx forgedock labels setup --domain frontend,backend,infra,design,legal-gated
```

Domain labels are optional and per-repo. They are not part of `bin/labels.json`, so `forgedock doctor` never requires them. Each one gets the description `Domain: <name>. Managed by ForgeDock.`. `frontend`, `backend`, `infra`, `design` and `legal-gated` have fixed colors; any other name is grey (`#EDEDED`). A name that is already in the manifest is not created twice. `/forgedock-init` derives the list from your spec or takes it from `--domain-labels`.

Running this command is idempotent — it creates labels that don't exist and updates the color/description of labels that do. Safe to re-run at any time.

**When to run it**: Once after `npx forgedock install`, or whenever a pipeline command fails with "label not found". The command bootstraps every label the pipeline relies on.

### Canonical label set

The full manifest lives in [`bin/labels.json`](../bin/labels.json) in the ForgeDock package. Each label has a fixed hex color and a description attributing it to ForgeDock.

| Family | Labels |
|--------|--------|
| Priority | `priority:P0` `priority:P1` `priority:P2` `priority:P3` |
| Workflow | `workflow:investigating` `workflow:ready-to-build` `workflow:building` `workflow:in-review` `workflow:merged` `workflow:decomposed` `workflow:invalid` |
| Pipeline | `needs-human` `review-finding` `needs-validation` `validated` `false-positive` `staging-review` `audit-finding` `orchestration-metrics` `health-report` |
| Category | `bug` `enhancement` `feature` `refactor` `dead-code` `improvement` `documentation` `qa` `security` `performance` |

### Colors

Colors are grouped by semantic meaning:
- **Critical/error** (`#B60205`): `priority:P0`, `security`
- **High/warning-red** (`#D93F0B`): `priority:P1`, `review-finding`, `audit-finding`
- **Medium/yellow** (`#FBCA04`): `priority:P2`, `needs-validation`
- **Low/green** (`#C2E0C6`, `#0E8A16`): `priority:P3`, `workflow:merged`, `validated`
- **Blue pipeline** (`#1D76DB`, `#0075CA`, `#0052CC`): active workflow states
- **Neutral** (`#CCCCCC`, `#E4E669`): terminal/dismissal states

---

## `branding` (OPTIONAL)

Controls attribution in FORGE annotation comments posted to GitHub issues and PRs by pipeline commands.

When `show_attribution` is `true` (the default), every annotation comment (`FORGE:INVESTIGATOR`, `FORGE:CONTRACT`, `FORGE:BUILDER`, `FORGE:TRAJECTORY`, `FORGE:DECOMPOSED`, etc.) ends with a one-line footer:

```
> Pipeline powered by [ForgeDock](https://github.com/RapierCraftStudios/ForgeDock)
```

This follows the pattern established by Dependabot, Renovate, and similar tools. It helps new users discover the tooling when they encounter FORGE: annotations in a public thread. Set to `false` to suppress the attribution entirely.

```yaml
branding:
  show_attribution: true
```

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `show_attribution` | boolean | No | `true` | When `true`, annotation comments posted by the pipeline include a one-line attribution footer. Set to `false` to suppress it entirely. Opt-out model — attribution is on by default. |

**Commands that use this section**: `work-on` (all phases that post FORGE: annotation comments)

**Config read pattern** (yq, with default-true fallback):

```bash
SHOW_ATTRIBUTION=$(yq '.branding.show_attribution // "true"' forge.yaml 2>/dev/null || echo "true")
[ "$SHOW_ATTRIBUTION" = "false" ] && ATTRIBUTION_LINE="" || ATTRIBUTION_LINE="
> Pipeline powered by [ForgeDock](https://github.com/RapierCraftStudios/ForgeDock)"
```

---

## Bot token refresh

Installation tokens expire after 1 hour. `scripts/refresh-bot-token.sh` mints a new one and records `~/.forge/bot-token.json` (`refreshedAt`, `expiresAt`; override the directory with `FORGE_HOME_DIR`). To run it on a schedule, install the systemd user timer (`OnBootSec=2min`, `OnUnitActiveSec=45min`, `Persistent=true`, so a missed run fires after a restart):

```bash
mkdir -p ~/.config/systemd/user
cp scripts/systemd/forgedock-bot-token-refresh.{service,timer} ~/.config/systemd/user/
# edit ExecStart in the .service to the path of refresh-bot-token.sh on this host
systemctl --user daemon-reload && systemctl --user enable --now forgedock-bot-token-refresh.timer
```

`forgedock doctor` (Check 12) reports the remaining lifetime and the last refresh, and fails when less than 10 min remain or the last refresh is older than 50 min. Without the stamp file it stays an informational warning. A core run that gets HTTP 401 from `gh` runs the refresh script once and retries; if that does not help the run ends `deferred` with `gh.auth` (see `docs/OUTCOME-CODES.md`), and `FORGE_REFRESH_TOKEN_SCRIPT` overrides the script it runs. `scripts/wait-ci-green.sh` retries a 401 a few times, then exits 2 with an auth message.

## GitHub App Install

During `npx forgedock`, the installer prompts you to install the ForgeDock GitHub App (`rapiercraft-forgedock`). Installing alone changes nothing; to run the pipeline as the App's bot (its own API budget, `<app>[bot]` authorship) sign in with `forgedock auth login`. Without a login, every pipeline `gh` call uses your own `gh auth`, exactly as before.

### Broker sign-in

```
forgedock auth login --broker-url https://<broker> --client-id <App client id> [--installation N]
forgedock auth status
forgedock auth logout
```

- Login uses the GitHub App **device flow** (client ID only; no secret on your machine). The CLI stores the user token and installation under `~/.forge/app-auth.json` (mode 0600; `FORGE_HOME_DIR` overrides the directory). `FORGEDOCK_BROKER_URL` and `FORGEDOCK_APP_CLIENT_ID` can replace the flags.
- On every CLI start the stored login yields a short-lived installation token, scoped to your repository ids and the permissions the pipeline uses, which is set as `GH_TOKEN` in the CLI process env only. It is not a global credential: no `gh auth login`, no git credential helper (#4565). It is refreshed when under 10 minutes remain, and long-running commands (`orchestrate`, `schedd`, `watch`, `issue-watch`, `prod-watch`) refresh it in process before it expires. Processes ForgeDock spawns, such as the auto-started `schedd`, recognise the token it set by a fingerprint in `FORGEDOCK_APP_TOKEN_FP` (never the token itself) and keep refreshing it. A `GH_TOKEN` you exported yourself is never overridden.
- If the broker is unreachable or refuses, one warning line is printed and the pipeline continues on your own `gh` auth. `FORGEDOCK_NO_APP_AUTH=1` skips the App identity.
- Broker contract (client side): `POST {broker}/v1/token` with `Authorization: Bearer <user token>` and body `{installation_id, repository_ids, permissions}`, answering `{token, expires_at}`. The broker server, quotas, mint logs, revocation and security page live on the platform side.

### Bring your own App

`forgedock auth login --byo [--org ORG] [--installation N]` runs GitHub's App manifest flow through a loopback page, stores the App id and private key (`~/.forge/app-byo.pem`, 0600) and mints installation tokens locally. No third-party broker is involved.

### Doctor

`npx forgedock doctor` (Check 12, "GitHub App / bot token") shows the active identity, its source (`broker`, `byo` or personal fallback) and the `core.limit` of the active token. Without a login it keeps the earlier messages, including the refresh-stamp check for the self-hosted `scripts/refresh-bot-token.sh` setup.

---

## `marketing` (OPTIONAL)

Controls opt-in growth features such as 'Powered by ForgeDock' footers on PR descriptions created by the pipeline.

> **Note**: `pr_footer` injection requires future pipeline support in `/work-on`. Setting `pr_footer: true` today has no effect — it is a configuration interface that will be activated when the feature ships. When implemented, the pipeline will append a one-line footer to every PR body it creates.

```yaml
marketing:
  pr_footer: false
```

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `pr_footer` | boolean | No | `false` | When `true`, the pipeline appends a 'Powered by ForgeDock' footer link to every PR description it creates. Opt-in only — non-intrusive one-line footer, not a banner. Requires pipeline support (not yet implemented). |

**Commands that use this section**: `work-on` (Phase 4 PR creation — when `pr_footer: true`)

---

## Environment Variables

These variables are read from the operator's runner environment, not from `forge.yaml`. Set them in a trusted environment only (shell profile, CI runner settings); never from PR content, issue text or contributor-controlled CI variables.

| Variable | Default | Purpose |
|----------|---------|---------|
| `FORGEDOCK_HOME` | unset | Absolute path to the ForgeDock install root (the directory holding `scripts/` and `commands/`). Authoritative over every other source when set. Relative values are rejected; Windows drive-letter forms (`C:/forge`, `C:\forge`) are normalized to `/c/forge`. |
| `FORGE_HOME` | unset | Absolute path to the ForgeDock clone. Used when `FORGEDOCK_HOME` is unset. Required for Codex, which has no `~/.claude` fallback. Relative values are ignored. |
| `FORGE_SKILL_NAMESPACE` | auto-detected | Forces the skill prefix and nesting separator for `Skill(...)` calls. `forgedock` = `forgedock:` / `:`; `none` = empty / `:`; `codex` = `forge-` / `-`; `opencode` = empty / `-`. Any other value is an error. When unset, `FORGE_RUNTIME` (`codex` or `opencode`) is used, then the available-skills list. |
| `FORGE_TRAIL_TRUSTED_LOGINS` | empty | Comma-separated GitHub logins whose FORGE markers count toward the phase-trail merge gate. Matching is case-sensitive. |
| `FORGE_TRAIL_TRUSTED_ASSOCIATIONS` | `OWNER,MEMBER,COLLABORATOR` | Comma-separated `author_association` values whose FORGE markers count toward the merge gate. Do not add `CONTRIBUTOR` here: any listed association can post FORGE markers that satisfy the gate. |
| `FORGE_TRAIL_OVERRIDE_ASSOCIATIONS` | the resolved `FORGE_TRAIL_TRUSTED_ASSOCIATIONS` value | Comma-separated `author_association` values prefiltering break-glass override candidates (the permission API stays authoritative). Never affects which FORGE markers count toward the gate. An approver with concealed org membership can show `CONTRIBUTOR`/`NONE`, so widen this variable (not the trail list) to accept them. An explicitly empty value means no override candidates. |
| `FORGE_TRAIL_PIPELINE_LOGINS` | empty | Comma-separated GitHub logins (case-insensitive) that are the pipeline's own identity and can never approve a phase-trail break-glass override. The authors of trusted FORGE marker comments on the issue are added automatically. |
| `FORGE_TRAIL_QG_SINCE` | `2026-10-07T03:40:12Z` | ISO-8601 UTC cutoff for the legacy `FORGE:QUALITY_GATE` grace. An issue whose trusted `FORGE:BUILDER:COMPLETE` comment was last updated before this time has `QUALITY_GATE` waived. Set to an empty string to disable the grace. A malformed or future value (including a runner clock earlier than this default) fails closed: the verifier exits 2, an infrastructure block rather than `MISSING`. |
| `FORGEDOCK_ALLOW_API_BACKEND` | unset | Set to `1` (host owner approval) together with forge.yaml `execution.agent_backend: api` to let `--backend auto` use the paid API backend when no `claude` CLI is available. Without both, `auto` never selects `api` (#4257). |
| `FORGE_TELEMETRY` | `on` | Set to `off` to disable gate telemetry. Gate scripts append one structured record per decision to a trusted `FORGE:TELEMETRY v1` comment; emission is best-effort and never changes a gate's output or exit code. See [TELEMETRY.md](TELEMETRY.md). |
| `FORGE_EVENTS` | `on` | Set to `off` to disable the lifecycle event stream (local JSONL and webhook). `FORGE_EVENTS_DIR` overrides the JSONL directory; the webhook secret is read from the env var named by `events.webhook_secret_env` (default `FORGE_EVENTS_SECRET`). See [EVENTS.md](EVENTS.md). |

### Install root resolution

`FORGE_ROOT` (where the merge trail gate, dispatch lint and engine modules are resolved) is computed in this order: `FORGEDOCK_HOME` (authoritative: when set, nothing else is consulted, and a relative value leaves `FORGE_ROOT` empty so the gate fails closed) > the running plugin's own root (substituted by Claude Code, not a runtime env var; the stub hands it to the helper as `FORGE_SOURCED_ROOT`, so it wins over `FORGE_ROOT`, `FORGE_HOME` and any newer cached version) > `FORGE_HOME` > the `~/.claude/commands/work-on.md` symlink target > the clone path recorded in `$CODEX_HOME/forge-home` (Codex; a relative `CODEX_HOME` is ignored) > the newest semver directory in the Claude plugin cache (official `forgedock` marketplace only; `FORGEDOCK_MARKETPLACE` pins a differently named one) > the marketplace directory. If nothing resolves, `FORGE_ROOT` stays empty and the trail gate refuses to merge (fail closed). See [CODEX.md](CODEX.md#forge_home-and-install-root-resolution).

### Keeping the phase-trail merge gate satisfiable

The merge gate (`scripts/verify-phase-trail.sh`) ignores FORGE markers posted by untrusted commenters. A commenter is trusted when ANY of these hold: `author_association` is in `FORGE_TRAIL_TRUSTED_ASSOCIATIONS`; the account type is `Bot` (the pipeline's GitHub App identity); or the login is in `FORGE_TRAIL_TRUSTED_LOGINS`.

The note-disposition gate (`FORGE:NOTE_DISPOSITION`) and the in-PR fix markers (`FORGE:INPR_FIX*`) in `commands/review-pr.md` and `commands/work-on/review.md` use the same predicate through one shared helper, `scripts/trusted-comments.sh`, so a disposition posted by the pipeline's bot identity counts. An unresolvable helper blocks the merge (fail closed).

Pipelines that run under a human login with association `CONTRIBUTOR`, `NONE` or `FIRST_TIME_CONTRIBUTOR` will see every marker reported `MISSING`, and the gate prints a NOTE when untrusted-author markers were seen. Fix it by either:

```bash
export FORGE_TRAIL_TRUSTED_LOGINS="my-pipeline-login,other-login"   # preferred: name the identity
export FORGE_TRAIL_TRUSTED_ASSOCIATIONS="OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR"   # broader
```

Warning: widening `FORGE_TRAIL_TRUSTED_ASSOCIATIONS` to include `CONTRIBUTOR` lets any contributor post forged `FORGE:*` markers that satisfy the merge gate. To only accept override approvers with concealed org membership, widen `FORGE_TRAIL_OVERRIDE_ASSOCIATIONS` instead.

#### Break-glass override

A misfiring phase-trail gate can be cleared by a human without a revert or manual merge. Post a comment on the issue that starts with `<!-- FORGE:PHASE_TRAIL_OVERRIDE -->` and has these lines:

```
**Head**: <full 40/64-hex head commit>
**Missing**: <the MISSING marker names, comma separated, e.g. CONTEXT,ARCHITECT>
**Reason**: <one line>
```

`scripts/verify-phase-trail.sh` honours it only when the verifier would otherwise exit 1 and every rule holds: the author is `user.type == "User"` with repo `admin` or `write` permission; the author is not a pipeline identity (`FORGE_TRAIL_PIPELINE_LOGINS` plus the authors of the issue's trusted FORGE marker comments, so a pipeline running under a human token cannot approve itself, and a solo operator needs a second human with write access); the comment was never edited (`updated_at == created_at`); `**Head**` equals the commit being gated (passed as `--head-sha`) and `**Missing**` equals the current MISSING set; and the comment is newer than the latest `FORGE:BUILDER:COMPLETE`. Any API error or missing field rejects it. An unreadable trail (exit 2) is never overridable. The reason is sanitized (control characters stripped, comment markers neutralized, capped at 200 characters) and `/review-pr` and `/work-on` record the accepted override as `FORGE:PHASE_TRAIL_OVERRIDE_APPLIED` from the verifier's output. A new commit invalidates the override: post a new one for the new head. Operational limits: the collaborator-permission lookup (`gh api repos/.../collaborators/<login>/permission`) needs a token with push access, otherwise it returns 403 and the override is rejected (a `NOTE:` is written to stderr); at most 5 eligible override comments are checked per run (comments failing the head, missing-set, reason, identity or edit checks do not count toward the cap); logins may contain letters, digits, `-` and `_` (Enterprise Managed User logins are accepted); the login the verifier itself runs under counts as a pipeline identity and cannot approve; with no trusted `FORGE:BUILDER:COMPLETE`, the override must be newer than the latest trusted FORGE marker instead; and `/review-pr` refuses to merge any commit other than the exact head the override was bound to.

Limits: `Bot` trusts any GitHub App or bot able to comment on the repo, and `COLLABORATOR` includes read-level collaborators. Tighten with the two variables above if that is too broad. An earlier `FORGE_TRAIL_QG_SINCE` waives `QUALITY_GATE` for every build completed before it, so never derive it from untrusted input.

---

## Config Reading Conventions

ForgeDock commands use two accepted patterns for reading `forge.yaml`:

- **`yq` (standard)**: Simple field reads use `yq '.section.field // ""' forge.yaml 2>/dev/null || echo ""`. This is the canonical pattern used by the majority of commands (`cleanup`, `orchestrate`, `work-on/close`, etc.).
- **Python `yaml.safe_load` (complex extraction)**: Commands that need to extract many fields from optional nested sections in a single pass (e.g., `analytics`, `geo-audit`, `qa-sweep`) use a Python heredoc. This avoids chaining many `yq` calls and allows structured error messaging when optional sections are absent.

Do **not** mix the two patterns for the same block of variables (e.g., `yq` with Python fallback). If a command needs more than 5 fields from a deeply nested optional section, use Python. Otherwise, use `yq`.

---

## ConfigDraft Contract

`ConfigDraft` is the shared data structure emitted by `bin/init-detect.mjs` and consumed by the AI enrichment backends (`init-enrich`) and the annotated review renderer (`review-render`). It mirrors the required sections of `forge.yaml` at a per-field granularity, adding provenance and confidence metadata.

### Field shape

Every leaf value in a `ConfigDraft` is a **ConfigField** object:

```ts
{
  value:      string,            // The detected or inferred value
  confidence: "high" | "medium" | "low",  // How certain the detection was
  source:     string,            // Human-readable label for where the value came from
  why:        string,            // Plain-language explanation of why this value was chosen
}
```

**Confidence levels:**

| Level | Meaning |
|-------|---------|
| `"high"` | Verified from a concrete, unambiguous source (e.g., parsed from the git remote URL) |
| `"medium"` | Inferred from available signals; likely correct but not guaranteed (e.g., current branch name, name derived from repo slug) |
| `"low"` | Guessed default — no supporting evidence was found (e.g., no git remote, not a git repo) |

### ConfigDraft shape

```js
{
  project: {
    owner: ConfigField,   // GitHub org or username
    repo:  ConfigField,   // Repository name (without owner prefix)
    name:  ConfigField,   // Human-readable project name
  },
  paths: {
    root:         ConfigField,  // Absolute path to the project root
    worktreeBase: ConfigField,  // Absolute path to the git worktree base dir
  },
  branches: {
    default: ConfigField,  // Default branch (e.g. "main")
    staging: ConfigField,  // Staging branch for fast-lane PRs
  },
  meta: {
    remoteDetected: boolean,  // true iff a parseable git remote URL was found
  },
}
```

### Example output (high-confidence repo)

```js
{
  project: {
    owner: { value: "acme-org",    confidence: "high",   source: "git remote origin (SSH)",   why: "Parsed from SSH remote URL: git@github.com:acme-org/acme-platform.git" },
    repo:  { value: "acme-platform", confidence: "high",   source: "git remote origin (SSH)",   why: "Parsed from SSH remote URL: git@github.com:acme-org/acme-platform.git" },
    name:  { value: "Acme Platform", confidence: "medium", source: "derived from repo slug",     why: "Title-cased version of repo name 'acme-platform' (split on hyphens/underscores)" },
  },
  paths: {
    root:         { value: "/home/user/acme",                      confidence: "high", source: "process.cwd()", why: "Absolute path passed to detectConfig — the project root" },
    worktreeBase: { value: "/home/user/acme/.claude/worktrees",    confidence: "high", source: "derived from root", why: "Convention: {root}/.claude/worktrees" },
  },
  branches: {
    default: { value: "main",    confidence: "high",   source: "git symbolic-ref refs/remotes/origin/HEAD", why: "Remote HEAD points to main" },
    staging: { value: "staging", confidence: "high",   source: "git branch -r",                             why: "Found 'origin/staging' in the remote branch listing" },
  },
  meta: { remoteDetected: true },
}
```

### Producing a ConfigDraft

```js
import { detectConfig } from "./bin/init-detect.mjs";

const draft = await detectConfig(process.cwd());
// draft.project.owner.value  → "acme-org"
// draft.project.owner.confidence  → "high"
```

`detectConfig(cwd)` is the sole public API. It never throws — every error path produces a `low`-confidence default.

### Consuming a ConfigDraft

Downstream consumers read `field.value` for the raw value and `field.confidence` to decide how to handle it:

- **`init-enrich`** (AI enrichment): passes `low`- and `medium`-confidence fields to the selected AI backend (a local `claude` CLI when available, otherwise the Anthropic API with `ANTHROPIC_API_KEY`) to raise their confidence; leaves `high`-confidence fields untouched.
- **`review-render`** (TUI review screen): shows each field with its source and why; highlights `low`-confidence fields with a `# TODO(forgedock:<field>)` annotation in the generated YAML.

---

## SessionStart Hook Integration

ForgeDock does **not** write anything into your project's `CLAUDE.md` or `AGENTS.md`. Instead, `npx forgedock` registers a `SessionStart` hook in `~/.claude/settings.json` — a small script that runs at the start of every Claude Code session and prints ForgeDock's context straight to that session, without touching any file in your repo.

### How It Works

The hook resolves the current directory's state and reacts accordingly:

| State | Behavior |
|-------|----------|
| `managed-active` (`forge.yaml` present, not opted out) | Prints a summary of `forge.yaml` (project, repo, branches) plus the available pipeline commands |
| `managed-active`, no `forge.yaml` yet | Suggests running `npx forgedock init` |
| `managed-optedout` | Completely silent — no output |
| `unmanaged` | Prints a one-time, suppressible nudge to run `npx forgedock enable` |

The hook entry is registered idempotently: re-installing (`npx forgedock update`) will not duplicate it, and unrelated hooks or settings in `~/.claude/settings.json` are left untouched. If `settings.json` is malformed, the installer skips writing rather than risk corrupting it.

### Commands

| Command | Action |
|---------|--------|
| `npx forgedock` / `npx forgedock install` | Registers the SessionStart hook (along with installing commands and writing `forge.yaml`) |
| `npx forgedock update` | Re-registers the hook when the resolved source can be safely refreshed (relink only — does not touch `forge.yaml`) |
| `npx forgedock uninstall` | Removes the hook entry from `settings.json` |

### Opting Out

Per-directory, independent of the global hook registration. Each command acts on the current working directory — run it inside the project directory:

```bash
npx forgedock disable  # the current directory goes silent (managed-optedout)
npx forgedock enable   # re-activate the current directory
npx forgedock status   # show the current directory's resolved state
```

See [Per-Directory State Registry](#per-directory-state-registry) below for how opt-out state is tracked.

---

## Persisted Toolset Home (`~/.forge/`)

`npx`/`npm` never installs `forgedock` to a stable location on your machine — it resolves to wherever `npx`'s cache (or a global npm install, or a git clone) happens to physically live. Historically, `~/.claude/commands/` and the SessionStart hook's script path were symlinked **directly** from that ephemeral location. When npm/npx (or the OS) later evicted its cache, those symlinks silently dangled — Claude Code sessions stopped getting ForgeDock context with no error shown.

For npm/npx sources, every `npx forgedock` (or `npx forgedock update`) run copies ForgeDock's own installable payload into a stable, version-independent home:

```
~/.forge/
  bin/          — the same bin/ tree bundled with the resolved package (hooks, CLI entry points)
  commands/     — the slash-command specs (.md)
  scripts/      — the universal pipeline-agent scripts (classify-lane.sh, etc.)
  templates/    — scaffold templates (e.g. the demo repo)
  version       — plain-text file containing the source package's version (e.g. "1.7.2")
```

`~/.claude/commands/` symlinks and the SessionStart hook's baked-in script path are then built from **this** copy, not the original ephemeral source — so they keep working even after the npm/npx cache that originally served them is cleared.

### When It Runs

| Command | Behavior |
|---------|----------|
| `npx forgedock` / `npx forgedock install` | Copies the resolved package's payload into `~/.forge/` (content-compared — unchanged files are never rewritten) before linking commands, then links from `~/.forge/`, not the original source |
| `npx forgedock init` | Does not touch `~/.forge/` — `init` only writes `forge.yaml`, it never installs commands |
| `npx forgedock update` (npm/npx install) | Refreshes `~/.forge/` from whatever the currently-resolved package looks like, then relinks |
| `npx forgedock update` (git-clone install) | Updates and relinks a `main` checkout; a non-main checkout is left untouched and gets actionable guidance because the current source must remain the source used after the command returns |
| `npx forgedock doctor` | Reports the effective source path, version, and git branch, then reports `~/.forge/version` and confirms `~/.forge/{bin,commands,scripts,templates}` for npm installs |

The copy is idempotent: files whose content is already byte-identical are never rewritten, so steady-state re-runs are fast and don't generate false "updated" noise.

### The Git-Clone Exemption

If you run ForgeDock from a git clone (or a git worktree) of the repo itself — the development/self-hosted install mode — nothing is copied into `~/.forge/`. A git clone is already a stable, user-owned location; copying it into `~/.forge/` and linking commands from the copy instead of the clone would silently disconnect `git pull` (or `npx forgedock update`'s git branch) from what's actually linked into `~/.claude/commands/`. So:

- `~/.claude/commands/` continues to symlink directly from the clone, exactly as before this feature.
- `~/.forge/{bin,commands,scripts,templates}` correctly does **not** exist for this install mode — `npx forgedock doctor` treats that absence as healthy, not a warning.
- `npx forgedock update` never switches a non-main checkout to `main` and then restores it. That transient update would leave the next invocation running the old branch source, so the command reports the effective path, branch, and version and tells you to run from a main checkout instead.

### Not the Same as `~/.forge/{runs,index}`

`~/.forge/` also hosts two **unrelated, pre-existing** directories used by other parts of ForgeDock:

- `~/.forge/runs/` — durable engine run state for `npx forgedock run-issue` / `resume-stalled` (see `bin/engine.mjs`).
- `~/.forge/index/` — the `recall` knowledge index (see `bin/recall.mjs`, `docs/FORGE-PROTOCOL.md`).

These are **engine data**, not the toolset itself, and this feature does not read, write, or otherwise change them. `~/.forge/{bin,commands,scripts,templates,version}` (this section) and `~/.forge/{runs,index}` (engine data) are unrelated siblings that merely happen to live under the same `~/.forge/` root — don't conflate the two when reading `~/.forge/`'s contents.

---

## Per-Directory State Registry

ForgeDock tracks per-directory opt-out state in a central registry file on the local machine.

### Registry File Location

```
~/.claude/forgedock/registry.json
```

The directory (`~/.claude/forgedock/`) is created automatically on first use with mode `0700`. The file is never committed to version control — it is per-user, per-machine state.

### Registry Schema

```json
{
  "version": 1,
  "optedOut": {
    "/absolute/path/to/project": { "at": "2026-06-09T12:00:00.000Z" }
  },
  "nudgeSeen": {
    "/absolute/path/to/project": { "at": "2026-06-09T12:00:00.000Z" }
  }
}
```

| Field | Type | Description |
|-------|------|-------------|
| `version` | number | Schema version — currently `1` |
| `optedOut` | object | Map of absolute directory paths to opt-out metadata |
| `optedOut[path].at` | string | ISO-8601 timestamp of when the opt-out was recorded |
| `nudgeSeen` | object | Map of absolute directory paths where the one-time "Enable ForgeDock here?" nudge has already been shown |
| `nudgeSeen[path].at` | string | ISO-8601 timestamp of when the nudge was shown for this directory |

### State Resolution

The `registry` module resolves one of three states for any directory:

| State | Meaning |
|-------|---------|
| `managed-active` | Directory contains `forge.yaml` or `.forgedock` and is **not** opted out — ForgeDock is active here |
| `managed-optedout` | Directory has a managed marker but the user has explicitly opted out — ForgeDock stays silent |
| `unmanaged` | No `forge.yaml` or `.forgedock` marker found — ForgeDock has no presence here |

**Opt-out wins over managed**: if a directory contains `forge.yaml` but its path is listed in `optedOut`, the state is `managed-optedout`.

### Failure Behaviour

A missing or corrupt `registry.json` is treated as an empty opt-out set. The registry always fails open — it never throws and never blocks a Claude Code session.

### Downgrade Behaviour

Registry keys are the **real path** of a directory (resolved via `realpathSync`) rather than the raw `resolve()` path. This has been the case since v1.0.x (PR #467, which fixed symlinked-directory key mismatches).

If you downgrade to a build older than PR #467 **and** your project is accessed via a symlinked directory path, the older build looks up registry entries using the pre-symlink `resolve()`-only key form. It will not find entries written by the newer build's real-path keys. The practical effect is benign:

- Opt-outs set on the newer build briefly stop applying for one session.
- The one-time "Enable ForgeDock here?" nudge may reappear once.
- No data is lost. No crash. Fail-open behaviour holds throughout.

**Recovery**: after downgrading, re-apply your opt-out with the older build (run inside the project directory):

```bash
npx forgedock disable
```

This re-writes the entry under the key form the older build expects.

### Managing Opt-Out State

Use the `forgedock enable` and `forgedock disable` commands to add or remove a directory from the opt-out set. Each command acts on the current working directory by default — run it inside the project directory, or pass an explicit path:

```bash
npx forgedock enable [dir]   # Remove a directory from the opt-out set (default: cwd)
npx forgedock disable [dir]  # Add a directory to the opt-out set (default: cwd)
npx forgedock status [dir]   # Show a directory's resolved state (default: cwd)
```

---

## Install Receipt

ForgeDock writes a machine-readable receipt of what the last install or update actually did, so debugging drift (wrong commands installed, wrong tier, stale hooks) can start from a recorded fact instead of re-deriving state from scratch.

### Receipt File Location

```
~/.forge/install-receipt.json
```

The directory (`~/.forge/`) is created automatically on first write with `mkdir(..., { recursive: true })`. The file is never committed to version control — it is per-user, per-machine state.

### When It's Written

- After every successful `npx forgedock install` (end of the onboarding journey, right after the "Forged." celebration screen).
- After every successful `npx forgedock update` — the main git-clone branch and npm branch route through the same repair step (`relinkAndHint()`), so the receipt is refreshed either way. A non-main git-clone advisory intentionally does not relink or rewrite the receipt.

The write is best-effort and never blocks or fails the install/update it records: any error (permission denied, disk full, unusual `FORGE_HOME` layout) degrades silently to a no-op, matching the fail-open contract already used by the command-manifest and hook-registration steps.

### Receipt Schema

```json
{
  "schemaVersion": 1,
  "timestamp": "2026-07-10T12:00:00.000Z",
  "forgedockVersion": "1.1.6",
  "installMode": "npm",
  "forgeHome": "/home/user/.npm/_npx/abc123/node_modules/forgedock",
  "cwd": "/home/user/projects/my-repo",
  "platform": {
    "platform": "linux",
    "platformLabel": "Linux",
    "isWSL": false,
    "wslDistro": null,
    "shell": "bash"
  },
  "tier": "core",
  "commands": {
    "count": 42,
    "list": ["work-on", "review-pr", "quality-gate", "orchestrate/phase-1-resolve"]
  },
  "hooks": {
    "sessionStart": "registered",
    "preToolUse": "registered",
    "subagentStopEnforce": null
  },
  "forgeYaml": {
    "present": true,
    "validShape": true
  }
}
```

| Field | Type | Description |
|-------|------|--------------|
| `schemaVersion` | number | Schema version — currently `1` |
| `timestamp` | string | ISO-8601 timestamp of this install/update |
| `forgedockVersion` | string | `version` field from `{forgeHome}/package.json` (empty string if unreadable) |
| `installMode` | `"npm"` \| `"git-clone"` | Detected from whether `{forgeHome}/.git` exists — same predicate `update()` already uses to choose its update strategy |
| `forgeHome` | string | Absolute path to the ForgeDock package install (`FORGE_HOME`) |
| `cwd` | string | Absolute path to the project directory the command was run in |
| `platform` | object | `detectEnvironment()`'s output — platform, human label, WSL status/distro, detected shell |
| `tier` | `"core"` \| `"extras"` | Whether `--extras` was passed (opt-in command tier, see `install: extras` frontmatter) |
| `commands` | object | `count` and `list` (relative slash-command names) of everything installed for the resolved tier, sourced from `findMarkdownFiles()` — never a separately maintained list |
| `hooks.sessionStart` | string \| null | SessionStart hook registration status (`"registered"`, `"already"`, `"skipped-malformed"`) |
| `hooks.preToolUse` | string \| null | PreToolUse enforcement hook status, or `null` when the installed Claude Code version doesn't support it |
| `hooks.subagentStopEnforce` | string \| null | Cleanup status of the (retired) SubagentStop enforce hook |
| `forgeYaml.present` | boolean | Whether `forge.yaml` exists in `cwd` at receipt-write time |
| `forgeYaml.validShape` | boolean | Whether `forge.yaml` contains the 3 required top-level sections (`project:`, `paths:`, `branches:`) — a lightweight regex check, not a full YAML parse |

### No PII or Secrets

The receipt never contains `process.env` values, GitHub tokens, API keys, or the contents of `forge.yaml` — only the `present`/`validShape` booleans above. Absolute filesystem paths (`forgeHome`, `cwd`) are included for drift debugging; they typically contain the OS username but nothing more sensitive, consistent with other per-machine ForgeDock state (e.g. `registry.json`'s path-keyed entries, see above).

### Reading the Receipt

```bash
cat ~/.forge/install-receipt.json
```

There is no CLI subcommand to read it yet — `doctor()` reading the receipt to detect drift is a deliberately deferred stretch goal, not part of this feature.

---

## Pool agent cache volumes

Keys of the pool agent's JSON config (`forgedock pool agent`), not of `forge.yaml`. Each repo's `cs-cache-<slug>` volume holds the package caches, depcache, env snapshots, git mirror and lane work dirs. The agent labels the volumes it creates `computeshare.cache=1` (`forgedock gc` reports them and never reclaims them) and sweeps them every `cache_sweep_interval_s`.

| Key | Type | Default | Description |
|---|---|---|---|
| `cache_max_age_days` | number | `14` | uv/npm/pip/poetry cache files, depcache and env snapshot entries older than this are deleted by the agent sweep, with no launch needed. The pnpm store is pruned and the git mirror gets `git gc --auto`. |
| `cache_max_gb` | number | unset (no cap) | Per-volume cap. A volume over it is shrunk oldest-first below the cap; work dirs of live sandboxes are never touched. |
| `depcache_max_gb` | number | `40` | Per-repo cap on `forge-depcache/<repo>/` (#5901). Over it, the least recently used snapshots (by their `last-used` stamp) are deleted, never one held by a lane lock. `/capacity` `cache_volumes.<volume>.depcache_gb` and `forgedock pool status` show each repo's depcache size. Snapshots are also aged out per snapshot by `cache_max_age_days`. |
| `cache_idle_days` | number | `30` | A volume with no launch for this long and no referencing sandbox is removed. Evicted only when its last use is known (`/cache/.last-used`, written by the lane entrypoint). |
| `cache_never_evict` | list of volume names | `[]` | Volumes (e.g. `cs-cache-marcode`) that are never swept or evicted. |
| `cache_sweep_interval_s` | number | `3600` | Gap between cache sweeps. |
| `lane_disk_cap_gb` | number | unset (off) | #5884: hard cap on lane disk (running sandbox dirs plus this agent's cache volumes). At or over it `/capacity` has `disk_capped: true`, a launch answers 503 `pool.disk_cap` (a deferral, like `pool.disk_low`) and the router skips the host. Fields `lane_disk_used_gb`/`lane_disk_cap_gb` appear only when set. A dedicated volume or filesystem quota for the state dir is the operator-side alternative. |
| `disk_prune_at_pct` | number | `80` | From this percent of `lane_disk_cap_gb` each reap prunes this agent's stopped containers, dangling images and build cache (agent-label scoped) and runs a cache sweep, then an fstrim. |
| `fstrim_interval_s` | number | `21600` | Gap between best-effort `fstrim -v <docker root>` runs (`sudo -n` when not root; failure is a log line). `fstrim: false` turns it off; `docker_root` overrides `/var/lib/docker`. The WSL installer also enables `sparseVhd=true` in `.wslconfig` and `wsl --manage --set-sparse`. |
| `agent_id` | string | `name` | Owner label `computeshare.agent=<id>` (#5881) on every container and cache volume the agent creates. Reap, orphan-volume, cache and work sweeps touch only resources carrying it, so a co-resident agent or foreign containers are never removed; unlabelled pre-existing items are left alone. Setting it also namespaces the cache volume (`cs-cache-<id>-<key>`) so two agents never share `/cache/work`. |

A failed or timed-out sweep (10 min limit) shows as `cache_sweep_error` in the agent's `/capacity`, next to `cache_volumes` (size per volume).

## Complete Example

See [`forge.yaml.example`](../forge.yaml.example) at the repository root for a fully annotated example covering all sections.

---

## Router config: `ci_autoscale` (#5695)

Keys of the pool router's own config file (not `forge.yaml`). The CI runner autoscaler is off by default.

| Key | Default | Meaning |
|---|---|---|
| `ci_autoscale.enabled` | `false` | Turns on `POST /ci/workflow-job` tracking and the reconcile at the end of each router tick. |
| `ci_autoscale.dry_run` | `false` | Log every scale decision with its inputs but start or stop nothing. |
| `ci_autoscale.repo` | unset | `owner/name` for `generate-jitconfig` and the jobs-API poll fallback. Uses the router host's `gh auth token`. |
| `ci_autoscale.poll_s` | `300` | Seconds between jobs-API polls. |
| `ci_autoscale.runner_group_id` | `1` | Runner group for JIT runners. |
| `ci_autoscale.labels.<label>` | none | One entry per runner label: `min` (warm runners), `max` (hard cap), `size` `{cpus, mem_gb}` (default 1 / 2). Only jobs carrying a configured label are counted. |
| `ci_autoscale.floors.mem_available_gb` | `3` | MemAvailable that must remain after the reservation. |
| `ci_autoscale.floors.load_per_cpu` | `0.8` | Load per vCPU allowed after the reservation. |
| `ci_autoscale.floors.net_rx_mbps_max` | unset | Refuse starts above this host RX rate (deploy exempt). |
| `ci_autoscale.lane_floor` | `{cpus: 2, mem_gb: 3}` | Pool `cpus_free`/`mem_free_gb` left for lanes. CI never takes it. |
| `ci_autoscale.windows` | `[]` | `[{from, to, why}]` ISO times: no starts or stops inside a window. |

Priority is deploy label > release branch (`release/*`, `hotfix/*`) > lanes > ordinary PR CI. Agent config `runner_image` (default `ghcr.io/actions/actions-runner:latest`) is the runner container image.
