Merge feature/guard-fail-closed into develop
This commit is contained in:
commit
a4b09cd2a3
12 files changed
+443
-22
No files matched your search
@@ -1488,6 +1488,7 @@ Supersedes [[BDR-030]].
|
||||
- **Alternatives rejected**: `$.ui.ask` mod gate, phrase-list gate (challenges 2026-10-25); 16 routing rows for the guard (run slot drops mid-run, would open first-use + ask-tier dialogs); `git -C * merge *` (asks on any commit text with " merge ", sub-agent ask refused); quoted finish rule (matcher ignores quote in pattern); `gitflow_finish*`, `bash -s*` (bench RAN); `Bash(/*)` (kills `*/rtk` twins); per-spawn guard.
|
||||
- **Residuals**: Bash write forms outside guard; latch reset on register.ts reload; sourced `gitflow_finish`, `git -C <dir> merge`; `rtk read -n .env` flag-first (security MEDIUM, TODO); code-limits TMPDIR state dir ownership unchecked; silent in this repo (code-origin foreign).
|
||||
- **Gates**: plan r1 correctness FATAL(8) robustness FATAL(5) → r2 → confirmation CONCERNS(4) → r3; user interactive ask check; SDD 11 tasks; final opus review With fixes → fix wave; GATE 0 ABANDONED(2) user-accepted; verifier ECARTS(6) → ECARTS(2) human-gated; security PASS (1 MEDIUM, 3 LOW). Refs [[BDR-125]], [[BDR-068]], [[BDR-123]], [[BLK-018]], [[LRN-256]], [[LRN-257]].
|
||||
- **Status (2026-11-16)**: accepted, amended: point (4) router write guard now fails closed via next.called (guard failure holds main-loop code write outside skill run; sub-agents, runs, .md/.txt pass); refused/isError Skill no longer latches. 859e504, BDR-125 gap A6, user choice 2026-11-12
|
||||
|
||||
## BDR-137 — Phase 4b memory capture mod: error-shaped Bash failures redacted into a per-project store, 4-gram index per call, one note per milestone, memory_pending (2026-11-04)
|
||||
- **Context**: BDR-125 phase 4b, `feature/memory-capture` (f1d4f9d..HEAD), contract `.claude/tasks/contracts/2026-11-03-memory-capture-0100.md`, spec `docs/superpowers/specs/2026-11-03-memory-capture-design.md`, plan r3, spike `.claude/tasks/plans/2026-11-03-memory-capture-spike/REPORT.md`. Capture = weak link: 5/7 real errors of 2026-10-23 no entry.
|
||||
|
||||
@@ -766,3 +766,4 @@ rules:
|
||||
|
||||
## 2026-11-16
|
||||
- A5 T18 bun guard: memory.test.sh T18 entriesOf/index parity prints SKIP when bun absent instead of FAIL (b9f2d81); no prior bun-skip convention (memory-feedback.test.sh still hard-fails). settings.json left dirty by user choice (/model opus[1m] save). Next A6.
|
||||
- A6 router write guard fail-closed: .catch uses next.called (called → replay next(e); not called → hold main-loop out-of-run non-doc write with user-chosen deny); Skill latch ignores isError answers (BDR-137 shape, was one-call bypass) (859e504). BDR-136 (4) amended. 3 plan rounds: r1/r2 latches unreachable, engine-documented pattern won. gates.sh 120s timeout < make test ~135s: GATES_TIMEOUT=400. Next A7.
|
||||
@@ -2114,3 +2114,9 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s
|
||||
- **Context**: A4 `check --staged` next-ID rule (e0311f4). r1 counted body ID lines as entries → valid `add` refused. r2 ran on v1 HEAD → `upgrade` commit refused (`### BDR-n` → `## BDR-n` read as new); replay of trucks_at_work 17536ce: rc 0 today, rc 2 under r2, remedy would have steered to renumbering.
|
||||
- **Apply**: replay allocator in same order (line order, any level, fenced or not); gate on dialect it assumes (v2 HEAD, ≥1 shape-valid entry, no open fence); before trusting, replay rule on real historical commits of each workflow (add, upgrade, merge, import). Tests must bite: mutate each gate clause, test must go red.
|
||||
- **Reference**: lib/memory.sh `_mem_check_next_ids`, `_mem_next_id`; lib/tests/memory.test.sh T8f-T8o
|
||||
|
||||
## LRN-293 — Mod hook failure handling: read engine API remarks first (next.called guard idiom) (2026-11-16)
|
||||
- **Pattern**: before designing failure handling for a mod hook, read the engine API remarks for that event; the engine may already document the pattern.
|
||||
- **Context**: A6 router write guard fail-closed (859e504). r1 try/catch around guardWrite, r2 cfgErr hold + `.catch` latches: challengers found latches unreachable (no ensureConfig throw source), typed-skill latch unable to fire. claude-code.d.ts tool.call remark already prescribes `.catch(($, e, next) => next.called ? next(e) : { deny })`; Caught.called splits guard failure from downstream error, next(e) replays without re-run. r3 used it: guardWrite unchanged, 3 `.catch` blocks only.
|
||||
- **Apply**: grep `~/.claude/plugins/marketplaces/claude-code-plugins/mods/types/claude-code.d.ts` for the event + `@remarks` before planning; prefer documented idiom over hand-built try/catch. Engine refusals reach hooks as `isError`, not `deny` (BDR-137): latch/success predicates test both.
|
||||
- **Reference**: mods/model-router/hooks/register.ts guardCaught, guardPasses; BDR-136 amended
|
||||
@@ -76,6 +76,7 @@ Open children of the shipped phases (History 2026-11-12), text verbatim.
|
||||
- [x] D3 add-ons (done 9b12b12) from G2 (plugin-advisor.md): plan-budget WARN :317 (unreachable: plugin-gate never sends PLAN, detect_plan gone), :42 "absolute COST ESTIMATE still reported", :105 `(budget: ~<N>t | n/a)`, :222 "passive cost estimate = highest-cost package profile", "0t passive" claims for impeccable / design-motion-principles (:226 :227 :268 :269); USAGE.md :248 "Budget Pro (~11k tokens/5h)", :494 `(~400t)`, :923 `(~200t)`; session-banner.test.sh SB10 `gone()` passes on a missing file (add an existence check)
|
||||
- [x] D6 project rule (done c69ce9c; lead paragraph fixed too, follow-ups in BUGS-FOUND): .claude/rules/graphify-vendored.md says `graphify install --platform claude` "touches nothing else", but graphifyy 0.9.67 appends a `# graphify` block to ~/.claude/CLAUDE.md (= CLAUDE.global.md); `graphify claude install` writes into the caller's cwd, so the install-plugins.sh trap protects $REPO only when run from $REPO
|
||||
- [ ] gates.sh: warn or reject a criterion row labelled `^[0-9]+[a-z]\.` (LRN-284: `1b.` absorbed into criterion 1, its CHECK/EXPECT overwritten, false MET)
|
||||
- [ ] gates.sh default `GATES_TIMEOUT=120` < full `make test` (~135 s on 2026-11-16): a "Full make test green" criterion goes NOT-MET on timeout alone (A6 run, re-run with GATES_TIMEOUT=400). Raise the default or have contract-interview write the timeout for full-suite criteria.
|
||||
- [ ] lib/design-tool-gate.sh:70 `perl -e 'alarm shift; exec @ARGV' 15 21st whoami` kills one process only (same limit as the old session-start runner, fixed 490ad83): reuse the group-kill runner when this file is next touched.
|
||||
- [ ] parked (code-clean 2026-11-09): hooks/rtk-rewrite.sh:84 no-op `[ "$CMD" = "$REWRITTEN" ] && REWRITTEN="$CMD"`: remove with the next real rtk-hook edit, re-pin `hooks/.rtk-hook.sha256` + rtk-rewrite.test.sh T13 in the same step
|
||||
- [ ] deferred (BDR-123): remap inline-writing best-tier skills (design Build stack, writing-skills, deprecation-and-migration, /tour single-project, /audit-delta 3d, /harden STEP 3); stale citers skills/feat/SKILL.md:6, skills/code-clean/SKILL.md:36; + impeccable row in routing.json (design Build stack has none; frontend-design has `reflect`; census test pins the table)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# CONTRACT — guard-fail-closed (BDR-125 gap audit A6)
|
||||
- date: 2026-11-16 | flow: feat | branch: feature/guard-fail-closed (off develop)
|
||||
- status: active
|
||||
|
||||
## REQUEST (verbatim — IMMUTABLE)
|
||||
A6 (BDR-125 gap audit, phase 2 shared rule "guards fail closed", user choice 2026-11-12): the model-router write guard (mods/model-router/hooks/register.ts registerGuard, ~:4441-4464) fails open: when guardWrite throws, the .catch logs and lets the Edit/Write/NotebookEdit through. Make it fail closed for the guard's own failure: a main-loop code write the guard could not decide is denied with "model-router: the write guard failed (<error kind>), so this write is held. Enter /hotfix, /feat, /bugfix or /ship-feature, or re-enter the skill you were running, then make this edit." Sub-agents, writes inside a skill run, and doc files still pass without touching the code that can fail. Errors from the downstream tool (next) keep today's behavior. Tests in mods/model-router/hooks/register.test.ts.
|
||||
|
||||
## CLARIFICATIONS
|
||||
- [gated 2026-11-16] deny text chosen by the user: "Same redirect + cause" (the text quoted in REQUEST, `<error kind>` = `errWord(err)`).
|
||||
- [internal 2026-11-16, challenge r1] plan .claude/tasks/plans/2026-11-16-guard-fail-closed-0025.md section r2 wins. Real throw sources are session.root and a raw ui.log in the config load (config READ errors never throw; an unreadable override turns the router off, unchanged). The config-load log goes through tryLog; the Skill and skill.prompt .catch paths latch so entering a skill stays a working exit. guardWrite returns the deny text; own warnOnce key 'write guard'. Rig gains a World `root: 'fail'` knob. Amends BDR-136 point (4) (guard fail-open) per the user's 2026-11-12 choice; recorded at capitalize.
|
||||
- [internal 2026-11-16, re-challenge r2] plan section r3 wins over r2: guardWrite unchanged; the three guard .catch blocks use the engine's documented `next.called` split (called → replay next(e) as today; not called → hold a main-loop out-of-run non-doc write with the user-chosen text, else pass). No tryLog or .catch-latch changes. Gate 0 note: criterion 1 CHECK runs `claude plugin test` (the kit `claude-code/testing` exists only under the engine; bare `bun test` cannot load it), as lib/tests/mods.test.sh does. Scope extension under the user's "fill every gap found" instruction: the Skill latch no longer opens on an `isError` output (BDR-137: engine refusals carry isError, not deny).
|
||||
|
||||
- [gated 2026-11-16, after verify] user accepted as built: the deny's kind is `next.error.kind` (throw | timeout, never a path), not `errWord(err)`; sub-agents, skill runs and doc files pass through the `.catch` fallback after the guard ran (engine-documented next.called pattern), not by being decided before code that can fail. Outcome unchanged and tested.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
1. model-router suite green, with the new fail-closed tests.
|
||||
CHECK: cd /home/bchanot/Documents/claude && PATH=$HOME/.bun/bin:$PATH claude plugin test mods/model-router </dev/null 2>&1 | grep -cE '(^| )0 fail'
|
||||
EXPECT: 1
|
||||
EVIDENCE: MET exit=0 marker-found :: 1
|
||||
2. Full make test green.
|
||||
CHECK: cd /home/bchanot/Documents/claude && PATH=$HOME/.bun/bin:$PATH make test </dev/null 2>&1 | tail -1
|
||||
EXPECT: all suites green
|
||||
EVIDENCE: MET exit=0 marker-found :: all suites green
|
||||
3. The deny tests (main Write, Edit, NotebookEdit held when session.root fails) and the isError-latch test fail on the pre-change register.ts; the doc, sub-agent, in-run and exit tests pass after the change; type-check clean if the repo has one for mods; lines ≤ 80 columns in the touched files (manual).
|
||||
|
||||
## FILE SCOPE
|
||||
mods/model-router/hooks/register.ts (guard region ~:4397-4465 and its comment, Skill handler latch predicate ~:4577), mods/model-router/hooks/register.test.ts (rig World type and session.root mock ~:40-212, GUARD section ~:7288-7470).
|
||||
@@ -6,7 +6,7 @@
|
||||
- [x] A3 DONE 87aecc1 (docs 038670e, residuals BUGS-FOUND 07f9a7f). /bugfix memory_index rc 0 on unreadable/non-regular blockers.md → digest `- open: none` (4c digest defect, BUGS-FOUND:87): non-zero rc → `- open: unknown`; SD9b/SD9c re-pinned.
|
||||
- [x] A4 DONE e0311f4 (tests strengthened in same commit, CHANGELOG eb801b7, residuals BUGS-FOUND 074cdde). memory.sh `check --staged`: new entry ID = max+1 (4a ask TODO:170; today comment "gap harmless" :162).
|
||||
- [x] A5 DONE b9f2d81. memory.test.sh T18 hard-fails without bun on PATH → SKIP line like other bun-gated tests.
|
||||
- A6 (user choice) routing guard fail mode (phase 2 shared rule "guards fail closed"; today fail-open).
|
||||
- [x] A6 DONE 859e504 (docs e8598df, BDR-136 amended). (user choice) routing guard fail mode (phase 2 shared rule "guards fail closed"; today fail-open).
|
||||
|
||||
## Batch B — measurements and live proofs (run by me headless where possible)
|
||||
- B1 /context delta never recorded for 4a, 5, 2, 4b-4d: headless pair method (LRN-270 caveat) with/without each phase's lever where reproducible; else a recorded "not measured" with bracketing figures.
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
# PLAN — guard-fail-closed (BDR-125 gap audit A6)
|
||||
|
||||
## CONTEXT
|
||||
- mods/model-router/hooks/register.ts ~:4397-4465. `guardWrite($, st, e)`
|
||||
awaits `ensureConfig` first, then checks `st.off`, `e.agentId`,
|
||||
`inRun(st)`, then `writtenPath` and `isFreePath(path, await
|
||||
$.session.root())`. `registerGuard` registers three `tool.call` handlers
|
||||
(Edit, Write, NotebookEdit): `guardWrite` true → `{ deny: GUARD_REASON }`,
|
||||
else `next(e)`; each `.catch(($, e, next) => { warnOnce(...); return
|
||||
next(e) })` fails open for ANY error, the guard's own or the downstream
|
||||
tool's.
|
||||
- Comment above (~:4402) says "Fail-open like every hook here".
|
||||
- `errWord(err)` (~:367) = the log-safe error kind. `warnOnce(st, $, hook,
|
||||
kind)` (~:1092) logs once per hook key with the fixed tail "routing
|
||||
skipped for this event".
|
||||
- Tests: register.test.ts GUARD section (~:7288-7470), helpers
|
||||
`guardRig`, `write`, `denied`, constant `GUARD`.
|
||||
|
||||
## APPROACH
|
||||
1. Reorder `guardWrite` so the cheap, infallible checks come first and the
|
||||
code that can fail is reached only for a main-loop out-of-run write:
|
||||
`if (e.agentId !== undefined || inRun(st)) return false` →
|
||||
`const path = writtenPath(e); if (path === undefined) return false` →
|
||||
`if (DOC_FILE.test(path) && !dotDot(path)) return false` is NOT added
|
||||
separately: instead split `isFreePath` so the doc-file test runs before
|
||||
`$.session.root()` is awaited (the `/../` rejection stays first, as
|
||||
today) → `await ensureConfig($, st)` → `if (st.off) return false` →
|
||||
`return !isFreePath(path, await $.session.root())`.
|
||||
Result for every input the guard decided before: unchanged (same
|
||||
predicates, same outcome; only order differs; ensureConfig is an
|
||||
idempotent lazy load that every other hook also calls).
|
||||
2. Fail closed on the guard's own failure only: each handler wraps the
|
||||
`guardWrite` call, not `next(e)`:
|
||||
```
|
||||
let held: boolean
|
||||
try { held = await guardWrite($, st, e) } catch (err) {
|
||||
return guardFailed($, st, '<Tool> guard', err)
|
||||
}
|
||||
if (held) return { deny: GUARD_REASON } as never
|
||||
return next(e)
|
||||
```
|
||||
Factor the three identical handlers into one helper
|
||||
`guardHandler(tool)` returning the handler, so the try/catch exists
|
||||
once (the file already repeats the block three times; one helper is
|
||||
the minimum that keeps the new logic in one place).
|
||||
`guardFailed` logs once per hook key via the existing `warnOnce`
|
||||
mechanism (new optional 5th param `effect`, default `'routing skipped
|
||||
for this event'`; the guard passes `'write held'`) and returns
|
||||
`{ deny: GUARD_FAIL(errWord(err)) }` where
|
||||
`GUARD_FAIL = (kind) => 'model-router: the write guard failed (' + kind
|
||||
+ '), so this write is held. Enter /hotfix, /feat, /bugfix or ' +
|
||||
'/ship-feature, or re-enter the skill you were running, then make ' +
|
||||
'this edit.'` (exact user-chosen text).
|
||||
3. The existing `.catch(... warnOnce; return next(e))` stays for errors
|
||||
thrown by `next(e)` (downstream tool): today's behavior, untouched.
|
||||
4. Comment above the guard: replace "Fail-open like every hook here" with
|
||||
one sentence: the guard's own failure holds a main-loop code write
|
||||
(fail closed, BDR-125 phase 2 rule); sub-agents, skill runs and doc
|
||||
files never reach the code that can fail; a downstream tool error
|
||||
passes through as before.
|
||||
|
||||
## EDGE CASES
|
||||
- `ensureConfig` throws (config read error) on a main-loop code write
|
||||
outside a run → denied with GUARD_FAIL. Same write inside a skill run or
|
||||
from a sub-agent → allowed (never reaches ensureConfig).
|
||||
- `$.session.root()` throws → a `.md`/`.txt` path still passes (doc test
|
||||
runs first); any other path → denied.
|
||||
- A path with `/../` → not free (unchanged), reaches root().
|
||||
- `st.off` (mod off) → allowed, but only once ensureConfig succeeded; if
|
||||
config cannot be read the mod's off state is unknown → held (fail
|
||||
closed). Entering a skill still writes.
|
||||
- warnOnce dedupe: one log line per tool key per session, as today.
|
||||
|
||||
## TESTS (register.test.ts, GUARD section)
|
||||
Make a guard step throw in the rig (e.g. a `$.session.root` that throws,
|
||||
or a config read that throws; use whatever the rig already offers to
|
||||
inject failures, read neighbouring tests for the idiom):
|
||||
- GUARD fail-closed: root() throws, main code write → deny contains
|
||||
"the write guard failed (" and "so this write is held".
|
||||
- GUARD fail-closed: root() throws, `README.md` write → not denied.
|
||||
- GUARD fail-closed: root() throws, sub-agent write (`agentId` set) → not
|
||||
denied.
|
||||
- GUARD fail-closed: root() throws, inside a skill run (latch opened as
|
||||
the existing "a typed skill opens it" test does) → not denied.
|
||||
- GUARD fail-closed: Edit and NotebookEdit get the same deny.
|
||||
- Downstream error untouched: a bottom `tool.call` handler that throws
|
||||
for a free path → the error behaves as before (not converted to the
|
||||
GUARD_FAIL deny).
|
||||
- Existing GUARD tests stay green unchanged.
|
||||
The fail-closed tests must fail on the pre-change register.ts.
|
||||
|
||||
## DISPOSITION
|
||||
Honors BDR-125 (phase 2 shared rule: guards fail closed) and follows
|
||||
BDR-112's precedent (push-guard text-only deny, fail closed). Honors the
|
||||
model-router CLAUDE.md doctrine (main loop writes no code outside a skill
|
||||
run): entering a skill stays the way out when the guard fails.
|
||||
|
||||
## FILES
|
||||
mods/model-router/hooks/register.ts, mods/model-router/hooks/register.test.ts.
|
||||
|
||||
## r2 (challenge r1: correctness CONCERNS(2), robustness CONCERNS(1), simplicity CONCERNS(1)) — SUPERSEDES APPROACH, EDGE CASES and TESTS above
|
||||
Landed: (a) when ensureConfig throws, every latch hook (Skill tool.call
|
||||
:4566, skill.prompt :4588, prompt.submit :4899, /route) also fails before
|
||||
latching, so "enter a skill" led nowhere (robustness 1); (b) config READ
|
||||
errors never throw (readLayer/readOverride catch; an unreadable override at
|
||||
first load turns the router off → write passes): the r1 edge case was false
|
||||
(correctness 2); the real throw sources are `$.session.root()` and a raw
|
||||
`$.ui.log` in reloadConfig (:2139) / registerTool's catch (:3612);
|
||||
(c) guardHandler + guardFailed + a warnOnce 5th param were heavier than
|
||||
needed (simplicity 1-2); (d) moving ensureConfig later dropped the lazy
|
||||
load other hooks rely on after /reload-plugins (robustness 2); (e) shared
|
||||
warnOnce key with the downstream .catch (robustness 3, correctness 5);
|
||||
(f) the rig cannot make session.root fail (correctness 1); (g) BDR-136
|
||||
point 4 records the guard as fail-open (correctness 7).
|
||||
|
||||
1. `guardWrite($, st, e): Promise<string | undefined>` returns the deny
|
||||
text, undefined = allow. Order:
|
||||
a. `let cfgErr: unknown; try { await ensureConfig($, st) } catch (err)
|
||||
{ cfgErr = err ?? 'error' }` — the lazy load still runs on every
|
||||
write, as today (keeps other hooks' first load after
|
||||
/reload-plugins).
|
||||
b. `e.agentId !== undefined || inRun(st)` → undefined.
|
||||
c. `path = writtenPath(e)`; undefined → undefined.
|
||||
d. root-free check, new function `freeWithoutRoot(path): boolean |
|
||||
undefined`: `/../` or trailing `/..` → false (not free, keep
|
||||
going); DOC_FILE → true (allow, return undefined); else undefined
|
||||
(needs the root).
|
||||
e. `cfgErr !== undefined` → `heldBy(st, $, cfgErr)`.
|
||||
f. `st.off` → undefined.
|
||||
g. `let root; try { root = await $.session.root() } catch (err) {
|
||||
return heldBy(st, $, err) }`.
|
||||
h. root-dependent check, `isFreePath(path, root)` reduced to the tree
|
||||
test only (`startsWith(root/)`, `.claude/` minus
|
||||
`.claude/worktrees/`, `docs/`); the `/../` rejection stays in front
|
||||
of it via step d (a `docs/../src/a.ts` path is never free).
|
||||
Not free → `GUARD_REASON`; free → undefined.
|
||||
`heldBy(st, $, err)`: `warnOnce(st, $, 'write guard', errWord(err))`
|
||||
(unchanged warnOnce, own key 'write guard', distinct from the
|
||||
'<Tool> guard' keys of the .catch blocks) and returns
|
||||
`GUARD_FAIL(errWord(err))`, `GUARD_FAIL` = the user-chosen text
|
||||
verbatim with the kind spliced in.
|
||||
Handlers change by one line each: `const deny = await guardWrite($,
|
||||
st, e); if (deny !== undefined) return { deny } as never; return
|
||||
next(e)`. The three `.catch` blocks stay as they are (downstream tool
|
||||
errors: unchanged behavior). No handler factory, warnOnce untouched.
|
||||
2. The exit always works:
|
||||
- reloadConfig's `log` (:2139) and registerTool's catch log (:3612)
|
||||
go through the existing `tryLog` so a failing ui.log can no longer
|
||||
abort the config load.
|
||||
- Skill tool.call `.catch` (:~4583): after `const out = await next(e)`,
|
||||
latch like the main handler does: main loop (`e.agentId ===
|
||||
undefined`) and `out` not a deny → `st.skillRun = true`; return out.
|
||||
- skill.prompt `.catch` (:~4598): `if (typedPath(st, e.skill) !==
|
||||
undefined) st.skillRun = true` before `return next(e)` (typedPath is
|
||||
config-independent; it reads typedSlash/promptAllowed/loops).
|
||||
3. Comment above the guard (:~4402) replaces "Fail-open like every hook
|
||||
here": the guard's own failure (session.root, a config load that
|
||||
throws) holds a main-loop code write outside a skill run (fail closed,
|
||||
BDR-125 phase 2 rule, amends BDR-136 (4)); sub-agents, skill runs and
|
||||
doc files are decided before anything that can fail; entering a skill
|
||||
latches even when the config load failed; a downstream tool error
|
||||
passes through the .catch as before.
|
||||
|
||||
EDGE CASES (real behavior):
|
||||
- Unreadable or broken routing.json / override: no throw; first load with
|
||||
an unreadable override → router off → write passes (unchanged).
|
||||
- session.root throws: doc file passes, sub-agent passes, in-run passes,
|
||||
main code write outside a run → GUARD_FAIL deny.
|
||||
- ensureConfig throws (residual, after tryLog): same as above for main
|
||||
code writes; a model Skill call or a typed skill still latches through
|
||||
the .catch paths, then writes pass.
|
||||
- `/../` paths: never free (unchanged), held or redirected.
|
||||
|
||||
TESTS (register.test.ts):
|
||||
- Rig: World gains `root?: 'fail'` (pattern of `repo: 'fail'`); the
|
||||
session.root mock (:209) reads `w.root` per call and throws when
|
||||
'fail', so a test flips it after boot. FILE SCOPE widened to the rig
|
||||
lines.
|
||||
- Red-first (fail on the pre-change code): root fails → main code Write
|
||||
denied with text containing "the write guard failed (" and "so this
|
||||
write is held"; same for Edit and NotebookEdit (one test, as :7423).
|
||||
- Regression guards (pass before and after): root fails → README.md
|
||||
write passes; sub-agent write passes; in-run write (typed skill latch,
|
||||
as :7347) passes.
|
||||
- Exit test: root fails → main code write held → a model Skill call
|
||||
(the existing "model-loaded skill opens it" idiom, :7366) → the same
|
||||
write passes.
|
||||
- If the rig can make ensureConfig throw (e.g. an unrecorded ui.log on a
|
||||
warning config at first load with st.loaded false), add: write held,
|
||||
then a model Skill call, then the write passes. If it cannot, say so in
|
||||
the report with the reason; do not invent a rig path beyond the World
|
||||
`root` knob.
|
||||
- No downstream-error test (behavior unchanged, re-run semantics already
|
||||
pinned at :6403).
|
||||
- Existing GUARD tests unchanged and green.
|
||||
|
||||
CAPITALIZE (closing step, not the executor): BDR-136 status line through
|
||||
`memory.sh status` naming the amendment of point (4).
|
||||
FILES: mods/model-router/hooks/register.ts,
|
||||
mods/model-router/hooks/register.test.ts.
|
||||
|
||||
## r3 (re-challenge r2: correctness CONCERNS(2 MAJOR), robustness CONCERNS(1 MAJOR)) — SUPERSEDES r2 §1-3, EDGE CASES and TESTS
|
||||
Landed: (a) after tryLog no known source makes ensureConfig throw: the
|
||||
cfgErr hold and both new .catch latches had no reachable trigger and no
|
||||
test; the skill.prompt latch could not fire in its target state (prompt
|
||||
.submit fails before noteTyped) (corr 1-2, rob 3); (b) the engine API
|
||||
documents the guard pattern: `.catch(($, e, next) => next.called ? next(e)
|
||||
: { deny })` (claude-code.d.ts tool.call remark ~:4744-4747; Caught
|
||||
~:1500-1511: when `called`, next(e) replays the settled result, nothing
|
||||
beneath runs again) — it covers EVERY guard-own failure, not two sources
|
||||
(corr 7, rob 4); (c) pre-existing latch hole: a Skill call the engine
|
||||
refused or that failed returns `isError` with no `deny` key (BDR-137), yet
|
||||
the main latch (:4577-4579) opens the guard for the session (rob 1; the
|
||||
memory mod already tests both, mods/memory/hooks/register.ts:1441);
|
||||
(d) warnOnce's fixed tail says "routing skipped" on a held write (corr 6,
|
||||
rob 5).
|
||||
|
||||
1. `guardWrite` and `isFreePath`: UNCHANGED (order, ensureConfig first,
|
||||
lazy load kept, `/../` handling kept). No tryLog change, no latch in
|
||||
any .catch, no prompt.submit change.
|
||||
2. The three guard `.catch` blocks (Edit, Write, NotebookEdit) call one
|
||||
new helper `guardCaught(st, $, e, next, hook)`:
|
||||
- `next.called` → `warnOnce(st, $, hook, next.error.kind); return
|
||||
next(e)` (downstream tool error: exactly today's behavior, replayed,
|
||||
nothing re-run).
|
||||
- not called (the guard itself failed): if `e.agentId !== undefined ||
|
||||
inRun(st)` or the write is a doc file (`writtenPath(e)` undefined, or
|
||||
DOC_FILE matches and the path has no `/../` and does not end in
|
||||
`/..`) → `warnOnce(st, $, hook, next.error.kind); return next(e)`
|
||||
(writes the guard never holds still pass).
|
||||
- else → log once per session through `tryLog` under the
|
||||
`st.warned` key `'write guard held'`: `model-router: write guard
|
||||
failed (<kind>): main-loop code writes are held until a skill runs`;
|
||||
return `{ deny: GUARD_FAIL(next.error.kind) }` with GUARD_FAIL = the
|
||||
user-chosen text verbatim, kind spliced in. A `.claude/` or `docs/`
|
||||
path is held too in this branch (the root is unknown when the guard
|
||||
failed: it could not decide).
|
||||
Type `next` as the engine's `Next & Caught` (or what the handler's
|
||||
inferred type is); no new dependency.
|
||||
3. Latch predicate fix (pre-existing hole, in scope per the user's
|
||||
"fill every gap found" instruction for this run): the Skill handler's
|
||||
`refused` (:~4577) = not a successful output: `typeof out !== 'object'
|
||||
|| out === null || 'deny' in out || (out as { isError?: unknown })
|
||||
.isError === true`; latch only when main loop and not refused.
|
||||
4. Comment above the guard: replace "Fail-open like every hook here" with:
|
||||
the guard's own failure holds a main-loop code write outside a skill
|
||||
run (fail closed via `next.called`, BDR-125 phase 2 rule, amends
|
||||
BDR-136 (4)); sub-agents, skill runs and doc files still pass; a
|
||||
downstream tool error is replayed as before. Residual (one line): if
|
||||
the config load itself threw, only a model Skill call can latch (no
|
||||
known throw source today).
|
||||
|
||||
TESTS (register.test.ts):
|
||||
- Rig: World gains `root?: 'fail'` (pattern of `repo: 'fail'`); the
|
||||
session.root mock (:209) reads `w.root` per call and throws when
|
||||
'fail'. Flip it after boot.
|
||||
- Red-first: root fails → main code Write, Edit and NotebookEdit each
|
||||
denied with text containing "the write guard failed (" and "so this
|
||||
write is held" (one test, as :7423).
|
||||
- Regression guards: root fails → README.md write passes; sub-agent write
|
||||
passes; in-run write (typed-skill latch, as :7347) passes.
|
||||
- Exit: root fails → main code write held → model Skill call (idiom
|
||||
:7366) → same write passes.
|
||||
- Latch hole, red-first: a Skill bottom returning `{ isError: true, ... }`
|
||||
(shape per the kit; read :7450-7471 for the deny variant) → a later
|
||||
main code write is still redirected with GUARD.
|
||||
- Existing GUARD tests unchanged and green; full suite green.
|
||||
FILES unchanged (register.ts, register.test.ts incl. rig lines).
|
||||
+3
-1
@@ -18,6 +18,7 @@ The BDR-125 context queue is delivered: phases 0, 0b, 4a, 1, 5, 2 and 4b-4d ship
|
||||
- **model-router**: the `fable` alias, head of the best tier, resolves to `claude-fable-5-2` (was `claude-fable-5-1`); every best-tier phase, row and skill pin naming `fable` follows. Kit tests updated.
|
||||
- **memory feedback**: precision, trigger precision and the miss share count only rows after the gate-1 fix (merge 2026-11-12T19:53:59Z); their actions wait for 20 post-fix asks (`Post-fix prompt asks: k/20` in FEEDBACK.md, one `NEW: post-fix prompt sample reached` line) and the session reminder keeps prompting until then. The third-pick signal is retired (recall keeps 2 picks). The reader holds one parsed transcript at a time; `labels.tsv` rows and `state.json` are validated on read.
|
||||
- **memory commit chokepoint**: `lib/memory.sh check --staged`, run by `lib/memory-commit.sh commit` before every memory commit (rc 6, registry unstaged), also refuses a staged v2 registry whose new `## ` entry does not carry the next free ID: the highest ID seen at any heading level, fenced or not, in HEAD and above the entry in the staged file, plus one, the same reading `add` uses. stderr: `memory: <file>:<line>: new entry <ID> is not the next free ID <PREFIX>-NNN`. A committed ID is never renamed: fix the uncommitted heading and every uncommitted mention of its ID (the `superseded by` line from `add --supersedes`, the journal line), or drop the new entry and re-add it with `memory.sh add`. Skipped when the registry is absent from HEAD, HEAD is v1 (an `upgrade` commit), HEAD has an open code fence, or HEAD has no well-formed `## ` entry. Tests: `lib/tests/memory.test.sh`.
|
||||
- **model-router write guard fails closed**: when the guard's own check throws or times out, a main-loop Edit, Write or NotebookEdit of a code file outside a skill run is held with `model-router: the write guard failed (<kind>), so this write is held. Enter /hotfix, /feat, /bugfix or /ship-feature, or re-enter the skill you were running, then make this edit.` One log line per session: `model-router: write guard failed (<kind>): main-loop code writes are held until a skill runs`. Sub-agents, skill runs (typed, model-declared phase, typed `/route`) and `.md` / `.txt` files still pass; an error raised by a downstream tool is replayed as before. The guard used to let the write through on its own failure. Tests: `mods/model-router/hooks/register.test.ts` (GUARD: a failing guard …).
|
||||
|
||||
### Removed
|
||||
- `hooks/design-toolchain-reminder.sh`, its `UserPromptSubmit` entry in `settings.json` (`ctx7-reminder` stays the only one) and its suite `lib/tests/design-toolchain-reminder.test.sh`. Measured 2026-10-31: 59 fires, 0 Reads of `rules/web-building.md`. Design routing stays with the `rules/web-building.md` path rule and the `CLAUDE.global.md` pointer. The fire log `~/.claude/logs/design-toolchain-fires.log` is left in place.
|
||||
@@ -35,7 +36,8 @@ The BDR-125 context queue is delivered: phases 0, 0b, 4a, 1, 5, 2 and 4b-4d ship
|
||||
- `hooks/session-start.sh`: the memory digest prints `- open: none` when no blocker is open and `- open: unknown (memory.sh index failed)` when `memory.sh index blocker` fails or times out. Both cases used to print no blocker line, so a failed read looked like a clean slate. `lib/profile-state.jq` (`profile.sh current --plain`): a newline or CR in a printed value becomes a space, and a plugin id that does not match `\A[A-Za-z0-9._-]+@[A-Za-z0-9._-]+\z` is dropped, so a settings value can no longer forge a `plugin:` line. Tests: `lib/tests/session-digest.test.sh` SD9a-SD9d, SD12; `lib/tests/profile.test.sh` T28.
|
||||
- doctor.sh: the user-scope residue check compares `enabledPlugins` and `skillOverrides` between HEAD and the working `settings.json` (it compared `enabledPlugins` only), so a UI write into user-scope `skillOverrides` that dirties the tracked file is now reported; the pass and skip lines name both keys. MIGRATION "Profiles and packs" step 1 restores both keys.
|
||||
- Agents and skills (77041e5): client-handover reads the project root through a quoted heredoc and refuses a root with control characters; `lib/plugin-gate.md` prints single-quoted remedies, never runs an unsafe root, checks against the git common dir and refuses `$HOME` (as `lib/profile.sh` now does); plugin-advisor recommends `minimal` only from project signals; onboard and tour use the packs vocabulary; graphify labels match the install trap.
|
||||
- `mods/` type-check under `claude plugin validate --strict` (CLI 2.1.323 started type-checking mods): 17 sites narrowed, guards stay fail-open (6433e4d, BLK-049).
|
||||
- `mods/` type-check under `claude plugin validate --strict` (CLI 2.1.323 started type-checking mods): 17 sites narrowed, failure behaviour unchanged (6433e4d, BLK-049); the write guard has since moved to fail-closed (see Changed).
|
||||
- model-router: a Skill call whose answer carries `isError` (refused or unknown skill) no longer opens the write guard for the rest of the session. Test: `mods/model-router/hooks/register.test.ts` (GUARD: an isError Skill answer leaves the latch closed).
|
||||
|
||||
## [3.0.0] — 2026-11-12
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ effort, never version. Transcript audit `python3 lib/effort-audit.py`.
|
||||
|
||||
- Main loop: every request gets the route in force. A typed skill with a row routes the main loop to it; a best-tier row (`plan`, `reflect`, `orchestrate`, `escalate`; `audit` is an agent row, never typed) holds across turns in a run slot until `/route clear`, `/route off`, a user `/model` (typed with a name, bare, 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.
|
||||
- Write guard: a main-loop Edit, Write or NotebookEdit of a code file is redirected with "model-router: code is written inside a skill run…" until a skill ran on the main loop in the session (typed or loaded by the model), a phase was declared this turn, or a typed `/route` holds. Free paths: `.md`, `.txt`, the project's `.claude/` except `worktrees/`, and `docs/`. Sub-agents write freely. `/route clear`, `/route off` and `/clear` re-arm the guard; `/route off` also turns it off, and `"enabled": false` in `~/.claude/model-router.json` turns the router and the guard off. A `/model` hand pick does not open it, and a `register.ts` reload resets it.
|
||||
- Write guard: a main-loop Edit, Write or NotebookEdit of a code file is redirected with "model-router: code is written inside a skill run…" until a skill ran on the main loop in the session (typed or loaded by the model; a refused or unknown skill does not count), a phase was declared this turn, or a typed `/route` holds. Free paths: `.md`, `.txt`, the project's `.claude/` except `worktrees/`, and `docs/`. Sub-agents write freely. If the guard's own check fails (throw or timeout), it holds such a write instead of letting it through, with "model-router: the write guard failed (<kind>), so this write is held…", logged once per session; sub-agents, a skill run, a declared phase or a typed `/route`, and `.md` / `.txt` files still pass, and an error raised by the tool itself is passed on unchanged. `/route clear`, `/route off` and `/clear` re-arm the guard; `/route off` also turns it off, and `"enabled": false` in `~/.claude/model-router.json` turns the router and the guard off. A `/model` hand pick does not open it, and a `register.ts` reload resets 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 bare `/model` opens the router's model, variant and scope dialog: fable, opus or sonnet, then Standard or `[1m]`, then the scope, the current model included; `Other model (native picker)` opens the native picker (haiku goes through it or `/model haiku`) and Esc changes nothing. A pick while another dialog is open is refused with `answer the open dialog first`. The picker's Default, 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.
|
||||
|
||||
@@ -202,7 +202,7 @@ 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 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
|
||||
|
||||
Garde d'écriture : un Edit, Write ou NotebookEdit d'un fichier de code par la boucle principale est redirigé avec « model-router: code is written inside a skill run… » tant qu'aucun skill n'a tourné sur la boucle principale dans la session (tapé ou chargé par le modèle), qu'aucune phase n'a été déclarée ce tour, et qu'aucun `/route` tapé ne tient. Chemins libres : `.md`, `.txt`, le `.claude/` du projet sauf `worktrees/`, et `docs/`. Les sous-agents écrivent librement. `/route clear`, `/route off` et `/clear` réarment le garde ; `/route off` le coupe aussi, et `"enabled": false` dans `~/.claude/model-router.json` coupe le routeur et le garde. Un choix à la main avec `/model` ne l'ouvre pas, et un rechargement de `register.ts` le remet à zéro.
|
||||
Garde d'écriture : un Edit, Write ou NotebookEdit d'un fichier de code par la boucle principale est redirigé avec « model-router: code is written inside a skill run… » tant qu'aucun skill n'a tourné sur la boucle principale dans la session (tapé ou chargé par le modèle ; un skill refusé ou inconnu ne compte pas), qu'aucune phase n'a été déclarée ce tour, et qu'aucun `/route` tapé ne tient. Chemins libres : `.md`, `.txt`, le `.claude/` du projet sauf `worktrees/`, et `docs/`. Les sous-agents écrivent librement. Si la vérification du garde échoue elle-même (exception ou délai dépassé), l'écriture est retenue au lieu de passer, avec « model-router: the write guard failed (<kind>), so this write is held… », journalisé une fois par session ; les sous-agents, un skill en cours, une phase déclarée ou un `/route` tapé, et les fichiers `.md` / `.txt` passent toujours, et une erreur levée par l'outil lui-même est transmise telle quelle. `/route clear`, `/route off` et `/clear` réarment le garde ; `/route off` le coupe aussi, et `"enabled": false` dans `~/.claude/model-router.json` coupe le routeur et le garde. Un choix à la main avec `/model` ne l'ouvre pas, et un rechargement de `register.ts` le remet à zéro.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ type World = {
|
||||
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'
|
||||
root: 'fail' | undefined // session.root throws (the guard's own failure)
|
||||
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, {
|
||||
@@ -146,6 +147,7 @@ function newWorld(fx: Fixture = {}): World {
|
||||
onAsk: undefined,
|
||||
onWrite: undefined,
|
||||
repo: fx.repo === undefined ? { root: ROOT, remote: REMOTE } : fx.repo,
|
||||
root: undefined,
|
||||
env: fx.noHome ? undefined : HOME,
|
||||
kinds: new Map(),
|
||||
dirs: new Map(),
|
||||
@@ -206,7 +208,10 @@ function installWorld(on: On, w: World): void {
|
||||
return { value: text }
|
||||
})
|
||||
installWrite(on, w)
|
||||
on('session.root', () => ({ value: ROOT }))
|
||||
on('session.root', () => {
|
||||
if (w.root === 'fail') throw new Error('no root')
|
||||
return { value: ROOT }
|
||||
})
|
||||
on('session.surfaces', () => ({ value: w.surfaces as never }))
|
||||
on('session.repo', () => {
|
||||
if (w.repo === 'fail') throw new Error('no repo')
|
||||
@@ -7469,3 +7474,79 @@ test('GUARD: a denied Skill answer leaves the latch closed', async (
|
||||
await $.tool.call({ tool: 'Skill', skill: 'diagram' } as never)
|
||||
expect(denied(await write($, `${ROOT}/src/a.ts`))).toContain(GUARD)
|
||||
})
|
||||
|
||||
// the guard's own failure (session.root throws) holds a main code write
|
||||
|
||||
const HELD = 'the write guard failed ('
|
||||
|
||||
const rootFails = async ($: Engine, on: On) => {
|
||||
const w = newWorld()
|
||||
await guardRig($, on, w)
|
||||
w.root = 'fail'
|
||||
return w
|
||||
}
|
||||
|
||||
test('GUARD: a failing guard holds Write, Edit and NotebookEdit', async (
|
||||
$, on) => {
|
||||
await rootFails($, on)
|
||||
const nb = await $.tool.call({ tool: 'NotebookEdit',
|
||||
notebook_path: `${ROOT}/n.ipynb`, new_source: 'x' } as never)
|
||||
const ed = await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/a.py`,
|
||||
old_string: 'a', new_string: 'b' } as never)
|
||||
for (const out of [await write($, `${ROOT}/src/a.ts`), ed, nb]) {
|
||||
expect(denied(out)).toContain(HELD)
|
||||
expect(denied(out)).toContain('so this write is held')
|
||||
}
|
||||
})
|
||||
|
||||
test('GUARD: a failing guard still passes docs and sub-agents', async (
|
||||
$, on) => {
|
||||
await rootFails($, on)
|
||||
expect(denied(await write($, `${ROOT}/README.md`))).toBe('')
|
||||
expect(denied(await write($, `${ROOT}/src/a.ts`, { agentId: 'a1' })))
|
||||
.toBe('')
|
||||
})
|
||||
|
||||
test('GUARD: a failing guard still passes an in-run write', async (
|
||||
$, on) => {
|
||||
const w = await rootFails($, on)
|
||||
w.root = undefined
|
||||
await typeFeat($)
|
||||
await endTurn($)
|
||||
w.root = 'fail'
|
||||
expect(denied(await write($, `${ROOT}/src/a.ts`))).toBe('')
|
||||
})
|
||||
|
||||
test('GUARD: a downstream tool failure is never turned into a hold', async (
|
||||
$, on) => {
|
||||
on('tool.call', { tool: 'Write' }, () => {
|
||||
throw new Error('disk full')
|
||||
})
|
||||
await bootRun($, on, OPUS, newWorld())
|
||||
const out = await $.tool.call({ tool: 'Write',
|
||||
file_path: `${ROOT}/README.md`, content: 'x' } as never)
|
||||
.catch((err: unknown) => ({ thrown: String(err) }))
|
||||
expect(denied(out)).not.toContain(HELD)
|
||||
expect(JSON.stringify(out)).not.toContain(HELD)
|
||||
// the kit rejects with HooksError ("no implementation for tool.call")
|
||||
expect((out as { thrown?: string }).thrown).toContain('HooksError')
|
||||
})
|
||||
|
||||
test('GUARD: a model Skill call frees a held write', async ($, on) => {
|
||||
await rootFails($, on)
|
||||
expect(denied(await write($, `${ROOT}/src/a.ts`))).toContain(HELD)
|
||||
await $.tool.call({ tool: 'Skill', skill: 'diagram' } as never)
|
||||
expect(denied(await write($, `${ROOT}/src/a.ts`))).toBe('')
|
||||
})
|
||||
|
||||
test('GUARD: an isError Skill answer leaves the latch closed', async (
|
||||
$, on) => {
|
||||
on('tool.call', { tool: 'Skill' }, () => ({
|
||||
result: { success: false } as never, isError: true,
|
||||
text: 'unknown skill',
|
||||
}) as never)
|
||||
writeBottoms(on)
|
||||
await bootRig($, on, OPUS, 1000, newWorld())
|
||||
await $.tool.call({ tool: 'Skill', skill: 'diagram' } as never)
|
||||
expect(denied(await write($, `${ROOT}/src/a.ts`))).toContain(GUARD)
|
||||
})
|
||||
@@ -4399,15 +4399,25 @@ async function onModelSwitch($: Api, st: State, e: SwitchIn): Promise<void> {
|
||||
// A main-loop Edit/Write/NotebookEdit of a code file is redirected until a
|
||||
// skill ran on main this session, a phase was declared this turn, or a typed
|
||||
// /route holds. Docs, <root>/.claude/ (worktrees excepted), <root>/docs/ and
|
||||
// sub-agents pass. Fail-open like every hook here. Limit: an unrowed typed
|
||||
// skill latches through the typed-fallback path (typedPath) only when no
|
||||
// sub-agent is live; the model's own Skill call latches it anyway.
|
||||
// sub-agents pass. The guard's own failure holds a main-loop code write
|
||||
// outside a skill run (fail closed via next.called, BDR-125 phase 2 rule,
|
||||
// amends BDR-136 (4)); sub-agents, skill runs and doc files still pass; a
|
||||
// downstream tool error is replayed as before. Residual: if the config load
|
||||
// keeps throwing, nothing latches in-session, so main-loop code writes stay
|
||||
// held while sub-agents (skill executors) still write; no throw source known.
|
||||
// Limit: an unrowed typed skill latches through the typed-fallback path
|
||||
// (typedPath) only when no sub-agent is live; the model's own Skill call
|
||||
// latches it anyway.
|
||||
|
||||
const DOC_FILE = /\.(md|txt)$/i
|
||||
const GUARD_REASON = 'model-router: code is written inside a skill run. ' +
|
||||
'Enter /hotfix (≤2 files, obvious fix), /feat, /bugfix or /ship-feature, ' +
|
||||
'or re-enter the skill you were running, then make this edit. This is a ' +
|
||||
'redirect, not a refusal.'
|
||||
const GUARD_FAIL = (kind: string): string =>
|
||||
`model-router: the write guard failed (${kind}), so this write is held. ` +
|
||||
'Enter /hotfix, /feat, /bugfix or /ship-feature, or re-enter the skill ' +
|
||||
'you were running, then make this edit.'
|
||||
|
||||
/** The path a write tool targets, from its own argument name. */
|
||||
function writtenPath(e: Rec): string | undefined {
|
||||
@@ -4439,28 +4449,52 @@ async function guardWrite($: Api, st: State, e: Rec): Promise<boolean> {
|
||||
return path !== undefined && !isFreePath(path, await $.session.root())
|
||||
}
|
||||
|
||||
type GuardNext = ((e: never) => unknown) & {
|
||||
readonly called: boolean
|
||||
readonly error: { readonly kind: string }
|
||||
}
|
||||
|
||||
/** Writes the guard never holds: sub-agents, skill runs, doc files. */
|
||||
function guardPasses(st: State, e: Rec): boolean {
|
||||
const path = writtenPath(e)
|
||||
const doc = path === undefined ||
|
||||
(DOC_FILE.test(path) && !path.includes('/../') && !path.endsWith('/..'))
|
||||
return e.agentId !== undefined || inRun(st) || doc
|
||||
}
|
||||
|
||||
/** The guard hook failed: replay a downstream error, else hold the write. */
|
||||
function guardCaught(
|
||||
st: State,
|
||||
$: Api,
|
||||
e: Rec,
|
||||
next: GuardNext,
|
||||
hook: string,
|
||||
) {
|
||||
if (next.called || guardPasses(st, e)) {
|
||||
warnOnce(st, $, hook, next.error.kind)
|
||||
return next(e as never) as never
|
||||
}
|
||||
if (!st.warned.has('write guard held')) {
|
||||
st.warned.add('write guard held')
|
||||
tryLog($, `model-router: write guard failed (${next.error.kind}): ` +
|
||||
'main-loop code writes are held until a skill runs')
|
||||
}
|
||||
return { deny: GUARD_FAIL(next.error.kind) } as never
|
||||
}
|
||||
|
||||
function registerGuard(on: On, st: State): void {
|
||||
on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
|
||||
if (await guardWrite($, st, e)) return { deny: GUARD_REASON } as never
|
||||
return next(e)
|
||||
}).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'Edit guard', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
}).catch(($, e, next) => guardCaught(st, $, e, next, 'Edit guard'))
|
||||
on('tool.call', { tool: 'Write' }, async ($, e, next) => {
|
||||
if (await guardWrite($, st, e)) return { deny: GUARD_REASON } as never
|
||||
return next(e)
|
||||
}).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'Write guard', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
}).catch(($, e, next) => guardCaught(st, $, e, next, 'Write guard'))
|
||||
on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
|
||||
if (await guardWrite($, st, e)) return { deny: GUARD_REASON } as never
|
||||
return next(e)
|
||||
}).catch(($, e, next) => {
|
||||
warnOnce(st, $, 'NotebookEdit guard', next.error.kind)
|
||||
return next(e)
|
||||
})
|
||||
}).catch(($, e, next) => guardCaught(st, $, e, next, 'NotebookEdit guard'))
|
||||
}
|
||||
|
||||
// ---- registration ----------------------------------------------------
|
||||
@@ -4574,8 +4608,8 @@ function registerSkills(on: On, st: State): void {
|
||||
await tierAsk($, st, st.turnMain, `Skill /${clean(skill, NAME_CAP)}`)
|
||||
}
|
||||
const out = await next(e)
|
||||
const refused = typeof out === 'object' && out !== null &&
|
||||
'deny' in out
|
||||
const refused = typeof out !== 'object' || out === null ||
|
||||
'deny' in out || (out as { isError?: unknown }).isError === true
|
||||
if (e.agentId === undefined && !refused) st.skillRun = true
|
||||
return out
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user