feat(router): the /model picker asks its scope; a hand pick always switches

A pick in the picker is held (PreModelSwitch deny), then the same project / conversation / everywhere question runs; only Everywhere reaches the native write to user settings.json. A model chosen in that dialog bypasses the cold-read caps but waits while held down.
This commit is contained in:
bchanot committed 2026-10-25 20:36:49 +01:00
1 parent 48778af154
commit 2202964d02
5 files changed
+709 -31

No files matched your search

@@ -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.