# Model Fallback Contract

<!-- toc -->
- [Tier ladder](#tier-ladder)
- [Prefs knob](#prefs-knob)
- [Turning the fable rung off](#turning-the-fable-rung-off)
- [Triggers (checked in this order)](#triggers-checked-in-this-order)
- [Logging](#logging)
- [Routing at dispatch](#routing-at-dispatch)
- [Non-goals](#non-goals)
- [Codex CLI](#codex-cli)
<!-- /toc -->

> Contract last revised in **v20.25.0** (current Claude generation; Copilot CLI model ids per rung). The version tag here tracks the last substantive change to this contract, not the pipeline release.

Personas route to the top available intelligence tier they declare in
`preferredModel`. That tier can be quota-limited or temporarily unavailable.
This contract defines when and how the orchestrator falls back, deterministically,
without ever editing persona files at runtime.

> **Fable is the top tier.** The `fable` rung resolves to `claude-fable-5-2`.
> Architect (`ios/android/backend-architect`), Reviewer-1 (`code-reviewer`),
> and triage personas declare `preferredModel: fable` - the deepest-reasoning
> roles. **If Fable is unavailable, the first fallback is opus (`claude-opus-5-5`).**
> Security and other `preferredModel: opus` personas keep opus as their top tier.
> The `premiumTierUntil` date gate stays in the contract as a generic mechanism
> for any plan-window-limited premium tier.

## Tier ladder

```
fable -> opus -> sonnet -> haiku
```

The orchestrator walks **one step down per trigger** from whichever tier a
persona prefers: a `fable` persona degrades `fable -> opus` first, then
`opus -> sonnet`, then `sonnet -> haiku`; an `opus` persona starts at
`opus -> sonnet`. So a Fable outage transparently promotes Opus into the
architect/reviewer roles with no file edits.

### Rung names are the contract; model IDs are not

Personas and dispatch read the **rung** (`fable`, `opus`, `sonnet`, `haiku`). The wire
model ID each rung resolves to lives in exactly two places: `scripts/cost-table.json`
(`prices.<rung>.modelId`) and the per-host reviewer table in
`phases/phase-3-review.md`. A generation move edits those; it never renames a rung and
never touches a persona file.

Current resolution: `fable` -> `claude-fable-5-2`, `opus` -> `claude-opus-5-5`,
`sonnet` -> `claude-sonnet-5-5`, `haiku` -> `claude-haiku-5-5`. These are the Claude Code
wire IDs. Copilot CLI dispatches only the models `copilot help config` lists, with dotted
names, so its column in the reviewer table names those (`claude-opus-4.7`,
`claude-sonnet-4.6`), recorded per rung as `copilotModelId` in the cost table (haiku:
`claude-haiku-4.5`). The fable rung has none and is not offered on Copilot CLI; a persona
that prefers it dispatches the opus rung there.

**Rate limits do not follow the rung.** A new generation can draw on a rate-limit pool
separate from the previous one, so a generation move does not inherit the previous
generation's headroom. Budget-ceiling downgrades below are unaffected - they read the
cost ledger, not the provider's quota - but a 429 on the opus rung after a generation
move is a limits question, not a fallback-contract question.

### Behavioural re-tuning the generation move implies

The pipeline's reviewer and dev prompts were tuned against the previous generation.
Three shifts on the current opus rung are worth knowing when reading a run that looks
different rather than broken, and none of them are bugs in this contract:

- **Longer user-facing output.** Effort is not the lever; prompt-level conciseness is.
  Phase 5 report length and reviewer prose are where this shows.
- **Self-verification without being asked.** Explicit "double-check your work"
  scaffolding now causes over-verification rather than preventing under-verification.
  Phase 2's exit gates already carry that load.
- **Readier subagent delegation.** The previous generation under-reached and needed
  encouragement; this one does not. Phase 1's parallel scan and Phase 3's reviewer
  panel are already bounded by explicit counts, which is the right shape - keep them
  bounded rather than adding "delegate more" guidance.

One step down per trigger, walking the ladder until a tier dispatches or the
floor (`haiku`) is reached. `haiku` is the last-resort floor: a run that reaches
it is heavily degraded but still makes progress instead of hard-halting because
two tiers happened to be unavailable at once. A dispatch error at the floor is a
genuine outage  -  it falls through to the normal phase-error path (pause ->
resume), since there is nothing left to step down to. The mechanism is the existing per-dispatch override:
set `PHASE_MODEL_OVERRIDE=<fallback>` before dispatch (the orchestrator exports
`CLAUDE_CODE_SUBAGENT_MODEL` on Claude Code, or passes `--model` on Copilot
CLI). Persona frontmatter stays the source of truth for the _preferred_ model;
the override is per-dispatch and leaves files untouched.

## Prefs knob

`prefs.global.modelFallback` (template default below; absent knob = `enabled: true`
with no date gate; an absent `modelFallback.floorModel` defaults to `haiku`, so installs that
predate this field still get the second downgrade step):

```json
"modelFallback": {
  "enabled": true,
  "premiumTierUntil": null,
  "fallbackModel": "sonnet",
  "floorModel": "haiku",
  "fableEnabled": false,
  "onDispatchError": true
}
```

| Field | Meaning |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled` | Master switch. `false` = always dispatch the persona's `preferredModel`, fail loudly on error. |
| `modelFallback.fableEnabled` | Whether the `fable` rung exists at all on Claude Code. **Ships `false`.** `false` starts every `preferredModel: fable` persona on `opus`; `/multi-agent:fable-on` opts the top rung back in and `/multi-agent:fable-off` takes it out. A cost control that defaults to on is not a control. See "Turning the fable rung off" below. |
| `premiumTierUntil` | ISO date (`YYYY-MM-DD`) or `null`. When set and today is **after** this date, every `preferredModel` dispatch is downgraded to `fallbackModel` unless the user re-confirms (see Date gate). Use when the top tier is included in a plan only until a known date. |
| `fallbackModel` | Target of the first downgrade step. Default `sonnet` (the next tier below opus). |
| `modelFallback.floorModel` | Last-resort tier when `fallbackModel` also fails to dispatch. Default `haiku`. Set to the same value as `fallbackModel` (or `null`) to disable the second step and halt after one downgrade. |
| `onDispatchError` | When `true`, a failed top-tier dispatch (model unavailable / quota / 4xx on model id) retries once on `fallbackModel`, and a failed `fallbackModel` dispatch retries once on `floorModel`, instead of aborting the phase. |

## Turning the fable rung off

`prefs.global.modelFallback.fableEnabled: false` is a **cost control, not a fallback**. The other three
triggers below react to something going wrong; this one asserts up front that a
rung is not in play, so there is no dispatch attempt, no error, and nothing to
recover from. That distinction is why it is checked before them.

Scope is Claude Code only, and the reason differs per host:

| Host | Effect of `fableEnabled: false` | Why |
| ----------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Claude Code | Every `preferredModel: fable` persona (`ios/android/backend-architect`, `code-reviewer`, triage) starts on `opus` | This is the only host where the rung means Fable 5.2 |
| Copilot CLI | none | Fable is not offered there; its personas never sat on this rung |
| Codex CLI | none, deliberately | The `fable` rung there means `gpt-5.6 @ xhigh`, a different model on a different account. Switching it off from a knob named after an Anthropic model would surprise a Codex user, so it does not |

**Phase 3 loses a reviewer, and says so.** Reviewer 1 lands on `opus`, which
Reviewer 2 already holds. Dispatching one model twice is not cross-model review,
so the Claude Code panel collapses to two reviewers (`opus` + `sonnet`),
`consensus.reviewerCount` records `2`, and the `unverified` verdict rule matters
more, not less: two Anthropic models agreeing on a judgment call was already weak
evidence, and there is now one fewer of them. Triage also runs on `opus`, which
makes it the same model as Reviewer 1; the Step 3 anonymisation requirement
already covers that case and is not optional here.

**Installed agents follow the switch.** Five personas declare
`preferredModel: fable` (code-reviewer, plan-critic, and the iOS, Android and
backend architects). A dispatch the router resolves passes its model explicitly,
but an agent spawned without one runs on its frontmatter `model:`. So the
installed copies are written from `fableEnabled`: `fable` while it is on, `opus`
while it is off. `model-rung.sh` re-applies them on every flip and the installer
on every install; sources keep `model: fable`, so `lint-personas.mjs` still holds
`model === preferredModel` there. A `--symlink` install links the source tree and
is left alone.

**Commands without Phase 0 resolve it themselves.** `/multi-agent:review`,
`/multi-agent:review-analysis` and the untracked-branch tail of
`/multi-agent:resume` dispatch reviewers and triage without a Phase 0 Step 0, so
each asks `lib/model-dispatch.sh subagent --persona <p> --default fable` for its
fable slots before any dispatch. The router applies this switch to the caller's
default on every path, routing on or off, so the answer is `opus` while the rung
is off. `smoke-model-dispatch.sh` holds both halves: the router's answer, and
that every command naming a Fable reviewer asks it.

**Cost accounting.** `prefs.global.costBudget.pricingModel` defaults to `fable` to
keep the estimate an upper bound. With the rung off, that default prices every
call above what it can cost and trips the budget ceiling early, which then
triggers a downgrade nobody needed. So the two keys move together:
`/multi-agent:fable-on` writes `fableEnabled: true` with `pricingModel: fable`,
`/multi-agent:fable-off` writes `false` with `opus`, both through
`lib/model-rung.sh` as one write or none. `/multi-agent:fable-status` reports the
pair and prints `MISMATCH` when a hand edit split it. Copilot CLI spells the
commands `/multi-agent-fable-on`, `/multi-agent-fable-off` and
`/multi-agent-fable-status`; Codex CLI reaches them as `multi-agent fable-on`,
`multi-agent fable-off` and `multi-agent fable-status` through its router skill.
On both they record the value and, per the host table above, change no dispatch:
`fable-off` prints that the reviewer panel is unchanged there instead of the
Claude Code panel change.

No log line is emitted per dispatch for this: it is a configured absence, not a
degrade event, and one line per persona per run would be noise. Phase 0 Step 0
prints it once instead:
`INFO: fable rung disabled by prefs; architect/reviewer/triage personas dispatch on opus (Phase 3 panel = 2 reviewers).`

## Triggers (checked in this order)

0. **Fable rung disabled (Phase 0 Step 0, once per run).** If
   `fableEnabled: false`, resolve every `preferredModel: fable` persona to `opus`
   for the whole run before any other trigger is considered. A later dispatch
   error then walks `opus -> sonnet -> haiku` from there, exactly as it does for
   a persona that declared `opus` in the first place.
1. **Date gate (Phase 0 Step 0, once per run).** If `premiumTierUntil` is set and
   in the past, print one line:
   `WARN: premium tier plan window ended <date>; preferredModel personas will dispatch on <fallbackModel>. Set prefs.global.modelFallback.premiumTierUntil to null to keep the top tier on usage credits.`
   Then export the override for every `preferredModel` persona this run. Interactive modes
   may instead ask once (`Keep top tier (usage credits) / Fall back to <model>`);
   autopilot never asks - it falls back, logs, and lists the fallback in `state.decisions[]`
   (`features/autopilot-decisions.md`).
2. **Dispatch error (per dispatch).** On a model-unavailable / quota error from a
   top-tier dispatch and `onDispatchError: true`: retry the same persona once with
   `PHASE_MODEL_OVERRIDE=<fallbackModel>`. If that retry also fails with a dispatch
   error and `floorModel` is set and differs from `fallbackModel`, retry once more
   with `PHASE_MODEL_OVERRIDE=<floorModel>`. A failure at the floor (or when no
   floor is configured) falls through to the normal phase-error path (pause ->
   resume). Never silent-skip the persona. Each downgrade emits its own
   `model_fallback` metric line so a two-step degrade is visible in Phase 5.
3. **Cost budget ceiling (existing gate).** When `cost-budget-check.mjs` exits 11
   (exceeded) mid-run, the run already pauses per the cost-budget contract; on
   user-approved continue, `preferredModel` personas downgrade to `fallbackModel` for the
   remainder of the run.

## Logging

Every fallback emits one `log-metric.sh` line (`metric: model_fallback`,
attributes: `persona`, `from`, `to`, `trigger: date-gate|dispatch-error|budget`)
and one agent-log line so Phase 5 reports show which phases ran degraded.
The cost ledger prices the dispatch at the model actually used (the tracker's
per-phase `model` field already carries the override).

## Routing at dispatch

How a dispatch hands a child its model differs per host, and the registry
(`schemas/hosts.json`) holds the mapping. This table is generated from it:

<!-- hosts:dispatch -->
| Host | Model | Effort | Required | Children at once | Personas |
|---|---|---|---|---|---|
| Claude Code | export `CLAUDE_CODE_SUBAGENT_MODEL` | - | - | no stated ceiling | `.claude/agents/*.md` |
| Copilot CLI | pass `--model` | - | - | no stated ceiling | `.copilot/agents/*.md` |
| Codex CLI | `model` on the spawn call | `reasoning_effort` | `fork_turns: none` | 3 | `.codex/agents/*.toml` |
| Local LLM | `model` on the spawn call | - | `fork_turns: none` | 1 | `.codex-local/agents/*.toml` |
<!-- /hosts -->

`$HOME/.claude/lib/model-dispatch.sh` turns `prefs.global.modelRouting` into a
rung. Three call sites ask it: the subagent dispatch contract in
`skills/shared/core/multi-agent/SKILL.md`, `bulk-read.sh`, and the `delegate`
call site for simple text tasks (`features/free-models.md`).

Routing is consulted only when the phase named no model. A per-dispatch
`PHASE_MODEL_OVERRIDE` is a decision the phase made for a reason - Phase 3 sets
Reviewer 3 to sonnet so the three reviewers disagree - and a policy able to
overrule it would turn a deliberate choice into a suggestion.

Two limits are enforced by the script rather than written here and hoped for:

- **A rule may not turn the fable rung on.** With `modelFallback.fableEnabled`
  false, a rule preferring `fable` falls past it to the next rung. Otherwise
  `/multi-agent:fable-off` would have a second door.
- **A rung this host does not offer is refused.** The preferences file is
  shared across every CLI on the machine, so a rule naming a rung only one of
  them carries is a normal thing for the router to find. It answers from the
  host it is installed under: a rung absent from that host's ladder, or one
  whose model belongs to a provider the host does not dispatch, is skipped and
  the rule's next rung answers, with the reason on stderr.
- **`free` only where the pipeline makes the call, and only when switched on.**
  The `free` rung (provider `free-chain`) answers at `bulk-read` and `delegate`
  while `modelRouting.free.enabled` is true (`route-on --free`), ahead of the
  matched rule's rungs. Its callers keep their own default as the fallback,
  because the toolkit answers `ESCALATE_TO_CLAUDE` whenever no free answer
  survives verification. A rung priced for a provider this host does not
  dispatch is refused everywhere: no call site here speaks it.

Strategies change the order of the candidate rungs, never the set: `task-fit`
tries the cheapest first by `cost-table.json` price, and `cost-ceiling` does the
same once `cost-budget-check.mjs` reports the run at the warn threshold of
`budgetCeilingUsd`. `recordDecisions: false` is honoured; `true` (the default)
logs each decision as `model_routing.decision`.

**Learned order (`modelRouting.learned.enabled`, ships false).** After the
strategy, `route-learn.mjs choose` may reorder the same candidates from a
promoted policy; the decision's reason then ends in `learned`. The loop:

1. `route-learn.mjs ingest --state <agent-state.json>` at the end of a run
   turns each `model_routing.decision` it logged into an outcome row for its
   bucket (call site, task kind, complexity band from `--complexity`) and rung.
   The reward is 0 when any gate's latest verdict failed, else
   `1 / (1 + first-round blockers + still-present findings + rework rounds)`.
   A model's own report never enters it, and a row with no gate or review
   signal is refused.
2. `route-learn.mjs promote` fits per-bucket Beta posteriors (older outcomes
   weighted down by `halfLifeDays`), calibrates them with isotonic regression,
   and replaces the policy only when it beats the current one by `margin` in
   Brier score on the newest `holdout` fraction (at least `minRows` rows).
   The old policy is kept as `policy.json.bak`.
3. `choose` draws one Thompson sample per rung, seeded by task id so the same
   task gets the same order, and tries the cheapest rung whose draw clears
   `target` first. Until two candidates have `minSamples` outcomes the rule's
   order stands; a rung whose last three outcomes scored 0 goes last on nine
   draws in ten.

The two limits above still hold on a learned order: the fable switch is
checked after it, and a rung this host does not offer is still refused.

The script never fails and never returns an empty rung: a missing preferences
file, a missing `jq`, unparseable JSON, an out-of-scope call site and a rung
absent from `cost-table.json` all return the caller's default and exit 0. A
router that can die would turn every call site into a place the run can die, for
a feature that ships disabled.

`cost-table.json` rows carry a `provider`, which is what tells the two layers
apart. `smoke-model-dispatch.sh` drives the script and also asserts that the call
sites invoke it: a correct router nothing calls is the same outage with
better internals.

## Non-goals

- No automatic re-upgrade mid-run (a run that fell back stays fallen back -
  deterministic over clever). Rework escalation (`features/rework-escalation.md`)
  moves one rework dispatch up a rung and refuses to on a run that fell back.
- No edits to `pipeline/agents/*.md` at runtime; frontmatter is install-time
  configuration only.
- Copilot CLI reviewer set is out of scope: Copilot CLI pins its own three
  reviewer models (GPT-5.4 + Opus + Sonnet - Fable is not offered there) and
  does not use this persona ladder. Only Claude Code dispatches Reviewer-1 on
  Fable.

## Codex CLI

Codex offers no Anthropic models, so the tier names map onto OpenAI models plus a
reasoning effort - effort carries the depth distinction that the model id carries
on Claude Code. The map is applied at install time by
`install/_codex-agents.mjs`, which writes `model` + `model_reasoning_effort` into
each `~/.codex/agents/<persona>.toml`:

| Tier | Codex model | Effort |
| -------- | --------------- | -------- |
| `fable` | `gpt-5.6` | `xhigh` |
| `opus` | `gpt-5.6` | `high` |
| `sonnet` | `gpt-5.4` | `medium` |
| `haiku` | `gpt-5.6-terra` | `low` |

This table is the persona default per tier. The Phase 3 review panel overrides it per slot (`phases/phase-3-review.md` Step 2): Reviewer 2 runs `gpt-5.4` @ `high` and Reviewer 3 runs `gpt-5.6` @ `medium`, so the panel buys its diversity from effort and one model change rather than from the tier ladder. `test/codex-model-tables.test.mjs` holds this table to `CODEX_TIER_MAP` and the panel tables to each other.

Ladder on Codex: `gpt-5.6 @ xhigh -> gpt-5.6 @ high -> gpt-5.4 -> gpt-5.6-terra`.
The first step down lowers effort rather than switching model, which is the
cheapest useful degradation when the top tier is rate-limited rather than
unavailable.

**Per-dispatch override on Codex** goes through `spawn_agent`, and it MUST pass
`fork_turns: "none"` (or a positive integer). A full-history fork inherits the
parent model and reasoning effort and silently discards the override, so a
fallback that omits it appears to apply while changing nothing.

The three model ids above live in exactly three places - this table,
`pipeline/scripts/cost-table.json`, and the Phase 3 reviewer matrix - so an OpenAI
rename is a three-file change.
