diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 038fbe0..9e0a1af 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1470,3 +1470,12 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Accepted risks**: `cc.sh` keeps `set -a; . ~/.claude/.env` (all secrets in the claude env, as `dtach_claude` did); `deniedMcpServers` union = `cc x web` on a `dev` project keeps the connectors denied (`set web` in the project fixes it). - **Branch**: feature/phase5-profiles-packs; spec docs/superpowers/specs/2026-11-01-phase5-profiles-packs-design.md; contract .claude/tasks/contracts/2026-11-01-phase5-profiles-packs-1300.md. Supersedes [[BDR-030]]. + +## BDR-135 — model-router askTier: consent before Fable, tier-name choice stamped on turn and run slots, per-type spawn memory [accepted] (2026-11-02) +- **Context**: user ask 2026-11-02: model-router must ask before routing main or a rowed spawn onto Fable. feature/router-ask-tier, contract `.claude/tasks/contracts/2026-11-02-router-ask-tier-1434.md`, plan r3 after 3 lenses + confirmation. +- **Decision**: `routing.json` `askTier` (`best` | `false`, machine override wins, absent = best, missing file = off, bad value logged once + best). Ask fires at route EVENTS only (typed or model-loaded rowed skill, main `route` tool phase, typed `/route `, rowed spawn from main), never in turn.step (LRN-231). Guards: router on, not paused, cur not head, `asking` free, slot unstamped, slot tier = best, slot = effective `mainModelSlot`, surfaces non-empty, then real decision via `snapshot`/`decideMain` lands on head. Options `Fable` · `Opus instead (big tier)` (dropped when opus down) · `Stop asking this session`. Choice = TIER NAME on `Routed.tierChoice` (`best` | `big`), stamped on turn slot AND run slot; inherited only same-tier, non-typed writes (typed skill = new span, work route never inherits). `big` resolves minus head (opus, else sonnet, head last), phase effort (no stand-in notch). Spawns: one answer per agent type per session (`State.tierSpawn`), stored answer applied before any guard. `/route ask-tier on|off` via `flagCommand` (shared with `ask`); `/route show` `ask-tier:`. Nothing written to `confirmed`. +- **Why**: Fable credits burn on best-tier rows (BLK-030/031); user wants consent per span, not per spawn (audit gates respawn verifier + security-auditor each loop). +- **Alternatives rejected**: stand-in rewrite (`isStandIn` keyed on held head, would print "stands in for" on a user pick); rebuilt decision from parts (diverges from `decideMain`: sticky slot, mainUpgrade off, cap); per-spawn ask (blocking dialog, no timeout, stalls unattended orchestration); generated labels from aliases (contract fixes the exact words); any tier name in `askTier`; `{ model: alias }` on spawn (explicit model bypasses breaker). +- **Residual (user-accepted, F)**: Fable held or cap exceeded at the route event → no question, slot unstamped; hold lapse / compaction → next step upgrades unasked (breaker behaviour today). `/model ` while any dialog holds `asking` falls to native (pre-existing, BDR-126). +- **Gates**: r1 correctness FATAL(6) robustness FATAL(6) simplicity CONCERNS(4) → r2 → confirmation CONCERNS(6) → r3; feater DONE 28 TIER tests (590 → 618); GATE 0 MET 5/5; verifier CONFORME 11/11 first pass; security PASS (1 LOW fixed: `clean(skill)`). Commits 9a24a62, docs 789fd00. +- **Refs**: [[BDR-116]], [[BDR-123]], [[BLK-032]], [[LRN-231]], [[LRN-242]], [[LRN-254]]. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 0355323..82e4dbf 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -426,3 +426,10 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Result**: r1 FATAL(11)/FATAL(10)/CONCERNS(5): BLOCKER = plan written on a stale tree (profile backend live); 30 jq per statusline refresh; settings.json procedure that would have discarded user writes; test precedence inverted; doctor abort under pipefail; worktree incompatibility. Confirmation on r2: 2 more BLOCKERs (keep list dropped the tracked `skills/model-router` link; census matched itself). All fixed before Task 1. Execution then needed 4 fix rounds (gates/reviews), none on those aspects. - **Anomalies**: the simplicity lens duplicated two robustness findings; the confirmation pass still found BLOCKERs, so one pass is the floor, not the ceiling. - **Action**: keep the 3+1 shape for plans over ~1000 lines; add "live state verified at Task 0" to the plan template. + +## EVAL-055 — BDR-125 phases 0/1/4a/5 re-verified: gates, SHAs, engine; 0 code defect, 5 stale TODO ticks [keep] (2026-11-02) +- **Checked**: BDR-125 phases ticked in TODO (pre-0, 0, 0b, 4a + minors, 1 + follow-ups, 5) vs original ask (TODO entry, contract REQUEST/CLARIFICATIONS, BDR). +- **Method**: `gates.sh run` on 5 contracts; 22 in-repo SHAs `merge-base --is-ancestor develop`; 9 cross-repo SHAs `cat-file -e` + `branch --contains` in zenquality/game/angelscar356/faunosteo/robin_petier; `reconcile.sh` engine (`reconcile_blk_open`, deferrals, contradiction candidates); direct fs probes (`~/.claude.json` mcpServers, `~/.claude/projects/*/memory/`, v2 markers, `## Index` count, profile NAME_RE, 21st CLI present + suite green). +- **Result**: 0 code defect. Gates: 3 MET, phase 0 UNMET(1), phase 1 UNMET(2), all oracle drift from later gated commits (LRN-255). TODO: 5 done-but-open (proof, mcp remove, auto-memory dirs, profile charset, design-tool-gate hermetic) + BLK-021 TMPDIR resolved by cc.sh + phase 5 follow-up lump (1 of 3 done). Reconcile: open BLK 001/003/017/018/022/029 all known upstream/deferred; 8 flag-overlap contradiction candidates, none real. +- **Anomalies**: `gates.sh run` dirtied two merged contracts (restored by checkout); TODO line 74 and BDR-134 cite purged spec/plan paths (BDR-065 purge); compound Bash with `git config`/`git diff settings.json` denied by permission rules (split calls). +- **Action**: chore/todo-reconcile-bdr125 e58a617 (5 ticks, split follow-ups), merge on user signal. LRN-255. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 24c430f..78ef07a 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -684,3 +684,4 @@ rules: ## 2026-11-02 - phase 5 profiles+packs shipped on feature/phase5-profiles-packs (13 tasks SDD, 3-lens challenge, gates MET/CONFORME/PASS after 3 passes): 9 packs, 9 profile fragments, profile.sh one-jq current --plain, cc [profile], census; BDR-134, LRN-248..253, BLK-039/040, EVAL-054; TODO: router ask-before-Fable queued +- BDR-125 re-verification (gates x5, 31 SHAs, reconcile engine): 0 code defect, 5 done-but-open ticks → chore/todo-reconcile-bdr125 e58a617 (merge on signal); EVAL-055, LRN-255. /feat router-ask-tier (feature/router-ask-tier): plan r1 FATAL x2 → r3, feater 28 TIER tests, GATE 0 MET, verifier CONFORME 11/11, security PASS (1 LOW fixed); 9a24a62 + docs 789fd00; BDR-135, LRN-254. Merge on signal. Next: phase 2 guards via /ship-feature. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 33fda44..3dffb62 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1911,3 +1911,13 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s - **Pattern**: commit a change to a tracked file whose working copy carries uncommitted writes you must keep (settings.json UI writes): `git show HEAD:f | jq '' > tmp && git update-index --cacheinfo 100644,"$(git hash-object -w tmp)",f && git commit`, then patch the working copy with jq into a temp file and `cp` it back. Never `git checkout -- f`, never `git stash` (pop can take someone else's stash), never `git add -p` (interactive, unavailable), never `jq … > f` (truncates on failure). - **Context**: phase 5 Task 13 listing budget; BLK-039. - **Apply**: any commit to settings.json or another file the harness writes to. + +## LRN-254 — A route-event dialog stamps every slot the event armed; trace slot lifecycle before storing a choice (2026-11-02) +- **Pattern**: a dialog answered at a route event must stamp EVERY slot the event armed, not the one in hand. `armTypedSkill` → `routeMainBySkill` derives `runMain = { ...turn }` BEFORE `confirmSkill` runs; a choice written on `turnMain` after dies at `endMainTurn` (turnMain nulled), run falls back to the choice-less runMain → "Opus instead" lasted one turn. Three blind lenses (correctness, robustness, simplicity) hit the same BLOCKER on plan r1. +- **Context**: feat router-ask-tier plan r1 → r2, `mods/model-router/hooks/register.ts` (`routeMainBySkill` ~3485, `confirmSkill` ~2984, `endMainTurn` ~4042). +- **Apply**: before storing state on a slot, trace its lifecycle: who writes it, who copies it (spread = snapshot, not link), who nulls it, who outranks it (`mainModelSlot` precedence). Stamp the asked slot + the derived one; inherit only same-tier, non-typed. Read the real decision (`snapshot`/`decideMain`) instead of rebuilding it from parts. + +## LRN-255 — gates.sh run rewrites contract evidence; re-audit of merged contracts: attribute drift by git log -S, then restore (2026-11-02) +- **Pattern**: `bash lib/gates.sh run ` REWRITES the `EVIDENCE:` lines of the contract file. Re-running a merged contract's gates for an audit: (1) oracles frozen on a base SHA (`c1-*.sh` vs develop 017a28b) read NOT-MET on later GATED changes (phase 5 added a pack-extras line to `rules/web-building.md`; 3330f0b restored "(dispatcher applies)" → 209/205 chars; 7899670 dropped `memory:`), (2) a CHECK string pinned to a test name goes stale after a review rename (`T10h-no-jq-rc0` → `T10h-empty-path-rc0`, 0b59687). Neither is a repo defect. +- **Context**: 2026-11-02 BDR-125 re-verification, 5 contracts re-gated: phase 5 / memory v2 write / minors MET, phase 0 UNMET(1), phase 1 UNMET(2), all explained by `git log -S`. +- **Apply**: on a re-audit, run gates, attribute each NOT-MET with `git log -S'' -- ` to a gated commit, then `git checkout -- ` to keep the ship-time evidence (historical record). Never commit re-run evidence over a merged contract. diff --git a/.claude/tasks/contracts/2026-11-02-router-ask-tier-1434.md b/.claude/tasks/contracts/2026-11-02-router-ask-tier-1434.md new file mode 100644 index 0000000..096d58a --- /dev/null +++ b/.claude/tasks/contracts/2026-11-02-router-ask-tier-1434.md @@ -0,0 +1,59 @@ +# CONTRACT — router-ask-tier +- date: 2026-11-02 | flow: feat | branch: feature/router-ask-tier (to be started off develop) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +/feat « model-router : demander avant de router vers Fable ». La spécification est l'entrée en tête du TODO : +- clé askTier, `/route ask-tier on|off` ; +- une question par span, avec la raison (phase et about, origine) ; +- options : Fable, Opus à la place, ne plus demander cette session ; +- jamais de question en -p. + +(user, 2026-11-02, step 2 of the session brief. The TODO entry it points at, `.claude/tasks/TODO.md` line 73 at develop 3cc4e0d:) +- [ ] **model-router: ask before routing to Fable** (user ask 2026-11-02, after the phase 5 merge: both touch `mods/model-router/routing.json`). `/feat` on the mod: a `routing.json` key `askTier` (default `best`; `/route ask-tier on|off`) makes the router ask, once per span, BEFORE applying a route whose resolved model sits in that tier, with the reason (phase + its `about`, origin: skill row / `/route` / prompt rule / agent row) and the options `Fable` · `Opus instead (big tier)` · `stop asking this session`; no memory in `confirmed` (the existing first-use confirmation stays as is); never asks in `-p` (`askOr` already falls back to LATER). Files: mods/model-router/hooks/register.ts (+ register.test.ts), routing.json, USAGE.md (`/route` section). + +Session constraints (same brief): default model opus; verifier, security-auditor and plan-challengers pinned on opus; never commit a `/model` or UI write of settings.json (LRN-253); plan text through Write/Edit, never a nested heredoc (BLK-039). + +## CLARIFICATIONS +Pass A (gaps): none blocking — outcome, scope and constraints are in the TODO entry. Facts verified in the code before the plan: +- "resolved model sits in that tier": `best` = [fable, opus, sonnet] (DEFAULT_CONFIG.tiers), so opus also "sits in" best. Read as: the resolved model is the HEAD of the `askTier` tier (`tiers[askTier][0]`, fable), and the loop or agent is not on it already. +- prompt rules write effort-only routes (BLK-032 / 786ee13): they never resolve a model, so that origin never asks today; the plan keeps the origin word for a rule that would one day carry a tier. +- `askOr` returns LATER on a rejected `$.ui.ask` (headless `-p`, no surface, dismissed dialog): the plan maps LATER to "apply the route as today" (fable), nothing blocked. +Pass B `[gated 2026-11-02]` (user: "défauts partout", plan r3 § Pass B): A. a dismissed dialog (Esc / free text) runs the span on Fable and is not asked again in that span; B. a best-tier skill the model loads on main asks too (skill row, BDR-123); C. sub-agents: one answer per agent type per session; F. held-head residual accepted (no question when Fable is held or the cold read is over the cap at the route event; a later lapse of the hold upgrades main unasked, today's breaker behaviour, documented in USAGE); D. "Opus instead" runs the phase's own effort; E. `askTier` accepts `best` or `false` only. Plan r3 approved for dispatch. +Executor deviations `[gated 2026-11-02, internal, orchestrator]`: (1) the invalid-`askTier` log is emitted by `warnAskTier(st, log)` from `applyLoaded`, deduped through `st.logged` (buildMemory has no state; AC1 "once per session" holds); (2) the derived `orchestrate` route (`pushOrchestrate`) inherits the span's `tierChoice` like any same-run helper slot, so a dispatch after "Opus instead" never lifts main unasked; (3) `inheritedChoice` takes the first of [turnMain, runMain] holding a choice for the same tier (a choice-less derived slot does not hide the run's); `failOnce` shares a `logOnce` helper with `tierFailOnce`; `routedTo` is `phaseWord` plus its prefix. + +## ACCEPTANCE CRITERIA +1. `routing.json` carries a top-level `askTier` key (shipped value `"best"`), serialized after `ask` (ROUTING_ORDER); the machine override `~/.claude/model-router.json` `askTier` wins over it like `ask`; accepted values `"best"` and `false` (r2: other tier names are out of scope, the option labels are the user's exact words); an absent key reads `best` silently, a missing or unreadable routing.json reads off, any other value is logged once per session and read as `best` (asking is the safe side). + CHECK: cd /home/bchanot/Documents/claude && jq -e '.askTier == "best"' mods/model-router/routing.json >/dev/null && grep -q "'ask', 'askTier'" mods/model-router/hooks/register.ts && echo ASKTIER-KEY-OK + EXPECT: ASKTIER-KEY-OK + EVIDENCE: MET exit=0 marker-found :: ASKTIER-KEY-OK +2. Main loop: when a route is set on main by a rowed skill (typed, or loaded by the model through the Skill tool), a main-loop `route` tool call with a phase, or a typed `/route `, and the real decision (`decideMain`, as `snapshot` reads it) would move the main loop onto the head model of the `askTier` tier from a model that is not it, one `$.ui.ask` opens BEFORE the route takes effect at the next step (for `/route`, the sticky slot is assigned only after the answer), with: the origin (`Skill /`, `Route tool`, `/route`), the phase and its `about` line, the head id and the effort the step would run; options exactly `Fable`, `Opus instead (big tier)`, `Stop asking this session` (the second dropped when opus is marked down: the label must be true when answered). No question when the decision would not land on the head (`mainUpgrade` off, cold-read cap, window, held head), when the slot is not the effective one (a sticky route outranks it), when the route names an explicit model (`/route model=…`, `/model` hand picks), from the prompt classifier, or when `$.session.surfaces()` is empty (headless, `-p`). +3. Answers: `Fable` applies the route as today. `Opus instead (big tier)` makes the span resolve through the `big` tier minus the head (opus; sonnet only as the mid-span fallback when opus goes down later; the head only when nothing else is up) at the phase's own effort (no stand-in notch); the choice is a tier name on the slot (`Routed.tierChoice`), stamped on the turn slot AND the run slot the event armed and inherited by every later main route of that run that names the same tier (a work or cheap route never inherits it; a typed rowed skill opens a new span and asks again), so a run asks once and survives the turn end; `/route show` names the choice. `Stop asking this session` silences the ask until the session ends (`resetSession`; `/clear` re-arms), nothing written. A dismissed dialog or a free-text answer applies the route as today and stamps the span (not asked again in that span); an answer arriving after `$.session.id()` changed is dropped. +4. Sub-agents: a rowed spawn from main (no explicit `model`, not inside an agent, not a fork or workflow) whose resolved target is the head model asks the same question with origin `Agent `, once per agent type per session (`State.tierSpawn`, cleared with the session); `Opus instead (big tier)` spawns it on the first non-head model of `big` that is up (resolved at each spawn); the first-use dialog, when it fires on the same spawn, runs first and the tier ask runs whatever it returned. Never inside an agent, never headless. +5. One dialog at a time: the ask holds the existing `asking` slot; a concurrent use finds it set and routes unasked (fable), like the first-use dialog. +6. `/route ask-tier on|off` writes `askTier` (`"best"` / `false`) into routing.json through `writeRouting` (serialized, capped, refused when the file is missing), answers `ask-tier on|off` with the override note when the machine file wins; any other argument answers `usage: /route ask-tier on|off`; `/route show` prints `ask-tier: best|off` plus ` (paused this session)` after a Stop answer; the `/route` argument hint names `ask-tier on|off`. +7. Nothing is written to `confirmed`, `changed` or `projects` by this dialog; `/route pending` and the first-use dialog are unchanged (their tests stay green). +8. Tests in `mods/model-router/hooks/register.test.ts` (fixture default `askTier: false`, opt-in per test like `ask`) cover the plan's D7 list: question text and exact options on a typed skill from an opus session; `Fable` → fable; `Opus instead` → opus at the phase effort, no second ask on a later route-tool call, still opus after the turn end; `Stop asking` → silent + `show` paused; already on fable → no ask; headless (no surface) → no ask; dismissed → fable, span not re-asked; route tool main asks, `agentId` does not; `/route plan` asks and assigns after the answer, `/route model=fable` does not; sticky `/route model=opus` → no ask; `mainUpgrade` off → no ask; opus down → two options; model-loaded `Skill` on main asks; rowed spawn (verifier on audit) asks once per type, `Opus instead` → opus spec, explicit model and nested spawn never ask, a work-tier spawn never asks; first-use then tier ask on one event with the outcome asserted; `asking` held → unasked; `/route ask-tier off|on` writes and silences, bad arg → usage, override wins note; invalid value logged once and read as best; absent routing.json → no ask; the existing `/route ask` and key-order tests stay green with `askTier` added to the order. + CHECK: cd /home/bchanot/Documents/claude && for n in 'ask-tier' 'Opus instead (big tier)' 'Stop asking this session' 'paused this session'; do grep -qF -- "$n" mods/model-router/hooks/register.test.ts || exit 1; done && a=$(make test suite=lib/tests/mods.test.sh 2>&1) && printf '%s\n' "$a" | grep -q 'all suites green' && echo MOD-TESTS-OK + EXPECT: MOD-TESTS-OK + EVIDENCE: MET exit=0 marker-found :: MOD-TESTS-OK +9. The repo suites that read routing.json stay green (`lib/tests/model-routing.test.sh`, `lib/tests/effort-routing.test.sh`, `lib/tests/doctrine-citers.test.sh`); `make test` all suites green. + CHECK: cd /home/bchanot/Documents/claude && t=$(make test 2>&1) && printf '%s\n' "$t" | grep -q 'all suites green' && echo MAKE-TEST-OK + EXPECT: MAKE-TEST-OK + EVIDENCE: MET exit=0 marker-found :: MAKE-TEST-OK +10. Docs: USAGE.md `/route` row and the model-router paragraph name `ask-tier on|off` and the question (one sentence each); the code's own comment block "first use" gains the ask-tier rule. README.md and CHANGELOG `[Unreleased]` follow through the doc-sync step. + CHECK: cd /home/bchanot/Documents/claude && grep -q 'ask-tier' USAGE.md && echo USAGE-OK + EXPECT: USAGE-OK + EVIDENCE: MET exit=0 marker-found :: USAGE-OK +11. settings.json is untouched by the branch (no UI write, no `model`), the contract and plan ride the memory commit. + CHECK: cd /home/bchanot/Documents/claude && [ -z "$(git diff develop...HEAD --stat -- settings.json)" ] && echo SETTINGS-UNTOUCHED + EXPECT: SETTINGS-UNTOUCHED + EVIDENCE: MET exit=0 marker-found :: SETTINGS-UNTOUCHED + +## FILE SCOPE +- mods/model-router/hooks/register.ts +- mods/model-router/hooks/register.test.ts +- mods/model-router/routing.json (`askTier` key only) +- USAGE.md (`/route` row + model-router paragraph) +- README.md, CHANGELOG.md through STEP 6 doc-sync only +- .claude/tasks/contracts/2026-11-02-router-ask-tier-1434.md, .claude/tasks/plans/2026-11-02-router-ask-tier-1434.md (run artifacts, memory commit) diff --git a/.claude/tasks/plans/2026-11-02-router-ask-tier-1434.md b/.claude/tasks/plans/2026-11-02-router-ask-tier-1434.md new file mode 100644 index 0000000..7dd433c --- /dev/null +++ b/.claude/tasks/plans/2026-11-02-router-ask-tier-1434.md @@ -0,0 +1,392 @@ +# /feat router-ask-tier — PLAN r3 (2026-11-02) + +r3 after the confirmation pass on r2 (correctness CONCERNS(6), no BLOCKER). +Named changes: inheritance of a choice only between slots of the SAME tier +and only for helper (non-typed) writes, so a typed run is a new span and a +work route never inherits 'big'; `tierAsk` writes on the real `st` and +reads a probe view (the `/route` path); "Opus instead" is offered only when +opus itself is up, sonnet is the mid-span fallback only; a stored per-type +spawn answer is applied BEFORE any ask guard and the spawn dialog holds +`asking`; `isStandIn` is false on a 'big' span; the pure `cur !== head` +guard runs first; question texts drop the "Routed to" prefix; `tierWord` +names a 'big' span; `flagCommand` takes one descriptor; the "first use" +comment block and the `asking` field comment are the ones edited; three +key-order assertions; the held-head lift (fable held at the route event, +hold lapses later) is a residual put to the gate (pass B F). + +r2 after 3 lenses on r1 (correctness FATAL(6), robustness FATAL(6), +simplicity CONCERNS(4)). Unanimous BLOCKER: r1 wrote the answer on +`turnMain` after `armTypedSkill` had already derived `runMain`, so "Opus +instead" lasted one turn and a run re-asked. r2 changes: the choice is a +TIER NAME stamped on every slot the event armed (turn + run), resolution +goes through `resolveName` (no stand-in rewrite), the ask reads the real +decision (`snapshot` / `decideMain`) instead of rebuilding it, a 4th call +site covers model-loaded best-tier skills, spawns remember one answer per +agent type per session, the "instead" option is offered only when its +model is up and never falls back onto the head, headless is guarded by +`$.session.surfaces()`, `/route ` assigns after the answer. +Pass-B choices are listed at the end; defaults taken are marked (default). + +FEAT: model-router asks before a route lifts the main loop, or sends a rowed +spawn, onto Fable — rule 7, 4 files (register.ts, register.test.ts, +routing.json, USAGE.md), README/CHANGELOG through doc-sync. +Contract: `.claude/tasks/contracts/2026-11-02-router-ask-tier-1434.md`. + +## Facts (verified in `mods/model-router/hooks/register.ts` at develop 3cc4e0d) +- Tiers (DEFAULT_CONFIG ~283): `best` = [fable, opus, sonnet], `big` = + [opus, fable, sonnet]. "Resolved model sits in that tier" = resolves to the + HEAD of the `askTier` tier (`tiers.best[0]` → `models.fable`). +- Main-loop route writers: `routeMainBySkill` (~3485; typed via + `armTypedSkill` 3537 in skill.prompt 4254, BEFORE `confirmSkill` 4259; + model-loaded via `onSkillLoad` 3502 in tool.call Skill 4242), `applyRoute` + (route tool, ~3395), `setUserRoute` (`/route`, 2019; `/route` is + `immediate: true`, 3370: it runs mid-turn). `mainModelSlot` (1466) = + userMain ?? turnMain ?? runMain; `wantedModel` (1547) resolves its tier; + `decideMain` (1445) is the ONE decision "used by the step and every text"; + `snapshot` (1922) = `decideFor` on `turnModel ?? sessionModel`. +- `endMainTurn` (4042) nulls turnMain; `userMovedEffort` (3976) nulls it + mid-turn; `resetSession` (1043) keeps `asking` but NOT `asked`. +- Dialogs render in skill.prompt (T1), tool.call (`confirmPhase`, + route tool; the Skill tool.call hook is the same hook kind), agent.spawn + (T2) and command.run (`/model`, LRN-243); never in turn.step (LRN-231). + `askOr` (2532) → LATER on a rejected ask; the `/model` paths guard first on + `$.session.surfaces()` empty (2409, 2472); `askStep` (2684) maps Later / + unrecognised / headless. `pickerDialog` checks `$.session.id()` before + applying a late answer (`stillHere`, ~2452). +- `confirmSkill` (2984) returns early when `confirmFirst` is false, and + re-runs `routeMainBySkill` (2990) when it is true. `routeSpawn` (2996) + returns the route from a ternary on `confirmFirst`. +- `resolveName` (1135): a tier skips down aliases then walks the chain; an + alias/id is explicit and never skipped. `availableIn` (1115). + `spawnTarget` (3630) → `inTier` picks the first alias not down at or above + the tier's head; an explicit `e.model` wins; `routeSpawn` already returns + early for frozen / unrowed / inside spawns. +- `askCommand` (3041) + `writeRouting` (2865) is the `/route ask` writer; + ROUTING_ORDER (189) is 74 columns: appending `'askTier'` needs a wrap. +- `buildMemory` (790) takes no cfg; callers `assemble` (939) and + `refreshMemory` (2527). `assemble` logs "routing.json missing; … no asks" + and uses `emptyMemory()`. +- Prompt rules and the classifier write effort-only routes (BLK-032): they + never resolve a model, so never ask; the classifier writes only when no + route is in force (`classifierIdle`), so it never reaches a call site. + +## Design +### D1 config, memory, state +- routing.json: `"askTier": "best"` after `"ask": true`. `ROUTING_ORDER` + gains `'askTier'`: the line is rewrapped as `'phases', 'skills', 'agents', + 'projects', 'confirmed', 'changed',` / `'ask', 'askTier',` (≤ 80 cols). +- `Memory.askTier: unknown` (raw file value, absent = undefined) and + `Memory.askTierLocal: unknown` (override). `buildMemory` copies both raw, + no new parameter. `emptyMemory()` → `askTier: false` (no file = no ask, + matching the "no asks" load log). +- `tierHead(st): string | undefined` — the one reader: value = + `st.mem.askTierLocal ?? st.mem.askTier`; `undefined` → `'best'` silently; + `false` → undefined (off); `'best'` → `st.cfg.models[st.cfg.tiers.best[0]]`; + any other value → `best`. The validation log line `model-router: askTier + must be "best" or false; read as best` is emitted by `buildMemory` + through its `log` parameter (live at `assemble`, silent at + `refreshMemory`), the same way `aboutOf` logs an overlong `about`: once + per config load, never on the hot path. (Default E: other tier names are + out of scope — the labels are the user's exact words.) +- `headId(st)` = `st.cfg.models[st.cfg.tiers.best[0]]` (the head whatever + the key says; used by `insteadName` so a span keeps avoiding fable after + `/route ask-tier off`). +- `State` gains `tierPaused: boolean` (Stop; `newState` false; NOT in + `resetSession`'s kept list → /clear re-arms) and `tierSpawn: Map` (agent type → answer; not kept either). +- `Routed.tierChoice?: Choice` where `type Choice = 'best' | 'big'` — the + TIER the span resolves through: `'best'` = Fable accepted (or Later / + Stop / headless), `'big'` = Opus instead. Constants `TIER_HEAD = 'Fable'`, + `TIER_INSTEAD = 'Opus instead (big tier)'`, `TIER_STOP = 'Stop asking this + session'`, `INSTEAD_TIER = 'big'` next to LATER/KEEP/CHANGE (192). + +### D2 resolution of a chosen span +- `wantedModel` (1547): `const name = slot.tierChoice === 'big' && + slot.route.tier === BEST ? (insteadName(st) ?? routeName(slot.route)) : + routeName(slot.route)`. `insteadName(st)` = `availableIn(st, + tiers.big.filter(a => models[a] !== headId(st)))` → the first non-head + alias of `big` that is up (opus, else sonnet); `undefined` only when + nothing but the head is up → the normal tier resolution (the span runs, + on whatever the breaker leaves; silent: the status line and `show` name + the model). Otherwise never the head: the model the user declined is not + the fallback of their refusal. +- Offer rule (one rule everywhere, D3/D5/AC2/AC8/test 11): the `Opus + instead` option is offered only when `models[tiers.big[0]]` (opus) is not + down — the label must stay true at answer time; sonnet is only the + mid-span fallback when opus goes down later. +- Effort: the phase's own (default D). `isStandIn` (1670) gains one guard: + `mainModelSlot(st)?.tierChoice === 'big'` → false (a chosen opus is not a + stand-in: no notch, no "stands in for" text). `standInEffort`, + `standInWord`, `heldHead` otherwise unchanged. +- Inheritance (`applyRoute` 3395 and `routeMainBySkill` 3485 for a + model-loaded skill, `typed === false` only): the new turnMain copies + `tierChoice` from the slot it replaces (`st.turnMain`) or else from + `st.runMain`, ONLY when `prev.route.tier === new.route.tier`. A typed + rowed skill (`typed === true`) never inherits: it opens a new span, so a + typed `/bugfix` after an answered `/feat` run asks again, and a work or + cheap route (`route phase=implement`, `gitflow`) never carries 'big'. + `routeMainBySkill` copies the turn's `tierChoice` into the run slot it + derives (the spread does it once the field is on `turn`). +- `tierWord` (1866): a slot with `tierChoice === 'big'` prints `[tier big + (instead of best)]` so `/route show` names the span's choice. + +### D3 when to ask (main loop) — `tierAsk($, st, slot, origin, view = st)` +`st` is the real state (every write: `asking`, `tierPaused`, `logged`); +`view` is the state the decision is read from (`st` everywhere except the +`/route` path, D4.4, where it is the probe copy). Pure cheap guards first, +in this order, all required: `!st.off`; `head = tierHead(st)` defined; +`!st.tierPaused`; `canonical(st.turnModel ?? st.sessionModel) !== head` +(main already on fable: a helper Skill inside a fable run costs nothing); +`st.asking === null`; `slot.tierChoice === undefined`; `slot.route.tier === +BEST` (an explicit `model` route never asks: `/route model=fable`, `/model` +hand picks; another tier never resolves to the head unless opus is held, +and then the breaker already decided); `slot === mainModelSlot(view)` (a +sticky slot that outranks it decides, not this one). Then the two awaits: +`(await $.session.surfaces()).length > 0` (headless asks nothing, like +`/model`), and `v = await snapshot($, view)`; ask only when +`canonical(v.call.model) === head` (so `mainUpgrade: false`, the cold-read +cap, a window miss or a held head → no question, nothing to decide; the +slot stays unstamped, see pass B F). +- The dialog holds `st.asking = 'tier:main'` (finally null) and records + `sid = await $.session.id()` first; an answer arriving after `$.session. + id()` changed (a /clear) is dropped. +- Text (main): `${origin} routes main to ${phaseWord(st, slot.phase)}: + ${idWord(st, v.call.model)} at ${effortWord(view, v)}. Run it on fable?` + where `phaseWord` = `phase` + ` (${about})` when `aboutLine` is set (the + body of `routedTo` without its "Routed to" prefix; `routedTo` calls it); + origin ∈ `Skill /feat` (typed or model-loaded), `Route tool`, `/route`. + Options: `[TIER_HEAD, TIER_INSTEAD, TIER_STOP]`, or `[TIER_HEAD, + TIER_STOP]` when opus is down (offer rule, D2). Answers via `askStep` + (Later / unrecognised / rejected → undefined): `TIER_HEAD` or undefined → + stamp `'best'`; `TIER_INSTEAD` → stamp `'big'`; `TIER_STOP` → + `st.tierPaused = true`, stamp `'best'`. (Default A: a dismissed dialog + stamps the span.) +- Stamp = write `tierChoice` on `slot` AND on `st.runMain` when + `st.runMain !== null && st.runMain.route.tier === slot.route.tier` + (the run derived from this event, or the run this route serves). After + a `'big'` stamp, `refresh($, st)` so the status line follows. +- Fail-open: everything inside try/catch; a throw logs once (`failOnce` + text pattern: `model-router: tier dialog failed (…); route kept`) and the + route applies as today. + +### D4 call sites +1. `confirmSkill` (typed rowed skill): restructured as `const changed = + await confirmFirst(...); if (changed) { re-route as today; toast }; await + tierAsk($, st, st.turnMain, `Skill /${skill}`)` — the tier ask runs on + both branches, after the re-route, so the stamp survives. +2. tool.call Skill on main (`registerSkills`, `e.agentId === undefined`): + after `onSkillLoad`, when `skillRow` exists → `await tierAsk($, st, + st.turnMain, `Skill /${skill}`)` (default, pass B B: a model-loaded + best-tier skill — brainstorming, writing-plans, requesting-code-review, + subagent-driven-development, writing-skills — is a skill-row lift, BDR-123). + Inside a run already on fable, the cheap guards end it at once (cur === + head), so helper skills cost nothing. +3. `handleRouteTool` main path: after `confirmPhase`, `await tierAsk($, st, + st.turnMain, 'Route tool')`. +4. `setUserRoute`: `parsed` is computed; `probe: State = { ...st, userMain: + parsed }` (the `wouldRunHead` pattern, read-only) is the `view` of + `tierAsk($, st, parsed, '/route', probe)`: guards and `snapshot` read + the probe, `asking` / `tierPaused` land on the real `st`, the answer + stamps `parsed`; THEN `st.userMain = parsed` (never assigned before the + answer: `/route` runs mid-turn and a step meanwhile would upgrade). + `show` follows. + +### D5 sub-agents — in `routeSpawn`, after its early returns and after the +first-use block (both branches of the ternary; `phase` re-read from +`st.cfg.agents[type]` after `confirmFirst`, a Change may have moved it) +Order: +1. Stored answer first, before any ask guard: `const kept = + st.tierSpawn.get(e.subagentType)`; `kept === 'big'` and the route is + best-tier → return `{ ...route, tier: undefined, model: insteadName(st) + ?? }` (opus, else sonnet, never the head; re-resolved + at every spawn); `kept === 'best'` → return the route as is. A stored + answer applies whatever `tierPaused`, `asking` or the key say (like a + stamped main slot). +2. Ask guards: `tierHead` defined, `!st.tierPaused`, `st.asking === null`, + `e.parentAgentId === undefined`, `e.model === undefined`, `route.tier === + BEST`, `spawnTarget($, st, e, route)` is the head id, then surfaces + non-empty. (Default C: one answer per agent type per session: the audit + gates spawn verifier and security-auditor at every loop iteration, a + per-spawn dialog with no timeout would stall unattended orchestration.) +3. The dialog holds `st.asking = 'tier:agent:'` (finally null), + records `sid` like D3. Text: `Agent ${type} runs ${phaseWord(st, phase)} + on ${head id} at ${explicitEffort.get(tool_use_id) ?? route.effort ?? + 'its own effort'}. Run it on fable?`; same options (instead dropped when + opus is down). Answer → `st.tierSpawn.set(type, choice)`, then step 1's + rule gives this spawn its route; Stop → `tierPaused` + `'best'` stored. + +### D6 command and show +- `handleCommand`: `case 'ask-tier': return flagCommand($, st, rest[0], + ASK_TIER_FLAG)` and `case 'ask': return flagCommand($, st, rest[0], + ASK_FLAG)` — `askCommand` generalized into `flagCommand($, st, arg, flag: + Flag)` with `type Flag = { word: string; key: string; value: (on: boolean) + => unknown; local: (m: Memory) => unknown }` (4 params): usage `usage: + /route ${word} on|off`, answer `${word} ${arg}`, override note `; + ~/.claude/model-router.json sets ${key} ${on|off} and wins here` when + `local(st.mem)` is defined. The `/route ask` strings locked by the + existing tests are unchanged. +- `registerCommand` argumentHint gains `ask-tier on|off`. +- `show`: router line gains ` · ask-tier: ${word}` with word `best` | `off` + | `best (paused this session)` (invalid value prints `best` too). +- Comments: the "first use" block (~2485) gains one sentence ("a route that + would lift main, or a rowed spawn, onto the head of `askTier` asks first: + Fable, Opus instead, or stop for the session; nothing written"), and the + `asking` field comment (line 122) reads "key of the one dialog in flight + (first-use or tier ask)". AC10 names the 2485 block. + +### D7 tests (register.test.ts) +Fixture: `baseRouting()` gains `askTier: false` (the fixture's `ask` +convention: no dialog by default); `Fixture.askTier?: 'best' | false`; +`asksTier(answers, fx?) = newWorld({ answers, askTier: 'best', ...fx })` +(first-use `ask` stays false unless a test sets it). The THREE key-order +assertions (test.ts ~2337, ~2408 reversed pre-write list, ~2414) gain +`'askTier'` at its place. A `verifier → audit` row and an `about` line on +`reflect`/`audit` go through per-test `edit:`. Tests, names `TIER:`: +1. typed /feat on OPUS, `edit` adds `phases.reflect.about = 'analysis'` → + one ask; text contains `Skill /feat routes main to reflect (analysis): + claude-fable-5-1 at high. Run it on fable?`; options equal exactly + `['Fable', 'Opus instead (big tier)', 'Stop asking this session']`. +2. `Fable` → next main step FABLE/high. +3. `Opus instead` → main step OPUS/high (phase's own effort, no notch); + then `$.tool.call route phase=orchestrate` in the same turn → no second + ask, step OPUS/medium; then `turn.complete` + a new turn's step → still + OPUS (run slot stamped); `/route show` main line contains `[tier big + (instead of best)]`. +3b. after `Opus instead`, `$.tool.call route phase=implement` → step SONNET + (a work route never inherits 'big'); a typed `/bugfix` (fixture row + `bugfix: 'reflect'`) after the answered `/feat` → a second ask (new span). +3c. fable marked down after an `Opus instead` answer → step stays OPUS at + high (no stand-in notch, no "stands in for" in `show`). +4. `Stop asking` → step FABLE; a second typed rowed best skill → no ask; + `/route show` contains `ask-tier: best (paused this session)`. +5. session already on FABLE → `w.asked` empty, step FABLE. +6. headless (`surfaces: []`) → `w.asked` empty, step FABLE (no REJECT + consumed); dismissed (`REJECT` answer with a surface) → step FABLE, a + later route-tool call of the span asks nothing. +7. route tool `phase: 'plan'` from main on OPUS → asks with `Route tool`; + with `agentId` → nothing. +8. `/route plan` → asks; the slot is set only after the answer (a step + recorded while the dialog is held — `gate` — stays OPUS); `Stop asking + this session` answered there → `tierPaused` real (a later typed /feat + asks nothing); `/route model=fable` → nothing, route set. +9. sticky `/route model=opus` then typed /feat → no ask (slot is not the + effective one), step OPUS. +10. `mainUpgrade: false` (home override) → typed /feat asks nothing, step + OPUS. +11. SONNET session, opus marked down (a `rate_limit` StopFailure charged + to OPUS through an earlier spawn), then typed /feat → the ask offers + `['Fable', 'Stop asking this session']` (instead dropped). +12. model-loaded skill: `$.tool.call Skill brainstorming` on main (row + `brainstorming: 'plan'` in the fixture edit) from OPUS → asks with + `Skill /brainstorming`; `Opus instead` → step OPUS/xhigh. +13. spawn: fixture `edit: f => { f.agents.verifier = 'audit'; + f.phases.audit.about = 'gates' }`, OPUS session, `spawnOf('verifier')` + → asks with `Agent verifier runs audit (gates) on claude-fable-5-1 at + xhigh`; `Opus instead` → `rig.specs` = [OPUS]; a second + `spawnOf('verifier')` → no ask, [OPUS] again; the same with a first-use + dialog held open (`gate`) on another type → still [OPUS], no second + dialog; `Fable` → [FABLE]; explicit `model` → no ask; nested + (`parentAgentId`) → no ask; `spawnOf('feater')` (work) → no ask. +14. first-use on (`ask: true`) + askTier: typed /feat with answers + `['Keep', 'Opus instead (big tier)']` → two asks in order (`First route + for /feat`, then the tier question) and the step is OPUS. +15. a dialog in flight (`gate` held on a first-use spawn ask) → a typed + rowed skill routes fable unasked. +16. `/route ask-tier off` → `routingOf(w).askTier === false`, typed /feat + asks nothing; `ask-tier on` → `'best'`; `ask-tier maybe` → `usage: /route + ask-tier on|off`, `w.written` empty; home `{ askTier: false }` → `/route + ask-tier on` answer contains `wins here` and no ask fires. +17. `edit: f => { f.askTier = 'work' }` → one ui.log line, the ask fires + (read as best); the line is not repeated on `/route reload`. +18. `routing: 'absent'`, OPUS session, `$.tool.call route phase=plan` on + main → no ask (emptyMemory false), route set. +19. `/route ask` tests unchanged and green (flagCommand refactor). + +### D8 docs +USAGE.md: `/route` row (173) gains `ask-tier on|off`; the model-router +paragraph (199) gains: before a route lifts the main loop, or sends a rowed +agent, onto Fable, the mod asks once per span (origin, phase and its +`about`, model and effort): `Fable`, `Opus à la place` (le tier big, effort +de la phase inchangé), `ne plus demander cette session` ; un skill chargé +par le modèle compte comme une ligne de skill ; une réponse par type +d'agent et par session ; jamais en `-p` ni dans un sous-agent ; la clé +`askTier` (`best` ou `false`) de `routing.json`, `/route ask-tier on|off`, +l'override machine gagne. README.md 144-146 + CHANGELOG `[Unreleased]` → +doc-sync STEP 6. + +## Plan (checklist, dispatch-ready) +- [ ] mods/model-router/routing.json — `"askTier": "best"` after `"ask": true`. +- [ ] register.ts — constants (TIER_*, INSTEAD_TIER, Choice), ROUTING_ORDER + rewrap, `Memory.askTier/askTierLocal` raw + `emptyMemory` false, + `State.tierPaused` + `tierSpawn` (not kept by resetSession), + `Routed.tierChoice`, `tierHead`, `insteadName`. +- [ ] register.ts — `wantedModel` branch (D2), inheritance in `applyRoute` + and `routeMainBySkill`. +- [ ] register.ts — `tierAsk` + `tierQuestion` + stamp (D3); call sites D4 + 1-4 (`confirmSkill` restructured, Skill tool.call on main, + `handleRouteTool`, `setUserRoute` assign-after-answer). +- [ ] register.ts — `routeSpawn` tier ask with `tierSpawn` memory (D5). +- [ ] register.ts — `flagCommand` (ask + ask-tier), `handleCommand` case, + argumentHint, `show` segment, header sentence (D6). +- [ ] register.test.ts — fixture + key-order assertions + TIER tests 1-19. +- [ ] USAGE.md — row + paragraph (D8). +- [ ] Executor runs `make test suite=lib/tests/mods.test.sh` and `make test`; + reports the first-use tests untouched and green. +- Style: new functions ≤ 25 logic lines, ≤ 5 params, 80 cols (the file keeps + 3 pre-existing long lines; add none). + +## Edge cases +- Opus held during a `'big'` span → `insteadName` → sonnet (never fable), + silently; opus back → opus again at the next step (resolution is per + step, like a tier). Opus AND sonnet held → the tier's normal resolution + (the span runs rather than stalls). +- RESIDUAL for the gate (pass B F): the ask fires at route events only + (a step cannot ask, LRN-231). When fable is HELD at the event (billing, + BLK-030/031) or the cold read is over the cap, no question fires and the + slot stays unstamped; when the hold lapses (`prune`) or a compaction + brings the context under `upgradeMaxTokens`, the next step upgrades main + to fable unasked. Alternative: treat an unstamped best slot as + `insteadName` until a route event asks (changes today's routing in the + held-head case: main would stay on opus after the hold lapses instead of + returning to fable). +- `[1m]`: comparisons on `canonical()`; `moveTo` carries the variant. +- `sessionModel === ''` cannot happen after session.start (4149 reads it); + if it does, `canonical('') !== head` → the decision decides (snapshot). +- Stop then `/route ask-tier on` → still paused this session (`show` says + so); `/clear` re-arms. +- A `/route forget` or first-use write never touches `askTier` + (serializeRouting keeps unknown keys; the key is in ROUTING_ORDER). +- Write failure of `ask-tier` → `failedWrite` text, like `ask`. +- Residual accepted (robustness 13): `/model ` typed while any dialog + holds `asking` falls to native (pre-existing path, BDR-126); not widened + by this feature beyond the dialog's open time. + +## Pass B (open choices, asked at the gate; defaults taken in r3) +A. Dismissed dialog (Esc / free text) → the span runs on Fable and is not + asked again (default) — or re-asked at the next route event of the span. +B. Model-loaded best-tier skill on main (brainstorming, writing-plans…) asks + too (default, BDR-123 "skill row") — or typed skills only. +C. Sub-agents: one answer per agent type per session (default) — or one + question per spawn. +F. Held-head residual (Edge cases): accept it (default: today's breaker + behaviour, documented) — or keep an unasked best slot off fable until a + route event asks. +Settled as defaults, not asked (internal or fixed by the request's words): +D. "Opus instead" runs the phase's own effort, shown in the question. +E. `askTier` accepts `best` or `false` only. + +## Disposition (STEP 0.6 RELATED MEMORY) +IN FORCE: BDR-116 (routing.json single source; `/route ask` writer; one +dialog at a time; never in `-p` or a sub-agent) — D1/D3/D6; BDR-123 / +BLK-032 (Fable on main only via skill row, route tool, `/route`, hand pick; +prompt rules effort-only) — D4 covers typed AND model-loaded skill rows, the +route tool and `/route `; BDR-126/127/132 (hand picks always switch) +— explicit-model routes never ask; LRN-242 (2-4 options) — 3 or 2; LRN-231 +(no dialog in a step hook) — asks at route-setting events only; LRN-243 +(interactive behaviour proven before building) — every hook kind used +already renders `$.ui.ask` in the shipped code. +ALREADY SEEN: LRN-229 (kit: forcing a throw after an answer), BLK-030/031 +(Fable without credits is the breaker's job, not this ask). +NON-BINDING: BDR-107, BDR-115, LRN-211, LRN-226. +SELECTION: scanned 4 registries, surfaced 14 = in-force 8 + seen 3 + +non-binding 4 (BLK-032 counted in two groups).