Merge feature/model-scope-dialog into develop
This commit is contained in:
commit
a6b94a4c46
17 files changed
+1611
-29
No files matched your search
@@ -351,3 +351,15 @@ rules:
|
||||
- **Cause**: CLI 2.1.306 `claude plugin validate` prints "Plugin directory checks" section (submission catalogue): `⚠ Found 1 plugin directory warning:` ICON_MISSING, `--json` `directory.findings[].blocking: false`. mods.test.sh:57 grepped whole output for `warning` (also matched hooks notes quoting register.ts identifiers, checkout paths). Prose scraping of a CLI with an exit-code contract: `--strict` → per-file warnings rc 1, directory findings rc only under `--profile directory`.
|
||||
- **Solution**: 801992a (bugfix/mods-validate-advisory). Helper `validate_strict` = rc of `claude plugin validate --strict`; check_cli + positive control share it; control = scratch manifests `{"name":"warnfix"}` (rc 1) / cleanfix with version+description+author (rc 0) under script-level `mktemp -d`. Plan r3 after 3 lenses + 1 re-challenge (sed range on closing marker killed: CLI prints it only when findings > 0, fail-open to EOF). GATE 0 7/7, verifier ECARTS(2) = out-of-scope routing.json dialog write only, auditor PASS.
|
||||
- **Residual**: 3 historical contracts carry old scrape as CHECK oracle (`.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md:22`, `2026-10-08-model-router-floor-1835.md:22`, `2026-10-09-model-router-tiers-1237.md:23`), left unedited; re-run fails on ICON_MISSING, not a model-router regression. Unverified: whether `--strict` escalates `advice[]`. Links [[LRN-225]], [[BDR-123]].
|
||||
|
||||
## BLK-035 — model-router: haiku session unrouted, table still on Haiku 4.5 [resolved]
|
||||
- **Friction**: integration_alphalink 2026-10-25T16:22:53Z `model-router: claude-haiku-5-5 unknown to the models table; no switch`. `/model haiku` → This project (BDR-126) would write stale id.
|
||||
- **Cause**: DEFAULT_CONFIG `haiku: 'claude-haiku-4-5-20251001'` + `windows` 200K entry; native alias moved to `claude-haiku-5-5` (1M, effort low–max) silently.
|
||||
- **Solution**: 2c39524 (feature/model-scope-dialog): haiku → `claude-haiku-5-5`, `windows: {}`; regression test + window test on explicit override. Negative control: revert → 20 tests red.
|
||||
- **Residual**: "haiku takes no effort" strip (effortWord, step plan, isHaiku sites, census `effort-routing.test.sh:170`) still 4.5-era → `mechanical` (low) runs haiku at default medium. Follow-up /bugfix. Links [[LRN-230]], [[BDR-126]].
|
||||
|
||||
## BLK-036 — bare `/model` picker writes tracked user settings for a per-project intent [resolved]
|
||||
- **Friction**: user picked haiku in native picker in integration_alphalink, wanted that project only → `"model": "haiku"` landed in tracked user settings.json (every project). Restored opus by hand; haiku pinned in alphalink `.claude/settings.local.json`.
|
||||
- **Cause**: BDR-126 dialog fires only on `/model <name>`; spec said "no args → native picker untouched". Picker = real usage path. Main applied spec without flagging gap.
|
||||
- **Next**: /feat picker scope: pick model in picker, then ask project vs user scope. Check engine types for a settings-write intercept first; else mod must restore user settings (BDR-116 amendment, user call). Links [[BDR-126]].
|
||||
- **Status 2026-10-25**: resolved for the picker, 2202964 (BDR-127: PreModelSwitch deny + deferred scope dialog, no user-settings write by the mod). Residual: `/config` Model row still native (source `command`).
|
||||
@@ -1506,3 +1506,18 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate).
|
||||
- **Amendment 7 (2026-10-25, Fable re-challenge of the whole queue)**: 4 lenses + native-features guide (CLI 2.1.308), synthesis `.claude/tasks/plans/2026-10-25-context-mod-queue-challenge.md` § RE-CHALLENGE. BLOCKER closed: hard_deny names off switches only, never mod paths/sources (classifier would refuse mod maintenance). Merge gate = native `ask` rules (`Bash(bash */gitflow.sh finish*)`, `Bash(gitflow_finish*)`, `Bash(git merge *)`), bench r3 G1-G7 all denied, `start` free; `$.ui.ask` mod dropped; BDR-068 /close auto-finish costs one click (user accepted). Routing guard hosted in model-router: `runMain` wrong signal (BEST tier only, never ends), mod state plugin-private; free when `turnMain.source ∈ {skill, model}` or `/route` sticky; Edit/Write/NotebookEdit only, Bash write forms deferred (no measured evasion). Interpreters (`python3 -c` 211, `node -e` 450 calls / 14 days) → soft_deny prose, not static ask; `Bash(/*)` dropped (kills rtk abs twins). Commit-msg hook deferred (4/78 overrun, hooks miss 6/7 repos on core.hooksPath). 4a shrunk: memory.sh add/status/journal/check/index + flock, own-header `[tag]` first then last status line wins (reconcile.sh:60-67 dropped own header = BLK-032..034 false-open), Index blocks removed via /prune-memory, no Meta backfill, no English validator (1/1,290), per-file v2 marker. Phase 1: design section appended to rules/web-building.md (hook one-liner, 2,131 fires), one lib/architecture-defaults.md, Supabase/functions keep always-on line (path rules fail open at scaffold), agent description diet at source, origin line already shipped. Phase 5: lib/profiles/<name>.json source of truth (no generator), detection via /plugin-check (no fingerprint), cleanup += toggle-external.sh + old-layout writers, migrate auto memories before autoMemoryEnabled:false, enable scope = --settings copy else settings.local, never user scope mid-skill. Phase 3 CONDITIONAL on the measured residual after 0/4a/1/5/2: listing filter, contexts field, hint classifier, agent rewrite, higgsfield deltas dropped. 4c = intent rerank + error 4-gram only, digest in session-start.sh on compact/clear; 4b redacts at capture, bounded ring; 4d deferred. Proof budget: static glob check + InstructionsLoaded log for path rules, model canaries for hook/mod levers only.
|
||||
- **Amendment 8 (2026-10-25, model per project and per conversation)**: user ask (one Claude Code conversation per project, often concurrent: Fable on one, opus on another). Measured headless (scratchpad modeltest): project `.claude/settings.local.json` `"model"` wins over user settings, `--settings '{"model":…}'` wins over both; same scopes as packs. `/model` writes the TRACKED user settings.json (fable landed there 2026-10-25): never the per-project route. Applied: tracked default `opus`, this repo local `claude-fable-5-1[1m]`. Phase 5 profile = `enabledPlugins` + `model`; doctor warns when tracked `model` ≠ `opus`. Residuals accepted by the user: interpreters (`python3 -c`, `node -e`) rest on prose + classifier (491/661 calls from sub-agents, an ask rule would fail executors); Bash write forms out of the routing guard until a measured evasion.
|
||||
|
||||
|
||||
## BDR-126 — model-router `/model <name>` scope dialog: project / conversation / everywhere [accepted] (2026-10-25)
|
||||
- **Decision**: `command.run` hook on core `model`. Composer origin, 1 token, name in `cfg.models` (alias or listed full id, `[1m]` stripped for test, `haiku[1m]` out), surface present, no dialog open, router on → `$.ui.ask` This project / This conversation / Everywhere. Project = full id (`[1m]` verbatim) into `<session root>/.claude/settings.local.json` + sticky model route; conversation = sticky route only; both drop `runMain`, keep sticky effort. Everywhere = drop sticky model+tier, native passthrough. Esc/free text = cancel. Else native, no question. Fail-open to native only BEFORE answer; post-answer own try/catch → text.
|
||||
- **Why**: native `/model` always writes tracked user settings.json (BDR-125 am. 8, LRN-098); user wants model per project and per conversation.
|
||||
- **Project write rules**: mod's first project-tree write. Stat-first absence ([[LRN-228]]), links refused (`.claude` and file), regular file only, 64 KiB cap, JSON object only, fixed cause words (never err.message), other keys kept.
|
||||
- **Alternatives rejected**: `$.config.set` (no scope arg); Esc = passthrough (silent tracked write); dialog on unknown names (router can't route them); `canonical()` for written id (strips `[1m]`); shared `modelAnswered` flag (concurrent dispatch clears it).
|
||||
- **Residuals**: stat-then-write race (no no-follow in `$.fs`); dangling-link refusal assumes lstat-like `$.fs.stat`; engine gitignore of created file unverified; live hot-switch on local `model` change unverified; worktree session writes worktree's file (documented). Live check pending ([[LRN-212]]).
|
||||
- **Refs**: contract `.claude/tasks/contracts/2026-10-25-model-scope-dialog-1450.md`, plan r3 same dir `plans/`, commits 1fde5bb, 773fe17. [[BDR-116]], [[BDR-125]], [[EVAL-049]].
|
||||
|
||||
## BDR-127 — model-router: `/model` picker asks its scope; hand pick always switches [accepted] (2026-10-25)
|
||||
- **Decision**: (1) picker = `classic.PreModelSwitch` source `picker`: gates (router on, string `requested_model` in table, surface present) → `$.session.id()` read → slot held = deny + toast `answer the open dialog first` (never native) → else set `st.asking` sync, `void pickerDialog`, return `{ permissionDecision: 'deny' }`. Dialog after 300 ms sleep = shared `scopeDialog` (same 3 scopes as BDR-126); Everywhere = `$.command.run model <requested>` (native write); stale `session.id` → nothing applied. Default/unknown/headless/other sources → native. (2) hand pick: `Routed.explicitModel` set by dialog answers; `decideMain` runs `handCall` first: target usable (not down, fits) → move/keep, no caps, no switch flags; unusable → existing `automaticCall` with no wanted model + one log. Hand pick clears target mark at pick; native user switch (PostModelSwitch command/picker/sdk) drops it, skipped while picker dialog open. `/route model=` keeps caps.
|
||||
- **Why**: BLK-036 (picker wrote tracked user settings for per-project intent, 3 times on 2026-10-25); user: picker → project or user scope, default opus, hand choice must switch even in long conversation.
|
||||
- **Alternatives rejected**: `$.ui.ask` inside hook (never renders, spike); bypass inside `upgradeCall`/`downgradeCall` (breaker never checked on target: 2 BLOCKERs r1); handCall `keep(cur)` when unusable (pins down model when hand pick == cur: BLOCKER r2); mod restoring user settings.json after native write (BDR-116); alias pins (user kept full id).
|
||||
- **Residuals**: `/config` Model row still native (PreModelSwitch source `command`, same as Everywhere's own run); hand pick dropped at `/clear`; no timeout on never-answered dialog (slot held → picks denied, no leak); window guard needs a `windows` entry (none shipped); PostModelSwitch on denied pick unverified live (guarded).
|
||||
- **Refs**: contract `.claude/tasks/contracts/2026-10-25-picker-scope-1952.md`, plan r3 same name in `plans/`, commits 2202964, 5d262d3. [[BDR-126]], [[BDR-116]], [[BLK-036]], [[LRN-231]], [[EVAL-050]].
|
||||
@@ -437,3 +437,13 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse
|
||||
- **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]].
|
||||
|
||||
## EVAL-049 — /feat model scope dialog: challenge + gates yield on 4-file hook feat (2026-10-25)
|
||||
- **Method**: /feat. 3 blind lenses r1: correctness FATAL(6), robustness CONCERNS(7), simplicity CONCERNS(3); r2 confirm CONCERNS(3) → r3 inline. feater DONE 540 tests; GATE 0 MET; verifier ECARTS(1) (no post-answer throw test on non-native branch) → feater → CONFORME 15/15; auditor PASS + MEDIUM (dangling link from main's contract) → feater → re-verify CONFORME + PASS. Doc-sync SIGNIFICANT 3 patches (1 = README defect from executor placement).
|
||||
- **Anomalies**: BLOCKER r1 `[1m]` ids never reached dialog (`MODEL_ID` rejects brackets): this repo's own local model is `[1m]`. Confirm pass caught FsStat kind `dir` vs plan `directory` (suite would stay green with bug). Main's contract wording introduced the MEDIUM.
|
||||
- **Action**: worth the cost on hooks that write settings. Plan API literals (`kind` values, regex coverage) against the types file before challenge. Links [[BDR-126]], [[LRN-228]].
|
||||
|
||||
## EVAL-050 — /feat picker scope: spike first, then 2 FATAL challenge rounds on the same axis (2026-10-25)
|
||||
- **Method**: dev-mod spike, 2 live runs by user (ask-inside froze; deny + continuation worked) before any plan. Plan r1: correctness FATAL(5), robustness FATAL(2), simplicity SOLID. r2 confirm FATAL(1). r3 inline. feater DONE 29 tests (574 total); GATE 0 MET; verifier CONFORME 14/14 1st pass; auditor PASS 1st pass; doc-sync SIGNIFICANT 12 patches.
|
||||
- **Anomalies**: both FATAL rounds on breaker-vs-target: r1 bypass skipped target-down check across turns; r2 early branch pinned a down model when hand pick == cur (user's exact scenario). Main wrote "leaveDown untouched: down still wins" without tracing which model `decideMain` checks.
|
||||
- **Action**: a new routing branch gets a trace of every exit against `st.down` for cur AND target, across a turn boundary, before challenge. Spike-first paid: zero rework on the UI mechanism. Links [[BDR-127]], [[LRN-231]].
|
||||
@@ -651,3 +651,6 @@ rules:
|
||||
- Shell deny probe (user: facts): 27 variants vs `Bash(echo SECRET*)`; matcher sees through compound/wrappers/assignments, misses `sh -c`, heredoc shell, `$(…)`, abs path, interpreters, quoted literal arg; auto mode classifier approved all misses. rtk-rewrite hook bypasses deny on rewritten cmds (`git push origin :feature`, `cat */*.pem`): ac23cc6 fix inert in real use. Fixes queued in phase 2 (BDR-125 amendment 6), order kept, mode stays auto.
|
||||
- Full queue re-challenge on Fable (user ask): correctness 13, robustness 18 (1 BLOCKER: hard_deny naming mod paths), simplicity 14, native guide. Plan halves: native ask merge gate (no mod), guard in model-router on `turnMain.source`, interpreters in prose, commit-msg hook deferred, 4a = memory.sh + status parser fix + Index removal (no Meta backfill), phase 3 conditional, 4c two channels. TODO queue rewritten, BDR-125 amendment 7. User picks: native gate, phase 3 conditional, rest in block.
|
||||
- Model per project measured (local settings > user, --settings > local); tracked settings.json back to opus, repo local on Fable; BDR-125 amendment 8; user keeps the two residuals (interpreters in prose, Bash writes deferred).
|
||||
- /feat `/model` scope dialog (feature/model-scope-dialog): 3 lenses r1 (1 BLOCKER `[1m]`), r3 plan, feater + 2 fix rounds (test gap, dangling link), verifier CONFORME 15/15, auditor PASS. 1fde5bb + docs 773fe17. BDR-126, LRN-228/229, EVAL-049. Merge on user go; live check next.
|
||||
- BLK-036: bare /model picker wrote haiku into tracked user settings (integration_alphalink intent). Restored opus, haiku pinned in alphalink settings.local.json. /bugfix haiku table 2c39524 (BLK-035, LRN-230): verifier CONFORME 7/7, auditor PASS. Next: haiku effort bugfix, picker scope feat. Merge of feature/model-scope-dialog held.
|
||||
- /feat picker scope (BLK-036): spike (user ran 2 live picker tests: ask inside hook froze, deny + continuation works), plan r1 FATAL x2 / r2 FATAL(1) on breaker-vs-target, r3 inline; verifier CONFORME 14/14, auditor PASS. 2202964 + docs 5d262d3. BDR-127, LRN-231, EVAL-050. Spike mod neutralized. Next: haiku effort bugfix; live check picker in fresh session.
|
||||
@@ -1890,3 +1890,19 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s
|
||||
## LRN-227 — Root-commit author ≠ name the user remembers; identity list must cover every root email
|
||||
- **Context**: BDR-124 verify. User expected lima `root n.turpault 2009`; real root = t.surrel 2009-02-25 (not shallow). Own repo root = `git@bchanot.fr`, absent from user.email + claude.identity → false foreign banner.
|
||||
- **Apply**: check origin claims against `git log --max-parents=0`, never memory. Every email ever used as root author → `git config --global --add claude.identity <email>`. Links [[BDR-124]].
|
||||
|
||||
## LRN-228 — Absence test in untrusted tree: stat first, `exists` only after stat rejects
|
||||
- **Context**: BDR-126 contract (main wrote it) said "absent = `$.fs.exists` false". GATE 2 MEDIUM: `exists` may follow links → dangling symlink reads absent → `$.fs.write` creates link target. `stat` answers `isLink` even dangling.
|
||||
- **Apply**: stat → resolves: isLink/kind/size checks; rejects → `exists` false = absent, true = fs error. Same for parent dir. Contract wording for a write path gets the same scrutiny as code. Links [[BDR-126]].
|
||||
|
||||
## LRN-229 — Mod test kit: forcing a throw after a dialog answer
|
||||
- **Context**: BDR-126 post-answer throw test. Kit drops `$.ui.status` (void event, hook never reached); bottom hooks register once ("registered twice"); hooks after first `$` call refused; `session.usage` swallowed by `readTokens`.
|
||||
- **Apply**: swap the mock clock at boot behind a fixture flag: `clock.now` answers until a dialog opened, then rejects (`show` → `readingFor` throws). Flag off by default; a test advancing that clock breaks. Links [[BDR-126]].
|
||||
|
||||
## LRN-230 — Native model alias moves under the mod silently; table facts rot with it
|
||||
- **Context**: BLK-035. haiku alias 4.5 → 5.5, no error anywhere; only signal = mod log `unknown to the models table`. Mod also hardcodes 4.5 facts (200K window, no effort).
|
||||
- **Apply**: at each Claude Code upgrade, check `cfg.models` ids vs claude-api skill model table (context, effort support); grep code for model-specific facts (`startsWith(HAIKU)`, windows) in same pass. A per-model behaviour rule names its model version in a comment. Links [[BLK-035]], [[LRN-203]].
|
||||
|
||||
## LRN-231 — PreModelSwitch hook: no dialog inside; deny at once, ask in a continuation
|
||||
- **Context**: picker spike 2026-10-25 (dev mod, user-run). `$.ui.ask` awaited inside `classic.PreModelSwitch` never renders: UI frozen on "Running PreModelSwitch hooks… (Esc to cancel)". Returning `{ permissionDecision: 'deny', permissionDecisionReason }` at once blocks switch AND user settings.json write; engine prints "Model switch to X was blocked by a PreModelSwitch hook: <reason>".
|
||||
- **Apply**: launch `void (async () => { await $.clock.sleep(300); … $.ui.ask … })()` before returning the deny; hold any shared dialog slot synchronously before return, free it in the continuation's `finally`. `$.command.run({ command: 'model', args })` from the continuation re-enters as PreModelSwitch source `command` + command.run origin plugin: gate both. Links [[BDR-127]].
|
||||
@@ -12,7 +12,10 @@ Shared rules for every phase:
|
||||
- Never: forced continuation / Stop block (BDR-083, BDR-087), per-turn nag (BDR-037), forced skill invocation, hiding a dispatchable agent via `agent.offer` (breaks dispatch, proved), a `hard_deny` that names a path, file or source line (the auto classifier would refuse all mod maintenance): hard_deny names off switches only (`"enabled": false`, `enabledPlugins`, `disableAllHooks`) and "never edit `permissions.ask/deny` to pass a gate".
|
||||
- Cleanup is part of each phase: delete what the phase makes obsolete (scripts, hooks, tests, doctrine lines, Makefile targets, doctor checks), grep every citer and patch in the same branch (doctrine-citers census in `make test`).
|
||||
|
||||
- [ ] **Before phase 0: /feat `/model` scope dialog in model-router** (user pick 2026-10-25). Fact (docs model-config): `/model <name>` always writes `model` to user settings.json (tracked here); picker key `s` = session only; project `model` honored at launch. Mod: `command.run` on `model` with args → `$.ui.ask` "This project / This conversation / Everywhere": project = `model` in `.claude/settings.local.json` + sticky route now; conversation = sticky route only (`/route model=`); everywhere = native passthrough. No args → native picker untouched; `-p` or no surface → passthrough. Files: register.ts, register.test.ts, lib/effort-shift.md. Doctor keeps the tracked ≠ opus warning.
|
||||
- [x] **Before phase 0: /feat `/model` scope dialog in model-router** (done 2026-10-25, 1fde5bb + docs 773fe17, BDR-126; merge on user signal; live check pending: dialog in a real session, no PostModelSwitch/down mark after This project, gitignore of a created file). (user pick 2026-10-25). Fact (docs model-config): `/model <name>` always writes `model` to user settings.json (tracked here); picker key `s` = session only; project `model` honored at launch. Mod: `command.run` on `model` with args → `$.ui.ask` "This project / This conversation / Everywhere": project = `model` in `.claude/settings.local.json` + sticky route now; conversation = sticky route only (`/route model=`); everywhere = native passthrough. No args → native picker untouched; `-p` or no surface → passthrough. Files: register.ts, register.test.ts, lib/effort-shift.md. Doctor keeps the tracked ≠ opus warning.
|
||||
|
||||
- [ ] **/bugfix model-router haiku effort strip** (BLK-035 residual, user pick 2026-10-25): Haiku 5.5 takes effort; drop 4.5-era "haiku takes no effort" (effortWord, step plan omission, isHaiku sites, census `lib/tests/effort-routing.test.sh:170`), so `mechanical` runs low.
|
||||
- [x] **/feat picker scope** (done 2026-10-25, 2202964 + docs 5d262d3, BDR-127; live check pending: picker in a fresh session, PostModelSwitch on a denied pick) (BLK-036, user ask 2026-10-25): bare `/model` → pick in native picker → ask project scope (`.claude/settings.local.json`) or user scope. First: engine types for a settings-write intercept; none → mod restores user settings.json = BDR-116 amendment, user decides before code.
|
||||
|
||||
- [ ] **Phase 0, no mod: split project CLAUDE.md**
|
||||
- Move the 4 project CLAUDE.md sections (graphify vendored skill 1.4k chars, mods/ 1.3k, rules/ maintenance 1.3k, transient planning artifacts 0.9k) to `.claude/rules/<name>.md` with `paths:` (`skills/graphify/**`; `mods/**`, `skills/model-router`; `rules/**`; `docs/superpowers/**`). Project scope only: no ~/.claude link points at `.claude/` (checked 2026-10-24); never into `rules/` (= ~/.claude/rules, every project).
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# CONTRACT — model-scope-dialog
|
||||
- date: 2026-10-25 | flow: feat | branch: feature/model-scope-dialog (from develop)
|
||||
- status: active
|
||||
|
||||
## REQUEST (verbatim — IMMUTABLE)
|
||||
/model scope dialog in model-router (TODO "Before phase 0"). Fact (docs model-config): `/model <name>` always writes `model` to user settings.json (tracked here); picker key `s` = session only; project `model` honored at launch. Mod: `command.run` on `model` with args → `$.ui.ask` "This project / This conversation / Everywhere": project = `model` in `.claude/settings.local.json` + sticky route now; conversation = sticky route only (`/route model=`); everywhere = native passthrough. No args → native picker untouched; `-p` or no surface → passthrough. Files: register.ts, register.test.ts, lib/effort-shift.md. Doctor keeps the tracked ≠ opus warning.
|
||||
|
||||
## CLARIFICATIONS
|
||||
- Pass A: none — request complete (outcome, scope, constraints all named).
|
||||
- Verified before planning: `command.run` fires on core commands too ("Core is the engine's command", types 2.1.306 l.4365-4378); a guard that fails is skipped and the command runs (fail-open = passthrough, matches BDR-125 "injections fail open"). `$.fs.write` creates the file and its directories. `$.session.root()` = project root (a shell `cd` never moves it). `$.config.set` has no scope argument, so the per-project write goes through `$.fs.write` on `<root>/.claude/settings.local.json`.
|
||||
- [gated 2026-10-25] Dismissed vs headless = SPLIT (user pick): `$.session.surfaces()` empty (plain `-p`, no surface) → native passthrough BEFORE any dialog; the dialog rejected (Esc, dismissed) or answered with free text → cancel: nothing written, nothing routed, output `model: no scope chosen, nothing changed`.
|
||||
- [gated 2026-10-25] A name the router does not know (`isModelName` false: `default`, `opusplan`, free text) → native passthrough, no dialog (user pick).
|
||||
- [gated 2026-10-25] The id written to `.claude/settings.local.json` is the FULL id (alias resolved through `cfg.models`; a full id or a `[1m]` variant kept verbatim) (user pick, LRN-203).
|
||||
- [after the challenge, 2026-10-25] "known name" = the router's TABLE (alias or a full id listed in `cfg.models`, `[1m]` stripped for the test); a shape-only id (`claude-opus-5-6`) is unknown → native (C10). The two non-native answers mirror a native user switch: sticky model route + run slot dropped, a prior sticky effort kept (C6/R4/R11). Everywhere drops a prior sticky model first (C4/R3). Project tree treated as untrusted: links refused (R5). Cause words fixed, never error messages (R6). Fail-open to native only before an answer (C3/R1). Confirmation pass K1-K14 folded (created = success, FsStat kind `dir`, `[1m]` note, bare token routed, no shared flag, partial-state text, absent = exists false, own reader with fixed words, pin note before the question, tier dropped too, kit `dirs` map, awaited show, `haiku[1m]` native, worktree limit documented). Deferred: engine gitignore behaviour on a created settings.local.json (R13), live hot-switch on a local `model` change (R15/C12) → LRN-212 live check.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
1. `/model <name>` typed by the person (origin `composer`), one token whose `[1m]`-stripped form is an alias of `cfg.models` or one of its full ids, opens one `$.ui.ask` with exactly the options `This project`, `This conversation`, `Everywhere` (that order), header `model-router`; the question names the full id (alias resolved through `cfg.models`, `[1m]` kept) and ends with "where?"; when the local settings file already holds a string `model`, a line before the final question says that at launch here the project pin wins over Everywhere (value through `clean()`).
|
||||
2. Answer `This project`: `<root>/.claude/settings.local.json` holds `"model": "<full id>"` (`[1m]` verbatim), every other key preserved (2-space indent, trailing newline), the file created when absent (success text + `file created: keep it gitignored`, no toast), an existing `.claude` directory (`kind: 'dir'`) accepted; `st.userMain.route.model` = the bare token (as `/route model=` stores it), a prior sticky effort kept, `st.runMain` = null; the native command does NOT run; the output names the file, says how to undo (remove the `model` key), and never promises `[1m]` on the route (note `[1m] follows the session's variant` when the token or the session carries it).
|
||||
3. Answer `This conversation`: same sticky slot change as 2, no file written anywhere, native does not run.
|
||||
4. Answer `Everywhere`: `next(e)` passthrough with args unchanged; any sticky model OR tier from an earlier answer or `/route` is dropped first (its effort kept); no file written.
|
||||
5. Passthrough with no dialog: no args; more than one token; origin not `composer`; a name not in the table (`default`, `opusplan`, shape-only `claude-opus-5-6`, free text, `haiku[1m]`); `st.off`; `st.asking !== null`; `$.session.surfaces()` empty. `ensureConfig` runs before the gates. A dismissed dialog (`askOr` → `Later`) or a free-text answer = cancel: nothing written, nothing routed, output `model: no scope chosen, nothing changed`.
|
||||
6. The project write refuses, without throwing: a `.claude` or `settings.local.json` that is a symlink or not a directory/regular file; a file that is not JSON or not a JSON object; a read over `MAX_CONFIG_BYTES`; an fs error (a rejecting `stat` or `read` on an existing path is an fs error, never "absent"). Then: toast + output with a FIXED cause word (never `err.message` or `String(err)`), the sticky route still set, the file untouched. "Absent" = `$.fs.exists` false AND `$.fs.stat` rejecting; a path whose `stat` answers `isLink` (a dangling link included) is refused as a link, never "absent" (GATE 2 MEDIUM, 2026-10-25: `exists` may follow links). Same order for `.claude`.
|
||||
7. The `model` hook's `.catch` uses the warnOnce key `command.run model` and passes through (`next(e)`); the post-answer section runs inside its own try/catch that returns `{ text: 'model failed (<kind>); … check /route show and .claude/settings.local.json' }`, so native never runs after an answer.
|
||||
8. Tests in `register.test.ts` cover each line of criteria 1-7 (the plan's list), including `fable[1m]` and `claude-fable-5-1[1m]`, the conversation → everywhere sequence, the post-answer throw, and the kit carve-out: `installWrite` accepts exactly `${ROOT}/.claude/settings.local.json` and stays loud for every other path.
|
||||
9. Mod suite green: validate --strict and `claude plugin test`.
|
||||
CHECK: make test suite=lib/tests/mods.test.sh 2>&1 | tail -1
|
||||
EXPECT: all suites green
|
||||
EVIDENCE: MET exit=0 marker-found :: all suites green
|
||||
10. `lib/effort-shift.md` documents the dialog (scopes, what each writes, the two non-native answers set a sticky route and drop the run slot, Esc = nothing, no args / unknown name / headless = native) and l.53 is amended; lines ≤ 80 columns.
|
||||
CHECK: a=$(grep -c 'This conversation' lib/effort-shift.md); b=$(awk 'length($0)>80' lib/effort-shift.md | wc -l); echo "doc=$a/$b"
|
||||
EXPECT: doc=1/0
|
||||
EVIDENCE: MET exit=0 marker-found :: doc=1/0
|
||||
11. README.md: l.139 names the scope dialog beside "a user `/model`" and the routing.json writes bullet names the `/model` → This project write of `.claude/settings.local.json`.
|
||||
CHECK: a=$(grep -c 'this project, this conversation, everywhere' README.md); b=$(grep -c 'This project writes `model` into' README.md); echo "readme=$a/$b"
|
||||
EXPECT: readme=1/1
|
||||
EVIDENCE: MET exit=0 marker-found :: readme=1/1
|
||||
12. Full suite green.
|
||||
CHECK: make test 2>&1 | tail -1
|
||||
EXPECT: all suites green
|
||||
EVIDENCE: MET exit=0 marker-found :: all suites green
|
||||
13. The diff touches only the FILE SCOPE.
|
||||
CHECK: git diff --name-only develop -- . ':!.claude' | grep -vcE '^(mods/model-router/hooks/register.ts|mods/model-router/hooks/register.test.ts|lib/effort-shift.md|README.md)$' | sed 's/^/n=/'
|
||||
EXPECT: n=0
|
||||
EVIDENCE: MET exit=0 marker-found :: n=0
|
||||
14. No new lint or test suppression in the diff.
|
||||
CHECK: git diff -U0 develop -- . ':!.claude' | grep -E '^\+' | grep -cE 'eslint-disable|@ts-ignore|@ts-expect-error|shellcheck disable' | sed 's/^/n=/'
|
||||
EXPECT: n=0
|
||||
EVIDENCE: MET exit=0 marker-found :: n=0
|
||||
15. `canonical()` is not used on the `/model` path (it strips `[1m]`); `fullId()` resolves the written id.
|
||||
CHECK: python3 -I -c "import re;s=open('mods/model-router/hooks/register.ts').read();i=s.index('async function handleModelCommand');j=s.index('\n}\n',i);print('canon=%d'%s[i:j].count('canonical('))"
|
||||
EXPECT: canon=0
|
||||
EVIDENCE: MET exit=0 marker-found :: canon=0
|
||||
|
||||
## FILE SCOPE
|
||||
- mods/model-router/hooks/register.ts
|
||||
- mods/model-router/hooks/register.test.ts
|
||||
- lib/effort-shift.md
|
||||
- README.md (l.139 and the routing.json writes bullet)
|
||||
@@ -0,0 +1,54 @@
|
||||
# CONTRACT — picker-scope
|
||||
- date: 2026-10-25 | flow: feat | branch: feature/model-scope-dialog (in place)
|
||||
- status: active
|
||||
|
||||
## REQUEST (verbatim — IMMUTABLE)
|
||||
"oui commence par la feat sélecteur. j'ai pris un nouveau dossier j'ai mis haiku, et j'ai mis un autre dossier encore et c'etait haiku de base alors que ca devrait etre opus par defaut si on a pas de pin par projet on pin opus. Et dans tout les cas, on utilise les dernieres verison de chaque model. bref corrige tout cela"
|
||||
+ earlier: "je voulais effectivement qu'on puisse dnas le selecteur, dire le model qu'on veut, puis que cela propose si on le veut project scope ou user scope"
|
||||
+ "Donc la, si je fais /model sur un projet, ce dit projet pin le model choisi, et il peut etre different pour chaque projet / conversation et a par defaut opus. On est ok la dessu ? fait le /feat si tu veux"
|
||||
|
||||
## CLARIFICATIONS
|
||||
- [gated 2026-10-25] Picker answers = This project / This conversation / Everywhere (same as `/model <name>`, BDR-126).
|
||||
- [gated 2026-10-25] Project pin = full id (`claude-fable-5-1`, `[1m]` kept); "latest version" = the router table carries the latest ids (2c39524).
|
||||
- [gated 2026-10-25] A model chosen by hand through the dialog (picker or `/model <name>`, scopes This project / This conversation) ALWAYS switches: it bypasses `mainUpgrade` / `mainModelSwitch` and the cold-read caps; the breaker (model down) and the context window (`fits`) stay in force.
|
||||
- [gated 2026-10-25] Picker "Default" (requested_model null) → native, no question.
|
||||
- Default with no project pin = opus: user settings.json is written only by Everywhere (native). Restored to opus 2026-10-25 after the picker leaks (BLK-036).
|
||||
- [after the challenge 2026-10-25] Plan r2: hand pick = own early branch in decideMain (breaker on the TARGET checked every turn); slot held → deny + toast (no native leak); a native user switch drops a hand pick; stale-conversation guard. Plan r3 (confirmation FATAL(1) folded inline): unusable hand pick falls through to the existing chain; Everywhere thunk returns {}; clock fixtures named; conv read before the slot check; hand-pick drop skipped while a picker dialog is open; hand pick clears its target's mark; effort-shift l.70 amended. Residuals: `/config` Model row still native (source `command`), hand pick dropped at `/clear`, no timeout on a never-settling dialog.
|
||||
- SPIKE PROVEN 2026-10-25 (dev mod picker-spike, user-run in a live session): `on('classic.PreModelSwitch')` fires for `source: 'picker'` with `requested_model`; `$.ui.ask` awaited INSIDE the hook never renders (UI frozen on "Running PreModelSwitch hooks…"); returning `{ permissionDecision: 'deny', permissionDecisionReason }` at once blocks the switch and the user settings.json write; a continuation launched before return and run after it (`await $.clock.sleep(300)` then `$.ui.ask`) renders; `$.command.run({ command: 'model', args })` from that continuation runs the native switch + user settings write.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
1. A `classic.PreModelSwitch` hook: `source: 'picker'`, router on, `requested_model` a string the table knows (`knownModel`), a surface present, no dialog in flight → returns `{ permissionDecision: 'deny', permissionDecisionReason }` WITHOUT awaiting any dialog, and holds the single-dialog slot (`st.asking`) from before the return until the deferred dialog ends.
|
||||
2. Passthrough (`next(e)`, no dialog, no deny) for: `source` `command` or `sdk` (a first-line source filter, ahead of `ensureConfig`); `requested_model` null or unknown to the table; router off; no surface. `ensureConfig` runs before those gates. `st.asking` already held → deny + toast `answer the open dialog first`, never native. The hook's `.catch` passes through with its own warnOnce key.
|
||||
3. The deferred dialog (after a short sleep) asks the same question and options as `/model <name>` (This project / This conversation / Everywhere, header `model-router`, pin note when the project already pins a model) for the picked model's full id.
|
||||
4. Picker → This project: same effects as `/model <name>` → This project (project settings.local.json written with the full id under the same refusal rules, sticky model route, run slot dropped, sticky effort kept); the outcome text reaches the transcript (`$.ui.log`); user settings.json never written (native never runs).
|
||||
5. Picker → This conversation: sticky route only, nothing written, native never runs; outcome logged.
|
||||
6. Picker → Everywhere: prior sticky model/tier dropped, then `$.command.run({ command: 'model', args: <requested_model> })` (native switch + user settings write); its PreModelSwitch (`source: 'command'`) and its `command.run` (origin plugin) both pass through, no second dialog.
|
||||
7. Picker dialog dismissed or free text → nothing written, nothing routed, native never runs, the NO_SCOPE text logged. A throw inside the deferred dialog (before or after the answer) is logged under the picker's own warn key and always releases `st.asking`. If the conversation changed (`$.session.id()`) between the deny and the answer, nothing is applied and that is logged.
|
||||
8. Hand choice always switches: with a sticky model route set by a dialog answer (picker or `/model <name>`, This project / This conversation), every main step, in later turns too, moves to that model even when the cold read exceeds `upgradeMaxTokens` / `downgradeMaxTokens`, `mainUpgrade` / `mainModelSwitch` is off, the current model is down or the session model is outside the table. When the hand-picked model is marked down or does not fit its known window, the hand pick waits (one log) and the EXISTING automatic chain decides as if no model were wanted (a down current model, even when it IS the hand pick, falls back to the next available model; windowReturn still applies), on every turn until the hand-picked model is usable again. A hand pick clears its target's breaker mark at the time of the pick, like a native user switch. A sticky route set by a typed `/route model=` keeps today's caps. A native user switch (PostModelSwitch source command/picker/sdk) drops a hand pick.
|
||||
9. Tests in register.test.ts cover criteria 1-8 as listed in the plan r2 §Tests (deny without awaiting, each passthrough, slot-held deny, the three answers, dismiss, sleep throw, post-answer throw, stale conversation, hand pick down ACROSS a turn boundary, cur down, unranked session, cap bypass up and down, `/route model=` still capped, native switch drops the hand pick).
|
||||
10. lib/effort-shift.md documents the picker (deny then scope question; Everywhere = native write) and the hand-choice cap bypass; lines ≤ 80 cols.
|
||||
CHECK: a=$(grep -c 'picker' lib/effort-shift.md); b=$(awk 'length($0)>80' lib/effort-shift.md | wc -l); echo "doc=$([ "$a" -ge 1 ] && echo ok)/$b"
|
||||
EXPECT: doc=ok/0
|
||||
EVIDENCE: MET exit=0 marker-found :: doc=ok/0
|
||||
11. Mod suite green.
|
||||
CHECK: make test suite=lib/tests/mods.test.sh 2>&1 | tail -1
|
||||
EXPECT: all suites green
|
||||
EVIDENCE: MET exit=0 marker-found :: all suites green
|
||||
12. Full suite green.
|
||||
CHECK: make test 2>&1 | tail -1
|
||||
EXPECT: all suites green
|
||||
EVIDENCE: MET exit=0 marker-found :: all suites green
|
||||
13. Diff since 48778af touches only the FILE SCOPE.
|
||||
CHECK: git diff --name-only 48778af -- . ':!.claude' | grep -vcE '^(mods/model-router/hooks/register.ts|mods/model-router/hooks/register.test.ts|lib/effort-shift.md)$' | sed 's/^/n=/'
|
||||
EXPECT: n=0
|
||||
EVIDENCE: MET exit=0 marker-found :: n=0
|
||||
14. No new lint or test suppression.
|
||||
CHECK: git diff -U0 48778af -- . ':!.claude' | grep -E '^\+' | grep -cE 'eslint-disable|@ts-ignore|@ts-expect-error|shellcheck disable' | sed 's/^/n=/'
|
||||
EXPECT: n=0
|
||||
EVIDENCE: MET exit=0 marker-found :: n=0
|
||||
|
||||
## FILE SCOPE
|
||||
- mods/model-router/hooks/register.ts
|
||||
- mods/model-router/hooks/register.test.ts
|
||||
- lib/effort-shift.md
|
||||
(README.md, USAGE.md, CHANGELOG.md: doc-sync step, not the executor)
|
||||
@@ -0,0 +1,40 @@
|
||||
# CONTRACT — router-haiku-table
|
||||
- date: 2026-10-25 | flow: bugfix | branch: feature/model-scope-dialog (in place, aiguillage WORKING)
|
||||
- status: active
|
||||
|
||||
## REQUEST (verbatim — IMMUTABLE)
|
||||
model-router models table stale: `haiku` → `claude-haiku-4-5-20251001` in DEFAULT_CONFIG (mods/model-router/hooks/register.ts ~l.256), while the native alias now resolves to `claude-haiku-5-5`. Evidence: integration_alphalink transcript 2026-10-25T16:22:53Z "model-router: claude-haiku-5-5 unknown to the models table; no switch". Impact: no switch on haiku sessions, and `/model haiku` → This project (BDR-126) would write the stale 4.5 id. Check the rest of the table (windows entry keyed on the old id, tiers, tests, census, docs citing the old id).
|
||||
|
||||
## CLARIFICATIONS
|
||||
- Facts (claude-api skill model table, cached 2026-10-06): `claude-haiku-5-5` context 1M, effort low–max (default medium); `claude-haiku-4-5` 200K, no effort.
|
||||
- [gated 2026-10-25] The "haiku takes no effort" strip (register.ts effortWord, step plan, isHaiku sites, census skip lib/tests/effort-routing.test.sh:170) is OUT of scope: separate /bugfix after this one (user pick).
|
||||
- Internal: the `windows` table becomes `{}` (5.5 is 1M like every other table model); the mechanism and the override key stay.
|
||||
- Rest of table checked: sonnet `claude-sonnet-5-5`, opus `claude-opus-5-5`, fable `claude-fable-5-1` are current. No doc (README, USAGE, CHANGELOG, MIGRATION) cites the 4.5 id.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
1. DEFAULT_CONFIG maps `haiku` to `claude-haiku-5-5` and `windows` holds no `claude-haiku-4-5*` key; no `claude-haiku-4-5` string left in register.ts or register.test.ts.
|
||||
CHECK: a=$(grep -c "haiku: 'claude-haiku-5-5'" mods/model-router/hooks/register.ts); b=$(grep -c 'claude-haiku-4-5' mods/model-router/hooks/register.ts mods/model-router/hooks/register.test.ts | awk -F: '{s+=$2} END{print s}'); echo "table=$a/$b"
|
||||
EXPECT: table=1/0
|
||||
EVIDENCE: MET exit=0 marker-found :: table=1/0
|
||||
2. A regression test in register.test.ts: a session whose model is `claude-haiku-5-5` is known to the table (no "unknown to the models table" log) and a route on it moves main like any table model.
|
||||
3. The tests that depended on the 200K haiku window still prove the window mechanism, now with an explicit `windows` override in their fixture (never deleted or weakened).
|
||||
4. Mod suite green.
|
||||
CHECK: make test suite=lib/tests/mods.test.sh 2>&1 | tail -1
|
||||
EXPECT: all suites green
|
||||
EVIDENCE: MET exit=0 marker-found :: all suites green
|
||||
5. Full suite green.
|
||||
CHECK: make test 2>&1 | tail -1
|
||||
EXPECT: all suites green
|
||||
EVIDENCE: MET exit=0 marker-found :: all suites green
|
||||
6. Diff since 20c6623 touches only the FILE SCOPE.
|
||||
CHECK: git diff --name-only 20c6623 -- . ':!.claude' | grep -vcE '^(mods/model-router/hooks/register.ts|mods/model-router/hooks/register.test.ts)$' | sed 's/^/n=/'
|
||||
EXPECT: n=0
|
||||
EVIDENCE: MET exit=0 marker-found :: n=0
|
||||
7. No new lint or test suppression.
|
||||
CHECK: git diff -U0 20c6623 -- . ':!.claude' | grep -E '^\+' | grep -cE 'eslint-disable|@ts-ignore|@ts-expect-error|shellcheck disable' | sed 's/^/n=/'
|
||||
EXPECT: n=0
|
||||
EVIDENCE: MET exit=0 marker-found :: n=0
|
||||
|
||||
## FILE SCOPE
|
||||
- mods/model-router/hooks/register.ts
|
||||
- mods/model-router/hooks/register.test.ts
|
||||
@@ -0,0 +1,74 @@
|
||||
# PLAN r3 — model-scope-dialog (feat)
|
||||
Contract: `.claude/tasks/contracts/2026-10-25-model-scope-dialog-1450.md`
|
||||
Scope rule: 7 (PROCEED), 4 files, logic in one mod hook + tests + docs.
|
||||
r1 → r2 after 3 lenses (correctness FATAL(6), robustness CONCERNS(7),
|
||||
simplicity CONCERNS(3)); r2 → r3 after the confirmation pass (CONCERNS(3), K1-K14).
|
||||
Every change below is named at the finding it closes.
|
||||
|
||||
## Files
|
||||
- `mods/model-router/hooks/register.ts`
|
||||
- `registerCommandHook` (l.3758): a second hook beside the `route` one:
|
||||
`on('command.run', { command: 'model' }, async ($, e, next) => handleModelCommand($, st, e, next))`
|
||||
`.catch(($, e, next) => { warnOnce(st, $, 'command.run model', next.error.kind); return next(e) })`.
|
||||
Own warnOnce key (C7/R1). The `.catch` can only be reached BEFORE an answer: the whole post-answer section runs inside its own try/catch that returns `{ text }` (K5: no shared flag). Fail-open to native only before an answer (C3/R1/S9).
|
||||
- `handleModelCommand($, st, e, next)` near `handleCommand` (l.2019), in this order:
|
||||
1. `await ensureConfig($, st)` (C2/R8/S7).
|
||||
2. gates, each `return next(e)`: `st.off`; `e.origin.kind !== 'composer'`; `tokens = e.args.trim().split(/\s+/)`, `tokens.length !== 1 || tokens[0] === ''` (no args or extra tokens: native owns its syntax); `bare = tokens[0].replace(ONE_M, '')`, `!knownModel(st.cfg, bare)`; `(await $.session.surfaces()).length === 0` (headless) BEFORE the slot check; then `st.asking !== null`; then `st.asking = \`model:${tokens[0]}\`` synchronously (R9 TOCTOU).
|
||||
3. `try { … } finally { st.asking = null }`.
|
||||
- `knownModel(cfg, token)`: `bare = token.replace(ONE_M, '')`; `hasKey(cfg.models, bare) || Object.values(cfg.models).includes(bare)`, AND NOT (`ONE_M.test(token)` and the resolved id starts with `HAIKU`) (K13: haiku has no `[1m]` tier, `haiku[1m]` goes to native). An alias or a full id IN THE TABLE. A shape-only `isFullId` (`claude-opus-5-6`) is NOT known → native (C10; refines the gated pick "unknown name → native": known = the router's table). `fullId(cfg, token)`: `hasKey(cfg.models, bare) ? cfg.models[bare] + (ONE_M.test(token) ? '[1m]' : '') : token`. NEVER `canonical()` (it strips `[1m]`, C11/R14/S6).
|
||||
- dialog: `askOr($, question, MODEL_SCOPES)` (S1: its LATER on a rejected dialog is the cancel; headless is already gated). Question text (ends with "where?"): `Switch main to <fullId> where?` preceded by one line per option: `This project: .claude/settings.local.json of this repo (wins at launch) + route now · This conversation: route now, nothing written · Everywhere: user settings.json, every project`; when the local file already holds a string `model` (read inside the slot through `readLocalSettings`, a cause word = no note, value through `clean(v, 60)`), one more line BEFORE the final question line: `Note: this project pins <that id> in .claude/settings.local.json: at launch here, the project pin wins over Everywhere` (C4b/R7, K9). Answer not in `MODEL_SCOPES` (LATER, free text) → `{ text: 'model: no scope chosen, nothing changed' }`.
|
||||
- `MODEL_SCOPES = [PROJECT_SCOPE, CONVERSATION, EVERYWHERE] as const` with `PROJECT_SCOPE = 'This project'` (comment: differs from `THIS_PROJECT` 'This project only', the first-use dialog's label; both fixed by their contracts) and `CONVERSATION = 'This conversation'`; reuse `EVERYWHERE` (S5).
|
||||
- branches (after `st.modelAnswered = true` for the first two):
|
||||
- `This conversation` → `stickyModel(st, bare)`; text = `model: sticky route ${bareFull} for this conversation` + ONE_M note + `\n` + `await show($, st)`. `bareFull` = the table id without `[1m]`; ONE_M note = ` ([1m] follows the session's variant)` whenever the token or the session model carries `[1m]` (K3: `route.model` cannot hold `[1m]`, `moveTo` carries the SESSION's variant, so the headline never promises `[1m]` the route cannot deliver; the file keeps the verbatim id).
|
||||
- `This project` → `const w = await writeLocalModel($, fullId)`; `stickyModel(st, bare)`; `ok = w === 'written' || w === 'created'`; text = (ok ? `model: ${fullId} written to .claude/settings.local.json (remove its "model" key to undo)` + (`w === 'created'` ? `, file created: keep it gitignored` : '') : `model: .claude/settings.local.json not written (${w})`) + `; sticky route ${bareFull} set` + ONE_M note (K3, below) + `\n` + `await show($, st)` (K12: awaited). On a cause word also `$.ui.toast(\`settings.local.json not written: ${w}\`)`.
|
||||
- `Everywhere` → `dropStickyModel(st)` (C4a/R3: a sticky model from an earlier answer would route main back after the native switch) then `return next(e)`; runMain is dropped by the native PostModelSwitch as today.
|
||||
- Post-answer section (the three branches) inside `try { … } catch (err) { failOnce or warnOnce; return { text: \`model failed (${errWord(err)}); the file write or the sticky route may have landed: check /route show and .claude/settings.local.json\` } }` (K5/K6).
|
||||
- `stickyModel(st, bare)`: `st.userMain = { phase: 'custom', route: { model: bare, ...(effort kept) }, source: 'user', ...(explicitEffort kept) }` where effort/explicitEffort come from the previous `st.userMain` (R11: a `/route effort=max` survives, native `/model` never touched effort); `st.runMain = null` (C6/R4: the two non-native answers mirror the native user switch, so "a user `/model` drops the run slot" stays true); `refresh($, st)`. `bare` routes without `[1m]`: `moveTo` (l.1206) carries the variant from the session model (C1).
|
||||
- `dropStickyModel(st)`: drop `route.model` AND `route.tier` from `st.userMain` (K10: `routeName = tier ?? model`, a sticky `/route plan` tier would upgrade main back); keep the effort if any, else `st.userMain = null`.
|
||||
- `writeLocalModel($, id): Promise<'written' | 'created' | string>` (string = a FIXED cause word, never `err.message`/`String(err)`: R6; causes: `project root unknown`, `.claude is a link`, `not a regular file`, `not JSON`, `not an object`, `too large`, `fs error <errWord>`):
|
||||
1. `root = await $.session.root()` (throw → `project root unknown`).
|
||||
2. `dir = ${root}/.claude`, `path = ${dir}/${LOCAL_SETTINGS_NAME}` (`LOCAL_SETTINGS_NAME = 'settings.local.json'`). `if (await $.fs.exists(dir))`: `st = await $.fs.stat(dir)` (reject → `fs error <errWord>`); `st.isLink` → `.claude is a link`; `st.kind !== 'dir'` (FsStat kinds are `file | dir | other`, K2) → `.claude is not a directory`. Absent → OK (`$.fs.write` creates it) (R5: the project tree is untrusted, BDR-116(3)).
|
||||
3. `readLocalSettings($, path)` (shared with the pre-dialog Note, K9; never throws, returns `{ data, created } | string`): `!(await $.fs.exists(path))` → `{ data: {}, created: true }` (absent is ONLY a false `exists`, K7); `stat = await $.fs.stat(path)` (reject → `fs error <errWord>`); `stat.isLink` → `settings.local.json is a link`; `stat.kind !== 'file'` → `not a regular file`; `stat.size > MAX_CONFIG_BYTES` → `too large`; `text = await $.fs.read(path)` (reject → `fs error <errWord>`); `JSON.parse` throw → `not JSON`; `!isRecord` → `not an object`. Own small reader instead of `readLayer` (K8: its log text folds I/O and syntax errors; the cause words here are fixed by the checks themselves).
|
||||
4. `data.model = id`; `await $.fs.write(path, JSON.stringify(data, null, 2) + '\n')` (fs throw → `fs error <errWord(err)>`). Return `created ? 'created' : 'written'`. SUCCESS = `'written' || 'created'` (K1); the toast fires only on a cause word.
|
||||
- `mods/model-router/hooks/register.test.ts` (kit changes NAMED, C5/R12/S3):
|
||||
- `installWrite`: allow exactly `${ROOT}/.claude/settings.local.json` with or without a prior read; every other non-routing path stays loud (`expect(...)` unchanged for them). `slot()` maps that path to `'local'`.
|
||||
- `World`/`Fixture`: `surfaces: readonly string[]` (default `['terminal']`), `installWorld` adds `on('session.surfaces', () => ({ value: w.surfaces }))`; a `dirs: Map<string, { kind: 'dir' | 'file' | 'other'; isLink: boolean }>` the world's `fs.exists`/`fs.stat` answer for paths WITHOUT file text (K11: today stat throws for them), so `${ROOT}/.claude` can be an existing dir, a link, or a file.
|
||||
- a bottom `on('command.run', { command: 'model' }, () => ({ text: 'native' }))` installed per test (or a `NATIVE` plugin like `PROBE`) to witness the passthrough; `modelCmd($, args, origin?)` helper mirroring `route()`.
|
||||
- `lib/effort-shift.md`: l.40 "a user `/model` drop it" → keep, then add to "Run slot and levers": `/model <name>` typed asks the scope (This project = `.claude/settings.local.json` + sticky model route, This conversation = sticky route only, Everywhere = the native write to user settings.json, every project); the two non-native answers set a sticky model route and drop the run slot like a native switch; Esc = nothing changes; no args, an unknown name or a headless run = native. l.53 "A user `/model` only moves the baseline" gets "(Everywhere; the two other scopes set a sticky route, which the classifier never overrides)". ≤ 80 cols.
|
||||
- `README.md` (S8, in scope, two edits): l.139 "a user `/model`" → "a user `/model` (typed with a name it asks the scope: this project, this conversation, everywhere)"; the writes bullet ("Only a dialog answer, `/route ask on|off` or `/route forget` writes `routing.json`") gains ", and `/model <name>` → This project writes `model` into the project's `.claude/settings.local.json`".
|
||||
- `register.ts` l.75 comment (`only a skill, /route clear|off or a user /model write or drop it`) stays true (runMain dropped on every answer path).
|
||||
|
||||
## Edge cases
|
||||
- `/model fable[1m]`, `/model claude-fable-5-1[1m]`: bare `fable`/`claude-fable-5-1` is known → dialog; file gets `claude-fable-5-1[1m]`; `stickyModel(st, bare)` stores the BARE TOKEN as `/route model=` does (`fable` or `claude-fable-5-1`, K4); the session's `[1m]` is carried by `moveTo`, the token's is not promised. Tests for both (C1/R2).
|
||||
- `haiku[1m]` → native (K13).
|
||||
- Worktree session: `$.session.root()` follows the worktree, so "This project" writes that worktree's `.claude/settings.local.json`; named as a limit in effort-shift.md (K14), not handled.
|
||||
- `.claude/settings.local.json` holds `null`, `[]`, `"x"` → `not an object`, nothing overwritten, route only (C8/S2).
|
||||
- `.claude` or the file is a symlink → refused, nothing written, route only (R5).
|
||||
- Dialog answered, then `show` throws → `.catch` returns `{ text: 'model failed …' }`, native never runs (C3).
|
||||
- Free text under Other → cancel, same text as Esc.
|
||||
- Headless (`surfaces()` = `[]`) → passthrough, no dialog.
|
||||
- The sticky route may be HELD by `decideMain` caps (switch off, cold read > cap): the output never claims "routed now"; the appended `show` line tells the truth (C9/R10).
|
||||
- `[deferred 2026-10-25]` R13: whether the engine gitignores a `settings.local.json` it creates is unverified; the output's "keep it gitignored" note stands in. R15 / C12: whether a live `model` change in the local file hot-switches the session (ConfigChange `local_settings`) is unverified → LRN-212 live check after the suite: after "This project", no PostModelSwitch, no down mark; output wording stays neutral ("written to", never "next launch").
|
||||
|
||||
## Tests (register.test.ts, "model command" block)
|
||||
- asks the three scopes in order with header `model-router` for `/model fable` and for `/model claude-fable-5-1[1m]`; question names the full id; native not run.
|
||||
- This project: writes `model` (full id, `[1m]` verbatim), keeps other keys (`permissions` fixture), `userMain.route.model` = bare token, `runMain` null, native not run, output names the file. Positive control with `${ROOT}/.claude` present as `{ kind: 'dir' }` (K2).
|
||||
- This project: in a `[1m]` session and in a plain session, the output carries the `[1m] follows the session's variant` note only when the token or the session has it (K3).
|
||||
- This project: creates the file when absent (success text + `file created: keep it gitignored`, no toast) (K1).
|
||||
- This project: `null` / array file → `not an object`, file unchanged, route set, toast.
|
||||
- This project: `.claude` link / `.claude` regular file / settings file link → refused with the matching cause word, file untouched; `exists` true but `stat` rejecting → `fs error`, file untouched (K7).
|
||||
- This project: fs.write throws → `fs error …`, route set.
|
||||
- This conversation: route = `/route model=` equivalent, sticky effort from a prior `/route effort=max` kept, nothing written, native not run.
|
||||
- Everywhere: native run with args unchanged; a prior sticky model dropped (sequence: conversation X → everywhere Y → `userMain.route.model` undefined).
|
||||
- passthrough, no question: no args; two tokens; `default`; `claude-opus-5-6` (shape only); `haiku[1m]`; sdk origin; `st.off`; `st.asking` set; `surfaces = []`.
|
||||
- question carries the project-pin note when the local file holds `model`, not otherwise (K9).
|
||||
- Everywhere after `/route plan` (sticky tier) drops the tier too (K10).
|
||||
- dismissed → cancel text, nothing written, nothing routed, native not run.
|
||||
- post-answer throw → `model failed …` text naming `/route show`, native not run (make `ui.status` throw from the world: `refresh` inside `stickyModel`; `session.usage` is swallowed by `readTokens`, K12).
|
||||
|
||||
## Disposition (STEP 0.6)
|
||||
- honors BDR-116 (composer-only writers; model never writes; project tree untrusted) by gating on `origin.kind === 'composer'`, refusing links, writing only the file the user chose.
|
||||
- honors BDR-125 amendment 8 by making `.claude/settings.local.json` the "This project" target and leaving the native user-settings write to "Everywhere".
|
||||
- honors BDR-115/LRN-203 (full ids in anything a hook writes) via `fullId()`; never `canonical()`.
|
||||
- honors LRN-098 (`/model` rewrites settings.json) by naming the user-settings write in the Everywhere option and by never reaching native after an answer.
|
||||
- applies LRN-212 (hot-loaded working-tree mod) for the live check named above.
|
||||
@@ -0,0 +1,78 @@
|
||||
# PLAN r2 — picker-scope (feat)
|
||||
Contract: `.claude/tasks/contracts/2026-10-25-picker-scope-1952.md`
|
||||
Scope rule 7: register.ts + register.test.ts + lib/effort-shift.md (docs README/USAGE/CHANGELOG via doc-sync).
|
||||
r1 → r2 after 3 lenses: correctness FATAL(5), robustness FATAL(2), simplicity SOLID(3 MINOR). Change named at the finding it closes (C = correctness, R = robustness, S = simplicity).
|
||||
|
||||
## Files
|
||||
- `mods/model-router/hooks/register.ts`
|
||||
- `Routed` type (beside `explicitEffort?`, l.~52): `explicitModel?: boolean // the model was chosen by hand in the scope dialog`.
|
||||
- `stickyModel` (l.~2095) sets `explicitModel: true`. `dropStickyModel` (l.~2109) builds its effort-only slot WITHOUT `explicitModel` (it is the one writer that copies fields, S2). No other writer changes.
|
||||
- HAND PICK BRANCH (closes C1/R1 BLOCKER, C2/R2, C3, R8). New helpers near `decideMain` (l.~1386):
|
||||
- `handPicked(st, wanted): boolean` = `st.userMain?.explicitModel === true && wanted !== undefined && wanted === <the id the userMain slot resolves to, through the same resolver mainPlan/wantedModel uses>` (the check names the TARGET, not only the slot, R8).
|
||||
- `handCall(st, cur, wanted, read): Call`: (a) same alias as `canonical(cur)` → `keep(cur)`; (b) `st.down.has(canonical(st.cfg, wanted))` → `keep(cur, 'hand pick down', <once log: model-router: <wanted> is held down; staying on <cur> until it is back>)`; (c) `!fits(st, wanted, read.tokens)` → `keep(cur, 'no fit', noFit(wanted))`; (d) else `moveTo(cur, wanted, 'hand pick', st.sessionModel)`.
|
||||
- `decideMain`: right after `if (st.off) return keep(cur)`, insert `if (handPicked(st, wanted)) return handCall(st, cur, wanted, read)`. It runs BEFORE `unknownCall` (an unranked session model no longer traps a hand pick, C3), before `windowReturn`, before the `cur` down branch (a down current model moves to the hand pick when that one is up, C2/R2). `upgradeCall`, `downgradeCall`, `leaveDown` stay UNCHANGED (r1's bypass inside them is dropped).
|
||||
- verbose transition cause word `hand pick` where the existing `why` words are mapped (follow the `upgrade`/`downgrade` mapping).
|
||||
- `scopeDialog` (S1): replace `answerScope` with `async function scopeDialog($, st, token, everywhere: () => Promise<CommandRunResult>, warnKey: string): Promise<CommandRunResult>`: `scopeQuestion($, fullId(st.cfg, token))` → `askOr($, question, MODEL_SCOPES)` → not in MODEL_SCOPES → `{ text: NO_SCOPE }`; Everywhere → `dropStickyModel(st); return await everywhere()`; else `applyLocalScope(...)` → `{ text }`; the post-answer try/catch keeps its text and uses `warnOnce(st, $, warnKey, …)` (C8/R6). `handleModelCommand` keeps its gates and slot, then `return await scopeDialog($, st, token, () => next(e), 'command.run model')`.
|
||||
- PICKER (new, in the `/model <name>` section after `handleModelCommand`):
|
||||
- `const PICKER_DELAY_MS = 300 // the engine draws nothing while a PreModelSwitch hook runs`
|
||||
- `const PICKER_DENY = 'model-router asks where this switch applies'`
|
||||
- `const PICKER_BUSY = 'answer the open dialog first'` (reuse the existing string constant if one exists at l.~3137)
|
||||
- `async function handlePicker($, st, e, next)`: the source filter is a matcher-like first line (`e.source !== 'picker'` → `return next(e)`; C6: the contract wording is amended to say so); then `await ensureConfig($, st)`; gates → `return next(e)`: `st.off`; `typeof e.requested_model !== 'string'` (Default); `!knownModel(st.cfg, asked)`; `(await $.session.surfaces()).length === 0`. Then `st.asking !== null` → `$.ui.toast(PICKER_BUSY)` and return the deny (R3: never native while a dialog is open, the BLK-036 leak). Then, synchronously: `st.asking = \`picker:${asked}\``; `const conv = await` is NOT allowed after this point, so read `$.session.id()` BEFORE the slot is set and pass it in; `void pickerDialog($, st, asked, conv)`; `return { permissionDecision: 'deny', permissionDecisionReason: PICKER_DENY }`.
|
||||
- `async function pickerDialog($, st, asked, conv): Promise<void>`: `try { await $.clock.sleep(PICKER_DELAY_MS); const out = await scopeDialog($, st, asked, () => $.command.run({ command: 'model', args: asked }), 'PreModelSwitch picker', conv-check); … } catch (err) { warnOnce(st, $, 'PreModelSwitch picker', errWord(err)) } finally { st.asking = null }`.
|
||||
- stale conversation (C10): `scopeDialog` gets an optional `stillHere: () => Promise<boolean>`; the picker passes `async () => (await $.session.id()) === conv`, checked right after the answer and before any effect; false → `{ text: 'model: the conversation changed, nothing applied' }`.
|
||||
- logging (C7): log `out.text` with the safe-log helper (`tryLog`, l.~353) only when the answer was not Everywhere (`$.command.run` already prints the native lines); NO_SCOPE and the stale text are logged.
|
||||
- registration (S3): in `registerCommandHook` (l.~4002), next to `command.run model`: `on('classic.PreModelSwitch', ($, e, next) => handlePicker($, st, e, next)).catch(($, e, next) => { warnOnce(st, $, 'PreModelSwitch', next.error.kind); return next(e) })`.
|
||||
- A native user switch drops a hand pick (C4): in `onModelSwitch` (l.~3930), for `USER_SWITCH.has(e.source)` and main (`e.agent_id === undefined`): `if (st.userMain?.explicitModel) dropStickyModel(st)`. So picker Default / unknown name / `/config` row / Everywhere all leave the native model in charge. Our denied switches raise no PostModelSwitch; `/model <name>` → This project/Conversation never runs native.
|
||||
- section comment of the `/model <name>` block: one line on the picker (deny now, ask after) and the hand-pick rule.
|
||||
- `mods/model-router/hooks/register.test.ts`
|
||||
- boot: bottom `on('classic.PreModelSwitch', () => ({}))` beside `classic.PostModelSwitch` (l.~278).
|
||||
- helper `picker($, requested, source = 'picker')` firing `$.classic.PreModelSwitch({...})` with every required field (mirror the PostModelSwitch helper at l.~727).
|
||||
- World flag `sleepFails` (C5/R6): boot swaps the mock clock's `clock.sleep` for one that rejects (same replacement pattern as `failingClock`, LRN-229; it keeps `clock.now`), so pickerDialog's own catch is reached.
|
||||
- native witness: the existing `model` command recorder.
|
||||
- `lib/effort-shift.md`: rewrite the `/model` paragraph (C9: l.~52 "no args … native, no question" is false now): `/model <name>` or a pick in the `/model` picker asks the scope (the picker's switch is held first: the engine prints that a hook blocked it, then the question comes); Esc = nothing; Everywhere = the native write to user settings.json; picker Default, an unknown name, a headless run = native, and a native switch drops a hand pick. Hand pick rule: a model chosen in that dialog always switches (no cold-read cap, no switch flag); a model held down keeps main where it is; the window guard needs a `windows` entry (none shipped, R4). Residuals: `/clear` drops a hand pick until relaunch (R7); the `/config` Model row still writes user settings.json (R5). ≤ 80 cols.
|
||||
|
||||
## Approach
|
||||
1. Deny now, ask in a continuation after the hook returned (spike-proven).
|
||||
2. One dialog function (`scopeDialog`) for both entries, an `everywhere` thunk and a warn key per entry.
|
||||
3. A hand pick is decided by its own branch in `decideMain`, ahead of every automatic rule; the automatic cap functions stay as they are.
|
||||
4. The native path stays the only writer of user settings.json (BDR-116).
|
||||
|
||||
## Edge cases
|
||||
- `[1m]` picks: `knownModel` accepts, the pin keeps `[1m]`, the route uses the bare token (BDR-126).
|
||||
- picker while a dialog is open → deny + toast, no native (R3).
|
||||
- `$.command.run` rejects on Everywhere → scopeDialog's catch text → logged under `PreModelSwitch picker`.
|
||||
- `/clear` while the picker dialog is open → stale check → nothing applied (C10).
|
||||
- hand-picked model marked down → stays on cur with one log; back up → moves (C1/R1).
|
||||
- `[deferred 2026-10-25]` R3 timeout: a `$.ui.ask` that never settles keeps the slot (no timeout, same as the first-use dialog); picker picks are then denied with the toast (no leak). R7: hand pick lost at `/clear` (BDR-126 residual). R5: `/config` Model row writes user settings (source `command`, indistinguishable from Everywhere's native run).
|
||||
|
||||
## Tests (register.test.ts, "picker" + "hand pick" blocks)
|
||||
- picker known model → hook result is the deny AND `w.asked` is empty at that moment; after `clock.advance(300)` + flush: the three-scope question.
|
||||
- passthrough, no deny, no question: source `command`, `sdk`; requested null; `opusplan`; `claude-opus-5-6`; router off; surfaces `[]`.
|
||||
- slot held (a `/model` dialog gated open) → deny + `answer the open dialog first` toast, no question, native empty.
|
||||
- picker → This project / This conversation / Everywhere (native recorder once with `model <requested>`, `w.asked` length 1, prior hand pick dropped); dismissed → NO_SCOPE logged, slot freed (a second picker asks again).
|
||||
- `sleepFails` → warn logged under `PreModelSwitch picker`, slot freed, nothing applied.
|
||||
- post-answer throw on the picker path → `model failed (` logged, native empty, slot freed.
|
||||
- stale conversation: `session.id` changes between deny and answer → `conversation changed` logged, nothing written, no route.
|
||||
- hand pick across turns (C1/R1): hand-pick fable, mark fable down, END THE TURN, next turn's first step on the session model → stays on the session model + one log; hold expires → next turn on fable.
|
||||
- hand pick cur down (C2/R2): session opus marked down, hand-pick fable with usage over `upgradeMaxTokens` and `mainUpgrade` off → fable.
|
||||
- hand pick bypass: usage over `upgradeMaxTokens` → fable; usage over `downgradeMaxTokens` + `switch off` → sonnet; `/route model=fable` same usage → held (unchanged).
|
||||
- unranked session model (C3): session on an id outside the table, hand pick opus → main on opus.
|
||||
- native user switch drops a hand pick (C4): hand pick fable, then `PostModelSwitch` source `picker` to sonnet → next step on sonnet.
|
||||
- existing `/model <name>` tests green with `scopeDialog`.
|
||||
|
||||
## Disposition (STEP 0.6)
|
||||
- extends BDR-126; amends its held-route residual (hand pick always switches, user pick); keeps its writer rules and full-id pin.
|
||||
- honors BDR-116: Everywhere = native command; the mod never writes user settings.json.
|
||||
- honors LRN-203 (`fullId`), LRN-228 (via `applyLocalScope`), LRN-229 (`sleepFails` follows its clock-swap pattern), LRN-230 (no new per-model fact; the window guard caveat is documented).
|
||||
- accepts LRN-204's cost (one cold re-read per hand switch), user pick.
|
||||
- BLK-036: picker leak closed; `/config` Model row named as residual (R5), not claimed closed.
|
||||
|
||||
## r3 — confirmation pass folded inline (FATAL(1) + 6 MINOR; re-challenge budget spent)
|
||||
These OVERRIDE the r2 text where they conflict.
|
||||
- K1 BLOCKER (hand pick unusable must not pin a down model): `handCall` returns `Call | undefined`. Order: (1) `usable = !st.down.has(canonical(st.cfg, wanted)) && fits(st, wanted, read.tokens)`; (2) not usable → return `undefined`; (3) same alias as `canonical(cur)` → `keep(cur)`; (4) else `moveTo(cur, wanted, 'hand pick', st.sessionModel)`. In `decideMain`: `if (handPicked(st, wanted)) { const hand = handCall(...); if (hand !== undefined) return hand; held = true; wanted = undefined }` then the EXISTING chain runs unchanged with no wanted model (unknownCall / windowReturn / cur down → leaveDown → nextAvailable / keep). When `held`, the returned call carries a `once` log `model-router: <wanted> is held down or does not fit; hand pick waits` (merge into the call's `once` only when it has none). Tests add: hand pick == current model (opus pinned, session opus), opus marked down → next step in the SAME turn and on the NEXT turn goes to the next available model (sonnet), never opus; hand pick fable mid-turn after the router moved there, fable fails (StopFailure) → next step leaves fable; hand pick outgrowing a known `windows` override → windowReturn still applies.
|
||||
- K2: the picker's Everywhere thunk is `() => $.command.run({ command: 'model', args: asked }).then(() => ({}))`; pickerDialog logs `out.text` whenever it is defined (so the catch text of a failed Everywhere is logged, the native lines are not printed twice).
|
||||
- K3 fixtures: `failingClock` (LRN-229 rig) ALSO answers `clock.sleep` at once (so `clockFailsAfterAsk` reaches the dialog); `sleepFails` = a separate whole-clock replacement answering `clock.now` and REJECTING `clock.sleep`. Post-answer-throw picker test uses `clockFailsAfterAsk`; the sleep-throw test uses `sleepFails`.
|
||||
- K4 order in handlePicker: all awaited gates AND `const conv = await $.session.id()` first; then `st.asking !== null` → deny + toast; then synchronously `st.asking = …`, `void pickerDialog(...)`, return deny. No await between the asking check and the set.
|
||||
- K5: `onModelSwitch` drop of a hand pick is skipped while `st.asking?.startsWith('picker:')` (a PostModelSwitch emitted for a switch the picker denied must not drop the earlier hand pick). Live check item: does the engine emit PostModelSwitch for a denied picker switch.
|
||||
- K6: a hand pick clears its target's breaker mark like a native user switch: `applyLocalScope` (both local scopes) calls `clearBreaker(st, canonical(st.cfg, fullId-bare))` before `stickyModel`.
|
||||
- K7: lib/effort-shift.md l.~70-71 ("Fable on main comes only from a skill row, the `route` tool or a typed `/route`") gains "or a hand pick (`/model`, picker)" in the same edit.
|
||||
+3
-2
@@ -9,8 +9,9 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project
|
||||
### Added
|
||||
- **Secure-by-default guardrails**: `rules/secure-by-default.md` (always on) makes six domains baseline on every project, plus systematic API and access hygiene (auth on every route, CORS, secrets, passwords hashed with argon2id or bcrypt, never compared in clear, logged or hardcoded): hosting (rate limit, CDN and firewall, hard spend cap), Supabase (RLS on every table, owner-scoped policies, no service role key client-side), SMS and email (recorded consent, unsubscribe, STOP), cloud functions (no self-trigger, instance cap, budget stop), injection (bound values in raw escapes, `format()` for dynamic SQL, allowlisted filters, no shell into a DB tool), exposure (no data in the console, no production source map, no debug flag, no secret in hydrated state, data attributes, hidden fields or shipped comments). `/guardrails` audits them: a stdlib Python scanner (`skills/guardrails/scripts/scan.py`, FAIL / WARN / MANUAL, exit 1 on FAIL) then judgment, report in `.claude/audits/GUARDRAILS.md`. The security-auditor gate runs the scanner's `api` and `supabase` domains and blocks on FAIL. Items only a provider dashboard can set stay MANUAL, never claimed done. An optional read-only live probe (`skills/guardrails/scripts/probe.py`, `--live`) confirms a finding from outside on a target the user owns and names: anon-read, cross-user, no-auth route, CORS reflection and a capped rate-limit burst, verdicts OPEN / CLOSED / SKIPPED / ERROR. An `exposure` block in the plan adds three read-only probes, meant for a production build or a staging URL: a served or inline source map for the page's scripts, a stack trace in a 404 or a user-named error route, sensitive keys in a JSON response (identifier-shaped names printed, never values); a target the probe could not observe is SKIPPED or ERROR, never CLOSED, and every plan path must start with `/`. It sends GET, HEAD and OPTIONS only (one opt-in POST burst, capped at 25), requires `--authorized`, takes secrets from the environment never the command line, never follows a redirect to another host, and stops at a request budget. After the report, `/guardrails` proposes fixes (plan phase, so Fable when the router can switch), applies only the ones the user accepts through the `bugfixer` executor and the `lib/verify-secure-loop.md` gates, then re-scans: each accepted fix is a contract criterion whose oracle is the scanner (`--assert-absent RULE:path`, marker `GUARDRAILS-CLEAR`), and a full pass against the pre-fix baseline (`--baseline`, marker `GUARDRAILS-NO-NEW`) catches regressions; a live probe replays on the user's go; two rounds at most, residuals reported open; `--report-only` keeps the audit alone. Suites: `lib/tests/guardrails-scan.test.sh` (clean fixture plus one mutant per rule, check modes, `gates.sh` integration) and `lib/tests/guardrails-probe.test.sh` (probe logic against a localhost fixture server).
|
||||
- **/a11y skill**: accessibility leaves `/guardrails` and becomes its own skill. Same A11Y-* rules (img alt, field label, click without keyboard, focus outline removed, positive tabindex) on the shared scan engine (`skills/guardrails/scripts/scanner.py`, a `Catalogue` per CLI; `skills/a11y/scripts/scan.py`, markers `A11Y-CLEAR` / `A11Y-NO-NEW`), a Tab-only walk of the main flow on `--live` through `/browse` (marked not done otherwise), report `.claude/audits/A11Y.md`, fixes proposed with the alt and label wording as the user's choice, applied through the bugfix circuit (`bugfixer`, verify-secure gates, `bugfix/a11y-<date>`), re-pass against a baseline. The keyboard, alt and label doctrine moves from `rules/secure-by-default.md` to the lazy `rules/a11y.md` (loads on UI files only; `rules/web-building.md` points at it). `/guardrails` scans `injection` (INJ-*) and `exposure` (EXP-*) instead, with per-language SQL patterns, shared `code_files` / `hits` / `dedupe_lines` / `client_reachable` helpers and a walker that lists files over 1 MB by path; `--domain a11y` is a usage error there. `/web-validate` keeps full WCAG conformance. Suite `lib/tests/a11y-scan.test.sh`; routing row `reflect`; profiles audit, dev, web, web-full, full, max.
|
||||
- **model-router mod**: `mods/model-router/`, a Claude Code mod (function-hooks plugin), routes every repo skill and agent from phase rows (`plan`, `reflect`, `orchestrate`, `escalate`, `judge`, `audit`, `implement`, `write`, `verify`, `explore`, `apply`, `mechanical`; built-ins Explore on sonnet/medium, Plan on opus/xhigh). A typed skill routes the main loop to its row, and a best-tier row holds across turns in a run slot until `/route clear`, `/route off`, a user `/model` or a typed skill on a non-best row. Agents get their row's model at spawn (within the tier, upward only) and its effort on every step; explicit Agent params win. Orchestrators declare their phases through the `mcp__model-router__route` tool. `ultrathink` in a prompt sets the turn's minimum effort and `/route effort=max` holds until `/route clear`; the built-in `/effort` is not a lever inside a run. `/route show` names the run slot (`main: run <phase>`), and a `null` row in the override drops a default row. The model gets a `route` tool and the user a `/route` command (`show|clear|off|on|reload|pending|ask on|off|forget <name|all|projects>|<phase>|model=<alias|id> effort=<level>|switch on|off|verbose on|off`). Optional per-machine config `~/.claude/model-router.json`, where `"enabled": false` turns it off on that machine. The spinner suffix and the status line show the route in force. It loads in every session through the tracked symlink `skills/model-router` (`model-router@skills-dir`). `make doctor` gains a Mods section; suite `make test suite=lib/tests/mods.test.sh`. Known limits: a main-loop switch runs only while the cold read it costs (the context minus what the target model's prompt cache holds) fits `upgradeMaxTokens` (200000) or `downgradeMaxTokens` (120000), and a downgrade also needs `mainModelSwitch` (on by default, off on any non-boolean value); the hooks send full model ids, so the `models` table has to follow new versions.
|
||||
- **model-router mod**: `mods/model-router/`, a Claude Code mod (function-hooks plugin), routes every repo skill and agent from phase rows (`plan`, `reflect`, `orchestrate`, `escalate`, `judge`, `audit`, `implement`, `write`, `verify`, `explore`, `apply`, `mechanical`; built-ins Explore on sonnet/medium, Plan on opus/xhigh). A typed skill routes the main loop to its row, and a best-tier row holds across turns in a run slot until `/route clear`, `/route off`, a user `/model` or a typed skill on a non-best row. Agents get their row's model at spawn (within the tier, upward only) and its effort on every step; explicit Agent params win. Orchestrators declare their phases through the `mcp__model-router__route` tool. `ultrathink` in a prompt sets the turn's minimum effort and `/route effort=max` holds until `/route clear`; the built-in `/effort` is not a lever inside a run. `/route show` names the run slot (`main: run <phase>`), and a `null` row in the override drops a default row. The model gets a `route` tool and the user a `/route` command (`show|clear|off|on|reload|pending|ask on|off|forget <name|all|projects>|<phase>|model=<alias|id> effort=<level>|switch on|off|verbose on|off`). Optional per-machine config `~/.claude/model-router.json`, where `"enabled": false` turns it off on that machine. The spinner suffix and the status line show the route in force. It loads in every session through the tracked symlink `skills/model-router` (`model-router@skills-dir`). `make doctor` gains a Mods section; suite `make test suite=lib/tests/mods.test.sh`. Known limits: a main-loop switch (a `/model` hand pick excepted) runs only while the cold read it costs (the context minus what the target model's prompt cache holds) fits `upgradeMaxTokens` (200000) or `downgradeMaxTokens` (120000), and a downgrade also needs `mainModelSwitch` (on by default, off on any non-boolean value); the hooks send full model ids, so the `models` table has to follow new versions.
|
||||
- **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`.
|
||||
- **model-router `/model` scope**: a `/model <name>` typed in the composer, or a pick in the `/model` picker, with a model the table knows asks where it applies. The picker's switch is held first (PreModelSwitch deny; the engine prints that a hook blocked it); a pick while another dialog is open is refused with `answer the open dialog first`. This project writes the full id as `model` into the project's `.claude/settings.local.json` (created if absent, refused through a link) and sets a sticky model route. This conversation sets the sticky route only. Everywhere runs the native `/model` (user `settings.json`). Both non-native answers drop the run slot and keep a sticky effort. With the picker's Default, no args, an unknown name, a headless run or another origin, the native command runs with no question. A model chosen in that dialog always switches: it bypasses the cold-read caps and the `mainUpgrade` / `mainModelSwitch` flags, and while it is marked down or outside a known window it waits and the automatic chain decides. A native switch or `/clear` drops it; `/route model=` keeps the caps. Known limits: the `/config` Model row still writes user `settings.json`; a dialog never answered has no timeout. 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 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)`.
|
||||
@@ -31,7 +32,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`.
|
||||
- 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, a typed `/route` or a `/model` hand pick (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.
|
||||
|
||||
@@ -136,18 +136,19 @@ effort, never version. Transcript audit `python3 lib/effort-audit.py`.
|
||||
|
||||
`mods/model-router/` is a Claude Code mod (a function-hooks plugin) that applies this table per request. It loads in every session through the tracked symlink `skills/model-router`, as `model-router@skills-dir`.
|
||||
|
||||
- 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.
|
||||
- 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` (typed with a name or picked in the `/model` picker, it asks the scope: this project, this conversation, everywhere) 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`. 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.
|
||||
- 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, a typed `/route` or a hand pick (`/model`, picker). The built-in `/effort` is not a lever inside a run, rows and routes outrank it.
|
||||
- `/model` scope: a pick in the `/model` picker is held first (the engine prints that a hook blocked it), then the same question as `/model <name>` comes. A pick while another dialog is open is refused with `answer the open dialog first`. The picker's Default, no args, an unknown name or a headless run go native, no question. A model chosen in that dialog (a hand pick) always switches: no cold-read cap, no `mainUpgrade` or `mainModelSwitch` flag. A hand pick marked down keeps main where it is until it is back. A native switch (the `/config` Model row included) or `/clear` drops a hand pick; a typed `/route model=` keeps the caps.
|
||||
- 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.
|
||||
- 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. The one other write: `/model <name>` or a `/model` picker pick → This project writes the full id as `model` into the session root's `.claude/settings.local.json` (created if absent, keep it gitignored; refused when `.claude` or the file is a link, or the file is over 64 KiB or not a JSON object). Remove its `model` key to undo.
|
||||
- The spinner suffix and the status line under the prompt show the route in force; the status line adds ` · switch off` when the downgrade switch is off.
|
||||
|
||||
Config layers: `mods/model-router/routing.json` (tracked: phases with their tier, effort and `about` line, rows, decisions, `ask`), then the optional per-machine `~/.claude/model-router.json`, which wins. A `.claude/model-router.json` inside a project is never read. Machine keys: `models` (alias → full id), `windows` (context window per full id), `tiers` (ordered alias lists per tier: `best` fable>opus>sonnet, `big` opus>fable>sonnet, `work` sonnet>opus, `cheap` haiku>sonnet; the first alias not down is used), `fallback` (the rank order of the aliases, best first, used by the breaker), `cooldownMinutes` (how long a model stays marked down after an availability error, 15 by default, doubling per episode up to 300), `mainUpgrade` (default `true`: the main loop may move up to a phase's tier), `upgradeMaxTokens` (default 200000: the largest cold read a main-loop upgrade may cost), `downgradeMaxTokens` (default 120000: the same cap for a downgrade; the cold read is the context minus what the target model's prompt cache already holds, taken from main's last step on that model within the prompt-cache TTL, forgotten by `/clear` and `/route reload`. The TTL follows the engine's `cache_ttl` (5 or 60 minutes) carried by main's model-switch events, is 60 minutes until the first one and survives `/clear`. The context also counts the prompt just submitted, which the engine's usage may not include yet: code points / 3 of its text, its context entries and a typed skill's body, summed and added at the turn's first main step unless usage already grew by half of it. A `document` attachment makes the size unknown, and an unknown context size blocks the switch; the step, `/route show`, the first-use dialog and the toast read the same adjusted size), `phases`, `agents`, `skills`, `prompt` (rules), `mainModelSwitch` (default `true`: the main loop may move down to a cheaper model; a value that is not a boolean turns it off and says so), `classify` (default `true`; `false` stops the prompt classifier on that machine), `probe` (default `true`: the model main runs on, moved to or kept, is tried once, 8 seconds at most, before main is sent to it; `false` skips the probe on that machine; a non-boolean value is ignored and said; `/route show` prints `probe:`), `verbose` (default `false`; `true` logs transitions only, a non-boolean value falls back to `false`), `spinner` (default `true`), `enabled` (default `true`; `false` turns the mod off on that machine), `ask` (overrides routing.json's `ask` on that machine). A `null` value in `agents` or `skills` drops a row. Edit phases and rows by hand in routing.json (a phase's `about`, 120 characters at most, is read from there only and shown in the dialog; a model and effort pair no phase offers needs a new phase there); without it the mod runs the code's default phases, with no rows and no dialog. `/route reload` re-reads both files.
|
||||
|
||||
Limits: a main-loop switch re-reads cold the part of the context the target model's cache does not hold; a switch whose cold read is over its cap (`upgradeMaxTokens` up, `downgradeMaxTokens` down) is skipped and main keeps its model, and a downgrade also needs `mainModelSwitch`. The prompt estimate is conservative (3 code points per token), so a long pasted prompt can hold back a switch that would have fit. The hooks send full model ids, so the `models` table has to follow new model versions. A probe costs one small completion per model main runs on, the session's own model included, repeated only after that model is marked down, and holds that step up to 8 seconds when the model does not answer.
|
||||
Limits: a main-loop switch re-reads cold the part of the context the target model's cache does not hold; a switch whose cold read is over its cap (`upgradeMaxTokens` up, `downgradeMaxTokens` down) is skipped (a `/model` hand pick is exempt) and main keeps its model, and a downgrade also needs `mainModelSwitch`. The prompt estimate is conservative (3 code points per token), so a long pasted prompt can hold back a switch that would have fit. The `/config` Model row still writes user `settings.json` with no scope question; a hand pick is dropped at `/clear`; a scope dialog never answered has no timeout. The hooks send full model ids, so the `models` table has to follow new model versions. A probe costs one small completion per model main runs on, the session's own model included, repeated only after that model is marked down, and holds that step up to 8 seconds when the model does not answer.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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 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
|
||||
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 choisi dans le sélecteur, ou un skill d'un autre tier tapé. Un `/model <nom>` tapé, ou un choix dans le sélecteur `/model`, avec un modèle de la table demande sa portée (Échap ne change rien). Le changement du sélecteur est d'abord retenu (le moteur affiche qu'un hook l'a bloqué), puis la question vient ; un choix fait pendant qu'un autre dialogue est ouvert est refusé (`answer the open dialog first`) : This project écrit l'id complet dans `model` du `.claude/settings.local.json` du projet (créé s'il manque, à garder dans le `.gitignore`) et pose une route de modèle tenue ; This conversation pose la route seule, sans rien écrire ; Everywhere lance le `/model` natif (`settings.json` utilisateur, tous les projets). Default dans le sélecteur, sans argument, avec un nom inconnu, en headless (`-p`) ou mod coupé, le `/model` natif passe sans question. Un modèle choisi dans ce dialogue change toujours : ni plafond de relecture à froid, ni `mainUpgrade` ni `mainModelSwitch`. S'il est en panne, la boucle principale reste où elle est jusqu'à son retour. Un changement natif (ligne Model de `/config` comprise) ou `/clear` l'abandonne ; un `/route model=` tapé garde les plafonds. La ligne Model de `/config` écrit toujours le `settings.json` utilisateur, et un dialogue jamais répondu n'a pas de délai. 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`, un `/route` tapé ou un choix à la main (`/model`, sélecteur). 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 princiLine 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.
|
||||
|
||||
|
||||
+25
-3
@@ -42,6 +42,26 @@ relaunch: `ultrathink` in the prompt (turn floor) or `/route effort=max`
|
||||
(sticky, `/route clear` after).
|
||||
Builtin `/effort` is NOT a lever inside a run: rows and routes outrank it.
|
||||
|
||||
`/model <name>` typed, or a pick in the `/model` picker, with a name the
|
||||
router knows asks the scope (Esc changes nothing). The picker's switch is
|
||||
held first: the engine prints that a hook blocked it, then the question
|
||||
comes. This project writes the full id as `model` into
|
||||
`.claude/settings.local.json` (created if absent: keep it gitignored) and
|
||||
sets a sticky model route. This conversation sets the sticky route only,
|
||||
nothing written. Everywhere is the native command: user `settings.json`,
|
||||
every project. The two non-native answers drop the run slot like a native
|
||||
switch and keep a sticky effort; Everywhere drops an earlier sticky model.
|
||||
Picker Default, no args, an unknown name or a run with no surface (`-p`)
|
||||
go native, no question. A native switch (`/config` Model row included)
|
||||
drops a hand pick. The file is the session root's: in a worktree, that
|
||||
worktree's.
|
||||
|
||||
A model chosen in that dialog (a hand pick) always switches: no cold-read
|
||||
cap, no `mainUpgrade` or `mainModelSwitch` flag, an unranked session model
|
||||
included. A pick held down keeps main where it is (one log) until it is
|
||||
back; the window guard needs a `windows` entry (none shipped). A typed
|
||||
`/route model=` keeps the caps. `/clear` drops a hand pick until relaunch.
|
||||
|
||||
## Limits
|
||||
|
||||
- A skill typed while a background agent is live routes only through the
|
||||
@@ -51,13 +71,15 @@ Builtin `/effort` is NOT a lever inside a run: rows and routes outrank it.
|
||||
model: the guessed phase sets the turn's effort and, under
|
||||
`mainModelSwitch` and `downgradeMaxTokens` (max cold read, default
|
||||
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`).
|
||||
baseline the guess starts from (Everywhere; the two other scopes set a
|
||||
sticky route, which the classifier never overrides) (`/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`.
|
||||
skill row, the `route` tool, a typed `/route` or a hand pick (`/model`,
|
||||
picker).
|
||||
- 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
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { On, TurnStepInput } from 'claude-code'
|
||||
const FABLE = 'claude-fable-5-1'
|
||||
const OPUS = 'claude-opus-5-5'
|
||||
const SONNET = 'claude-sonnet-5-5'
|
||||
const HAIKU = 'claude-haiku-4-5-20251001'
|
||||
const HAIKU = 'claude-haiku-5-5'
|
||||
|
||||
type Rec = Record<string, unknown>
|
||||
type Asked = { text: string; options: string[]; header: string }
|
||||
@@ -39,11 +39,22 @@ type World = {
|
||||
gate: Promise<void> | undefined // holds a dialog open until it settles
|
||||
writeGate: Promise<void> | undefined // holds an fs.write open
|
||||
failWrite: boolean // fs.write rejects
|
||||
clockFailsAfterAsk: boolean // clock.now rejects once a dialog opened
|
||||
sleepFails: boolean // clock.sleep rejects (the picker's delay)
|
||||
sessionId: string // what session.id answers
|
||||
onAsk: (() => void) | undefined // called when a dialog opens
|
||||
onWrite: (() => void) | undefined // called when an fs.write starts
|
||||
repo: { root: string; remote: string | null } | null | 'fail'
|
||||
env: string | undefined // HOME as env.get answers it (undefined = unset)
|
||||
kinds: Map<string, 'file' | 'dir' | 'other'> // per-path stat kind override
|
||||
dirs: Map<string, {
|
||||
kind: 'dir' | 'file' | 'other'
|
||||
isLink: boolean
|
||||
exists?: false // a dangling link: stat answers, exists does not
|
||||
}>
|
||||
// paths fs.exists/fs.stat answer for, with or without file text
|
||||
brokenStat: Set<string> // paths that exist but whose stat rejects
|
||||
surfaces: readonly string[] // what session.surfaces answers ([] = headless)
|
||||
complete: (model: string) => unknown // what a completion resolves to
|
||||
completions: string[] // every model a completion was asked of
|
||||
}
|
||||
@@ -56,6 +67,9 @@ type Fixture = {
|
||||
answers?: string[]
|
||||
repo?: World['repo']
|
||||
noHome?: boolean // HOME unset: env.get answers undefined
|
||||
surfaces?: readonly string[] // default ['terminal']
|
||||
clockFailsAfterAsk?: boolean // see World; the rig gets no MockClock
|
||||
sleepFails?: boolean // see World; the rig gets no MockClock
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,18 +131,27 @@ function newWorld(fx: Fixture = {}): World {
|
||||
gate: undefined,
|
||||
writeGate: undefined,
|
||||
failWrite: false,
|
||||
clockFailsAfterAsk: fx.clockFailsAfterAsk ?? false,
|
||||
sleepFails: fx.sleepFails ?? false,
|
||||
sessionId: 's1',
|
||||
onAsk: undefined,
|
||||
onWrite: undefined,
|
||||
repo: fx.repo === undefined ? { root: ROOT, remote: REMOTE } : fx.repo,
|
||||
env: fx.noHome ? undefined : HOME,
|
||||
kinds: new Map(),
|
||||
dirs: new Map(),
|
||||
brokenStat: new Set(),
|
||||
surfaces: fx.surfaces ?? ['terminal'],
|
||||
complete: () => PROBE_OK,
|
||||
completions: [],
|
||||
}
|
||||
}
|
||||
|
||||
const LOCAL_FILE = `${ROOT}/.claude/settings.local.json`
|
||||
|
||||
const slot = (path: string): string => {
|
||||
if (path.endsWith('/routing.json')) return 'routing'
|
||||
if (path === LOCAL_FILE) return 'local'
|
||||
// the engine resolves a relative path against its cwd: `undefined/...`
|
||||
// (a HOME read as unset and not guarded) comes back absolute
|
||||
const rel = /\/(undefined\/\.claude\/.*)$/.exec(path)
|
||||
@@ -146,18 +169,23 @@ const routingOf = (w: World): Rec =>
|
||||
function installWorld(on: On, w: World): void {
|
||||
on('env.get', () => ({ value: w.env }))
|
||||
on('fs.exists', (_a, e) => ({
|
||||
value: w.files.has(slot(e.path)) || e.path === ROOT,
|
||||
value: w.dirs.get(e.path)?.exists === false ? false :
|
||||
w.files.has(slot(e.path)) || e.path === ROOT || w.dirs.has(e.path),
|
||||
}))
|
||||
on('fs.stat', (_a, e) => {
|
||||
const text = w.files.get(slot(e.path))
|
||||
if (text === undefined && e.path !== ROOT) throw new Error('ENOENT')
|
||||
const known = w.dirs.get(e.path)
|
||||
if (w.brokenStat.has(e.path)) throw new Error('EIO')
|
||||
if (text === undefined && e.path !== ROOT && known === undefined) {
|
||||
throw new Error('ENOENT')
|
||||
}
|
||||
return {
|
||||
value: {
|
||||
kind: w.kinds.get(e.path) ??
|
||||
kind: known?.kind ?? w.kinds.get(e.path) ??
|
||||
(text === undefined ? 'dir' as const : 'file' as const),
|
||||
size: text?.length ?? 0,
|
||||
mtimeMs: 0,
|
||||
isLink: false,
|
||||
isLink: known?.isLink ?? false,
|
||||
...(e.resolve ? { realPath: REAL_ROOT } : {}),
|
||||
},
|
||||
}
|
||||
@@ -170,6 +198,7 @@ function installWorld(on: On, w: World): void {
|
||||
})
|
||||
installWrite(on, w)
|
||||
on('session.root', () => ({ value: ROOT }))
|
||||
on('session.surfaces', () => ({ value: w.surfaces as never }))
|
||||
on('session.repo', () => {
|
||||
if (w.repo === 'fail') throw new Error('no repo')
|
||||
return { value: w.repo === null ? null : {
|
||||
@@ -180,13 +209,19 @@ function installWorld(on: On, w: World): void {
|
||||
installDialog(on, w)
|
||||
}
|
||||
|
||||
/** The paths the world's fs.write accepts: see installWrite. */
|
||||
const worldServes = (w: World, path: string): boolean =>
|
||||
path === LOCAL_FILE || (slot(path) === 'routing' && w.reads.includes(path))
|
||||
|
||||
/**
|
||||
* The world's fs.write. Loud: a write anywhere but the routing.json the mod
|
||||
* read fails the test (never a project tree, never the machine override).
|
||||
* One carve-out: the project's .claude/settings.local.json, which the
|
||||
* /model scope dialog writes, read or not (a missing file is created).
|
||||
*/
|
||||
function installWrite(on: On, w: World): void {
|
||||
on('fs.write', async (_a, e) => {
|
||||
expect(slot(e.path) === 'routing' && w.reads.includes(e.path),
|
||||
expect(worldServes(w, e.path),
|
||||
`the world never served ${e.path}`).toBe(true)
|
||||
w.written.push(e.path)
|
||||
w.onWrite?.()
|
||||
@@ -217,6 +252,31 @@ function installDialog(on: On, w: World): void {
|
||||
})
|
||||
}
|
||||
|
||||
/** A clock that rejects once a dialog opened (no MockClock: never advanced). */
|
||||
function failingClock(on: On, w: World): MockClock {
|
||||
on('clock.now', () => {
|
||||
if (w.asked.length > 0) throw new Error('boom')
|
||||
return { value: 0 }
|
||||
})
|
||||
on('clock.sleep', () => ({ value: undefined }))
|
||||
return undefined as unknown as MockClock
|
||||
}
|
||||
|
||||
/** A clock whose sleep rejects (LRN-229: a whole-clock replacement). */
|
||||
function sleepFailsClock(on: On): MockClock {
|
||||
on('clock.now', () => ({ value: 0 }))
|
||||
on('clock.sleep', () => {
|
||||
throw new Error('boom')
|
||||
})
|
||||
return undefined as unknown as MockClock
|
||||
}
|
||||
|
||||
/** The clock the world asks for: a mock one unless a fixture breaks it. */
|
||||
function clockOf(on: On, w: World): MockClock {
|
||||
if (w.clockFailsAfterAsk) return failingClock(on, w)
|
||||
return w.sleepFails ? sleepFailsClock(on) : mock.clock(on)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires session.start so the mod loads its config and registers /route.
|
||||
* The bottom hooks the router reads are in place before the first `$` call:
|
||||
@@ -231,10 +291,12 @@ async function boot(
|
||||
tokens: number | null = 1000,
|
||||
world: World = newWorld(),
|
||||
): Promise<MockClock> {
|
||||
const clock = mock.clock(on)
|
||||
const clock = clockOf(on, world)
|
||||
on('session.model', () => ({ value: model }))
|
||||
on('classic.StopFailure', () => ({}))
|
||||
on('classic.PostModelSwitch', () => ({}))
|
||||
on('classic.PreModelSwitch', () => ({}))
|
||||
on('session.id', () => ({ value: world.sessionId }))
|
||||
on('skill.prompt', ($, e) => ({ text: e.text }))
|
||||
on('agent.offer', () => ({ isOffered: true }))
|
||||
// the probe of the model main runs on: every model answers unless a test says not
|
||||
@@ -680,7 +742,7 @@ const switchTo = (
|
||||
$: Engine,
|
||||
from: string,
|
||||
to: string,
|
||||
source: 'command' | 'auto',
|
||||
source: 'command' | 'auto' | 'picker',
|
||||
cache_ttl: '5m' | '1h' = '5m',
|
||||
agent_id?: string,
|
||||
) => $.classic.PostModelSwitch({
|
||||
@@ -884,6 +946,15 @@ test('unknown: a session model absent from the table is never switched', async (
|
||||
expect((await stepOn($, rig, 'claude-zz-9')).model).toBe('claude-zz-9')
|
||||
})
|
||||
|
||||
test('unknown: the haiku alias id is in the table, a route moves it', async (
|
||||
$, on) => {
|
||||
const logs = recordLogs(on)
|
||||
const rig = await bootRig($, on, HAIKU)
|
||||
await planRoute($)
|
||||
expect((await stepOn($, rig, HAIKU)).model).toBe(FABLE)
|
||||
expect(logsWith(logs, 'unknown to the models table')).toBe(0)
|
||||
})
|
||||
|
||||
test('spawn: Explore goes to opus while sonnet is down', async ($, on) => {
|
||||
const rig = await bootRig($, on)
|
||||
await $.agent.spawn(spawnInput())
|
||||
@@ -5212,7 +5283,8 @@ test('cap: a smaller context than the record is cold', async ($, on) => {
|
||||
test('window: haiku outgrown returns main to the session model', async (
|
||||
$, on) => {
|
||||
const logs = recordLogs(on)
|
||||
const { rig, usage } = await bootRigVar($, on, FABLE, 1000)
|
||||
const world = newWorld({ home: { windows: { [HAIKU]: 200000 } } })
|
||||
const { rig, usage } = await bootRigVar($, on, FABLE, 1000, world)
|
||||
expect(await routedStep($, rig, 'mechanical')).toBe(HAIKU)
|
||||
usage.set(250000)
|
||||
expect((await stepOn($, rig, FABLE)).model).toBe(FABLE)
|
||||
@@ -5918,3 +5990,733 @@ test('keyword cap: a dispatch outside a run keeps main on the session model', as
|
||||
await dispatch($)
|
||||
expect(await stepOn($, rig, OPUS)).toEqual({ model: OPUS, effort: 'medium' })
|
||||
})
|
||||
|
||||
// ---- /model <name>: the scope dialog -------------------------------------
|
||||
|
||||
const SCOPES = ['This project', 'This conversation', 'Everywhere']
|
||||
const FABLE_1M = `${FABLE}[1m]`
|
||||
const NO_SCOPE = 'model: no scope chosen, nothing changed'
|
||||
|
||||
type ModelRig = {
|
||||
w: World
|
||||
ran: string[] // the args the native /model got
|
||||
toasts: string[]
|
||||
rig: Rig
|
||||
}
|
||||
|
||||
/** Boots with a bottom native /model that records its args. */
|
||||
async function bootModel(
|
||||
$: Engine,
|
||||
on: On,
|
||||
answers: string[],
|
||||
session: string = OPUS,
|
||||
fx: Fixture = {},
|
||||
): Promise<ModelRig> {
|
||||
const ran: string[] = []
|
||||
on('command.run', { command: 'model' }, (_a, e) => {
|
||||
ran.push(e.args)
|
||||
return { text: 'native' }
|
||||
})
|
||||
const toasts = recordToasts(on)
|
||||
const w = newWorld({ answers, ...fx })
|
||||
const rig = await bootRig($, on, session, 1000, w)
|
||||
return { w, ran, toasts, rig }
|
||||
}
|
||||
|
||||
/** Runs `/model <args>` as typed (or from another origin). */
|
||||
async function modelCmd(
|
||||
$: Engine,
|
||||
args: string,
|
||||
kind: 'composer' | 'sdk' = 'composer',
|
||||
): Promise<string> {
|
||||
const out = await $.command.run({
|
||||
command: 'model',
|
||||
args,
|
||||
origin: { kind },
|
||||
presentation: { isFullscreen: false, columns: 80 },
|
||||
})
|
||||
return out.text ?? ''
|
||||
}
|
||||
|
||||
const localOf = (w: World): Rec =>
|
||||
JSON.parse(w.files.get('local') ?? '{}') as Rec
|
||||
|
||||
test('model command: asks the three scopes, the full id, native not run', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['Later', 'Later'])
|
||||
await modelCmd($, 'fable')
|
||||
await modelCmd($, 'claude-fable-5-1[1m]')
|
||||
expect(m.w.asked.map(q => q.options)).toEqual([SCOPES, SCOPES])
|
||||
expect(m.w.asked.map(q => q.header)).toEqual(['model-router', 'model-router'])
|
||||
const [plain, long] = m.w.asked as [Asked, Asked]
|
||||
expect(plain.text.endsWith(`Switch main to ${FABLE} where?`)).toBe(true)
|
||||
expect(long.text.endsWith(`Switch main to ${FABLE_1M} where?`)).toBe(true)
|
||||
expect(m.ran).toEqual([])
|
||||
})
|
||||
|
||||
test('model command: This project writes the full id and keeps the keys', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This project'])
|
||||
m.w.files.set('local', JSON.stringify({ permissions: { allow: ['Bash'] } }))
|
||||
m.w.dirs.set(`${ROOT}/.claude`, { kind: 'dir', isLink: false })
|
||||
const out = await modelCmd($, 'fable')
|
||||
expect(localOf(m.w)).toEqual({
|
||||
permissions: { allow: ['Bash'] }, model: FABLE,
|
||||
})
|
||||
expect(m.w.files.get('local')).toBe(
|
||||
JSON.stringify(localOf(m.w), null, 2) + '\n')
|
||||
expect(out).toContain(`${FABLE} written to .claude/settings.local.json`)
|
||||
expect(out).toContain('remove its "model" key to undo')
|
||||
expect(out).not.toContain('file created')
|
||||
expect(m.toasts).toEqual([])
|
||||
expect(m.ran).toEqual([])
|
||||
expect((await stepOn($, m.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('model command: This project keeps [1m] verbatim in the file', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This project', 'This project'])
|
||||
await modelCmd($, 'fable[1m]')
|
||||
expect(localOf(m.w).model).toBe(FABLE_1M)
|
||||
await modelCmd($, 'claude-fable-5-1[1m]')
|
||||
expect(localOf(m.w).model).toBe(FABLE_1M)
|
||||
expect((await stepOn($, m.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('model command: the [1m] note shows only for a token or session [1m]', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This project', 'This project'])
|
||||
expect(await modelCmd($, 'fable')).not.toContain('[1m] follows')
|
||||
expect(await modelCmd($, 'fable[1m]')).toContain(
|
||||
"[1m] follows the session's variant")
|
||||
expect(m.ran).toEqual([])
|
||||
})
|
||||
|
||||
test('model command: a [1m] session adds the note to a plain token', async (
|
||||
$, on) => {
|
||||
await bootModel($, on, ['This project'], `${OPUS}[1m]`)
|
||||
expect(await modelCmd($, 'fable')).toContain('[1m] follows')
|
||||
})
|
||||
|
||||
test('model command: This project creates the file when absent', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This project'])
|
||||
const out = await modelCmd($, 'opus')
|
||||
expect(localOf(m.w)).toEqual({ model: OPUS })
|
||||
expect(out).toContain('file created: keep it gitignored')
|
||||
expect(m.toasts).toEqual([])
|
||||
})
|
||||
|
||||
const BAD_TEXT: [string, string, string][] = [
|
||||
['null', 'null', 'not an object'],
|
||||
['an array', '[]', 'not an object'],
|
||||
['a string', '"x"', 'not an object'],
|
||||
['broken JSON', '{nope', 'not JSON'],
|
||||
['over the size cap', JSON.stringify({ pad: 'x'.repeat(70000) }),
|
||||
'too large'],
|
||||
]
|
||||
|
||||
for (const [name, text, cause] of BAD_TEXT) {
|
||||
test(`model command: This project refuses a file: ${name}`, async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This project'])
|
||||
m.w.files.set('local', text)
|
||||
expect(await modelCmd($, 'fable')).toContain(`not written (${cause})`)
|
||||
expect(m.w.files.get('local')).toBe(text)
|
||||
expect(m.w.written).toEqual([])
|
||||
expect(m.toasts).toEqual([`settings.local.json not written: ${cause}`])
|
||||
expect(mainLine(await route($, 'show'))).toContain('user custom')
|
||||
})
|
||||
}
|
||||
|
||||
const refusals: [string, (w: World) => void, string][] = [
|
||||
['.claude link', w => w.dirs.set(`${ROOT}/.claude`,
|
||||
{ kind: 'dir', isLink: true }), '.claude is a link'],
|
||||
['.claude file', w => w.dirs.set(`${ROOT}/.claude`,
|
||||
{ kind: 'file', isLink: false }), '.claude is not a directory'],
|
||||
['settings link', w => {
|
||||
w.files.set('local', '{}')
|
||||
w.dirs.set(LOCAL_FILE, { kind: 'file', isLink: true })
|
||||
}, 'settings.local.json is a link'],
|
||||
['.claude dangling link', w => w.dirs.set(`${ROOT}/.claude`,
|
||||
{ kind: 'other', isLink: true, exists: false }), '.claude is a link'],
|
||||
['settings dangling link', w => w.dirs.set(LOCAL_FILE,
|
||||
{ kind: 'other', isLink: true, exists: false }),
|
||||
'settings.local.json is a link'],
|
||||
['settings dir', w => {
|
||||
w.files.set('local', '{}')
|
||||
w.dirs.set(LOCAL_FILE, { kind: 'dir', isLink: false })
|
||||
}, 'not a regular file'],
|
||||
['stat error', w => {
|
||||
w.files.set('local', '{}')
|
||||
w.brokenStat.add(LOCAL_FILE)
|
||||
}, 'fs error HooksError'],
|
||||
]
|
||||
|
||||
for (const [name, setup, cause] of refusals) {
|
||||
test(`model command: This project refuses: ${name}`, async ($, on) => {
|
||||
const m = await bootModel($, on, ['This project'])
|
||||
setup(m.w)
|
||||
const before = m.w.files.get('local')
|
||||
const out = await modelCmd($, 'fable')
|
||||
expect(out).toContain(`not written (${cause})`)
|
||||
expect(m.w.files.get('local')).toBe(before)
|
||||
expect(m.w.written).toEqual([])
|
||||
expect(m.toasts).toEqual([`settings.local.json not written: ${cause}`])
|
||||
expect(mainLine(await route($, 'show'))).toContain('user custom')
|
||||
expect(m.ran).toEqual([])
|
||||
})
|
||||
}
|
||||
|
||||
test('model command: a failing write reports an fs error, route set', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This project'])
|
||||
m.w.failWrite = true
|
||||
const out = await modelCmd($, 'fable')
|
||||
expect(out).toContain('not written (fs error')
|
||||
expect(m.toasts).toHaveLength(1)
|
||||
expect(out).not.toContain('EACCES')
|
||||
expect(mainLine(await route($, 'show'))).toContain('user custom')
|
||||
})
|
||||
|
||||
test('model command: This conversation sets the route, writes nothing', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This conversation'])
|
||||
await route($, 'effort=max')
|
||||
const out = await modelCmd($, 'fable')
|
||||
expect(out).toContain(`sticky route ${FABLE} for this conversation`)
|
||||
expect(m.w.written).toEqual([])
|
||||
expect(m.w.files.has('local')).toBe(false)
|
||||
expect(m.ran).toEqual([])
|
||||
const line = mainLine(await route($, 'show'))
|
||||
expect(line).toContain('user custom')
|
||||
expect(line).toContain('effort max')
|
||||
expect((await stepOn($, m.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('model command: the local scopes drop the run slot', async ($, on) => {
|
||||
on('command.run', { command: 'model' }, () => ({ text: 'native' }))
|
||||
await bootRun($, on, OPUS, newWorld({ answers: ['This conversation'] }))
|
||||
await loadSkill($, 'feat')
|
||||
await endTurn($)
|
||||
expect(await modelCmd($, 'sonnet')).toContain('sticky route')
|
||||
expect(await route($, 'clear')).not.toContain('run slot dropped')
|
||||
})
|
||||
|
||||
test('model command: Everywhere runs native, args unchanged', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['Everywhere'])
|
||||
expect(await modelCmd($, 'opus')).toBe('native')
|
||||
expect(m.ran).toEqual(['opus'])
|
||||
expect(m.w.written).toEqual([])
|
||||
})
|
||||
|
||||
test('model command: Everywhere drops an earlier sticky model', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This conversation', 'Everywhere'])
|
||||
await modelCmd($, 'fable')
|
||||
expect(mainLine(await route($, 'show'))).toContain('user custom')
|
||||
await modelCmd($, 'opus')
|
||||
expect(mainLine(await route($, 'show'))).toContain('session defaults')
|
||||
expect(m.ran).toEqual(['opus'])
|
||||
})
|
||||
|
||||
test('model command: Everywhere drops a sticky tier too, keeps effort', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['Everywhere'])
|
||||
await route($, 'plan')
|
||||
await modelCmd($, 'opus')
|
||||
const line = mainLine(await route($, 'show'))
|
||||
expect(line).toContain('effort xhigh')
|
||||
expect(line).not.toContain(FABLE)
|
||||
expect(m.ran).toEqual(['opus'])
|
||||
})
|
||||
|
||||
test('model command: no dialog for a call native owns', async ($, on) => {
|
||||
const m = await bootModel($, on, [])
|
||||
const args = ['', 'fable opus', 'default', 'opusplan', 'claude-opus-5-6',
|
||||
'haiku[1m]', 'whatever']
|
||||
for (const a of args) expect(await modelCmd($, a)).toBe('native')
|
||||
expect(m.ran).toEqual(args)
|
||||
expect(m.w.asked).toEqual([])
|
||||
})
|
||||
|
||||
test('model command: no dialog from another origin', async ($, on) => {
|
||||
const m = await bootModel($, on, [])
|
||||
expect(await modelCmd($, 'fable', 'sdk')).toBe('native')
|
||||
expect(m.w.asked).toEqual([])
|
||||
})
|
||||
|
||||
test('model command: no dialog when the router is off', async ($, on) => {
|
||||
const m = await bootModel($, on, [])
|
||||
await route($, 'off')
|
||||
expect(await modelCmd($, 'fable')).toBe('native')
|
||||
expect(m.w.asked).toEqual([])
|
||||
})
|
||||
|
||||
test('model command: no dialog without a surface', async ($, on) => {
|
||||
const m = await bootModel($, on, [], OPUS, { surfaces: [] })
|
||||
expect(await modelCmd($, 'fable')).toBe('native')
|
||||
expect(m.w.asked).toEqual([])
|
||||
})
|
||||
|
||||
test('model command: a second /model while one is open goes native', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['This conversation'])
|
||||
const held = deferred()
|
||||
const open = deferred()
|
||||
m.w.gate = held.gate
|
||||
m.w.onAsk = open.release
|
||||
const first = modelCmd($, 'fable')
|
||||
await open.gate
|
||||
expect(await modelCmd($, 'opus')).toBe('native')
|
||||
held.release()
|
||||
expect(await first).toContain('sticky route')
|
||||
expect(m.w.asked).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('model command: the question notes a project pin only when set', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, ['Later', 'Later'])
|
||||
await modelCmd($, 'fable')
|
||||
m.w.files.set('local', JSON.stringify({ model: OPUS }))
|
||||
await modelCmd($, 'fable')
|
||||
const [bare, pinned] = m.w.asked as [Asked, Asked]
|
||||
expect(bare.text).not.toContain('pins')
|
||||
const lines = pinned.text.split('\n')
|
||||
const note = lines[lines.length - 2] ?? ''
|
||||
expect(note).toContain(
|
||||
`this project pins ${OPUS} in .claude/settings.local.json`)
|
||||
expect(note).toContain('the project pin wins')
|
||||
expect(lines[lines.length - 1]).toBe(`Switch main to ${FABLE} where?`)
|
||||
})
|
||||
|
||||
test('model command: Esc or free text cancels, nothing changes', async (
|
||||
$, on) => {
|
||||
const m = await bootModel($, on, [])
|
||||
expect(await modelCmd($, 'fable')).toBe(NO_SCOPE)
|
||||
m.w.answers.push('maybe')
|
||||
expect(await modelCmd($, 'fable')).toBe(NO_SCOPE)
|
||||
expect(m.ran).toEqual([])
|
||||
expect(m.w.written).toEqual([])
|
||||
expect(mainLine(await route($, 'show'))).toContain('session defaults')
|
||||
})
|
||||
|
||||
test('model command: Everywhere: native runs once, its throw is reported, not re-run', async (
|
||||
$, on) => {
|
||||
const ran: string[] = []
|
||||
on('command.run', { command: 'model' }, (_a, e) => {
|
||||
ran.push(e.args)
|
||||
throw new Error('boom')
|
||||
})
|
||||
await bootRig($, on, OPUS, 1000, newWorld({ answers: ['Everywhere'] }))
|
||||
const out = await modelCmd($, 'opus')
|
||||
expect(out).toContain('model failed (')
|
||||
expect(out).toContain('/route show')
|
||||
expect(out).not.toContain('boom')
|
||||
expect(ran).toEqual(['opus'])
|
||||
})
|
||||
|
||||
for (const scope of ['This conversation', 'This project']) {
|
||||
test(`model command: ${scope}: a throw after the answer never reaches native`, async (
|
||||
$, on) => {
|
||||
// the dialog is answered, then the status text reads the clock
|
||||
const m = await bootModel($, on, [scope], OPUS, {
|
||||
clockFailsAfterAsk: true,
|
||||
})
|
||||
const out = await modelCmd($, 'fable')
|
||||
expect(out).toContain('model failed (')
|
||||
expect(out).toContain('/route show')
|
||||
expect(out).not.toContain('boom')
|
||||
expect(m.ran).toEqual([])
|
||||
})
|
||||
}
|
||||
|
||||
test('writes: kit: only the project settings.local.json is carved out', {
|
||||
plugins: [PROBE],
|
||||
}, async ($, on) => {
|
||||
const m = await bootModel($, on, [])
|
||||
const out = await $.command.run({
|
||||
command: 'probe',
|
||||
args: LOCAL_FILE,
|
||||
origin: { kind: 'composer' },
|
||||
presentation: { isFullscreen: false, columns: 80 },
|
||||
})
|
||||
expect(out.text).toBe('written')
|
||||
for (const path of [`${ROOT}/.claude/settings.json`,
|
||||
`${LOCAL_FILE}.bak`, `${ROOT}/other/settings.local.json`, HOME_FILE]) {
|
||||
expect(worldServes(m.w, path), path).toBe(false)
|
||||
}
|
||||
expect(worldServes(m.w, LOCAL_FILE)).toBe(true)
|
||||
})
|
||||
|
||||
// ---- /model picker: deny now, ask after ----------------------------------
|
||||
|
||||
const BUSY = 'answer the open dialog first'
|
||||
const DENY = 'model-router asks where this switch applies'
|
||||
|
||||
type SwitchSource = 'picker' | 'command' | 'sdk'
|
||||
|
||||
/** The PreModelSwitch input of a switch to `requested` from `source`. */
|
||||
const preSwitch = (requested: string | null, source: SwitchSource) => ({
|
||||
from_model: OPUS,
|
||||
to_model: requested ?? OPUS,
|
||||
requested_model: requested,
|
||||
source,
|
||||
context_tokens: 0,
|
||||
prompt_cache_warm: false,
|
||||
cache_ttl: '5m' as const,
|
||||
estimated_cache_write_usd: 0,
|
||||
pricing: 'catalog' as const,
|
||||
})
|
||||
|
||||
const pick = (
|
||||
$: Engine,
|
||||
requested: string | null,
|
||||
source: SwitchSource = 'picker',
|
||||
) => $.classic.PreModelSwitch(preSwitch(requested, source))
|
||||
|
||||
/** Lets the timers and the hooks of the deferred dialog run. */
|
||||
async function settle(done: () => boolean = () => false): Promise<void> {
|
||||
for (let i = 0; i < 100 && !done(); i++) {
|
||||
await new Promise(r => setTimeout(r, 0))
|
||||
}
|
||||
for (let i = 0; i < 5; i++) await new Promise(r => setTimeout(r, 0))
|
||||
}
|
||||
|
||||
type PickerRig = ModelRig & { logs: string[] }
|
||||
|
||||
async function bootPicker(
|
||||
$: Engine,
|
||||
on: On,
|
||||
answers: string[],
|
||||
fx: Fixture = {},
|
||||
): Promise<PickerRig> {
|
||||
const logs = recordLogs(on)
|
||||
const m = await bootModel($, on, answers, OPUS, fx)
|
||||
return { ...m, logs }
|
||||
}
|
||||
|
||||
/** The picker's switch, then the deferred question answered. */
|
||||
async function pickAndAnswer(
|
||||
$: Engine,
|
||||
p: PickerRig,
|
||||
requested: string,
|
||||
): Promise<unknown> {
|
||||
const out = await pick($, requested)
|
||||
await p.rig.clock.advance(300)
|
||||
await settle(() => p.w.asked.length > 0 && p.logs.length > 0)
|
||||
return out
|
||||
}
|
||||
|
||||
test('picker: a known model is denied at once, the question comes after', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, ['This conversation'])
|
||||
const held = deferred()
|
||||
p.w.gate = held.gate
|
||||
const out = await pick($, 'fable')
|
||||
expect(JSON.stringify(out)).toContain(DENY)
|
||||
expect(JSON.stringify(out)).toContain('deny')
|
||||
expect(p.w.asked).toEqual([])
|
||||
await p.rig.clock.advance(300)
|
||||
await settle(() => p.w.asked.length > 0)
|
||||
const [q] = p.w.asked as [Asked]
|
||||
expect(q.options).toEqual(SCOPES)
|
||||
expect(q.header).toBe('model-router')
|
||||
expect(q.text.endsWith(`Switch main to ${FABLE} where?`)).toBe(true)
|
||||
held.release()
|
||||
await settle()
|
||||
expect(p.ran).toEqual([])
|
||||
})
|
||||
|
||||
const PASSTHROUGH: [string, string | null, SwitchSource][] = [
|
||||
['source command', 'fable', 'command'],
|
||||
['source sdk', 'fable', 'sdk'],
|
||||
['Default (null)', null, 'picker'],
|
||||
['opusplan', 'opusplan', 'picker'],
|
||||
['an unknown id', 'claude-opus-5-6', 'picker'],
|
||||
]
|
||||
|
||||
for (const [name, requested, source] of PASSTHROUGH) {
|
||||
test(`picker: ${name} passes through, no question`, async ($, on) => {
|
||||
const p = await bootPicker($, on, ['This project'])
|
||||
const out = await pick($, requested, source)
|
||||
await p.rig.clock.advance(300)
|
||||
await settle()
|
||||
expect(JSON.stringify(out)).not.toContain('deny')
|
||||
expect(p.w.asked).toEqual([])
|
||||
expect(p.toasts).toEqual([])
|
||||
})
|
||||
}
|
||||
|
||||
test('picker: router off passes through', async ($, on) => {
|
||||
const p = await bootPicker($, on, [])
|
||||
await route($, 'off')
|
||||
expect(JSON.stringify(await pick($, 'fable'))).not.toContain('deny')
|
||||
await settle()
|
||||
expect(p.w.asked).toEqual([])
|
||||
})
|
||||
|
||||
test('picker: no surface passes through', async ($, on) => {
|
||||
const p = await bootPicker($, on, [], { surfaces: [] })
|
||||
expect(JSON.stringify(await pick($, 'fable'))).not.toContain('deny')
|
||||
await settle()
|
||||
expect(p.w.asked).toEqual([])
|
||||
})
|
||||
|
||||
test('picker: an open dialog denies with a toast, never native', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, ['This conversation'])
|
||||
const held = deferred()
|
||||
const open = deferred()
|
||||
p.w.gate = held.gate
|
||||
p.w.onAsk = open.release
|
||||
const first = modelCmd($, 'fable')
|
||||
await open.gate
|
||||
const out = await pick($, 'sonnet')
|
||||
expect(JSON.stringify(out)).toContain('deny')
|
||||
expect(p.toasts).toEqual([BUSY])
|
||||
held.release()
|
||||
await first
|
||||
expect(p.w.asked).toHaveLength(1)
|
||||
expect(p.ran).toEqual([])
|
||||
})
|
||||
|
||||
test('picker: This project writes the full id, native never runs', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, ['This project'])
|
||||
await pickAndAnswer($, p, 'fable')
|
||||
expect(localOf(p.w)).toEqual({ model: FABLE })
|
||||
expect(p.logs.join('\n')).toContain(`${FABLE} written to`)
|
||||
expect(p.ran).toEqual([])
|
||||
expect((await stepOn($, p.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('picker: This conversation routes only, writes nothing', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, ['This conversation'])
|
||||
await pickAndAnswer($, p, 'fable')
|
||||
expect(p.w.written).toEqual([])
|
||||
expect(p.logs.join('\n')).toContain('for this conversation')
|
||||
expect(p.ran).toEqual([])
|
||||
expect((await stepOn($, p.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('picker: Everywhere drops a hand pick, runs native once', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, ['This conversation', 'Everywhere'])
|
||||
await modelCmd($, 'fable')
|
||||
await pickAndAnswer($, p, 'sonnet')
|
||||
expect(p.ran).toEqual(['sonnet'])
|
||||
expect(p.w.asked).toHaveLength(2)
|
||||
expect(p.w.written).toEqual([])
|
||||
expect(mainLine(await route($, 'show'))).toContain('session defaults')
|
||||
expect(p.logs.filter(l => l.includes('native'))).toEqual([])
|
||||
})
|
||||
|
||||
test('picker: dismissed logs the no-scope text and frees the slot', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, [])
|
||||
await pickAndAnswer($, p, 'fable')
|
||||
expect(p.logs).toContain(NO_SCOPE)
|
||||
expect(p.ran).toEqual([])
|
||||
expect(p.w.written).toEqual([])
|
||||
await pickAndAnswer($, p, 'fable')
|
||||
expect(p.w.asked).toHaveLength(2)
|
||||
})
|
||||
|
||||
test('picker: a throwing sleep is logged under its key, slot freed', async (
|
||||
$, on) => {
|
||||
const logs = recordLogs(on)
|
||||
const m = await bootModel($, on, ['This project'], OPUS,
|
||||
{ sleepFails: true })
|
||||
expect(JSON.stringify(await pick($, 'fable'))).toContain('deny')
|
||||
await settle(() => logs.some(l => l.includes('PreModelSwitch picker')))
|
||||
expect(logs.join('\n')).toContain('PreModelSwitch picker failed')
|
||||
expect(m.w.asked).toEqual([])
|
||||
expect(m.w.written).toEqual([])
|
||||
const again = await pick($, 'fable')
|
||||
expect(JSON.stringify(again)).toContain('deny')
|
||||
expect(m.toasts).toEqual([])
|
||||
})
|
||||
|
||||
test('picker: a throw after the answer is logged, native never runs', async (
|
||||
$, on) => {
|
||||
const logs = recordLogs(on)
|
||||
const m = await bootModel($, on, ['This conversation'], OPUS,
|
||||
{ clockFailsAfterAsk: true })
|
||||
await pick($, 'fable')
|
||||
await settle(() => logs.some(l => l.includes('model failed (')))
|
||||
expect(logs.join('\n')).toContain('model failed (')
|
||||
expect(m.ran).toEqual([])
|
||||
await pick($, 'fable')
|
||||
await settle()
|
||||
expect(m.w.asked).toHaveLength(2)
|
||||
})
|
||||
|
||||
test('picker: a changed conversation applies nothing', async ($, on) => {
|
||||
const p = await bootPicker($, on, ['This project'])
|
||||
const held = deferred()
|
||||
const open = deferred()
|
||||
p.w.gate = held.gate
|
||||
p.w.onAsk = open.release
|
||||
await pick($, 'fable')
|
||||
await p.rig.clock.advance(300)
|
||||
await open.gate
|
||||
p.w.sessionId = 's2'
|
||||
held.release()
|
||||
await settle(() => p.logs.length > 0)
|
||||
expect(p.logs.join('\n')).toContain('conversation changed')
|
||||
expect(p.w.written).toEqual([])
|
||||
expect(mainLine(await route($, 'show'))).toContain('session defaults')
|
||||
})
|
||||
|
||||
test('picker: a native switch passes without a second dialog', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, ['Everywhere'])
|
||||
await pickAndAnswer($, p, 'opus')
|
||||
expect(JSON.stringify(await pick($, 'opus', 'command'))).not.toContain('deny')
|
||||
expect(p.w.asked).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('picker: a pick clears the mark of its target', async ($, on) => {
|
||||
const p = await bootPicker($, on, ['This conversation'])
|
||||
await route($, 'model=fable')
|
||||
await stepOn($, p.rig, FABLE)
|
||||
await failWith($, 'overloaded')
|
||||
expect(await route($, 'show')).toContain('claude-fable-5-1 for')
|
||||
await pickAndAnswer($, p, 'fable')
|
||||
expect(await route($, 'show')).toContain('down: none')
|
||||
})
|
||||
|
||||
test('picker: a PostModelSwitch of a denied pick keeps the hand pick', async (
|
||||
$, on) => {
|
||||
const p = await bootPicker($, on, ['This conversation', 'This conversation'])
|
||||
await modelCmd($, 'fable')
|
||||
const held = deferred()
|
||||
p.w.gate = held.gate
|
||||
await pick($, 'sonnet')
|
||||
await switchTo($, OPUS, SONNET, 'picker')
|
||||
held.release()
|
||||
await settle()
|
||||
expect(mainLine(await route($, 'show'))).toContain('user custom')
|
||||
})
|
||||
|
||||
// ---- hand pick: a model chosen by hand always switches --------------------
|
||||
|
||||
type HandRig = {
|
||||
w: World
|
||||
rig: Rig
|
||||
usage: { set: (n: number) => void }
|
||||
logs: string[]
|
||||
}
|
||||
|
||||
async function bootHand(
|
||||
$: Engine,
|
||||
on: On,
|
||||
answers: string[],
|
||||
session: string = OPUS,
|
||||
tokens = 1000,
|
||||
fx: Fixture = {},
|
||||
): Promise<HandRig> {
|
||||
on('command.run', { command: 'model' }, () => ({ text: 'native' }))
|
||||
const logs = recordLogs(on)
|
||||
const w = newWorld({ answers, ...fx })
|
||||
const { rig, usage } = await bootRigVar($, on, session, tokens, w)
|
||||
return { w, rig, usage, logs }
|
||||
}
|
||||
|
||||
test('hand pick: a held-down target waits across the turn boundary', async (
|
||||
$, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'])
|
||||
await modelCmd($, 'fable')
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE)
|
||||
await failWith($, 'overloaded')
|
||||
await endTurn($)
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(OPUS)
|
||||
await stepOn($, h.rig, OPUS)
|
||||
expect(h.logs.filter(l => l.includes('hand pick waits'))).toHaveLength(1)
|
||||
await endTurn($)
|
||||
await h.rig.clock.advance(15 * 60000)
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('hand pick: the current model down leaves it for the hand pick', async (
|
||||
$, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'], OPUS, 300000,
|
||||
{ home: { mainUpgrade: false } })
|
||||
await stepOn($, h.rig, OPUS)
|
||||
await failWith($, 'overloaded')
|
||||
await endTurn($)
|
||||
await modelCmd($, 'fable')
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('hand pick: an unranked session model does not trap it', async (
|
||||
$, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'], 'claude-zz-9')
|
||||
await modelCmd($, 'opus')
|
||||
expect((await stepOn($, h.rig, 'claude-zz-9')).model).toBe(OPUS)
|
||||
})
|
||||
|
||||
test('hand pick: over the upgrade cap and with the switch off still moves', async (
|
||||
$, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'], OPUS, 300000,
|
||||
{ home: { mainUpgrade: false } })
|
||||
await modelCmd($, 'fable')
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE)
|
||||
await endTurn($)
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('hand pick: over the downgrade cap with switch off still moves', async (
|
||||
$, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'], FABLE, 300000)
|
||||
await route($, 'switch off')
|
||||
await modelCmd($, 'sonnet')
|
||||
expect((await stepOn($, h.rig, FABLE)).model).toBe(SONNET)
|
||||
})
|
||||
|
||||
test('hand pick: a typed /route model= keeps the caps', async ($, on) => {
|
||||
const h = await bootHand($, on, [], OPUS, 300000)
|
||||
await route($, 'model=fable')
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(OPUS)
|
||||
})
|
||||
|
||||
test('hand pick: the current model pinned and down falls to the next', async (
|
||||
$, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'])
|
||||
await modelCmd($, 'opus')
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(OPUS)
|
||||
await failWith($, 'overloaded')
|
||||
const same = (await stepOn($, h.rig, OPUS)).model
|
||||
expect(same).not.toBe(OPUS)
|
||||
await endTurn($)
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(same)
|
||||
})
|
||||
|
||||
test('hand pick: a target that fails mid-turn is left', async ($, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'])
|
||||
await modelCmd($, 'fable')
|
||||
expect((await stepOn($, h.rig, OPUS)).model).toBe(FABLE)
|
||||
await failWith($, 'overloaded')
|
||||
expect((await stepOn($, h.rig, OPUS)).model).not.toBe(FABLE)
|
||||
})
|
||||
|
||||
test('hand pick: outgrowing a known window still returns home', async (
|
||||
$, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'], FABLE, 1000,
|
||||
{ home: { windows: { [HAIKU]: 200000 } } })
|
||||
await modelCmd($, 'haiku')
|
||||
expect((await stepOn($, h.rig, FABLE)).model).toBe(HAIKU)
|
||||
h.usage.set(250000)
|
||||
expect((await stepOn($, h.rig, FABLE)).model).toBe(FABLE)
|
||||
})
|
||||
|
||||
test('hand pick: a native user switch drops it', async ($, on) => {
|
||||
const h = await bootHand($, on, ['This conversation'])
|
||||
await modelCmd($, 'fable')
|
||||
await switchTo($, OPUS, SONNET, 'picker')
|
||||
expect((await stepOn($, h.rig, SONNET)).model).toBe(SONNET)
|
||||
expect(mainLine(await route($, 'show'))).toContain('session defaults')
|
||||
})
|
||||
@@ -7,7 +7,10 @@
|
||||
// DEFAULT_CONFIG; ~/.claude/model-router.json overrides both per machine.
|
||||
// One writer per concern: the Agent tool's own params are never rewritten,
|
||||
// the spawn hook sets an agent's model once, turn.step sets efforts.
|
||||
import type { EngineInterface, On, Register, TurnStepInput } from 'claude-code'
|
||||
import type {
|
||||
CommandRunInput, CommandRunResult, EngineInterface, Next, On, Register,
|
||||
TurnStepInput,
|
||||
} from 'claude-code'
|
||||
|
||||
type Api = EngineInterface
|
||||
type Level = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
|
||||
@@ -47,6 +50,7 @@ type Routed = {
|
||||
source: Source
|
||||
label?: string // the skill a skill route came from, for the logs
|
||||
explicitEffort?: boolean // the effort was asked for, not the phase's own
|
||||
explicitModel?: boolean // the model was chosen by hand in the scope dialog
|
||||
}
|
||||
type Served = { at: number; tokens: number } // ms, context tokens
|
||||
type Hold = { until: number; reason: string } // until: ms, Infinity = reload
|
||||
@@ -190,6 +194,15 @@ const KEEP = 'Keep'
|
||||
const CHANGE = 'Change'
|
||||
const EVERYWHERE = 'Everywhere'
|
||||
const THIS_PROJECT = 'This project only'
|
||||
// `/model <name>` scope dialog. PROJECT_SCOPE differs from THIS_PROJECT, the
|
||||
// first-use label: both are fixed by their own contracts.
|
||||
const PROJECT_SCOPE = 'This project'
|
||||
const CONVERSATION = 'This conversation'
|
||||
const MODEL_SCOPES: readonly string[] = [
|
||||
PROJECT_SCOPE, CONVERSATION, EVERYWHERE,
|
||||
]
|
||||
const NO_SCOPE = 'model: no scope chosen, nothing changed'
|
||||
const LOCAL_SETTINGS = '.claude/settings.local.json'
|
||||
const CHOICE_ALIASES: readonly string[] = ['fable', 'opus', 'sonnet', 'haiku']
|
||||
const MAX_DESC = 140 // chars of a skill or agent description in a question
|
||||
const MAX_ABOUT = 120 // chars of a phase `about`
|
||||
@@ -254,12 +267,12 @@ const TIMEOUT: unique symbol = Symbol('timeout')
|
||||
|
||||
const DEFAULT_CONFIG: Config = {
|
||||
models: {
|
||||
haiku: 'claude-haiku-4-5-20251001',
|
||||
haiku: 'claude-haiku-5-5',
|
||||
sonnet: 'claude-sonnet-5-5',
|
||||
opus: 'claude-opus-5-5',
|
||||
fable: 'claude-fable-5-1',
|
||||
},
|
||||
windows: { 'claude-haiku-4-5-20251001': 200000 },
|
||||
windows: {},
|
||||
// A tier is an ordered alias list: the first one not down is used.
|
||||
tiers: {
|
||||
best: ['fable', 'opus', 'sonnet'],
|
||||
@@ -1365,13 +1378,12 @@ function windowReturn(
|
||||
}
|
||||
|
||||
/**
|
||||
* The one decision of the main loop's model, in this order: router off, a
|
||||
* model the table does not rank (never touched), a model whose window the
|
||||
* context outgrew (back to the session model), `cur` down (leave it,
|
||||
* always), no or same wanted model, a better one (upgrade), a cheaper one
|
||||
* (downgrade). Used by the step AND by every text, so they agree.
|
||||
* The automatic chain, in this order: router off, a model the table does
|
||||
* not rank (never touched), a model whose window the context outgrew (back
|
||||
* to the session model), `cur` down (leave it, always), no or same wanted
|
||||
* model, a better one (upgrade), a cheaper one (downgrade).
|
||||
*/
|
||||
function decideMain(
|
||||
function automaticCall(
|
||||
st: State,
|
||||
cur: string,
|
||||
wanted: string | undefined,
|
||||
@@ -1390,6 +1402,57 @@ function decideMain(
|
||||
: downgradeCall(st, cur, wanted, read)
|
||||
}
|
||||
|
||||
/** The sticky model slot holds a model chosen by hand, and it is `wanted`. */
|
||||
function handPicked(
|
||||
st: State,
|
||||
wanted: string | undefined,
|
||||
): wanted is string {
|
||||
return wanted !== undefined && st.userMain?.explicitModel === true &&
|
||||
mainModelSlot(st) === st.userMain
|
||||
}
|
||||
|
||||
/**
|
||||
* A hand pick (the scope dialog) always switches: no switch flag, no cold
|
||||
* read cap, ahead of every automatic rule. Undefined when it cannot run
|
||||
* (held down, or the context outgrew its known window): then it waits.
|
||||
*/
|
||||
function handCall(
|
||||
st: State,
|
||||
cur: string,
|
||||
wanted: string,
|
||||
read: Reading,
|
||||
): Call | undefined {
|
||||
const usable = !st.down.has(canonical(st.cfg, wanted)) &&
|
||||
fits(st, wanted, read.tokens)
|
||||
if (!usable) return undefined
|
||||
if (aliasOf(st.cfg, wanted) === aliasOf(st.cfg, canonical(st.cfg, cur))) {
|
||||
return keep(cur)
|
||||
}
|
||||
return moveTo(cur, wanted, 'hand pick', st.sessionModel)
|
||||
}
|
||||
|
||||
/**
|
||||
* The one decision of the main loop's model: a hand pick when one can run,
|
||||
* else the automatic chain. Used by the step AND by every text, so they
|
||||
* agree.
|
||||
*/
|
||||
function decideMain(
|
||||
st: State,
|
||||
cur: string,
|
||||
wanted: string | undefined,
|
||||
read: Reading,
|
||||
): Call {
|
||||
if (st.off || !handPicked(st, wanted)) {
|
||||
return automaticCall(st, cur, wanted, read)
|
||||
}
|
||||
const hand = handCall(st, cur, wanted, read)
|
||||
if (hand !== undefined) return hand
|
||||
const call = automaticCall(st, cur, undefined, read)
|
||||
const once = `model-router: ${canonical(st.cfg, wanted)} is held down or ` +
|
||||
'does not fit; hand pick waits'
|
||||
return { ...call, once: call.once ?? once }
|
||||
}
|
||||
|
||||
/**
|
||||
* The slot that names main's model: sticky, turn route, then run slot. A
|
||||
* floor names no model (prompt rules set the effort only).
|
||||
@@ -2054,6 +2117,316 @@ async function handleCommand($: Api, st: State, args: string): Promise<string> {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- /model <name>: the scope of a switch ---------------------------------
|
||||
// A typed `/model <name>` of a model the table knows asks where it applies.
|
||||
// Everywhere is the native command (user settings.json); the two others set
|
||||
// a sticky model route, This project also pins `model` in the project's
|
||||
// settings.local.json. Fail-open to native only before an answer.
|
||||
|
||||
type ModelNext = Next<'command.run'>
|
||||
type PreSwitchNext = Next<'classic.PreModelSwitch'>
|
||||
type PreSwitchIn = Parameters<PreSwitchNext>[0]
|
||||
type Local = { data: Rec; created: boolean }
|
||||
type Unreadable = { cause: string }
|
||||
|
||||
/** An alias or a full id of the table; haiku has no `[1m]` variant. */
|
||||
function knownModel(cfg: Config, token: string): boolean {
|
||||
const bare = token.replace(ONE_M, '')
|
||||
const id = hasKey(cfg.models, bare) ? cfg.models[bare] ?? bare : bare
|
||||
if (!Object.values(cfg.models).includes(id)) return false
|
||||
return !(ONE_M.test(token) && id.startsWith(HAIKU))
|
||||
}
|
||||
|
||||
/** The id a token stands for, `[1m]` kept; never `canonical` (it strips). */
|
||||
function fullId(cfg: Config, token: string): string {
|
||||
const bare = token.replace(ONE_M, '')
|
||||
if (!hasKey(cfg.models, bare)) return token
|
||||
return `${cfg.models[bare] ?? bare}${ONE_M.test(token) ? '[1m]' : ''}`
|
||||
}
|
||||
|
||||
/** A user switch by hand: sticky model, the run slot dropped, effort kept. */
|
||||
function stickyModel($: Api, st: State, bare: string): void {
|
||||
const prev = st.userMain
|
||||
const effort = prev?.route.effort
|
||||
st.userMain = {
|
||||
phase: 'custom',
|
||||
route: { model: bare, ...(effort === undefined ? {} : { effort }) },
|
||||
source: 'user',
|
||||
explicitModel: true,
|
||||
...(prev?.explicitEffort ? { explicitEffort: true } : {}),
|
||||
}
|
||||
st.runMain = null
|
||||
refresh($, st)
|
||||
}
|
||||
|
||||
/** Everywhere: a sticky model or tier would route main back after native. */
|
||||
function dropStickyModel(st: State): void {
|
||||
if (st.userMain === null) return
|
||||
const { explicitModel: _hand, ...rest } = st.userMain
|
||||
const effort = rest.route.effort
|
||||
st.userMain = effort === undefined
|
||||
? null
|
||||
: { ...rest, phase: 'custom', route: { effort } }
|
||||
}
|
||||
|
||||
async function localPath($: Api): Promise<string | undefined> {
|
||||
try {
|
||||
return `${await $.session.root()}/${LOCAL_SETTINGS}`
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** The file's text; null when absent (`stat` rejects and `exists` false). */
|
||||
async function localText(
|
||||
$: Api,
|
||||
path: string,
|
||||
): Promise<string | null | Unreadable> {
|
||||
try {
|
||||
let info
|
||||
try {
|
||||
info = await $.fs.stat(path)
|
||||
} catch (err) {
|
||||
if (!(await $.fs.exists(path))) return null
|
||||
return { cause: `fs error ${errWord(err)}` }
|
||||
}
|
||||
if (info.isLink) return { cause: 'settings.local.json is a link' }
|
||||
if (info.kind !== 'file') return { cause: 'not a regular file' }
|
||||
if (info.size > MAX_CONFIG_BYTES) return { cause: 'too large' }
|
||||
const text = await $.fs.read(path)
|
||||
return text.length > MAX_CONFIG_BYTES ? { cause: 'too large' } : text
|
||||
} catch (err) {
|
||||
return { cause: `fs error ${errWord(err)}` }
|
||||
}
|
||||
}
|
||||
|
||||
/** The local settings as an object, or a fixed cause word; never throws. */
|
||||
async function readLocalSettings(
|
||||
$: Api,
|
||||
path: string,
|
||||
): Promise<Local | string> {
|
||||
const text = await localText($, path)
|
||||
if (text === null) return { data: {}, created: true }
|
||||
if (typeof text !== 'string') return text.cause
|
||||
let data: unknown
|
||||
try {
|
||||
data = JSON.parse(text)
|
||||
} catch {
|
||||
return 'not JSON'
|
||||
}
|
||||
return isRecord(data) ? { data, created: false } : 'not an object'
|
||||
}
|
||||
|
||||
/** The project's `.claude`: absent is fine, a link or a file is not. */
|
||||
async function claudeDirCause($: Api, path: string): Promise<string | null> {
|
||||
const dir = path.slice(0, path.lastIndexOf('/'))
|
||||
try {
|
||||
let info
|
||||
try {
|
||||
info = await $.fs.stat(dir)
|
||||
} catch (err) {
|
||||
if (!(await $.fs.exists(dir))) return null
|
||||
return `fs error ${errWord(err)}`
|
||||
}
|
||||
if (info.isLink) return '.claude is a link'
|
||||
return info.kind === 'dir' ? null : '.claude is not a directory'
|
||||
} catch (err) {
|
||||
return `fs error ${errWord(err)}`
|
||||
}
|
||||
}
|
||||
|
||||
/** 'written', 'created', or a fixed cause word (never an error message). */
|
||||
async function writeLocalModel($: Api, id: string): Promise<string> {
|
||||
const path = await localPath($)
|
||||
if (path === undefined) return 'project root unknown'
|
||||
const bad = await claudeDirCause($, path)
|
||||
if (bad !== null) return bad
|
||||
const local = await readLocalSettings($, path)
|
||||
if (typeof local === 'string') return local
|
||||
local.data.model = id
|
||||
try {
|
||||
await $.fs.write(path, `${JSON.stringify(local.data, null, 2)}\n`)
|
||||
} catch (err) {
|
||||
return `fs error ${errWord(err)}`
|
||||
}
|
||||
return local.created ? 'created' : 'written'
|
||||
}
|
||||
|
||||
/** The question: the id, the three scopes, the project pin if any. */
|
||||
async function scopeQuestion($: Api, id: string): Promise<string> {
|
||||
const path = await localPath($)
|
||||
const local = path === undefined ? '' : await readLocalSettings($, path)
|
||||
const pin = typeof local === 'string' ? undefined : local.data.model
|
||||
const note = typeof pin === 'string'
|
||||
? `Note: this project pins ${clean(pin, 60)} in ${LOCAL_SETTINGS}: ` +
|
||||
'at launch here, the project pin wins over Everywhere\n'
|
||||
: ''
|
||||
return `${PROJECT_SCOPE}: ${LOCAL_SETTINGS} of this repo (wins at ` +
|
||||
`launch) + route now · ${CONVERSATION}: route now, nothing written · ` +
|
||||
`${EVERYWHERE}: user settings.json, every project\n${note}` +
|
||||
`Switch main to ${id} where?`
|
||||
}
|
||||
|
||||
/** The route cannot hold `[1m]`: the session's variant is what carries. */
|
||||
function variantNote(st: State, token: string, bareFull: string): string {
|
||||
const long = ONE_M.test(token) || ONE_M.test(st.sessionModel)
|
||||
return long && !bareFull.startsWith(HAIKU)
|
||||
? " ([1m] follows the session's variant)"
|
||||
: ''
|
||||
}
|
||||
|
||||
function writtenText(id: string, wrote: string): string {
|
||||
if (wrote !== 'written' && wrote !== 'created') {
|
||||
return `model: ${LOCAL_SETTINGS} not written (${wrote})`
|
||||
}
|
||||
return `model: ${id} written to ${LOCAL_SETTINGS} (remove its "model" key ` +
|
||||
`to undo)${wrote === 'created' ? ', file created: keep it gitignored' : ''}`
|
||||
}
|
||||
|
||||
/** This project (file + route) or This conversation (route only). */
|
||||
async function applyLocalScope(
|
||||
$: Api,
|
||||
st: State,
|
||||
token: string,
|
||||
toFile: boolean,
|
||||
): Promise<string> {
|
||||
const id = fullId(st.cfg, token)
|
||||
const wrote = toFile ? await writeLocalModel($, id) : undefined
|
||||
const bare = token.replace(ONE_M, '')
|
||||
clearBreaker(st, canonical(st.cfg, bare)) // a hand pick, like a native one
|
||||
stickyModel($, st, bare)
|
||||
if (wrote !== undefined && wrote !== 'written' && wrote !== 'created') {
|
||||
$.ui.toast(`settings.local.json not written: ${wrote}`)
|
||||
}
|
||||
const route = `sticky route ${fullId(st.cfg, bare)}`
|
||||
const head = wrote === undefined
|
||||
? `model: ${route} for this conversation`
|
||||
: `${writtenText(id, wrote)}; ${route} set`
|
||||
const note = variantNote(st, token, fullId(st.cfg, bare))
|
||||
return `${head}${note}\n${await show($, st)}`
|
||||
}
|
||||
|
||||
/** How a dialog entry reaches native, names its failures, checks it. */
|
||||
type ScopeVia = {
|
||||
everywhere: () => Promise<CommandRunResult> // the native switch
|
||||
warnKey: string // the fail-open log key of this entry
|
||||
stillHere?: () => Promise<boolean> // false: the dialog's moment is gone
|
||||
}
|
||||
|
||||
/**
|
||||
* The scope question and its answer, for both entries. Before an answer a
|
||||
* failure fails open (the caller's `.catch`); after one native never runs
|
||||
* on a failure: a text says what to do.
|
||||
*/
|
||||
async function scopeDialog(
|
||||
$: Api,
|
||||
st: State,
|
||||
token: string,
|
||||
via: ScopeVia,
|
||||
): Promise<CommandRunResult> {
|
||||
const question = await scopeQuestion($, fullId(st.cfg, token))
|
||||
const answer = await askOr($, question, MODEL_SCOPES)
|
||||
if (!MODEL_SCOPES.includes(answer)) return { text: NO_SCOPE }
|
||||
try {
|
||||
if (via.stillHere !== undefined && !(await via.stillHere())) {
|
||||
return { text: 'model: the conversation changed, nothing applied' }
|
||||
}
|
||||
if (answer === EVERYWHERE) {
|
||||
dropStickyModel(st)
|
||||
return await via.everywhere()
|
||||
}
|
||||
return { text: await applyLocalScope(
|
||||
$, st, token, answer === PROJECT_SCOPE) }
|
||||
} catch (err) {
|
||||
warnOnce(st, $, via.warnKey, errWord(err))
|
||||
return { text: `model failed (${errWord(err)}); the file write or the ` +
|
||||
`sticky route may have landed: check /route show and ${LOCAL_SETTINGS}` }
|
||||
}
|
||||
}
|
||||
|
||||
async function handleModelCommand(
|
||||
$: Api,
|
||||
st: State,
|
||||
e: CommandRunInput,
|
||||
next: ModelNext,
|
||||
): Promise<CommandRunResult> {
|
||||
await ensureConfig($, st)
|
||||
const tokens = e.args.trim().split(/\s+/)
|
||||
const token = tokens[0] ?? ''
|
||||
if (st.off || e.origin.kind !== 'composer' || tokens.length !== 1 ||
|
||||
!knownModel(st.cfg, token) ||
|
||||
(await $.session.surfaces()).length === 0 || st.asking !== null) {
|
||||
return next(e)
|
||||
}
|
||||
st.asking = `model:${token}`
|
||||
try {
|
||||
return await scopeDialog($, st, token,
|
||||
{ everywhere: () => next(e), warnKey: 'command.run model' })
|
||||
} finally {
|
||||
st.asking = null
|
||||
}
|
||||
}
|
||||
|
||||
// The /model picker: the engine draws nothing while a PreModelSwitch hook
|
||||
// runs, so the switch is denied at once and the question comes after the
|
||||
// hook returned. Everywhere then runs the native command (its own hooks
|
||||
// pass through); the two local scopes never reach native.
|
||||
|
||||
const PICKER_DELAY_MS = 300
|
||||
const PICKER_DENY = 'model-router asks where this switch applies'
|
||||
const PICKER_BUSY = 'answer the open dialog first'
|
||||
|
||||
const pickerDeny = {
|
||||
permissionDecision: 'deny' as const,
|
||||
permissionDecisionReason: PICKER_DENY,
|
||||
}
|
||||
|
||||
/** The question after the deny; always frees the slot, never throws. */
|
||||
async function pickerDialog(
|
||||
$: Api,
|
||||
st: State,
|
||||
asked: string,
|
||||
conv: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await $.clock.sleep(PICKER_DELAY_MS)
|
||||
const out = await scopeDialog($, st, asked, {
|
||||
everywhere: () => $.command.run({ command: 'model', args: asked })
|
||||
.then(() => ({})),
|
||||
warnKey: 'PreModelSwitch picker',
|
||||
stillHere: async () => (await $.session.id()) === conv,
|
||||
})
|
||||
if (out.text !== undefined) tryLog($, out.text)
|
||||
} catch (err) {
|
||||
warnOnce(st, $, 'PreModelSwitch picker', errWord(err))
|
||||
} finally {
|
||||
st.asking = null
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePicker(
|
||||
$: Api,
|
||||
st: State,
|
||||
e: PreSwitchIn,
|
||||
next: PreSwitchNext,
|
||||
) {
|
||||
if (e.source !== 'picker') return next(e)
|
||||
await ensureConfig($, st)
|
||||
const asked = e.requested_model
|
||||
if (st.off || typeof asked !== 'string' || !knownModel(st.cfg, asked) ||
|
||||
(await $.session.surfaces()).length === 0) {
|
||||
return next(e)
|
||||
}
|
||||
const conv = await $.session.id()
|
||||
if (st.asking !== null) {
|
||||
$.ui.toast(PICKER_BUSY)
|
||||
return pickerDeny
|
||||
}
|
||||
st.asking = `picker:${asked}`
|
||||
void pickerDialog($, st, asked, conv)
|
||||
return pickerDeny
|
||||
}
|
||||
|
||||
// ---- first use: one dialog per row, the answer kept in routing.json -----
|
||||
// The first time a row routes (a typed skill, an agent spawn, a phase
|
||||
// declared through the route tool) the user confirms it once, for every
|
||||
@@ -3364,6 +3737,7 @@ function modelCause(st: State, why: Why): string | undefined {
|
||||
if (call.why === 'upgrade') return 'upgrade'
|
||||
if (call.why === 'downgrade') return 'switch'
|
||||
if (call.why === 'window') return 'window'
|
||||
if (call.why === 'hand pick') return 'hand pick'
|
||||
return `fallback: ${nameOf(st.cfg, cur)} down`
|
||||
}
|
||||
|
||||
@@ -3679,6 +4053,12 @@ async function onAutoSwitch($: Api, st: State, e: SwitchIn): Promise<void> {
|
||||
markDown($, st, target, 'engine fallback', await $.clock.now())
|
||||
}
|
||||
|
||||
/** A native user switch on main ends a hand pick, the picker's own aside. */
|
||||
const handPickEnds = (st: State, e: SwitchIn): boolean =>
|
||||
USER_SWITCH.has(e.source) && e.agent_id === undefined &&
|
||||
st.userMain?.explicitModel === true &&
|
||||
st.asking?.startsWith('picker:') !== true
|
||||
|
||||
/**
|
||||
* Any model change: keeps `sessionModel` and the cache TTL (main's own
|
||||
* switches only); a user choice clears its mark.
|
||||
@@ -3689,6 +4069,7 @@ async function onModelSwitch($: Api, st: State, e: SwitchIn): Promise<void> {
|
||||
st.cacheTtlMs = ttlOf(e.cache_ttl) ?? st.cacheTtlMs
|
||||
}
|
||||
if (USER_SWITCH.has(e.source)) st.runMain = null
|
||||
if (handPickEnds(st, e)) dropStickyModel(st)
|
||||
if (st.off || e.source === 'resume') return
|
||||
if (e.source === 'auto') await onAutoSwitch($, st, e)
|
||||
else clearBreaker(st, canonical(st.cfg, e.to_model))
|
||||
@@ -3756,6 +4137,18 @@ function registerCwd(on: On, st: State): void {
|
||||
}
|
||||
|
||||
function registerCommandHook(on: On, st: State): void {
|
||||
on('command.run', { command: 'model' }, async ($, e, next) =>
|
||||
handleModelCommand($, st, e, next)
|
||||
).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'command.run model', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
on('classic.PreModelSwitch', async ($, e, next) =>
|
||||
handlePicker($, st, e, next)
|
||||
).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'PreModelSwitch', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
on('command.run', { command: 'route' }, async ($, e) => {
|
||||
if (e.origin.kind !== 'composer') {
|
||||
return { text: 'route: user-only command' }
|
||||
|
||||
Reference in new issue
Block a user