Merge feature/router-keyword-cap into develop

This commit is contained in:
bchanot committed 2026-10-23 17:40:14 +02:00
commit 34c6534620
15 files changed
+461 -49

No files matched your search

+4 -2
View File
@@ -51,7 +51,7 @@ rules:
| BLK-029 | 2026-10-08 | Claude Code mods (2.1.294): alias → id resolution for a model set by a hook lags the Agent tool's (`sonnet` → `claude-sonnet-5`, 404); Agent tool schema refuses full ids | upstream |
| BLK-030 | 2026-10-15 | model-router kept routing best-tier phases to Fable out of usage credits: each new session + each hold lapse lost a turn to 429 `model_requires_usage_credits`; breaker reactive only | resolved |
| BLK-031 | 2026-10-16 | model-router: session starting on Fable w/o credits lost 1st turn + each hold lapse; probe skipped kept cur | resolved |
| BLK-032 | 2026-10-19 | Main loop pinned on Fable in long sessions: session model Fable 1M + downgrade cap 120k + prompt rule `plan` → inline code on Fable xhigh; feat A+B shipped (BDR-123), closes after feat C | open |
| BLK-032 | 2026-10-19 | Main loop pinned on Fable in long sessions: session model Fable 1M + downgrade cap 120k + prompt rule `plan` → inline code on Fable xhigh; feat A+B shipped (BDR-123), closed by feat C 786ee13 | resolved |
| BLK-033 | 2026-10-21 | Guardrails residuals: probe trusted plan `supabase.url`, redirects free of budget, unread bodies read CLOSED, `str(URLError)` hid budget signal; rules 5 FP / 7 misses | resolved |
| BLK-034 | 2026-10-22 | mods.test.sh red on CLI 2.1.306: whole-output `warning` grep caught advisory plugin-directory section (ICON_MISSING, blocking: false); verdict = `--strict` exit code now | resolved |
@@ -333,10 +333,12 @@ rules:
- **Status**: resolved. Open: leaveDown follows classifier `wanted` (implement → sonnet), not opus; "context size unknown" likely document attachment → `promptSize` unknown.
- **Reference**: [[BLK-030]], [[LRN-218]], contract `.claude/tasks/contracts/2026-10-16-router-probe-session-model-1850.md`.
## BLK-032 — Main loop pinned on Fable in long sessions: session model Fable 1M + downgrade cap 120k + prompt rule `plan` → inline code on Fable xhigh [open]
## BLK-032 — Main loop pinned on Fable in long sessions: session model Fable 1M + downgrade cap 120k + prompt rule `plan` → inline code on Fable xhigh [resolved]
- **Cause**: `~/.claude/settings.json` `"model": "claude-fable-5-1[1m]"` (every session starts on Fable); model-router never moves main above the session model, moves DOWN only under `downgradeMaxTokens` 120000 (LRN-204 cold read) → a long session (faunosteo R4.x, context > 120k) never reaches `implement`/sonnet; prompt rule `(plan|design|architecture…)` → phase plan = best/xhigh each turn ("plan §B.1.7"). No doctrine ceiling: CLAUDE.md allows inline work "doable in a few tool calls", BDR-115 "pin = default, never ceiling".
- **User policy 2026-10-19**: session model Opus 5.5; sonnet writes, opus decides what to write; Fable only for orchestrator reflection/plans and the important audits (security, functional), other judges opus. → next `/feat`: settings model, `judge` split, ceiling rule in CLAUDE.md, BDR superseding part of BDR-066 / BDR-115. Links [[BDR-066]], [[BDR-107]], [[BDR-115]], [[LRN-204]].
- **Solution (2026-10-23)**: feat A+B (BDR-123) + feat C 786ee13 (feature/router-keyword-cap): keyword prompt rules, `ultrathink` floor, derived `orchestrate` dispatch write effort-only routes (`effortRoute`, `belowRun` pattern) → never lift main above session model; held best-tier run keeps its model (per-axis fall-through); `mainModelSlot` drops `turnFloor`. Fable on main only via skill row, `route` tool, `/route`. Docs d2d590f. Links [[LRN-226]], [[EVAL-048]].
## BLK-033 — Guardrails residuals: probe trusted plan `supabase.url`, redirects free of budget, unread bodies read CLOSED; rules 5 FP / 7 misses [resolved]
- **Friction**: GATE 2 of the a11y split (f586304) left a MEDIUM + 3 LOW on probe.py, opus review left Minors on the rules. Parked in TODO, fixed via `/bugfix` 2026-10-20/21.
- **Cause**: `supabase.url` read from the plan w/o `_http_url` → planted SUPABASE_URL would receive GUARDRAILS_ANON_KEY / JWT2, `file://` read CLOSED; `_SameHost` redirector followed hops w/o charging `session.budget`; `_rows_state` collapsed non-200 / empty / >1 MB / non-JSON into CLOSED (unobserved = CLOSED, breaks LRN-220); plan r2 mapped budget exhaustion on `str(URLError)`, which wraps the reason → never matched. Rules: SENSITIVE_KEY on metadata names (`token_type`, `has_password`), 403 on first map candidate stopped the walk, hydrated scan read whole route file, NOSQL `$where` fired on GraphQL `_bool_exp`; misses: Go backtick Sprintf, `rf`/triple-quoted f-strings, `sql|db|trx.raw`, empty `.select()`, multi-line hidden input, Rust `{}` shell arg, `"sources"` map head.
+1
View File
@@ -1478,3 +1478,4 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate).
- **[deferred]** inline-writing best-tier skills = declared exception, visible in this repo only: design Build stack (frontend-design, 21st-ui-build, emil-design-eng, design-motion-principles Create, site-motion, build-threejs-scroll-worlds, scroll-*, 21st-ai), writing-skills, deprecation-and-migration, /tour single-project, /audit-delta STEP 3d, /harden STEP 3. Remap = own task (TODO).
- **Known gaps**: default keyword prompt rules (plan|design|architecture, why|review|audit|analyze, ultrathink) lift main to Fable unwitnessed → feat C caps them at session model; Fable held down → opus stand-in, ceiling does not bind; stale "session model" citers `skills/feat/SKILL.md:6`, `skills/code-clean/SKILL.md:36`.
- **Refs**: feat A feature/routing-audit-phase d3635b6 a7d747c dae142b; feat B feature/routing-ceiling-rule ef13713 887cf89, contract `.claude/tasks/contracts/2026-10-21-routing-ceiling-rule-1753.md`, plan `.claude/tasks/plans/2026-10-21-routing-ceiling-rule-1753.md`. Links [[BDR-066]] [[BDR-115]] [[BLK-032]] [[LRN-224]].
- **Amendment (2026-10-23, feat C 786ee13 + docs d2d590f)**: keyword-lift gap CLOSED: prompt rules (keywords, `ultrathink`, user rules) + derived `orchestrate` on main Agent dispatch (user pick 2026-10-23) write effort-only routes; model axis falls through to held run or stays on cur. Amends [[BDR-115]] amendment 2026-10-13 clause "ultrathink floor model beats guess": mid-turn ultrathink after classifier demotion keeps guessed model that turn (floor raises effort only). Accepted edges: haiku session → keywords no-op; session model held → keyword turn = plain-turn fallback (sonnet), not fable; no stand-in notch on keyword/dispatch turns; dispatch after demotion orchestrates on demoted model. Rejected: cap in `wantedModel` (r1) → shadowed held run slot + fail-open on `sessionModel` '' after /reload-plugins. Contract `.claude/tasks/contracts/2026-10-23-router-keyword-cap-0019.md`, plan r2.1 `.claude/tasks/plans/2026-10-23-router-keyword-cap-0019.md`. Links [[LRN-226]], [[EVAL-048]].
+7
View File
@@ -66,6 +66,7 @@ rules:
| EVAL-043 | 2026-10-11 | model-router W3-A: 3 lenses + 1 confirmation (census BLOCKER, project-tree layer dropped), feater DONE + 4 rounds, verifier 3× then re-verify after a REAL security BLOCK (credential fragment in the tracked key) | challenge + security gates both earned their cost; coverage-shaped criteria still cost 3 verifier rounds; live mod side effects misread as a test leak |
| EVAL-044 | 2026-10-11 | model-router W3-B (dialog with context): 3 lenses converged on 2 BLOCKERs of my r1 (inline rows, phase edits) + 1 confirmation; feater DONE + 2 coverage rounds; verifier 3× to CONFORME; security PASS; user's first real decision through the new dialog | the lenses pay most when the plan adds a data shape; coverage criteria still cost rounds; live dialogs during the gates must be announced and their data reconciled before commit |
| EVAL-045 | 2026-10-11 | model-router W4-B (prompt classifier): 3 lenses (BLOCKER: unbounded classify await) + 1 confirmation; feater DONE + 1 round; verifier ECARTS(2) → CONFORME; security PASS 0 findings; LRN-210 applied (one coverage clause per criterion) | first wave since W2 with no verifier cap: per-clause criteria + abort paths declared unverifiable up front cut the rounds to one |
| EVAL-048 | 2026-10-23 | model-router feat C keyword cap: 3 lenses FATAL(4)/FATAL(5)/CONCERNS on r1 (3 BLOCKER: run-slot shadow, probe-test hang, reload fail-open), mechanism rewritten, confirmation SOLID; verifier CONFORME 1st pass; 1st verifier died 429 on Fable |
---
@@ -430,3 +431,9 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse
- **Method**: /feat. r1 (author): context-size cap + engine-model return bypass + classifier full route. 3 blind lenses on r1: simplicity CONCERNS(3), correctness CONCERNS(4), robustness CONCERNS(3), 10 MAJOR, 0 BLOCKER, convergent (cold-read measure, classifier upgrade leak, bypass useless, test list incomplete, helper-skill demotion, haiku window). r2 written. ONE confirmation challenger on r2: FATAL(7) — BLOCKER served record only on routed steps (session model's cache invisible), + 6 MAJOR (test (d) `turnModel` survives `/route clear`, guess vs `cur` + breaker → haiku, floor hidden by guess tier, `pickSwitch` fails OPEN, compaction floor-at-0, `engineBase` process-wide kill). r3 → feater DONE first pass, 450 tests, verifier CONFORME 10/10 first pass, security PASS.
- **Anomalies**: author's r2 introduced 1 BLOCKER + 6 MAJOR while fixing r1 — a material rewrite is a NEW plan, the confirmation pass is not optional. `pickSwitch` "fail closed" was wrong by name: falls back to seeded default (now true). Verifier noticed 2 stale texts outside criteria (label comment, route tool description) — fixed by hand pre-commit (minor, justified). Doc-sync SIGNIFICANT: 13 patches, 3 docs stated the old default as a promise.
- **Action**: keep the single confirmation pass mandatory after any r2 that changes the mechanism (not just wording); when a plan says "fail closed", name the picker and its fallback value in the plan; TODO residuals (parentModel inheritance, usage lag, TTL const) carried, not dropped. Links [[BDR-116]], [[LRN-216]], [[EVAL-045]].
## EVAL-048 — model-router feat C: lenses killed r1 mechanism; second mechanism passed every gate first time
- **Method**: /feat. r1 = cap in `wantedModel` mirroring classifier. 3 blind lenses: correctness FATAL(4), robustness FATAL(5), simplicity CONCERNS(1). BLOCKERs: capped prompt slot shadowed held run (both correctness + robustness), probe-test one-line swap hangs (route tool answer probes), cap fail-open on `sessionModel` '' (/reload-plugins). r2 = effort-only routes at 3 writers + user pick (derived orchestrate too). 1 confirmation: SOLID, 5 MINOR applied (r2.1). feater DONE no deviation, 509 tests; GATE 0 12/12 MET; verifier CONFORME 14/14 1st pass; auditor PASS 0 findings; doc-sync SIGNIFICANT 5 patches.
- **Anomalies**: author r1 claim "identical to classifier" false: classifier never runs under a held route, prompt rules do. First verifier dispatched on Fable died 429 (credits out): LRN-224 residual (spawn path unprobed) seen live; retry landed on opus floor. Push of remote branch delete + first /feat Skill call blocked by auto-mode classifier.
- **Action**: when reusing a mechanism from another source, list the guards that source runs under (idle gate) before claiming equivalence. Links [[LRN-226]], [[LRN-224]], [[BLK-032]].
+4
View File
@@ -638,3 +638,7 @@ rules:
## 2026-10-22
- feat B merged (df38fd4). /bugfix mods.test.sh (bugfix/mods-validate-advisory): CLI 2.1.306 advisory ICON_MISSING section read as warning → verdict = `claude plugin validate --strict` rc through one helper + warnfix/cleanfix control; plan r3 (3 lenses + 1 re-challenge, sed-range fail-open killed), GATE 0 7/7, verifier ECARTS = out-of-scope routing.json dialog write (`confirmed.phases.audit`, uncommitted, user call), auditor PASS. 801992a. BLK-034, LRN-225. Next: feat C keyword rules capped at session model, close BLK-032.
## 2026-10-23
- Remote bugfix/mods-validate-advisory delete blocked by auto-mode classifier → user runs `git push origin --delete`. routing.json audit confirm committed eb4771e.
- /feat C (feature/router-keyword-cap): r1 cap in wantedModel killed by 3 BLOCKERs → r2 effort-only routes at writers + derived orchestrate (user pick), confirmation SOLID. 786ee13, verifier CONFORME 1st pass (1st died 429 Fable), auditor PASS, docs d2d590f. BLK-032 resolved, LRN-226, EVAL-048. Merge on user go.
+7
View File
@@ -245,6 +245,7 @@ rules:
| LRN-223 | 2026-10-21 | Regex timing lock is vacuous when the input matches early: feed a non-matching worst-path input, assert `is None`, keep ≥ 2x margin under the lock | every bounded regex test |
| LRN-224 | 2026-10-21 | Best-tier agent row floors on tier 2nd alias: inTier writes head-or-above only, fable frontmatter = no fallback in credit outage | pinning agents on best tier, census floors |
| LRN-225 | 2026-10-22 | Gate on tool's exit-code contract, never its prose; positive control through gate's own helper on clean/dirty fixture pair; mktemp EXIT trap script-level | any test that wraps a CLI verdict |
| LRN-226 | 2026-10-23 | Cap one axis of a layered route at the WRITER (effort-only route), never by filtering at the reader: reader cap shadows lower slots + depends on a baseline that can be unknown | any slot/precedence router, per-axis caps |
---
@@ -1878,3 +1879,9 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s
- **Context**: BLK-034. `grep -qi warning` on `claude plugin validate` output broke when CLI 2.1.306 added an advisory section; first plan (sed range delete between two markers) was fail-open: closing marker printed only when findings > 0, else range ran to EOF and hid `✔ Validation passed with warnings`.
- **Pattern**: (1) a CLI with `--strict` / `--json` / rc semantics → gate on rc, prose only in the ko message. (2) Positive control runs the SAME helper the gate uses (a copy of the invocation stays green when the gate drifts). (3) Pair of fixtures differing only in the guarded cause (warnfix vs cleanfix): parse error (`error: unknown option`, rc 1 on both) or scrape added back turns the pair red; a lone "rc must be 1" accepts any failure. (4) Inline sample strings test the author's literal, not the code: a check that cannot fail is not a check. (5) `WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT` stays script-level: `local` WORK + EXIT trap → `unbound variable` under `set -u`, dir leaks.
- **Apply**: any suite wrapping a third-party CLI verdict (plugin validate, linters, validators). Links [[BLK-034]], [[LRN-223]].
## LRN-226 — Cap one axis of a layered route at the writer, not at the reader
- **Context**: feat C model-router (BLK-032). r1 capped prompt routes inside `wantedModel` (drop model when above session). Challenge r1: capped `turnMain` still won slot order → hid held best-tier `runMain` (keyword reply in /feat run → opus); cap read `sessionModel`, '' after /reload-plugins → fail-open lift to fable.
- **Pattern**: writer emits effort-only route (`{effort}`, no tier/model, same as `belowRun`); existing per-axis rule (model-less slot skipped for model axis) falls through to run slot or keeps cur. No baseline read, no new predicate, dead floor-model branch removed.
- **Apply**: when a source must stop driving one axis, strip that axis where the route is written; check every lower-priority slot it used to shadow; a reader-side cap needs the baseline to be known at decision time, prove it or don't use it. Links [[BDR-123]], [[BDR-115]], [[EVAL-048]].
+2 -2
View File
@@ -7,7 +7,7 @@
- [~] routing policy /feat (user 2026-10-19, BLK-032): settings model → Opus 5.5; `judge` split (security-auditor + verifier → Fable, plan-challenger/analyzer/code review → opus); executors stay sonnet, "what to write" on opus; ceiling rule: main on Fable never writes code beyond a hotfix edit → dispatched executor; BDR superseding part of BDR-066 / BDR-115.
- [x] feat A audit phase: d3635b6 (dialog writes, session model opus), a7d747c (audit row, opus floor, census, citers), dae142b (docs); gates 0/1/2 green, LRN-224
- [x] feat B (feature/routing-ceiling-rule): ceiling rule CLAUDE.global.md, README doctrine, challenge citers, deploy `effort: xhigh`, routing.json `changed` cleared; ef13713 + 887cf89, gates 0/1/2 green, BDR-123; merge = user go
- [ ] feat C: cap the default keyword prompt rules (plan|design|architecture, why|review|audit|analyze, ultrathink) at the session model, effort only like the classifier; close BLK-032 after
- [x] feat C: cap the default keyword prompt rules (plan|design|architecture, why|review|audit|analyze, ultrathink) at the session model, effort only like the classifier; close BLK-032 after — DONE 2026-10-23 feature/router-keyword-cap: 786ee13 effort-only routes (keywords, ultrathink, derived orchestrate), d2d590f docs, gates green, BLK-032 resolved; merge = user go
- [x] bugfix lib/tests/mods.test.sh (bugfix/mods-validate-advisory): verdict = `--strict` rc, positive control warnfix/cleanfix; 801992a, gates green, BLK-034 LRN-225; merge = user go. Residual: 3 historical contracts keep the old scrape oracle (BLK-034)
- [ ] deferred (BDR-123): remap inline-writing best-tier skills (design Build stack, writing-skills, deprecation-and-migration, /tour single-project, /audit-delta 3d, /harden STEP 3); stale citers skills/feat/SKILL.md:6, skills/code-clean/SKILL.md:36
- [ ] residuals (accepted): spawn path unprobed, 1st gate of an outage window dies once (tour/onboard/audit-delta no retry); onAutoSwitch with main on opus marks nothing if engine auto-falls a gate off Fable
@@ -90,7 +90,7 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router
- [x] W1-B2 residuals CLOSED 2026-10-11: mods suite probe greps the `claude plugin test` usage line; doctor `plugin list --json` under `timeout 60`; update-all skips `@skills-dir` mods. Left (accepted): doctor `echo -e` helpers (tracked names only); fallback timeout guard orphans grandchildren without coreutils timeout.
- [x] W1 close-out (2026-10-09): doc-sync opus audit SIGNIFICANT → user go all 10 → patched (README effort routing + Explore row + /route, USAGE, ARCHITECTURE mods/, CHANGELOG Unreleased) b22f894; hot-reload link removed from `~/.claude/dev-mods/<session>/`; BDR-115 amended (a6e2003). Pending user: `/reload-plugins` in this session (new sessions load the skills-dir copy by themselves); merge decision on feature/model-router-mod (`gitflow finish`, human signal)
- [x] W1-C adaptive tiers (user 2026-10-09, contract `2026-10-09-model-router-tiers-1237`, plan r4 after 3 lenses + 2 confirmations: 6 BLOCKER + 29 MAJOR closed by named changes): phases name absolute tiers (best fable>opus>sonnet · big opus>fable>sonnet · work sonnet>opus · cheap haiku>sonnet); breaker fed by `classic.StopFailure` kinds rate_limit|overloaded|billing_error|model_not_found + `PostModelSwitch` auto (episode backoff 15→300 min, `/model` clears, `/clear` keeps, `/route reload` clears); fallback chain fable→opus→sonnet→haiku; main UPGRADE by default under `upgradeMaxTokens` 200k (fails closed on unknown usage), DOWNGRADE gated by `mainModelSwitch`; sticky `turnModel` per turn; derived `orchestrate` on background dispatches; prompt default rules (plan/reflect FR+EN, Unicode guards, skipped on `/…`, floor match, mid-turn). 58 tests; verifier CONFORME then 3 gap/hardening rounds; security PASS
- [ ] W1-C accepted-by-design (security 2026-10-09, MEDIUM, not coded around; 2026-10-11 closed: unranked `models` alias → `withEveryAlias` on the default chain too, `canonical` segment boundary `known + '-'`): (1) the model itself can raise the main loop to fable for the rest of a turn through the `route` tool (plan/reflect/escalate/judge) or a background dispatch (derived orchestrate = best tier) — bounded by the turn and `upgradeMaxTokens`, no sticky route is model-callable; (2) `ultrathink` and the default keyword rules now mean "best tier" (fable) at the phase's effort, so an incidental keyword in a pasted composer prompt costs a fable turn (origin composer only). Residuals: `PostModelSwitch` `auto` covers "other programmatic change" (a healthy model could be marked 15 min); strikes never decay inside a session; a `[1m]` variant's `model_not_found` marks the base model until reload; a `models` alias added by the override without a `fallback` key stays unranked (`withEveryAlias` not applied to the default chain) so `leaveDown` skips the upgrade gates for it; `canonical` prefix match has no segment boundary (`claude-sonnet-5-50` would map to sonnet); classifier deferred to W2
- [ ] W1-C accepted-by-design (security 2026-10-09, MEDIUM, not coded around; 2026-10-11 closed: unranked `models` alias → `withEveryAlias` on the default chain too, `canonical` segment boundary `known + '-'`): (1) the model itself can raise the main loop to fable for the rest of a turn through the `route` tool (plan/reflect/escalate/judge) or a background dispatch (derived orchestrate = best tier) — bounded by the turn and `upgradeMaxTokens`, no sticky route is model-callable; (2) `ultrathink` and the default keyword rules now mean "best tier" (fable) at the phase's effort, so an incidental keyword in a pasted composer prompt costs a fable turn (origin composer only). Residuals: `PostModelSwitch` `auto` covers "other programmatic change" (a healthy model could be marked 15 min); strikes never decay inside a session; a `[1m]` variant's `model_not_found` marks the base model until reload; a `models` alias added by the override without a `fallback` key stays unranked (`withEveryAlias` not applied to the default chain) so `leaveDown` skips the upgrade gates for it; `canonical` prefix match has no segment boundary (`claude-sonnet-5-50` would map to sonnet); classifier deferred to W2. 2026-10-23 feat C 786ee13: (1) derived-orchestrate part and (2) keyword/ultrathink part CLOSED (effort-only routes); (1) route-tool lift stays by design (sanctioned path)
- [x] W1-C live verification part 1 (2026-10-09 after `/reload-plugins`, skills-dir copy loaded, 12 hooks): derived orchestrate on a real background Explore (main high → medium while it ran → high after its end); Explore on sonnet/medium; `route plan` → next request xhigh (engine record); `Skill(effort-low)` bridged → next request low (engine record); `/route show` resolves all 10 phases to full ids, `down: none`; steps arrive as bare `claude-fable-5-1` (no `[1m]`) so the suffix carry never fires on this session
- [ ] W1-C live verification part 2 (needs a real incident): StopFailure vs turn.complete order; `PostModelSwitch` `auto` semantics and its `from_model` after a router upgrade; whether a router rewrite raises `auto`; `[1m]` carry validity on opus (only on a session whose steps carry it)
- [x] W2-A mod (2026-10-09, bb56f3e on feature/model-router-w2, contract `2026-10-09-model-router-w2a-1546`, plan r4 `2026-10-09-model-router-w2-1546`): user decisions — effort-* skills deleted (W2-B), pins REWORKED not deleted (rows = phases by role; frontmatter `model:`/`effort:` kept as census-locked off-state floor after a robustness BLOCKER), orchestrators declare phases, slim model gate. Phases `write` work/high + `apply` work/low; 56 skill rows, 21 agent rows; agents' model at spawn within tier, upward only, project-defined agents skipped (agent.offer); typed slash → name-bound marker (composer|sdk|bridge) + pending slot + idle fallback; best-tier rows in a `runMain` slot surviving turn end; unrowed skill leaves the route; route answer always names the id; `null` override rows. 3 lenses + 2 confirmations (1 BLOCKER each round closed), feater + 4 gap rounds, GATE 0 MET, verifier 3× ECARTS on coverage clauses only → user accepted at the cap, security PASS (2 MEDIUM pre-existing: first-load kill switch fails open, ReDoS size-bounded). Kit 58 → 88 tests. Doc-sync skipped for A (mod-only, docs at B).
@@ -0,0 +1,78 @@
# CONTRACT — router-keyword-cap (feat C of the routing policy, BLK-032)
- date: 2026-10-23 | flow: feat | branch: feature/router-keyword-cap
- status: active
## REQUEST (verbatim — IMMUTABLE)
push tout ce qui doit etre push et suprprime ce qui doit etre supprime et apres passe au feat C !
lance le /feat il ne cdevrait pas etre bloque je comprend pas
/feat args: feat C: model-router keyword rules capped at the session model (BDR-123 deferred item: keyword-lift gap), closes BLK-032. Context: .claude/memory/decisions.md BDR-123, blockers.md BLK-032, journal 2026-10-19..22. Uncommitted mods/model-router/routing.json adds "audit": "audit" in the phases map (dialog write from feat A).
TODO.md:10 (the feat C definition the request points at): "feat C: cap the default keyword prompt rules (plan|design|architecture, why|review|audit|analyze, ultrathink) at the session model, effort only like the classifier; close BLK-032 after"
## CLARIFICATIONS
- Internal: the cap reuses the classifier's ceiling (`wantedModel` + `wouldRunHead` in register.ts): a route whose source is `prompt` (default keyword rules AND prompt floor rules such as `ultrathink`, user-added rules from the machine config included) never names a model ranked above the session model; above it → no model move (main keeps its current model), the phase's effort still applies. Same semantics as the classifier, one shared predicate.
- Internal: the route tool (`source: model`), skill rows (`skill`/`run`), sticky `/route` (`user`) and derived dispatches stay uncapped: they are the sanctioned paths to Fable (BDR-123).
- Internal: an unknown or unranked session model leaves the cap inert, like the classifier; harmless because main is never switched off an unranked model (test `unknown: a session model absent from the table is never switched`).
- Internal: the mods/model-router/routing.json `"audit": "audit"` line (feat A dialog write, flagged out of scope by the BLK-034 verifier) is committed on this branch as its own commit by the orchestrator before dispatch; it is not part of the executor's diff.
- [gated 2026-10-23, after challenge r1] MECHANISM CHANGED (supersedes the first 3 internal bullets above): prompt rules (default keyword rules, `ultrathink` floor, user-added rules) and the derived `orchestrate` route on a main Agent dispatch write EFFORT-ONLY routes (`belowRun` pattern), so they never name a model; the model axis falls through to a held run slot or stays on the current model. `wantedModel`/`wouldRunHead` (classifier ceiling) are not edited. Reason: the r1 cap shadowed a held best-tier run slot (keyword reply inside /feat dropped Fable) and failed open on an unknown session model.
- [gated 2026-10-23] Derived orchestrate (background agent dispatch) capped too, same mechanism (user pick: "Oui, effort seul aussi").
- [gated 2026-10-23] Accepted edges (plan r2 §Edge cases): haiku session → keywords are no-ops; session model held down → keyword turn follows the plain-turn fallback; mid-turn ultrathink after a classifier demotion keeps the guessed model for that turn (amends BDR-115 2026-10-13 clause "floor model beats guess"); no stand-in notch on keyword turns.
## ACCEPTANCE CRITERIA
1. The mods suite is green (manifest, link, validate --strict, `claude plugin test` running register.test.ts).
CHECK: cd /home/bchanot/Documents/claude && make test suite=lib/tests/mods.test.sh 2>&1 | tail -3
EXPECT: all suites green
EVIDENCE: MET exit=0 marker-found :: PASS model-router: plugin test passed mods: 6 pass, 0 fail all suites green
2. On an opus session, a typed default keyword prompt of the `plan` rule (e.g. `plan the billing migration`) runs the next main step on opus, never fable, at the plan phase's effort (xhigh). A dedicated test named `keyword cap: a plan keyword on an opus session stays on opus at xhigh` exists in register.test.ts.
CHECK: grep -c "test('keyword cap: a plan keyword on an opus session stays on opus at xhigh'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
3. On an opus session, a typed `reflect` keyword prompt (e.g. `why does the cache miss`) runs on opus at the reflect phase's effort (high). Test `keyword cap: a reflect keyword on an opus session stays on opus at high`.
CHECK: grep -c "test('keyword cap: a reflect keyword on an opus session stays on opus at high'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
4. On an opus session, `ultrathink` runs on opus at effort max (floor kept, model capped). Test `keyword cap: ultrathink on an opus session stays on opus at max`.
CHECK: grep -c "test('keyword cap: ultrathink on an opus session stays on opus at max'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
5. The sanctioned lifts still reach fable on an opus session: a keyword turn followed by a route tool call `phase: 'plan'` runs on fable. Test `keyword cap: a route tool call after a keyword still lifts to fable`.
CHECK: grep -c "test('keyword cap: a route tool call after a keyword still lifts to fable'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
6. A capped keyword is never a stand-in: on an opus session with fable held down, a `plan` keyword runs on opus at xhigh (no +1 stand-in notch), and no probe of fable is made. Test `keyword cap: a held fable gives no stand-in notch to a capped keyword`.
CHECK: grep -c "test('keyword cap: a held fable gives no stand-in notch to a capped keyword'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
7. [gated 2026-10-23] Fable-session tests keep their expectations, except the ones plan r2 §Tests B names (l.935 rebased, l.5300 renamed, l.5690 effort max→xhigh), each edit carrying a one-line comment saying why (verifier reads the diff).
8. [gated 2026-10-23] The probe tests l.5564, l.5597, l.5636 lift through `planRoute($)` as plan r2 §Tests B spells out; their subject (probe of fable, hold lengths, in-flight failure leaves the target unverified) is still asserted; expectation edits limited to what plan r2 names, each commented.
9. [gated 2026-10-23] `defaultFromPrompt`, the floor branch of `routeFromPrompt` and `pushOrchestrate` write routes with an `effort` and no `tier`/`model` (one shared helper); `wantedModel` and `wouldRunHead` are byte-identical to develop; `mainModelSlot` no longer reads `turnFloor`.
CHECK: cd /home/bchanot/Documents/claude && f=mods/model-router/hooks/register.ts && a=$(git show HEAD:$f | sed -n '/^function wantedModel/,/^}/p;/^function wouldRunHead/,/^}/p' | md5sum) && b=$(sed -n '/^function wantedModel/,/^}/p;/^function wouldRunHead/,/^}/p' $f | md5sum) && c=$(sed -n '/^function mainModelSlot/,/^}/p' $f | grep -c turnFloor || true) && d=$(sed -n '/^function defaultFromPrompt/,/^}/p;/^function routeFromPrompt/,/^}/p;/^function pushOrchestrate/,/^}/p' $f | grep -c 'phaseRoute(' || true) && e=$(grep -c '^function mainModelSlot' $f || true) && [ "$a" = "$b" ] && [ "$e" = 1 ] && echo "ceiling-same slot-floor=$c phaseRoute-in-writers=$d"
EXPECT: ceiling-same slot-floor=0 phaseRoute-in-writers=0
EVIDENCE: MET exit=0 marker-found :: ceiling-same slot-floor=0 phaseRoute-in-writers=0
10. lib/effort-shift.md "Limits" states that keyword prompt rules, `ultrathink` and a background agent dispatch set the turn's effort only, never a model above the session model, Fable on main coming only from a skill row, the `route` tool or a typed `/route`; lines ≤ 80 columns.
CHECK: f=/home/bchanot/Documents/claude/lib/effort-shift.md; a=$(tr '\n' ' ' < $f | tr -s ' ' | grep -c 'never a model above the session model'); b=$(awk 'length($0)>80' $f | wc -l); echo "cap=$a/long=$b"
EXPECT: cap=1/long=0
EVIDENCE: MET exit=0 marker-found :: cap=1/long=0
11. The executor's diff touches only the FILE SCOPE.
CHECK: cd /home/bchanot/Documents/claude && git diff --name-only HEAD | grep -v -x -e mods/model-router/hooks/register.ts -e mods/model-router/hooks/register.test.ts -e lib/effort-shift.md | wc -l | sed 's/^/outside=/'
EXPECT: outside=0
EVIDENCE: MET exit=0 marker-found :: outside=0
12. [gated 2026-10-23] A keyword reply inside a held best-tier run keeps main on fable (opus session). Test `keyword cap: a keyword inside a held best-tier run keeps the run on fable`.
CHECK: grep -c "test('keyword cap: a keyword inside a held best-tier run keeps the run on fable'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
13. [gated 2026-10-23] An unknown session model ('') never lets a keyword lift main. Test `keyword cap: an unknown session model never lets a keyword lift main`.
CHECK: grep -c "test('keyword cap: an unknown session model never lets a keyword lift main'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
14. [gated 2026-10-23] A main background dispatch outside a run keeps main on the opus session model at orchestrate's effort. Test `keyword cap: a dispatch outside a run keeps main on the session model`.
CHECK: grep -c "test('keyword cap: a dispatch outside a run keeps main on the session model'" /home/bchanot/Documents/claude/mods/model-router/hooks/register.test.ts
EXPECT: 1
EVIDENCE: MET exit=0 marker-found :: 1
## FILE SCOPE
- mods/model-router/hooks/register.ts
- mods/model-router/hooks/register.test.ts
- lib/effort-shift.md
@@ -0,0 +1,231 @@
# PLAN r2.1 — router-keyword-cap (feat C, BLK-032)
Contract: `.claude/tasks/contracts/2026-10-23-router-keyword-cap-0019.md`
Branch: feature/router-keyword-cap (off develop 6168d90)
## r1 → r2 (challenge round 1: correctness FATAL(4), robustness FATAL(5), simplicity CONCERNS(1))
- BLOCKER (correctness 1, robustness 1): r1 capped the prompt slot in
`wantedModel`; a capped `turnMain` then shadowed a held best-tier
`runMain` (mainModelSlot order) → a keyword reply inside a /feat run
dropped main from Fable to opus. CLOSED by changing the mechanism:
prompt rules write EFFORT-ONLY routes (the `belowRun` pattern,
register.ts:3060), so the model axis falls through to `runMain` by the
existing per-axis rule (test `per axis: a model-less sticky never hides
a turn route tier`). `wantedModel` / `wouldRunHead` are NOT edited.
- MAJOR (robustness 2, correctness 7): r1 failed open when `sessionModel`
is '' (after /reload-plugins). CLOSED by the same change: an
effort-only route never names a model, whatever the session model.
- BLOCKER (correctness 2) / MAJOR (robustness 3): r1's one-line swap of
the probe tests hangs or goes red (the route tool's answer runs the
probe). CLOSED: per-test rewrites spelled out below.
- MAJOR (all three): tests l.935 and l.1011 (HAIKU sessions) missed.
CLOSED: named below with their new form.
- MAJOR (robustness 5, correctness 6): derived `orchestrate` on a main
Agent dispatch still lifted main to Fable. User decision 2026-10-23:
cap it too, same mechanism (effort-only).
- MINOR (test 5 setup, all three): hold fable with
`switchTo($, FABLE, OPUS, 'auto')`, as the classifier stand-in test.
- MINOR (correctness 5, 8; robustness 6, 7): edge notes corrected below;
robustness 7 (auto fallback rewrites sessionModel) is moot, nothing
reads sessionModel any more for prompt routes.
## r2 → r2.1 (confirmation pass: correctness SOLID, 5 MINOR, all applied)
- l.5636 completions spelled out: `[FABLE, OPUS, FABLE]`.
- `effortRoute` returns `{}` (not undefined) for a phase with no effort,
so a matched rule still claims the turn and the classifier stays off.
- Derived-dispatch edges added below.
- `mainModelSlot` stays a `function` declaration (oracle reads it).
- A6 types a PLAN keyword and expects `{ model: FABLE, effort: 'xhigh' }`;
every new test name stays on ONE line even past 80 columns (oracles
grep it; l.5690 is the precedent).
## Problem
`register.ts` DEFAULTS.prompt (l.295-309): `ultrathink` (floor, phase
escalate), plan keywords (default, phase plan), reflect keywords
(default, phase reflect); all three phases are `tier: best` → fable.
`defaultFromPrompt` (l.3924) writes `turnMain` and `routeFromPrompt`
(l.3937-3943) writes `turnFloor` with the phase's FULL route (tier +
effort), `source: 'prompt'`. `pushOrchestrate` (l.3251) writes the full
`orchestrate` route (`tier: best`), `source: 'derived'`, on every main
Agent dispatch not under a model/skill route. On the `opus` session
(BDR-123) each lifts main to Fable with no skill row involved.
## Approach
1. register.ts — one helper next to `phaseRoute` (l.352):
```ts
/** A phase's effort alone: a route that never moves main's model. */
function effortRoute(cfg: Config, phase: string): Route | undefined {
const route = phaseRoute(cfg, phase)
if (route === undefined) return undefined
return route.effort === undefined ? {} : { effort: route.effort }
}
```
2. Use it at the three writers, replacing `phaseRoute(...)` +
`{ ...route }`:
- `defaultFromPrompt` (l.3926-3928): `effortRoute(st.cfg, rule.phase)`;
- `routeFromPrompt` floor (l.3940-3942): `effortRoute(st.cfg,
floor.phase)`;
- `pushOrchestrate` (l.3253-3257): `effortRoute(st.cfg,
'orchestrate')`.
Phase names, sources, labels, precedence: unchanged. The effort path
(`mainEffort` l.1663) reads `route.effort` only, so efforts are
unchanged; only the model axis changes.
3. Dead code: no floor route carries a model any more (`turnFloor` is
written only by `floorFromPrompt`/`endMainTurn` from prompt rules;
`PromptRule` has no `model` field). In `mainModelSlot` (l.1385-1397)
drop `st.turnFloor` from the slot list and the classifier-vs-floor
branch; the function becomes `[userMain, turnMain, runMain].find(...)`,
kept as a `function` declaration.
Update its doc comment (no "floor's own model").
4. Comments: DEFAULTS comment above `prompt:` (l.293-294): "Rules set the
turn's effort only, never a model." `pushOrchestrate` doc: "the turn's
effort becomes orchestrate's; the model stays where it is (a held run
keeps its model)." Keep 80 columns.
5. lib/effort-shift.md "Limits", new bullet after the classifier one:
```
- Keyword prompt rules (`plan|design|architecture…`,
`why|review|audit…`), `ultrathink` and a background agent
dispatch (derived `orchestrate`) set the turn's effort only, never
a model above the session model: Fable on main comes only from a
skill row, the `route` tool or a typed `/route`.
```
(wording: "never a model above the session model" is the contract
oracle string; effort-only routes name no model at all, which
satisfies it.)
## Out of scope (unchanged on purpose)
- Route tool (`model`), skill rows (`skill`/`run`), sticky `/route`
(`user`): the sanctioned Fable paths (BDR-123).
- Classifier: unchanged (its ceiling in `wantedModel`/`wouldRunHead`
stays as is; it never runs under a held route).
- `userMovedEffort` (l.3501): classifier-only, unchanged.
- README.md / USAGE.md / CHANGELOG: STEP 6 doc-sync (README l.142 says
"an `ultrathink` floor in the same turn keeps its own model": stale
after this change, doc-sync must catch it).
## Edge cases (decided)
- Keyword reply inside a best-tier run: effort from the keyword, model
from `runMain` (Fable). New test.
- `sessionModel` '' (after /reload-plugins): no lift, the route names no
model. New test.
- Fable session (old setting): keyword turns start on fable and stay
there (cur = session); efforts unchanged.
- Haiku session: a keyword or `ultrathink` never moves main off haiku;
`planStep` strips effort on haiku (l.3572-3574), so they are no-ops.
Accepted (never above the session model).
- Session model held down (e.g. opus outage on an opus session): a
keyword turn follows `leaveDown(cur, undefined)` like any plain turn
(→ sonnet), where it used to reach fable. Accepted: same as a plain
prompt; the route tool or a skill row still reach fable.
- Fable held + keyword: the prompt route names no tier, `heldHead`
(l.1565) is undefined → no stand-in notch. On a fable session whose
fable is dead (`probe: a session model that never answers…`, l.5690)
the keyword turn lands on opus at xhigh, no longer max.
- Mid-turn `ultrathink` after a classifier demotion in the same turn:
the floor names no model, so the guess's model holds for the rest of
that turn (sonnet, at max); the pending floor carries to the next turn,
which starts on the session model. This AMENDS BDR-115 amendment
2026-10-13 "ultrathink floor model beats guess" (recorded at
CAPITALIZE).
- Derived orchestrate outside a run on the opus session: main stays on
opus at orchestrate's effort (medium). Inside a held run: the run's
model (Fable). After the pop nothing to restore on the model axis.
- Derived dispatch after a classifier demotion in the same turn: main
orchestrates on the demoted model (`turnModel`, e.g. sonnet) for the
rest of the turn, where develop lifted it to fable; spawned agents are
still pinned to the session model by `sessionPin` (l.3184). Accepted.
- Derived dispatch with fable held: no stand-in notch (no tier named).
Accepted.
- A phase with no effort (machine config): the rule writes an empty
route `{}`, still claiming the turn (classifier stays off).
- `turnModel` (sticky per turn) is only set when the router moved main;
effort-only routes never move it, so no sticky fable after a dispatch.
## Tests (mods/model-router/hooks/register.test.ts)
A. New block `// ---- keyword cap: prompt rules and dispatches set effort only`,
each test asserting the step's `{ model, effort }`:
1. `keyword cap: a plan keyword on an opus session stays on opus at xhigh`
— `bootRig($, on, OPUS)`, typed `plan the billing migration`,
`stepOn($, rig, OPUS)` → `{ model: OPUS, effort: 'xhigh' }`.
2. `keyword cap: a reflect keyword on an opus session stays on opus at high`
— typed `why does the cache miss` → `{ model: OPUS, effort: 'high' }`.
3. `keyword cap: ultrathink on an opus session stays on opus at max`
— `ultrathink($)` → `{ model: OPUS, effort: 'max' }`.
4. `keyword cap: a route tool call after a keyword still lifts to fable`
— typed plan keyword, `planRoute($)`, step → model FABLE.
5. `keyword cap: a held fable gives no stand-in notch to a capped keyword`
— `bootRig($, on, OPUS, 1000, world)` with `newWorld()`,
`switchTo($, FABLE, OPUS, 'auto')` (marks fable down, no probe),
typed plan keyword, step on OPUS → `{ model: OPUS, effort: 'xhigh' }`,
`world.completions` contains no FABLE.
6. `keyword cap: a keyword inside a held best-tier run keeps the run on fable`
— opus session; hold a best-tier run slot the way the existing
`run slot:` tests do (l.1159-1230: typed rowed best-tier skill +
Skill call), `endTurn($)`, typed `plan the next step`, step on
OPUS → `{ model: FABLE, effort: 'xhigh' }`.
7. `keyword cap: an unknown session model never lets a keyword lift main`
— `bootRig($, on, '')` (session.model answers ''), typed plan
keyword, `stepOn($, rig, OPUS)` → model OPUS.
8. `keyword cap: a dispatch outside a run keeps main on the session model`
— opus session, a main background Agent dispatch the way the
existing `derived:` tests do (l.914), step during the dispatch on
OPUS → `{ model: OPUS, effort: 'medium' }`.
B. Existing tests to rewrite (expectation edits allowed ONLY here, each
with a one-line comment saying why):
- l.935 `default rule: planifie sets plan, a later route overrides`:
boot on FABLE (`bootRig($, on)`), `stepOn($, rig, FABLE)`, expect
`{ model: FABLE, effort: 'xhigh' }`; rest unchanged.
- l.1011 `text: show names the model a floor upgrade moves to`:
the behaviour is gone; replace with `text: show names no model move
for an ultrathink floor` — `bootRig($, on, OPUS)`, ultrathink, the
main line contains `floor max` and not `(upgrade)` nor FABLE.
- l.5300 `classify: a mid-turn ultrathink floor still reaches fable max`:
rename `classify: a mid-turn ultrathink floor raises effort only`,
expect `{ model: SONNET, effort: 'max' }`.
- l.5564 `probe: a fable that never answers lands the plan step on opus`:
`await pastProbe(rig, planRoute($))` in place of the typed keyword,
then `await runStep($, { ...highStep(), model: OPUS })`; `seen`
and the `down:` line unchanged; `completions` → `[FABLE, OPUS]`
(fable probed by the route call, opus by the step).
- l.5597 `probe: a lapsed hold probes again and holds longer`:
`await pastProbe(rig, planRoute($))` per loop turn in place of the
typed keyword; expectations unchanged if they hold (derive: route
probes FABLE, first step probes OPUS, second turn probes FABLE).
- l.5636 `probe: a failure during the flight keeps the target unverified`:
start `const call = planRoute($)` (in flight on the gated probe),
`await rig.clock.settle()`, `switchTo($, FABLE, OPUS, 'auto')`,
`open()`, `await call`, then the step; after the 15 min advance a
second `planRoute($)` + step. Invariant asserted: FABLE appears
twice in `completions` (still unverified after the in-flight
failure): `completions` → `[FABLE, OPUS, FABLE]` (route probe
fails in flight, re-decision lands on opus unprobed, the step
probes opus, the second route probes fable); `seen[0]` stays
`{ model: OPUS, effort: 'max' }`.
- l.5690 `probe: a session model that never answers leaves for opus on the first step`:
effort `max` → `xhigh` (a keyword names no tier: no stand-in notch).
- Any OTHER test the suite turns red: if its subject is a model lift
by a keyword, `ultrathink` or a derived dispatch, rewrite it to the
effort-only result with a comment; for any other subject → STOP,
report BLOCKED with the test names and failures.
Suite: `make test suite=lib/tests/mods.test.sh`.
## Disposition (memory)
- honors BDR-123: Fable on main only through rows, route tool, `/route`;
closes its keyword-lift known gap and the derived-orchestrate leak.
- honors BDR-115 rule 5 "per axis" and the `belowRun` precedent
(effort-only route under a run); AMENDS BDR-115 amendment 2026-10-13
clause "ultrathink floor model beats guess" (edge above).
- honors LRN-218 / BLK-031: probe lands on the decided model, untouched.
- LRN-224: agent rows untouched.
- BLK-032 → resolved at CAPITALIZE; TODO W1-C accepted-by-design (1)
derived-orchestrate part and (2) keyword part closed.
+2 -1
View File
@@ -13,7 +13,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project
- **model-router first-use confirmation**: `mods/model-router/routing.json` (tracked) is the single source of the phase table and of every skill and agent row, and keeps the decisions: `confirmed`, `changed` (`from`/`to`), `projects` exceptions keyed by the origin remote reduced to `host/path` (credentials and local paths never stored), and `ask`. The first use of a rowed typed skill, a rowed agent spawn or a main-loop phase declared through the `route` tool opens a dialog with context: the skill's description (first sentence of its `SKILL.md` frontmatter) or the agent's, the phase with its `about` line (a new field on each of the 12 phases) and the model id and effort the next step really runs on. A row offers Later, Keep or Change; a main-loop phase Later or Keep. Change asks the model (fable, opus, sonnet, haiku with their tier), then the effort among those the phases of that model use (skipped when there is only one), then Everywhere or This project only; the pair maps to an existing phase (rows stay phase names, the same phase counts as Keep, a pair no phase offers is added by hand as a new phase). A skill-row change toasts the model and effort it now runs on, with the `/route switch on` hint when the main loop holds back a downgrade; a free-text answer counts as Later. One dialog at a time, never in headless (`-p`) runs or inside a sub-agent. Only a dialog answer, `/route ask on|off` or `/route forget` (which takes decisions back; a changed row returns to its shipped phase, the frontmatter floors stay yours to realign) writes the file (serialized, 64 KiB cap, never created when absent); each write asks you to commit it from the config repo. `/route pending` lists unconfirmed rows and phases. Layers: routing.json < `~/.claude/model-router.json` (its `ask` wins); a project's `.claude/model-router.json` is never read. Tests: `mods/model-router/hooks/register.test.ts`.
- **Manual-push mode**: `git config gitflow.autopush false` (human-set) now stops every push the gitflow lib makes, not only the post-commit / post-merge hooks. `gitflow start` and `finish` branch, commit and merge locally and push nothing; `gitflow delete` leaves the `origin/` copy in place and prints `git push origin --delete <br>` for the user to run. `hooks/unpushed-guard.sh` stays silent at turn end in this mode and opens each session with one `ℹ manual push mode:` line counting the commits no remote holds across every local branch; an unparseable or unreadable `gitflow.autopush` value is treated as manual push mode too, and that line names it. `hooks/push-guard.sh` (PreToolUse, `Bash|Monitor`) refuses any `git push` Claude types while `gitflow.autopush` reads false in the session cwd or in a literal `-C`/`cd` directory the command names (global config counts outside a repo); the refusal tells the user to run it with `! git push`. It reads the mode through the same lib verb as every other reader and fails closed: an unparseable or unreadable value reads as manual, and an internal error, a missing `lib/gitflow.sh`, more than 20 distinct directory tokens in one command (capped before any token is classified), a `cd`/`-C` directory token mixing quoted and unquoted parts, or a payload jq cannot parse whose raw text looks like a push refuse the push (these pathological cases fire in auto mode too). Directory tokens are read as whole shell words, adjacent quoted segments and backslash escapes included. Once the text looks like a push, the command is split into simple commands (quotes, escapes, separators, heredoc bodies dropped) and a push must be git's own subcommand in one of them: `grep "git push"`, `git log -S "git push"`, `git config --get push.default`, `git stash push`, a heredoc quoting a push or a commit message naming one are allowed; `bash -c` scripts are re-checked, wrappers (`sudo`, `env`, `eval`, `xargs`, `timeout`, `git subtree`...) and assignments keep the text verdict. The misses listed in its header fall to a new `autoMode.soft_deny` rule that no request in the turn clears. The session banner adds `🔒 push : manual (autopush=false) — ! git push` when the key reads false, and `🔒 push : manual (autopush bad) — ! git push` when the value is invalid. Skills read the mode through a new lib verb, `bash ~/.claude/lib/gitflow.sh push-mode`: it prints `auto`, `manual` or `invalid` (rc 0) and names an invalid value on stderr (printable characters only, 64 at most). It is the one reader a skill may call, since the `git config` read of the key is denied to Claude. Skills push nothing on their own, except the `/release-candidate` tag in auto-push mode on an explicit go. Every "on origin" or "not pushed" line they print comes from `git rev-list --count origin/<br>..<br>` read after the fact, with the complete `! git …` command when something is left for the user to push. An invalid value (anything but unset, true or false, or a read that fails) is manual push mode for every reader and is named where it is read (see Fixed). Tests: `lib/gitflow-test.sh` T11b (push-mode verb), T18m and T18q blocks, `lib/tests/unpushed-guard.test.sh` T10-T16, `lib/tests/push-guard.test.sh` (98 checks).
- **model-router prompt classifier**: a plain prompt typed in the composer (12 characters or more, not a slash command, not mid-turn, never under `-p` or in a sub-agent) that no keyword rule, skill, run slot, `/route` or floor covers is labelled by one call to the engine's small model (`design`, `analysis`, `coding`, `bookkeeping`, `chat`), bounded to 3 s. The label maps to plan, reflect, implement or apply and the turn takes that phase's route: its effort, and its model under the switch and the downgrade cap, never above the session model (an `ultrathink` floor keeps its model); no dialog, no file write, gone at the end of the turn, replaced by any route call or typed skill, and dropped for that turn by a `/effort` typed between turns. Three failures in a row pause it for `cooldownMinutes` (one toast, `classifier: paused` in the status line). `"classify": false` in `~/.claude/model-router.json` and `/route classify on|off` turn it off; `/route show` prints `classify:`. The status line reads `route: classifier <phase>` and `/route verbose on` adds `(<phase>: classifier)`.
- **model-router prompt classifier**: a plain prompt typed in the composer (12 characters or more, not a slash command, not mid-turn, never under `-p` or in a sub-agent) that no keyword rule, skill, run slot, `/route` or floor covers is labelled by one call to the engine's small model (`design`, `analysis`, `coding`, `bookkeeping`, `chat`), bounded to 3 s. The label maps to plan, reflect, implement or apply and the turn takes that phase's route: its effort, and its model under the switch and the downgrade cap, never above the session model (an `ultrathink` floor raises the effort only, the guess's model holds); no dialog, no file write, gone at the end of the turn, replaced by any route call or typed skill, and dropped for that turn by a `/effort` typed between turns. Three failures in a row pause it for `cooldownMinutes` (one toast, `classifier: paused` in the status line). `"classify": false` in `~/.claude/model-router.json` and `/route classify on|off` turn it off; `/route show` prints `classify:`. The status line reads `route: classifier <phase>` and `/route verbose on` adds `(<phase>: classifier)`.
- **model-router cold-read caps**: both main-loop caps measure the cold read a switch costs, from a per-model record of main's last step, warm within the engine's prompt-cache TTL (`cache_ttl` 5m or 1h from main's model-switch events, 1 h before the first, kept across `/clear`; records cleared by `/clear` and `/route reload`), plus the submitted prompt the engine's usage may not count yet (code points / 3 of its text, context entries and a typed skill's body, added at the turn's first main step unless usage already grew by half of it; a `document` attachment blocks the switch for that step); `downgradeMaxTokens` (default 120000) joins `upgradeMaxTokens` (200000). A model-loaded helper skill inside a best-tier run moves effort only; main routed onto a model whose window the context outgrew returns to the session model. `/route show` prints `switch: on (downgrade, cap 120000 tokens cold, ttl 60 min)`, the status line shows ` · switch off` only when the switch is off, the skip line is logged once per cap crossing and the change toast names a cap hold. A built-in `general-purpose` agent that main spawns with no model while main sits below the session model starts on the session model instead of inheriting the lower one.
- **/explain-diff skill**: turns a change (commit, range, branch, merge, PR, staged or uncommitted work) into one self-contained HTML page saved outside the repo, under `~/Documents/explanations/<project>/YYYY-MM-DD-<slug>.html`. The page has a background, an intuition built on toy data with HTML diagrams, a code walkthrough grouped by concern and a 5-question interactive quiz. Adapted from Geoffrey Litt's explain-diff gist. A bundled template (light and dark, works offline) and a checker (`scripts/check_explanation.py`: file name, location, sections, quiz, code escaping, no ASCII art, no em-dash) hold every page to the same floor. Routing row `reflect`; profiles full, max and dev.
@@ -31,6 +31,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project
- `/client-handover` no longer asks "Push to origin now?" and no longer pushes: the hooks had already pushed in auto-push mode, and push-guard refuses it in manual mode. The agent reads the branch's ahead count after the fix-loop commits, at the deploy pause and before each end report. A pending push is handed to the user as `! git push -u origin <branch>` before the deploy pause, and both reports carry a `Push:` line. A branch name outside `^[A-Za-z0-9._/][A-Za-z0-9._/-]*$` is never interpolated into a command.
- `/release-candidate` STEP 6: in manual push mode, with an invalid mode value, or when main or develop is not on origin, Claude pushes nothing and prints one command for the user, `! git push --atomic origin main develop v<X.Y.Z>`. The tag-push question remains for auto-push mode with both branches on origin. The version must match `^[0-9]+\.[0-9]+\.[0-9]+$` before it enters a command or tag; `release-executor` checks it too and blocks on anything else.
- `/tour`: each summary row says `on origin` or `local only` with the `! git -C "<project>" push -u origin <branch>` to run. The tour never pushes or retries.
- model-router keyword prompt rules (`plan|design|architecture…`, `why|review|audit…`), the `ultrathink` floor and the derived `orchestrate` route of a main Agent dispatch set the turn's effort only, never a model: they no longer lift main above the session model, and a held best-tier run keeps its model. Fable on main comes only from a skill row, the `route` tool or a typed `/route` (BDR-123). Tests: `mods/model-router/hooks/register.test.ts`.
### Removed
- The five `effort-low` … `effort-max` skills, `lib/effort-pins.txt`, `lib/effort-pins.sh` and `lib/model-check.sh`, with their tests and the effort-pin re-apply steps of `install-plugins.sh` and `update-all.sh`. The model-router rows replace them. A typed `/effort-<level>` no longer exists: use `ultrathink` or `/route effort=max`. Breaking: the next release is 3.0.0.
+2 -2
View File
@@ -138,8 +138,8 @@ effort, never version. Transcript audit `python3 lib/effort-audit.py`.
- Main loop: every request gets the route in force. A typed skill with a row routes the main loop to it; a best-tier row (`plan`, `reflect`, `orchestrate`, `escalate`; `audit` is an agent row, never typed) holds across turns in a run slot until `/route clear`, `/route off`, a user `/model` or a typed skill on a non-best row. A skill without a row leaves the route as it is. A rowed skill the model loads inside a best-tier run moves effort only when its row ranks below the run's model. Main routed onto a model whose context window the conversation outgrew returns to the session model. Before main runs on a model, the one it moves to or the one it keeps (the session's own model included), the mod probes it with one small completion bounded to 8 seconds; the step (and `/route show`, the route tool's answer) waits for it. A timeout or an error marks the model down (reason `probe`, held for `cooldownMinutes` like any breaker hold) and the decision is taken again once. A model already marked down is never probed, and a model that answered is not probed again, `/clear` included, until it is marked down. When a lower model stands in for its tier's head held down (Opus for Fable on a best-tier phase), the phase's own effort goes one notch up: `reflect` xhigh, `plan` max, `orchestrate` high, `escalate` stays max. An effort asked explicitly (`/route ... effort=`, the `route` tool's `effort`) or set by a floor is never raised. `/route show` and the route tool's answer print the level with `(opus stands in for fable)`; the verbose transition line names `stand-in` as a cause.
- Sub-agents: a routed agent gets its row's model at spawn, within its tier and only upward from its frontmatter model, and the row's effort on every step. Explicit `model` / `effort` params on the Agent call win; a project-defined agent of the same name keeps its own definition. Built-ins: Explore runs on sonnet/medium, Plan on opus/xhigh. A built-in `general-purpose` agent that main spawns with no `model` param, while main runs below the session model (a downgrade or a breaker fallback), starts on the session model instead of inheriting the lower one; it is not pinned when the session model is marked down, for a fork, a workflow or a nested spawn, or when a project or user definition shadows the built-in. Other agent types are never pinned this way: the hook cannot see their frontmatter model.
- Levers inside a run: `ultrathink` in a prompt sets the turn's minimum effort; `/route effort=max` holds until `/route clear`. The built-in `/effort` is not a lever inside a run, rows and routes outrank it.
- Prompt classifier: a plain prompt typed in the composer (12 characters or more, not a slash command) that no keyword rule, skill, run slot, `/route` or floor covers is sent to the engine's small fast model, one call, bounded to 3 seconds (the prompt waits for it, typically under a second). The label (`design`, `analysis`, `coding`, `bookkeeping`, `chat`) maps to plan, reflect, implement or apply (`chat` routes nothing), and the turn takes that phase's route: its effort becomes the turn's default, and its model may move the main loop, never above the session model. A `coding` or `bookkeeping` guess moves main down only when `mainModelSwitch` is on and the cold read fits `downgradeMaxTokens`; an `ultrathink` floor in the same turn keeps its own model. No dialog opens and no file is written. The route is gone at the end of the turn, a later route call or typed skill replaces it, and a `/effort` you type between turns drops the guess for that turn only. A typed best-tier skill holds its run slot across turns, so nothing is classified there until `/route clear`. Long prompts are sampled (first 500 and last 1500 code points), so pasted text at the end can steer one turn's route. Three failures in a row pause it for `cooldownMinutes` (one toast, `classifier: paused` in the status line). Never in a sub-agent, mid-turn or under `-p`. Off per session with `/route classify off`, per machine with `"classify": false`. The status line reads `route: classifier <phase>`; `/route verbose on` adds the transition line.
- Levers inside a run: `ultrathink` in a prompt sets the turn's minimum effort; `/route effort=max` holds until `/route clear`. Keyword prompt rules (`plan`, `design`, `architecture`… take plan's effort; `why`, `review`, `audit`… reflect's), `ultrathink` and a main Agent dispatch (the derived `orchestrate` route, held until its background agents end) set the turn's effort only, never a model: they never lift main above the session model, and a held best-tier run keeps its model. Fable on main comes only from a skill row, the `route` tool or a typed `/route`. The built-in `/effort` is not a lever inside a run, rows and routes outrank it.
- Prompt classifier: a plain prompt typed in the composer (12 characters or more, not a slash command) that no keyword rule, skill, run slot, `/route` or floor covers is sent to the engine's small fast model, one call, bounded to 3 seconds (the prompt waits for it, typically under a second). The label (`design`, `analysis`, `coding`, `bookkeeping`, `chat`) maps to plan, reflect, implement or apply (`chat` routes nothing), and the turn takes that phase's route: its effort becomes the turn's default, and its model may move the main loop, never above the session model. A `coding` or `bookkeeping` guess moves main down only when `mainModelSwitch` is on and the cold read fits `downgradeMaxTokens`; an `ultrathink` floor in the same turn raises the effort only, the guess's model holds. No dialog opens and no file is written. The route is gone at the end of the turn, a later route call or typed skill replaces it, and a `/effort` you type between turns drops the guess for that turn only. A typed best-tier skill holds its run slot across turns, so nothing is classified there until `/route clear`. Long prompts are sampled (first 500 and last 1500 code points), so pasted text at the end can steer one turn's route. Three failures in a row pause it for `cooldownMinutes` (one toast, `classifier: paused` in the status line). Never in a sub-agent, mid-turn or under `-p`. Off per session with `/route classify off`, per machine with `"classify": false`. The status line reads `route: classifier <phase>`; `/route verbose on` adds the transition line.
- `/route` (user command) shows or sets the route: `show`, `clear`, `off`, `on`, `reload`, `pending` (rows and phases not confirmed yet), `ask on|off` (first-use dialog on or off), `forget <name|all|projects>` (takes decisions back: a changed row returns to its shipped phase; `all` and `projects` ask first), a phase name, `model=<alias|id> effort=<level>`, `switch on|off`, `classify on|off` (the prompt classifier, below), `verbose on|off` (logs transitions only: each change of model or effort, with a few words of cause). `/route show` names the run slot when one holds (`main: run <phase>`) and prints the switch with its cap and the prompt-cache TTL (`switch: on (downgrade, cap 120000 tokens cold, ttl 60 min)`). The model sets routes through a `route` tool.
- First use: the first time a rowed skill is typed, a rowed agent is spawned or a phase is declared on the main loop through the `route` tool, the mod asks once whether the route is right. The question gives context: the skill's description (first sentence of its `SKILL.md` frontmatter) or the agent's, the phase with its `about` line, and the model id and effort the next step really runs on; a declared phase also says what uses it (rows, prompt rules). A row offers Later, Keep or Change; a declared phase offers Later or Keep. Change asks the model (fable, opus, sonnet, haiku, each shown with the tier it heads), then the effort among those the phases on that model use (shipped table: fable medium, high, xhigh or max; sonnet low, medium, high or xhigh; opus and haiku have one level each, so no question), then Everywhere or This project only. Rows stay phase names, so the pair maps to an existing phase: the row's current phase wins a tie and the same phase counts as Keep; a pair no phase offers needs a new phase added by hand in routing.json. Everywhere moves the row and records the shipped phase under `changed`; This project only stores an exception under `projects`, keyed by the origin remote reduced to `host/path` (no credentials, no local paths; a remote that cannot be read that way offers no project choice). Keep lands under `confirmed`; Later, a dismissed dialog or a free-text answer asks again next session. After a skill row changes, a toast names the model and effort that skill now runs on, plus a hint when the main loop holds back a downgrade: `/route switch on` when the switch is off, the cap hold (`held: downgrade skipped: cold read <n> tokens over <cap>`) when the cold read is over `downgradeMaxTokens`. One dialog at a time, never in a headless (`-p`) run, never inside a sub-agent.
- Only a dialog answer, `/route ask on|off` or `/route forget` writes `routing.json`, never the model. Writes are serialized, capped at 64 KiB, and refused when the file is missing (it is never created). Each write leaves the config repo dirty; a toast reminds you to commit it from there.
+1 -1
View File
@@ -194,7 +194,7 @@ l'outil `mcp__model-router__route` (`lib/effort-shift.md`). Les skills
externes vendorés (pile design, superpowers, agent-skills, skills scroll
MengTo, 21st) ont aussi leur ligne.
Taper un skill qui a une ligne route la boucle principale dessus. Une ligne du tier best (plan, reflect, orchestrate, escalate ; `audit` est une ligne d'agent, jamais tapée) tient d'un tour à l'autre pendant tout le run, jusqu'à `/route clear`, `/route off`, un `/model` tapé ou un skill d'un autre tier tapé. Pour relancer un tour bloqué : `ultrathink` dans le prompt (plancher du tour) ou `/route effort=max` (tient jusqu'à `/route clear`). Le `/effort` intégré n'a pas d'effet dans un run : les lignes et les routes passent devant. Un prompt tapé sans règle, skill ni route en cours passe par un classifieur (un appel au petit modèle, 3 secondes au plus) : le tour prend la route de la phase devinée : son niveau d'effort, et son modèle, jamais au-dessus de celui de la session. Une devinette `coding` ou `bookkeeping` fait descendre la boucle principale vers un modèle moins cher quand `mainModelSwitch` est actif (par défaut) et que la relecture à froid tient sous `downgradeMaxTokens` (120000 tokens par défaut). Cette relecture compte aussi le prompt qui vient d'être envoyé (un token pour 3 caractères), et un document joint bloque la descente pour cette étape. Le cache compte comme chaud pendant le TTL du moteur (`cache_ttl`, 5 ou 60 minutes), 60 minutes par défaut. `/route classify off` ou `"classify": false` dans la config machine le coupe, et un `/effort` tapé entre deux tours annule la devinette pour ce tour seulement. Avant d'envoyer la boucle principale sur un modèle, celui vers lequel elle se déplace comme celui qu'elle garde (le modèle de la session compris), le mod l'essaie une fois (un appel minimal, 8 secondes au plus) : sans réponse, ce modèle est marqué en panne (raison `probe`) et la décision est reprise une fois ; `"probe": false` dans la config machine coupe cet essai, et `/route show` affiche `probe:`. Quand un modèle inférieur remplace la tête de son tier en panne (Opus pour Fable), le niveau propre de la phase monte d'un cran (reflect xhigh, plan max, orchestrate high) ; un niveau demandé explicitement ou un plancher ne bouge jamais. Les sous-agents reçoivent le modèle de leur ligne au lancement (dans leur tier, jamais en dessous de leur frontmatter) et son niveau à chaque étape ; un `model` ou `effort` explicite sur l'appel gagne. Explore tourne en sonnet/medium, Plan en opus/xhigh. Un agent intégré `general-purpose` lancé par la boucle principale sans `model`, pendant que celle-ci tourne sous le modèle de la session (descente, ou repli quand un modèle est en panne), part sur le modèle de la session au lieu d'hériter du modèle inférieur ; les autres types d'agents ne sont jamais épinglés ainsi. `/route show` affiche la route en cours, slot de run compris (`main: run <phase>`), et le switch avec son plafond et ce TTL (`switch: on (downgrade, cap 120000 tokens cold, ttl 60 min)`). Première utilisation : la première fois qu'un skill avec ligne est tapé, qu'un agent avec ligne est lancé ou qu'une phase est déclarée sur la boucle principale via l'outil `route`, le mod demande une fois si la route convient. La question donne le contexte : la description du skill (première phrase du frontmatter de son `SKILL.md`) ou celle de l'agent, la phase avec sa ligne `about` (champ de la phase dans `routing.json`), puis le modèle et le niveau réels de l'étape suivante ; une phase déclarée dit aussi qui l'utilise. Pour une ligne : Later, Keep ou Change ; pour une phase déclarée : Later ou Keep. Change demande le modèle (fable, opus, sonnet, haiku, chacun avec son tier), puis le niveau parmi ceux des phases de ce modèle (fable : medium, high, xhigh ou max ; sonnet : low, medium, high ou xhigh ; opus et haiku n'en ont qu'un, la question est sautée), puis Everywhere ou This project only (exception rangée sous le remote origin du dépôt réduit à `host/path`, jamais d'identifiants). Une ligne reste un nom de phase : le couple modèle et niveau désigne une phase existante, et la même phase qu'avant vaut Keep. Un couple qu'aucune phase n'offre s'ajoute à la main comme nouvelle phase dans `routing.json`. Après un changement sur un skill, un toast donne le modèle et le niveau réels, et rappelle `/route switch on` quand le switch est coupé, ou nomme le plafond quand la relecture à froid bloque la descente. La réponse est écrite dans `routing.json` ; Later, un texte libre (Other) ou un dialogue fermé redemande à une session suivante. Un seul dialogue à la fois, jamais en headless (`-p`) ni dans un sous-agent, et le modèle n'écrit jamais ce fichier. Chaque réponse laisse le repo de config modifié : commite-le depuis ce repo. `/route pending` liste ce qui reste à confirmer, `/route ask off|on` coupe ou rallume le dialogue, `/route forget <nom|all|projects>` efface une décision (une ligne changée revient à la phase livrée ; `all` et `projects` demandent d'abord).
Taper un skill qui a une ligne route la boucle principale dessus. Une ligne du tier best (plan, reflect, orchestrate, escalate ; `audit` est une ligne d'agent, jamais tapée) tient d'un tour à l'autre pendant tout le run, jusqu'à `/route clear`, `/route off`, un `/model` tapé ou un skill d'un autre tier tapé. Pour relancer un tour bloqué : `ultrathink` dans le prompt (plancher d'effort du tour) ou `/route effort=max` (tient jusqu'à `/route clear`). Le `/effort` intégré n'a pas d'effet dans un run : les lignes et les routes passent devant. Les règles de mots-clés du prompt (`plan`, `design`, `architecture`… prennent l'effort de plan ; `pourquoi`, `review`, `audit`… celui de reflect), `ultrathink` et un lancement d'agent par la boucle principale (route `orchestrate` dérivée, tenue jusqu'à la fin de ses agents en arrière-plan) ne fixent que le niveau d'effort du tour, jamais le modèle : ils ne font jamais monter la boucle principale au-dessus du modèle de la session, et un run best tenu garde son modèle. Fable n'arrive sur la boucle principale que par une ligne de skill, l'outil `route` ou un `/route` tapé. Un prompt tapé sans règle, skill ni route en cours passe par un classifieur (un appel au petit modèle, 3 secondes au plus) : le tour prend la route de la phase devinée : son niveau d'effort, et son modèle, jamais au-dessus de celui de la session. Une devinette `coding` ou `bookkeeping` fait descendre la boucle principale vers un modèle moins cher quand `mainModelSwitch` est actif (par défaut) et que la relecture à froid tient sous `downgradeMaxTokens` (120000 tokens par défaut). Cette relecture compte aussi le prompt qui vient d'être envoyé (un token pour 3 caractères), et un document joint bloque la descente pour cette étape. Le cache compte comme chaud pendant le TTL du moteur (`cache_ttl`, 5 ou 60 minutes), 60 minutes par défaut. `/route classify off` ou `"classify": false` dans la config machine le coupe, et un `/effort` tapé entre deux tours annule la devinette pour ce tour seulement. Avant d'envoyer la boucle principale sur un modèle, celui vers lequel elle se déplace comme celui qu'elle garde (le modèle de la session compris), le mod l'essaie une fois (un appel minimal, 8 secondes au plus) : sans réponse, ce modèle est marqué en panne (raison `probe`) et la décision est reprise une fois ; `"probe": false` dans la config machine coupe cet essai, et `/route show` affiche `probe:`. Quand un modèle inférieur remplace la tête de son tier en panne (Opus pour Fable), le niveau propre de la phase monte d'un cran (reflect xhigh, plan max, orchestrate high) ; un niveau demandé explicitement ou un plancher ne bouge jamais. Les sous-agents reçoivent le modèle de leur ligne au lancement (dans leur tier, jamais en dessous de leur frontmatter) et son niveau à chaque étape ; un `model` ou `effort` explicite sur l'appel gagne. Explore tourne en sonnet/medium, Plan en opus/xhigh. Un agent intégré `general-purpose` lancé par la boucle principale sans `model`, pendant que celle-ci tourne sous le modèle de la session (descente, ou repli quand un modèle est en panne), part sur le modèle de la session au lieu d'hériter du modèle inférieur ; les autres types d'agents ne sont jamais épinglés ainsi. `/route show` affiche la route en cours, slot de run compris (`main: run <phase>`), et le switch avec son plafond et ce TTL (`switch: on (downgrade, cap 120000 tokens cold, ttl 60 min)`). Première utilisation : la première fois qu'un skill avec ligne est tapé, qu'un agent avec ligne est lancé ou qu'une phase est déclarée sur la boucle principale via l'outil `route`, le mod demande une fois si la route convient. La question donne le contexte : la description du skill (première phrase du frontmatter de son `SKILL.md`) ou celle de l'agent, la phase avec sa ligne `about` (champ de la phase dans `routing.json`), puis le modèle et le niveau réels de l'étape suivante ; une phase déclarée dit aussi qui l'utilise. Pour une ligne : Later, Keep ou Change ; pour une phase déclarée : Later ou Keep. Change demande le modèle (fable, opus, sonnet, haiku, chacun avec son tier), puis le niveau parmi ceux des phases de ce modèle (fable : medium, high, xhigh ou max ; sonnet : low, medium, high ou xhigh ; opus et haiku n'en ont qu'un, la question est sautée), puis Everywhere ou This project only (exception rangée sous le remote origin du dépôt réduit à `host/path`, jamais d'identifiants). Une ligne reste un nom de phase : le couple modèle et niveau désigne une phase existante, et la même phase qu'avant vaut Keep. Un couple qu'aucune phase n'offre s'ajoute à la main comme nouvelle phase dans `routing.json`. Après un changement sur un skill, un toast donne le modèle et le niveau réels, et rappelle `/route switch on` quand le switch est coupé, ou nomme le plafond quand la relecture à froid bloque la descente. La réponse est écrite dans `routing.json` ; Later,Line truncated
La config par machine, optionnelle, vit dans `~/.claude/model-router.json` et passe devant `routing.json` ; `"enabled": false` y coupe le mod sur cette machine, `"ask": false` y coupe le dialogue, une ligne à `null` y retire une ligne. Un `.claude/model-router.json` dans un projet n'est jamais lu. Les phases et les lignes se modifient à la main dans `routing.json` ; `/route reload` relit les deux fichiers.
+5
View File
@@ -53,6 +53,11 @@ Builtin `/effort` is NOT a lever inside a run: rows and routes outrank it.
120000), may move main DOWN, never up. A user `/model` only moves the
baseline the guess starts from (`/route classify off` to stop guessing;
never `-p`).
- Keyword prompt rules (`plan|design|architecture…`,
`why|review|audit…`), `ultrathink` and a background agent
dispatch (derived `orchestrate`) set the turn's effort only, never
a model above the session model: Fable on main comes only from a
skill row, the `route` tool or a typed `/route`.
- Mod off: typed agents fall back to their `model:`/`effort:` frontmatter.
- First use of a row asks once, with context (Later, Keep or Change: model,
then effort, then Everywhere or this project only); the answer is kept in
+94 -23
View File
@@ -934,9 +934,10 @@ test('derived: a route declared after the dispatch survives the pop', async (
test('default rule: planifie sets plan, a later route overrides', async (
$, on) => {
const rig = await bootRig($, on, HAIKU)
// a keyword sets effort only: the fable session keeps its model
const rig = await bootRig($, on)
await typed($, 'planifie la migration')
expect(await stepOn($, rig, HAIKU)).toEqual({ model: FABLE, effort: 'xhigh' })
expect(await stepOn($, rig, FABLE)).toEqual({ model: FABLE, effort: 'xhigh' })
await $.tool.call({ tool: ROUTE_TOOL, phase: 'implement' })
const line = mainLine(await route($, 'show'))
expect(line).toContain('model implement')
@@ -1008,16 +1009,15 @@ test('text: an unknown session model prints "session model"', async (
expect(mainLine(await route($, 'show'))).toContain('keeps session model')
})
test('text: show names the model a floor upgrade moves to', async (
test('text: show names no model move for an ultrathink floor', async (
$, on) => {
await bootRig($, on, HAIKU)
await $.prompt.submit({
text: 'ultrathink please',
wait: false,
origin: { kind: 'composer' },
})
// a floor names no model any more, so show has no upgrade to report
await bootRig($, on, OPUS)
await ultrathink($)
const line = mainLine(await route($, 'show'))
expect(line).toContain(`${FABLE} (upgrade)`)
expect(line).toContain('floor max')
expect(line).not.toContain('(upgrade)')
expect(line).not.toContain(FABLE)
})
// ---- wave 2: skill rows, run slot, agent rows ---------------------------
@@ -5297,7 +5297,7 @@ test('classify: a user /effort drops the guess for one turn only', async (
expect(lastSeen(c)).toEqual({ model: SONNET, effort: 'medium' })
})
test('classify: a mid-turn ultrathink floor still reaches fable max', async (
test('classify: a mid-turn ultrathink floor raises effort only', async (
$, on) => {
const c = await bootCls($, on)
await typed($, PLAIN)
@@ -5305,7 +5305,8 @@ test('classify: a mid-turn ultrathink floor still reaches fable max', async (
expect(lastSeen(c)?.model).toBe(SONNET)
await queued($, 'composer', 'ultrathink please')
await runStep($, highStep())
expect(lastSeen(c)).toEqual({ model: FABLE, effort: 'max' })
// the floor names no model: the guess's sonnet holds, at the floor's max
expect(lastSeen(c)).toEqual({ model: SONNET, effort: 'max' })
})
test('classify: a guessed sonnet rate-limited falls to opus, not haiku', async (
@@ -5564,10 +5565,12 @@ test('probe: a fable that never answers lands the plan step on opus', async (
$, on) => {
const world = probeWorld(hangsOn(FABLE))
const rig = await bootRig($, on, OPUS, 1000, world)
await typed($, FABLE_PLAN)
await pastProbe(rig, runStep($, { ...highStep(), model: OPUS }))
// a keyword no longer lifts: the route tool carries the plan tier
await pastProbe(rig, planRoute($))
await runStep($, { ...highStep(), model: OPUS })
expect(rig.seen).toEqual([{ model: OPUS, effort: 'max' }])
expect(world.completions).toEqual([FABLE])
// fable probed by the route call, opus by the step
expect(world.completions).toEqual([FABLE, OPUS])
expect(downLine(await route($, 'show'))).toContain(
`${FABLE} for 15 min (probe)`)
})
@@ -5599,8 +5602,9 @@ test('probe: a lapsed hold probes again and holds longer', async ($, on) => {
const world = probeWorld(hangsOn(FABLE))
const rig = await bootRig($, on, OPUS, 1000, world)
for (const wait of [15, 30]) {
await typed($, FABLE_PLAN)
await pastProbe(rig, runStep($, { ...highStep(), model: OPUS }))
// the route tool lifts, a keyword no longer does
await pastProbe(rig, planRoute($))
await runStep($, { ...highStep(), model: OPUS })
expect(downLine(await route($, 'show'))).toContain(`for ${wait} min`)
await endTurn($)
await rig.clock.advance(wait * 60000)
@@ -5638,18 +5642,20 @@ test('probe: a failure during the flight keeps the target unverified', async (
const gate = new Promise<void>(resolve => { open = resolve })
const world = probeWorld(async () => { await gate; return PROBE_OK })
const rig = await bootRig($, on, OPUS, 1000, world)
await typed($, FABLE_PLAN)
const step = runStep($, { ...highStep(), model: OPUS })
// the route tool's probe is the one in flight (a keyword no longer lifts)
const call = planRoute($)
await rig.clock.settle()
await switchTo($, FABLE, OPUS, 'auto')
open()
await step
await call
await runStep($, { ...highStep(), model: OPUS })
expect(rig.seen).toEqual([{ model: OPUS, effort: 'max' }])
await endTurn($)
await rig.clock.advance(15 * 60000)
await typed($, FABLE_PLAN)
await planRoute($)
await runStep($, { ...highStep(), model: OPUS })
expect(world.completions).toEqual([FABLE, FABLE])
// route probe fails in flight, the step probes opus, the second route fable
expect(world.completions).toEqual([FABLE, OPUS, FABLE])
})
test('probe: an explicit route onto a held model probes once in all', async (
@@ -5693,7 +5699,8 @@ test('probe: a session model that never answers leaves for opus on the first ste
const rig = await bootRig($, on, FABLE, 1000, world)
await typed($, FABLE_PLAN)
await pastProbe(rig, runStep($, { ...highStep(), model: FABLE }))
expect(rig.seen).toEqual([{ model: OPUS, effort: 'max' }])
// a keyword names no tier: no stand-in notch, xhigh instead of max
expect(rig.seen).toEqual([{ model: OPUS, effort: 'xhigh' }])
expect(world.completions).toEqual([FABLE])
expect(downLine(await route($, 'show'))).toContain(
`${FABLE} for 15 min (probe)`)
@@ -5847,3 +5854,67 @@ test('stand-in: the verbose line names it as a cause', async ($, on) => {
expect(logs.some(l => l.startsWith('main:') && l.includes('stand-in')))
.toBe(true)
})
// ---- keyword cap: prompt rules and dispatches set effort only ------------
test('keyword cap: a plan keyword on an opus session stays on opus at xhigh', async (
$, on) => {
const rig = await bootRig($, on, OPUS)
await typed($, 'plan the billing migration')
expect(await stepOn($, rig, OPUS)).toEqual({ model: OPUS, effort: 'xhigh' })
})
test('keyword cap: a reflect keyword on an opus session stays on opus at high', async (
$, on) => {
const rig = await bootRig($, on, OPUS)
await typed($, 'why does the cache miss')
expect(await stepOn($, rig, OPUS)).toEqual({ model: OPUS, effort: 'high' })
})
test('keyword cap: ultrathink on an opus session stays on opus at max', async (
$, on) => {
const rig = await bootRig($, on, OPUS)
await ultrathink($)
expect(await stepOn($, rig, OPUS)).toEqual({ model: OPUS, effort: 'max' })
})
test('keyword cap: a route tool call after a keyword still lifts to fable', async (
$, on) => {
const rig = await bootRig($, on, OPUS)
await typed($, 'plan the billing migration')
await planRoute($)
expect((await stepOn($, rig, OPUS)).model).toBe(FABLE)
})
test('keyword cap: a held fable gives no stand-in notch to a capped keyword', async (
$, on) => {
const world = newWorld()
const rig = await bootRig($, on, OPUS, 1000, world)
await switchTo($, FABLE, OPUS, 'auto')
await typed($, 'plan the billing migration')
expect(await stepOn($, rig, OPUS)).toEqual({ model: OPUS, effort: 'xhigh' })
expect(world.completions).not.toContain(FABLE)
})
test('keyword cap: a keyword inside a held best-tier run keeps the run on fable', async (
$, on) => {
const rig = await bootRun($, on, OPUS)
await loadSkill($, 'feat')
await endTurn($)
await typed($, 'plan the next step')
expect(await stepOn($, rig, OPUS)).toEqual({ model: FABLE, effort: 'xhigh' })
})
test('keyword cap: an unknown session model never lets a keyword lift main', async (
$, on) => {
const rig = await bootRig($, on, '')
await typed($, 'plan the billing migration')
expect((await stepOn($, rig, OPUS)).model).toBe(OPUS)
})
test('keyword cap: a dispatch outside a run keeps main on the session model', async (
$, on) => {
const rig = await bootRig($, on, OPUS)
await dispatch($)
expect(await stepOn($, rig, OPUS)).toEqual({ model: OPUS, effort: 'medium' })
})
+21 -17
View File
@@ -292,6 +292,7 @@ const DEFAULT_CONFIG: Config = {
skills: {},
// `floor` rules set the turn's minimum effort; `default` rules set the
// turn's route, which a route call or a skill overrides. Neither lowers.
// Rules set the turn's effort only, never a model.
prompt: [
{ pattern: '\\bultrathink\\b', phase: 'escalate', mode: 'floor' },
{
@@ -353,6 +354,13 @@ function phaseRoute(cfg: Config, phase: string): Route | undefined {
return hasKey(cfg.phases, phase) ? cfg.phases[phase] : undefined
}
/** A phase's effort alone: a route that never moves main's model. */
function effortRoute(cfg: Config, phase: string): Route | undefined {
const route = phaseRoute(cfg, phase)
if (route === undefined) return undefined
return route.effort === undefined ? {} : { effort: route.effort }
}
/** Merges a user table over a default one, dropping invalid entries. */
function mergeTable<T>(
base: Record<string, T>,
@@ -1383,17 +1391,12 @@ function decideMain(
}
/**
* The slot that names main's model: sticky, turn route, run slot, then the
* floor's own model. A floor with a model beats a classifier's guess.
* The slot that names main's model: sticky, turn route, then run slot. A
* floor names no model (prompt rules set the effort only).
*/
function mainModelSlot(st: State): Routed | null {
const slots = [st.userMain, st.turnMain, st.runMain, st.turnFloor]
const slot = slots.find(s => routeName(s?.route) !== undefined) ?? null
const floor = st.turnFloor
if (slot?.source === 'classifier' && routeName(floor?.route) !== undefined) {
return floor
}
return slot
const slots = [st.userMain, st.turnMain, st.runMain]
return slots.find(s => routeName(s?.route) !== undefined) ?? null
}
const mainModel = (st: State): string | undefined =>
@@ -3244,17 +3247,18 @@ function rememberAgent(st: State, agentId: string, model: string): void {
// ---- derived orchestrate ---------------------------------------------
/**
* A main Agent dispatch is orchestration: the turn's route becomes
* `orchestrate` until the spawned agents end. A route the model or a skill
* declared is never replaced.
* A main Agent dispatch is orchestration: the turn's effort becomes
* orchestrate's until the spawned agents end; the model stays where it is
* (a held run keeps its model). A route the model or a skill declared is
* never replaced.
*/
function pushOrchestrate(st: State): void {
const src = st.turnMain?.source
const route = phaseRoute(st.cfg, 'orchestrate')
const route = effortRoute(st.cfg, 'orchestrate')
if (st.pushed !== null || !route) return
if (src === 'model' || src === 'skill') return
st.pushed = { prev: st.turnMain, spawnIds: new Set() }
st.turnMain = { phase: 'orchestrate', route: { ...route }, source: 'derived' }
st.turnMain = { phase: 'orchestrate', route, source: 'derived' }
}
/** Restores the route from before the dispatch, unless one replaced it. */
@@ -3923,9 +3927,9 @@ const firstRule = (st: State, mode: PromptMode, text: string) =>
/** A default rule sets the idle turn's route; routes and skills override. */
function defaultFromPrompt(st: State, scanned: string): void {
const rule = firstRule(st, 'default', scanned)
const route = rule ? phaseRoute(st.cfg, rule.phase) : undefined
const route = rule ? effortRoute(st.cfg, rule.phase) : undefined
if (rule && route) {
st.turnMain = { phase: rule.phase, route: { ...route }, source: 'prompt' }
st.turnMain = { phase: rule.phase, route, source: 'prompt' }
}
}
@@ -3937,7 +3941,7 @@ function defaultFromPrompt(st: State, scanned: string): void {
function routeFromPrompt(st: State, text: string, midTurn: boolean): void {
const scanned = text.slice(0, MAX_PROMPT_SCAN)
const floor = firstRule(st, 'floor', scanned)
const route = floor ? phaseRoute(st.cfg, floor.phase) : undefined
const route = floor ? effortRoute(st.cfg, floor.phase) : undefined
if (floor && route) {
const routed: Routed = { phase: floor.phase, route, source: 'prompt' }
floorFromPrompt(st, midTurn, routed)
+2 -1
View File
@@ -176,7 +176,8 @@
"reflect": "reflect",
"plan": "plan",
"apply": "apply",
"explore": "explore"
"explore": "explore",
"audit": "audit"
},
"skills": {
"gitflow": "implement",