From fa67664bac2bddfe2800dc55a2fb45a1b4912cfa Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 6 Oct 2026 16:15:10 +0200 Subject: [PATCH 001/547] =?UTF-8?q?chore(memory):=20journal=20=E2=80=94=20?= =?UTF-8?q?release=202.0.0=20cut=20and=20tagged=202026-10-06?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index ccaecb7..92938d7 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -567,3 +567,4 @@ rules: - Reconcile 2026-10-06: TODO:15 + TODO:10 closed (npm soft_deny covers), TODO:892 re-verified open; 6 BLK external/open unchanged; BLK-018 due at the running release. - /prune-memory 2026-10-06: A none, D none; B BLK-019+020 → BLK-028 (merge); C bounded 37 entries ≥9% filler → 37 edited, 1 untouched (LRN-075 all-negation), cuts 1-11% only (negation guard protects "X not Y" lessons); fidelity + index OK. 110 bloated entries left for a later run. - /doc global audit 2026-10-06 (opus): 45 items, 6 docs. Applied 34 (24 AUTO + 9 HUMAN drafts + clone URL → Gitea): README components/slash/flow, Makefile help (11 profiles), USAGE /health→make doctor + GSD 3.0.0, ARCHITECTURE layout, MIGRATION retitled + "Upgrading to 2.0.0", SETTINGS package-install guard, CHANGELOG SemVer + default model + upgrade pointer → c6fb2e4. 10 deferred logged in TODO (LICENSE, Known-residual vs release, README restructure, USAGE narrative, templates/settings.json ask inert). +- Release 2.0.0 cut (user go x3: release, tag push, MIT): bugfix merged 370f35a; develop merged into release/2.0.0 (b47bba7, CHANGELOG conflict resolved: upgrade pointer under [2.0.0]); suite 46/46 green on release; 9ef66e2 MIT LICENSE + README License + Linux residual reworded; gitflow finish by release-executor (BLK-018 did not fire) -> main 4093cca, tag v2.0.0 pushed on user go. Open after release: Linux make test (TODO), make plugin + .env on this machine (BLK-027). From 2fc88304acdc81f9b91ff497b0e41ef315d2e373 Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 6 Oct 2026 17:49:20 +0200 Subject: [PATCH 002/547] feat(gitflow): manual-push mode honoured by the lib, quiet unpushed-guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `gitflow.autopush false` (human-set git config) now means "nothing is pushed" end to end, not only in the post-commit/post-merge hooks: - lib/gitflow.sh: `_gitflow_push_off` is the single reader of GITFLOW_NO_PUSH / gitflow.autopush for the lib's push sites; `start` and `finish` stop pushing in manual mode. `gitflow_delete` checks out the base that contains the branch and drops a lagging upstream before `git branch -d` (LRN-161: `-d` judges against the upstream when set). Skipped remote deletes say `left in place`; `_gitflow_sync_base` replaces the silent `pull --ff-only || true` and warns when a base is behind origin and cannot fast-forward. - hooks/unpushed-guard.sh: manual mode is silent at Stop and gives one `ℹ manual push mode:` line at SessionStart counting every local branch; an unparseable value is named and treated as auto. - CLAUDE.global.md: manual-push mode doctrine, "ahead = defect" scoped to auto mode. - Tests: gitflow-test T18m block (T18m0, T18i-T18o, 7 cases), unpushed-guard T10-T16. Follow-ups (TODO.md): run B push-guard hook + settings deny widening + banner; run C skills that push on their own (/close STEP 5C, …). Do not enable manual mode on the work machine before B and C land. --- CLAUDE.global.md | 12 ++++--- hooks/unpushed-guard.sh | 37 ++++++++++++++++++- lib/gitflow-test.sh | 35 ++++++++++++++++++ lib/gitflow.sh | 61 ++++++++++++++++++++++++++++---- lib/tests/unpushed-guard.test.sh | 38 ++++++++++++++++++++ 5 files changed, 172 insertions(+), 11 deletions(-) diff --git a/CLAUDE.global.md b/CLAUDE.global.md index 8a00c4e..59969d0 100644 --- a/CLAUDE.global.md +++ b/CLAUDE.global.md @@ -183,9 +183,12 @@ auto-pushed upstream). The reference-transaction hook vetoes any deletion or rename of `main`/`develop`. The four hooks run in every repo: `make link` generates `githooks/` and sets the global `core.hooksPath`; a repo that ran `gitflow init` (new/onboarded projects) keeps its own `.githooks/`, -refreshed at session start. Foreign clone: `git config gitflow.protect -false` / `gitflow.autopush false`; `GITFLOW_NO_PUSH=1` only for throwaway -test repos. A branch ahead of its upstream is a defect, not a state. +refreshed at session start. Human-set opt-outs: `git config +gitflow.protect false` (foreign clone) and `gitflow.autopush false` = +manual-push mode (work machine): branches, commits and local merges run as +usual, nothing is pushed, Claude never pushes (`/close` included) unless +the user asks; `GITFLOW_NO_PUSH=1` only for throwaway test repos. Outside +manual mode a branch ahead of its upstream is a defect, not a state. ## Security — non-negotiable defaults Apply at every step: design, scaffolding, implementation, review. @@ -227,7 +230,8 @@ days of work never pushed. - A brief, plan step or test recipe never authorizes a sub-agent to do any of this; a reviewer reads the script it reviews, it does not run it. - Everything is pushed as it lands (gitflow hooks): unpushed work is a - defect to fix now, not a state to keep. + defect to fix now, not a state to keep. Manual-push mode (above) is the + one exception. # Communication mode: radical honesty - TRUTH OVER COMFORT: point out flaws immediately, no sugarcoating, no "not diff --git a/hooks/unpushed-guard.sh b/hooks/unpushed-guard.sh index 2689a91..1c464c2 100755 --- a/hooks/unpushed-guard.sh +++ b/hooks/unpushed-guard.sh @@ -9,6 +9,10 @@ # SessionStart also reports uncommitted changes (a dead session leaves some # behind); Stop reports unpushed commits only, since a dirty tree mid-work is # the normal state at a turn end. +# +# Manual-push mode (git config gitflow.autopush false, human-set): unpushed +# work is expected, so Stop stays silent; SessionStart gives one info line +# counting every local branch, with the branches to push by hand. set -u payload=$(cat 2>/dev/null) @@ -19,9 +23,37 @@ cd "$cwd" 2>/dev/null || exit 0 git rev-parse --is-inside-work-tree >/dev/null 2>&1 || exit 0 br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 +raw=$(git config gitflow.autopush 2>/dev/null) +manual=0; invalid=0 +[ "$(git config --bool --default true gitflow.autopush 2>/dev/null)" = false ] && manual=1 +[ -n "$raw" ] && ! git config --bool gitflow.autopush >/dev/null 2>&1 && invalid=1 +[ "$manual" = 1 ] && [ "$event" != SessionStart ] && exit 0 # BDR-087: info at start only + +# Local branches holding commits no remote has, one per line. +ahead_branches() { + local b + while IFS= read -r b; do + [ "$(git rev-list --count "$b" --not --remotes 2>/dev/null)" -gt 0 ] && echo "$b" + done < <(git for-each-ref --format='%(refname:short)' refs/heads) +} + +# Manual mode: commits on every local branch that no remote holds. +manual_clause() { + local n list first + n=$(git rev-list --count --branches --not --remotes 2>/dev/null || echo 0) + [ "$n" -gt 0 ] || return 0 + if ! git remote get-url origin >/dev/null 2>&1; then + echo "no 'origin' remote, $n commit(s) on this disk only" + return + fi + list=$(ahead_branches); first=$(printf '%s\n' "$list" | head -n 1) + echo "$n commit(s) not on origin ($(printf '%s' "$list" | paste -sd, - | sed 's/,/, /g')), push by hand: git push -u origin $first" +} + # Commits that no remote holds, as one clause; empty when everything is pushed. unpushed_clause() { local up n + [ "$manual" = 1 ] && { manual_clause; return; } if ! git remote get-url origin >/dev/null 2>&1; then echo "no 'origin' remote, every commit lives on this disk only" return @@ -41,9 +73,12 @@ if [ "$event" = "SessionStart" ]; then dirty=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ') [ "$dirty" -gt 0 ] && msg="${msg:+$msg; }$dirty uncommitted change(s) in $cwd" fi +if [ "$invalid" = 1 ] && [ "$event" = "SessionStart" ]; then + msg="${msg:+$msg; }gitflow.autopush='$raw' is not a boolean, treated as auto (pushes run)" +fi [ -n "$msg" ] || exit 0 -msg="⚠ unpushed work: $msg" +if [ "$manual" = 1 ]; then msg="ℹ manual push mode: $msg"; else msg="⚠ unpushed work: $msg"; fi if [ "$event" = "SessionStart" ]; then jq -cn --arg m "$msg" \ '{systemMessage: $m, hookSpecificOutput: {hookEventName: "SessionStart", additionalContext: $m}}' diff --git a/lib/gitflow-test.sh b/lib/gitflow-test.sh index bdefd10..3579b83 100644 --- a/lib/gitflow-test.sh +++ b/lib/gitflow-test.sh @@ -354,6 +354,41 @@ gitflow_start feature nr >/dev/null 2>&1; echo w>w; git add w nr_out="$(git commit -q -m w 2>&1)"; nr_rc=$? chk "T18g no origin → silent, commit ok" "[ $nr_rc -eq 0 ] && ! printf '%s' \"\$nr_out\" | grep -q FAILED" +echo "T18m — manual-push mode: gitflow.autopush=false (human-set) → nothing pushed, finish still deletes" +newrepo manual; echo a>a; hookon; gitflow_init >/dev/null 2>&1 +bare="$WORK/manual.git"; git init -q --bare "$bare"; git remote add origin "$bare" +git push -q -u origin main develop 2>/dev/null +chk "T18m0 develop tracks origin/develop" "git rev-parse -q --verify 'develop@{u}' >/dev/null" +git config gitflow.autopush false +gitflow_start feature manual >/dev/null 2>&1 +chk "T18i start → branch local, no copy on origin" 'git rev-parse --verify -q refs/heads/feature/manual >/dev/null && ! git ls-remote --exit-code --heads origin feature/manual >/dev/null 2>&1' +echo m>m.txt; git add m.txt; git commit -q -m m +dev_remote_before=$(git -C "$bare" rev-parse develop) +gitflow_finish >/dev/null 2>&1; fin_rc=$? +chk "T18j finish → merged locally, origin develop unchanged, branch deleted" "[ $fin_rc -eq 0 ] && grep -q 'Merge feature/manual into develop' < <(git log develop --format=%s) && [ \"\$(git -C \"$bare\" rev-parse develop)\" = \"$dev_remote_before\" ] && ! git rev-parse --verify -q refs/heads/feature/manual >/dev/null" +git config gitflow.autopush true; gitflow_start feature lag >/dev/null 2>&1 +git config gitflow.autopush false +echo l>l.txt; git add l.txt; git commit -q -m l +gitflow_finish >"$WORK/lag.out" 2>&1; lag_rc=$? +chk "T18k lagging upstream → finish deletes, remote copy left in place" "[ $lag_rc -eq 0 ] && ! git rev-parse --verify -q refs/heads/feature/lag >/dev/null && [ \"\$(git -C \"$bare\" rev-parse develop)\" = \"$dev_remote_before\" ] && grep -q 'left in place' \"$WORK/lag.out\" && git ls-remote --exit-code --heads origin feature/lag >/dev/null 2>&1" +git config gitflow.autopush true; gitflow_start feature np >/dev/null 2>&1 +git config gitflow.autopush false +echo n>n.txt; git add n.txt; git commit -q -m n +GITFLOW_NO_PUSH=1 gitflow_finish >"$WORK/np.out" 2>&1; np_rc=$? +chk "T18o NO_PUSH → silent on the remote copy" "[ $np_rc -eq 0 ] && ! git rev-parse --verify -q refs/heads/feature/np >/dev/null && ! grep -q 'left in place' \"$WORK/np.out\" && git ls-remote --exit-code --heads origin feature/np >/dev/null 2>&1" +git remote set-url origin /nonexistent/x.git +gitflow_start feature off2 >"$WORK/off2.out" 2>&1 +chk "T18n offline, nothing recorded → silent, branch created" "! grep -q behind \"$WORK/off2.out\" && git rev-parse --verify -q refs/heads/feature/off2 >/dev/null" +git remote set-url origin "$bare"; git checkout -q develop +other="$WORK/manual-other"; git clone -q "$bare" "$other" 2>/dev/null +( cd "$other" && git config user.email t@t && git config user.name t \ + && git config core.hooksPath /dev/null && git checkout -q develop \ + && echo o>o.txt && git add o.txt && git commit -q -m o \ + && git push -q origin develop ) >/dev/null 2>&1 +div_err="$WORK/div.err" +div_out=$(gitflow_start feature div 2>"$div_err") +chk "T18l diverged base → warns on stderr, stdout stays the branch name" "[ \"$div_out\" = feature/div ] && grep -q 'behind origin/develop' \"$div_err\" && git rev-parse --verify -q refs/heads/feature/div >/dev/null" + echo "T19 — installed hooks == emitted hooks in the config repo (LRN-114 drift gate)" if [ -d "$HERE/../.githooks" ]; then chk "T19a pre-commit installed == emitted" 'diff -q <(_gitflow_emit_pre_commit) "$HERE/../.githooks/pre-commit" >/dev/null' diff --git a/lib/gitflow.sh b/lib/gitflow.sh index 1b34a6b..1ef2cd1 100644 --- a/lib/gitflow.sh +++ b/lib/gitflow.sh @@ -70,15 +70,23 @@ gitflow_release_open() { # ── start ──────────────────────────────────────────────────────────────────── +# rc 0 when pushing is off: GITFLOW_NO_PUSH=1 (throwaway test repos) or +# gitflow.autopush=false (manual-push mode, human-set: work machine, foreign +# clone). The single reader of both flags for the lib's own push sites. +_gitflow_push_off() { + [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && return 0 + [ "$(git config --bool --default true gitflow.autopush)" = false ] +} + # gitflow_start → checkout -b / from the correct base. # _gitflow_push_branch
→ push + set upstream on origin (BDR-095: a remote # only backs up what it holds, so a branch is pushed the moment it exists). # Best effort BY CONTRACT: no origin, offline, or refused → loud warning, rc 0. # A failed push must never block the work, only make the gap visible. -# GITFLOW_NO_PUSH=1 opts out (throwaway test repos). +# Opt-outs: see _gitflow_push_off. _gitflow_push_branch() { local br="$1" - [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && return 0 + _gitflow_push_off && return 0 git remote get-url origin >/dev/null 2>&1 || return 0 if _gitflow_timeout git push -q -u --follow-tags origin "$br" >/dev/null 2>&1; then return 0 @@ -96,6 +104,20 @@ _gitflow_timeout() { fi } +# _gitflow_sync_base → fast-forward the checked-out base from its upstream. +# Never blocks. A base that cannot fast-forward while the remote is ahead (a +# recorded divergence) is warned about: auto-push used to be the only thing +# that surfaced it. No upstream, or offline with nothing recorded → silent. +_gitflow_sync_base() { + local behind + _gitflow_timeout git pull --ff-only -q >/dev/null 2>&1 && return 0 + git rev-parse -q --verify '@{u}' >/dev/null 2>&1 || return 0 + behind=$(git rev-list --count 'HEAD..@{u}' 2>/dev/null || echo 0) + [ "$behind" -gt 0 ] || return 0 + echo "gitflow: $(git symbolic-ref --short -q HEAD) is behind origin/$(git symbolic-ref --short -q HEAD) by $behind and cannot fast-forward — reconcile by hand (git pull, then push)" >&2 + return 0 +} + gitflow_start() { local type="${1:-}" name="${2:-}" base base="$(gitflow_base_for "$type")" || return 2 @@ -103,7 +125,7 @@ gitflow_start() { git rev-parse --verify -q "$base" >/dev/null \ || { echo "gitflow_start: base '$base' missing — run 'gitflow init' first" >&2; return 3; } git checkout -q "$base" || return 1 - git pull --ff-only -q 2>/dev/null || true # best-effort sync; offline / no-upstream ok + _gitflow_sync_base # best-effort sync; warns on divergence, never blocks git checkout -q -b "$type/$name" || return 1 _gitflow_push_branch "$type/$name" echo "$type/$name" @@ -114,7 +136,7 @@ gitflow_start() { _gitflow_merge_into() { # _gitflow_merge_into local target="$1" source="$2" git checkout -q "$target" || return 1 - git pull --ff-only -q 2>/dev/null || true + _gitflow_sync_base git merge --no-ff -q -m "Merge $source into $target" "$source" \ || { echo "gitflow: conflict merging $source → $target — resolve, commit, re-run finish" >&2; return 4; } _gitflow_push_branch "$target" # git merge fires post-merge, not post-commit; push here too @@ -143,6 +165,15 @@ gitflow_merged_into_base() { return 1 } +# _gitflow_note_remote_left
→ manual mode never deletes origin/
; say +# so when a remote-tracking ref shows a copy exists (no network call). +_gitflow_note_remote_left() { + local br="$1" + gitflow_protected_base "$br" && return 0 + git rev-parse -q --verify "refs/remotes/origin/$br" >/dev/null || return 0 + echo "gitflow: origin/$br left in place (manual push mode) — by hand: git push origin --delete $br" >&2 +} + # _gitflow_delete_remote
→ remove origin/
once the LOCAL copy is gone. # Same contract as the pushes (BDR-095): best effort, warn never fail; skipped # under GITFLOW_NO_PUSH=1, gitflow.autopush=false or no origin. The REMOTE tip @@ -153,8 +184,11 @@ gitflow_merged_into_base() { _gitflow_delete_remote() { local br="$1" out rc tip [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && return 0 - [ "$(git config --bool --default true gitflow.autopush)" = false ] && return 0 git remote get-url origin >/dev/null 2>&1 || return 0 + if _gitflow_push_off; then + _gitflow_note_remote_left "$br" + return 0 + fi gitflow_protected_base "$br" && return 0 out="$(_gitflow_timeout git ls-remote --exit-code --heads origin "refs/heads/$br" 2>/dev/null)"; rc=$? [ "$rc" -eq 2 ] && return 0 # no remote copy — nothing to remove @@ -175,6 +209,17 @@ _gitflow_delete_remote() { return 0 } +# _gitflow_checkout_containing_base
→ leave
, landing on the base that +# contains it (develop first, main for a branch merged into main only). +_gitflow_checkout_containing_base() { + local br="$1" + if git merge-base --is-ancestor "$br" "$GITFLOW_DEVELOP" 2>/dev/null; then + git checkout -q "$GITFLOW_DEVELOP" + else + git checkout -q "$GITFLOW_MAIN" + fi +} + # gitflow_delete → the one sanctioned way to delete a branch, local # copy then origin copy. finish calls it after its merges; the CLI exposes it # for a branch merged elsewhere (a Gitea PR, a hand merge). Refuses, branch @@ -192,7 +237,11 @@ gitflow_delete() { echo "gitflow: REFUSED — '$br' is not merged into $GITFLOW_DEVELOP or $GITFLOW_MAIN — branch kept" >&2 return 5 fi - git checkout -q "$GITFLOW_DEVELOP" 2>/dev/null || git checkout -q "$GITFLOW_MAIN" 2>/dev/null + _gitflow_checkout_containing_base "$br" + # LRN-161: `-d` judges against the upstream when one is set, against HEAD + # otherwise. The ancestor check above is the real gate, so HEAD must be the + # base that contains
and a lagging upstream (manual mode) must go. + git branch -q --unset-upstream "$br" 2>/dev/null || true git branch -q -d "$br" || { echo "gitflow: git refused to delete '$br' — branch kept" >&2; return 5; } _gitflow_delete_remote "$br" } diff --git a/lib/tests/unpushed-guard.test.sh b/lib/tests/unpushed-guard.test.sh index ad3630c..6b4c9c0 100755 --- a/lib/tests/unpushed-guard.test.sh +++ b/lib/tests/unpushed-guard.test.sh @@ -38,4 +38,42 @@ check T8-dirty-start-reported "$(has "$(fire SessionStart "$PWD")" "uncommitted" out=$(jq -n --arg d "$PWD" '{hook_event_name:"SessionStart", cwd:$d}' | bash "$H" 2>/dev/null) check T9-start-adds-context "$(printf '%s' "$out" | jq -r '.hookSpecificOutput.hookEventName')" SessionStart +# ── manual-push mode (gitflow.autopush=false) ── +git checkout -q -- a +git config gitflow.autopush false +check T10-manual-clean-start "$(fire SessionStart "$PWD")" silent +check T10-manual-clean-stop "$(fire Stop "$PWD")" silent +echo m>m; git add m; git commit -q -m m +git branch side HEAD; git checkout -q side; echo s>s; git add s; git commit -q -m s +git checkout -q - +check T11-manual-stop-silent "$(fire Stop "$PWD")" silent +out=$(fire SessionStart "$PWD") +check T11-manual-info "$(has "$out" "manual push mode")" yes +check T11-manual-count "$(has "$out" "2 commit(s)")" yes +check T11-manual-lists-branch "$(has "$out" "side")" yes +check T11-manual-no-warning "$(has "$out" "unpushed work")" no +git checkout -q -b fresh +check T12-fresh-branch-repo-wide "$(has "$(fire SessionStart "$PWD")" "2 commit(s)")" yes +git checkout -q - +git push -q origin HEAD side 2>/dev/null; echo d>>a +out=$(fire SessionStart "$PWD") +check T13-dirty-info "$(has "$out" "manual push mode")" yes +check T13-dirty-uncommitted "$(has "$out" "uncommitted")" yes +check T13-dirty-no-commit-clause "$(has "$out" "commit(s) not on origin")" no +check T13-dirty-stop-silent "$(fire Stop "$PWD")" silent +git checkout -q -- a +git config gitflow.autopush flase +echo i>i; git add i; git commit -q -m i +out=$(fire SessionStart "$PWD") +check T14-invalid-named "$(has "$out" "not a boolean")" yes +check T14-invalid-treated-auto "$(has "$out" "unpushed work")" yes +check T14-invalid-stop-auto "$(has "$(fire Stop "$PWD")" "1 commit(s)")" yes +git config --unset gitflow.autopush +check T15-unset-auto-intact "$(has "$(fire Stop "$PWD")" "1 commit(s)")" yes +git config gitflow.autopush false; git remote remove origin +out=$(fire SessionStart "$PWD") +check T16-no-origin-manual "$(has "$out" "manual push mode")" yes +check T16-no-origin-clause "$(has "$out" "no 'origin' remote")" yes +check T16-no-origin-stop-silent "$(fire Stop "$PWD")" silent + printf 'PASS=%s FAIL=%s\n' "$pass" "$fail"; [ "$fail" -eq 0 ] From e6cccc17407e5e347cdba3e9c83b34236a7156fa Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 6 Oct 2026 17:50:24 +0200 Subject: [PATCH 003/547] =?UTF-8?q?chore(memory):=20journal=20+=20contract?= =?UTF-8?q?/plan=20=E2=80=94=20feat=20manual-push-mode=20run=20A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 10 ++++ .../2026-10-06-manual-push-mode-1632.md | 51 +++++++++++++++++++ .../plans/2026-10-06-manual-push-mode-1632.md | 48 +++++++++++++++++ 4 files changed, 110 insertions(+) create mode 100644 .claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md create mode 100644 .claude/tasks/plans/2026-10-06-manual-push-mode-1632.md diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 92938d7..a3e170d 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -568,3 +568,4 @@ rules: - /prune-memory 2026-10-06: A none, D none; B BLK-019+020 → BLK-028 (merge); C bounded 37 entries ≥9% filler → 37 edited, 1 untouched (LRN-075 all-negation), cuts 1-11% only (negation guard protects "X not Y" lessons); fidelity + index OK. 110 bloated entries left for a later run. - /doc global audit 2026-10-06 (opus): 45 items, 6 docs. Applied 34 (24 AUTO + 9 HUMAN drafts + clone URL → Gitea): README components/slash/flow, Makefile help (11 profiles), USAGE /health→make doctor + GSD 3.0.0, ARCHITECTURE layout, MIGRATION retitled + "Upgrading to 2.0.0", SETTINGS package-install guard, CHANGELOG SemVer + default model + upgrade pointer → c6fb2e4. 10 deferred logged in TODO (LICENSE, Known-residual vs release, README restructure, USAGE narrative, templates/settings.json ask inert). - Release 2.0.0 cut (user go x3: release, tag push, MIT): bugfix merged 370f35a; develop merged into release/2.0.0 (b47bba7, CHANGELOG conflict resolved: upgrade pointer under [2.0.0]); suite 46/46 green on release; 9ef66e2 MIT LICENSE + README License + Linux residual reworded; gitflow finish by release-executor (BLK-018 did not fire) -> main 4093cca, tag v2.0.0 pushed on user go. Open after release: Linux make test (TODO), make plugin + .env on this machine (BLK-027). +- /feat manual-push-mode run A (user: work machine, same flow, never push alone): `gitflow.autopush false` = manual-push mode end to end. Plan challenged 3 lenses + 1 confirm → 2 MAJOR (`-d` re-arms on lagging upstream LRN-161; /close STEP 5C pushes develop) + 3 BLOCKER in r2 (T22j regress, develop untracked in fixture, T18l/T18n order) all closed by named changes. feater ×2 (gaps: pipefail flake `git log | grep -q`, 9 SC2034 suppressions removed), GATE 0 7/8, verifier ECARTS(1) = AC6 env red only (design-tool-gate, 21st CLI present, same on develop fa67664), security PASS ×2. Commit 2fc8830 on feature/manual-push-mode, UNMERGED. Runs B (push-guard hook, settings deny widening, banner) + C (skills that push) queued in TODO; do NOT enable manual mode at work before B+C. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 115fc7f..9910f02 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -2055,3 +2055,13 @@ dans un runner; capitalize reste main-loop. - [ ] P33 USAGE token figures ("Budget Pro ~11k tokens/5h", per-pattern) have no source in code — verify or drop - [ ] P34 USAGE + agents/plugin-advisor.md "gstack ON/OFF", "context7 ON" vocabulary — gstack is per-profile, ctx7 is a CLI; move both together - [ ] P41 templates/settings/settings.json: `permissions.ask` entries (npx, docker rm, make deploy, psql…) inert under defaultMode auto → config fix, not doc + +## manual-push-mode (2026-10-06, /feat × 3) +- [x] run A — `gitflow.autopush=false` honoured by `_gitflow_push_branch`, quiet unpushed-guard, doctrine line; plan `.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md` → commit 2fc8830 on feature/manual-push-mode; verifier ECARTS(1) = AC6 only (design-tool-gate env red, pre-existing on develop) → human waiver; merge human-gated +- [ ] run B — `hooks/push-guard.sh` PreToolUse (deny `git push` in manual mode) + test + settings.json (hook wiring, widen `gitflow.*` deny: `git config * gitflow.*`, `git -c gitflow.*`, `GIT_CONFIG_COUNT=*`; environment prose ~480/~499) + session-start banner push mode +- [ ] run C — skills that push on their own, gate on `gitflow.autopush`: capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims +- [ ] run B also: fail-CLOSED on an unparseable `gitflow.autopush` value in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks, unpushed-guard) — run A keeps fail-open for consistency with the untouched emitters (security gate MEDIUM, 2026-10-06); `--end-of-options`/`--` on refname args and `printf %q` in copy-paste hints (LOW); `gitflow_delete`: check `_gitflow_checkout_containing_base` rc before `--unset-upstream` (LOW, 2nd gate) +- [ ] ORDER: do not set `gitflow.autopush false` on the work machine before B + C are merged (until then `/close` still pushes develop) + +## test hermeticity (2026-10-06, found during manual-push-mode run A) +- [ ] `lib/tests/design-tool-gate.test.sh` reds on any machine with the 21st CLI installed ("FAIL precondition: system-wide 21st present, CLI_ABSENT case not hermetic") — pre-existing on develop (fa67664), independent of the diff. Make the CLI_ABSENT case hermetic (PATH shim / stubbed probe) so `make test` is green on a design-profile machine. Until then full-suite oracles (`make test` exit 0) cannot be MET here. diff --git a/.claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md b/.claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md new file mode 100644 index 0000000..564a5ac --- /dev/null +++ b/.claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md @@ -0,0 +1,51 @@ +# CONTRACT — manual-push-mode +- date: 2026-10-06 | flow: feat | branch: feature/manual-push-mode (run A of 2; run B = push-guard hook + banner) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "est-ce qu'on a un moyen de regler le flow automatique de git. Activer / desactiver le fait que ca pousse tout seul, que ca ne merge pas tout seul etc. Q`'il y ai forcement la demande ou l'authorisation humaine pour cela ? Il faut pouvoir le toggle on ou toggle off" +User (fr): "ok donc ou sera la cle gitflow.mode ? Pour expliaquer, c'est pour pouvoir utiliser la config au taff. Il faut tout faire pareil, juste rien push seul. Mais faire les branches locale,ment, faire les commits localements etc. Juste il faut pas push. seulement manuel" +/feat args: Manual-push mode via the existing `gitflow.autopush` git-config key (no new key). Scope: (1) lib/gitflow.sh `_gitflow_push_branch` must honour `gitflow.autopush=false` like the hooks and `_gitflow_delete_remote` do (today `start`/`finish` push regardless, bug); (2) guard-bash: when `git config --bool --default true gitflow.autopush` is false in the cwd repo, deny any `git push` from Claude with a message pointing to `! git push` (human runs it); (3) hooks/unpushed-guard.sh: in manual mode, SessionStart emits "push manuel : N commit(s) à pousser" info only, Stop emits nothing; (4) hooks/session-start.sh banner shows push mode (auto/manual); (5) CLAUDE.global.md: one line in the gitflow section, autopush=false → unpushed work is expected, never push unless the user asks; (6) tests updated (guard-bash.test.sh, unpushed-guard.test.sh, gitflow-test.sh). User decisions already taken: mechanical block of git push (chosen), guard info at SessionStart only (chosen). + +## CLARIFICATIONS +Q: Mechanical block of `git push` when autopush=false? / A: yes, block (user, pre-flow) [gated 2026-10-06] +Q: unpushed-guard behaviour in manual mode? / A: info at SessionStart only, silent at Stop (user, pre-flow) [gated 2026-10-06] +Q: scope split — request spans ~10 files (> /feat max 5) / A: run A (this contract) = items 1, 3, 5 + their tests; run B = items 2, 4 as `hooks/push-guard.sh` + test + settings.json wiring + banner. `hooks/guard-bash.sh` does not exist (BLK-022), so item 2 lands in a new dedicated hook, and `guard-bash.test.sh` (spec of an absent hook) is left untouched. [gated 2026-10-06, orchestrator — scope class, surfaced to user in pass B] +Q: manual-mode SessionStart message language / A: English, consistent with the hook family. Exact line: `ℹ manual push mode: commit(s) on '' to push by hand (git push)`; no-upstream variant: `ℹ manual push mode: '' has no upstream ( commit(s) on this disk only), push by hand: git push -u origin `; the existing `; uncommitted change(s) in ` clause follows when the tree is dirty. [gated 2026-10-06] +Q: run B hook name / A: `hooks/push-guard.sh` + `lib/tests/push-guard.test.sh` [gated 2026-10-06] +Q: challenge r1 — skills push on their own (`skills/capitalize/SKILL.md:338` `git push origin develop` after the BDR-068 auto-finish; `skills/client-handover/SKILL.md:48` + `agents/client-handover-writer.md:586` `git push`; `skills/release-candidate/SKILL.md:96` and `skills/tour/SKILL.md:273` claim the branch is already on origin) and `settings.json` environment prose (lines ~480, ~499) says unpushed = defect / A: out of run A's 5-file scope. Run B (settings.json: hook wiring + widen the `gitflow.*` deny to `git config * gitflow.*`, `git -c gitflow.*`, `GIT_CONFIG_COUNT=*` + prose) and run C (the 5 skill/agent files: gate each push on `git config --bool --default true gitflow.autopush`, report `manual push mode: not pushed`). DEPLOYMENT ORDER: `gitflow.autopush false` is not to be set on the work machine before B and C are merged. [gated 2026-10-06, orchestrator — scope class, surfaced to the user] +Q: challenge r1 — manual-mode count scope / A: all local branches (`--branches --not --remotes`), listing the ahead branches; the gated sentence shape stays (`ℹ manual push mode: commit(s) not on origin (, ), push by hand: git push -u origin `). Auto mode unchanged. [gated 2026-10-06, orchestrator — refinement of the chosen wording, surfaced to the user] + +## ACCEPTANCE CRITERIA +1. `_gitflow_push_branch` returns without pushing when `gitflow.autopush` is false: `gitflow start` under autopush=false creates the branch locally and origin has no copy; `gitflow finish` under autopush=false merges locally and origin's develop tip is unchanged. A branch whose upstream lags (pushed once by hand, then committed to) is still deleted by `finish` (rc 0): `--unset-upstream` before `-d` (LRN-161). Skipped remote delete says `left in place`. A base that cannot fast-forward from origin warns `behind origin/`; offline stays silent. Locked by the new isolated gitflow-test block T18i–T18n. + CHECK: out=$(make test suite=lib/gitflow-test.sh 2>&1); printf '%s' "$out" | grep -q ' FAIL ' && exit 1; for t in T18m0 T18i T18j T18k T18o T18n T18l; do printf '%s' "$out" | grep -q "ok $t" || exit 1; done; echo GITFLOW-MANUAL-OK + EXPECT: GITFLOW-MANUAL-OK + EVIDENCE: MET exit=0 marker-found :: GITFLOW-MANUAL-OK +2. Auto mode unchanged: existing T18a–T18h, T24a–T24f and the T19 installed==emitted drift gate stay green (no hook emitter touched). + CHECK: out=$(make test suite=lib/gitflow-test.sh 2>&1); printf '%s' "$out" | grep -q ' FAIL ' && exit 1; for t in T18a T18b T18c T18h T18f T19a T19b T19c T22i T22j T24b T24f; do printf '%s' "$out" | grep -q "ok $t" || exit 1; done; echo GITFLOW-AUTO-OK + EXPECT: GITFLOW-AUTO-OK + EVIDENCE: MET exit=0 marker-found :: GITFLOW-AUTO-OK +3. `hooks/unpushed-guard.sh` in manual mode (`gitflow.autopush=false` in the cwd repo): Stop emits nothing even with unpushed commits; SessionStart emits the manual-mode info line (`ℹ manual push mode: commit(s) not on origin (), push by hand: …`) counting every local branch, silent at n=0 with a clean tree, plus the existing uncommitted-changes clause; an invalid `gitflow.autopush` value is named at SessionStart and treated as auto; no "⚠ unpushed work" wording in manual mode. Auto mode output unchanged (T1–T9). Locked by new test cases T10–T16. + CHECK: out=$(make test suite=lib/tests/unpushed-guard.test.sh 2>&1); printf '%s' "$out" | grep -q '^FAIL' && exit 1; printf '%s' "$out" | grep -qE 'PASS=(1[6-9]|[2-9][0-9]) FAIL=0' && echo GUARD-OK + EXPECT: GUARD-OK + EVIDENCE: MET exit=0 marker-found :: GUARD-OK +4. `CLAUDE.global.md` gitflow section gains one statement: `gitflow.autopush false` = manual-push mode, unpushed work is expected there, Claude never pushes unless the user asks; the "ahead of its upstream is a defect" sentence is scoped to auto mode. File stays within the 320-line density budget. + CHECK: grep -q 'autopush false' CLAUDE.global.md && grep -qi 'manual' CLAUDE.global.md && [ "$(wc -l < CLAUDE.global.md)" -le 320 ] && echo DOCTRINE-OK + EXPECT: DOCTRINE-OK + EVIDENCE: MET exit=0 marker-found :: DOCTRINE-OK +5. shellcheck clean on the two touched scripts. + CHECK: shellcheck lib/gitflow.sh hooks/unpushed-guard.sh && echo SHELLCHECK-OK + EXPECT: SHELLCHECK-OK + EVIDENCE: MET exit=0 marker-found :: SHELLCHECK-OK +6. Full hermetic suite green. + CHECK: make test >/dev/null 2>&1 && echo SUITE-GREEN + EXPECT: SUITE-GREEN + EVIDENCE: NOT-MET exit=2 (nonzero) :: +7. No new git-config key, no new env var, no change to `GITFLOW_NO_PUSH` semantics, no edit to hook emitters (`_gitflow_emit_*`) or to `githooks/`/`.githooks/`. +8. shellcheck stays clean on `lib/gitflow-test.sh` and `lib/tests/unpushed-guard.test.sh` too (Health Stack `shellcheck lib/*.sh`). + CHECK: shellcheck lib/gitflow-test.sh lib/tests/unpushed-guard.test.sh && echo SHELLCHECK-TESTS-OK + EXPECT: SHELLCHECK-TESTS-OK + EVIDENCE: MET exit=0 marker-found :: SHELLCHECK-TESTS-OK + +## FILE SCOPE +lib/gitflow.sh · hooks/unpushed-guard.sh · CLAUDE.global.md · lib/gitflow-test.sh · lib/tests/unpushed-guard.test.sh diff --git a/.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md b/.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md new file mode 100644 index 0000000..9387086 --- /dev/null +++ b/.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md @@ -0,0 +1,48 @@ +# PLAN — manual-push-mode (run A) — REVISED after challenge r1 + confirmation r2 +Contract: .claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md + +## Context +`gitflow.autopush` (git config, default true) already silences the post-commit/post-merge push hooks and `_gitflow_delete_remote`. Gap: `_gitflow_push_branch` (lib/gitflow.sh:78-88) only reads `GITFLOW_NO_PUSH`, so `start`/`finish` push even in manual mode. `hooks/unpushed-guard.sh` nags at every Stop regardless of mode. Doctrine says unpushed = defect, which would drive Claude to push by hand. +Challenge r1 added: (a) in manual mode a branch's upstream lags, and `git branch -d` checks the UPSTREAM when one is set (LRN-161), so `gitflow_delete` would refuse after a successful merge (rc 5, false "unmerged"); (b) `git pull --ff-only … || true` swallows a diverged base silently, which only auto-push used to surface; (c) `_gitflow_delete_remote` skipping leaves `origin/
` behind with no word; (d) skills push on their own (`/capitalize` STEP 5C `git push origin develop`, client-handover, release-candidate/tour "already on origin" claims) and settings.json prose says unpushed = defect → run C (skills) and run B (settings), see contract. + +## Checklist +- [ ] lib/gitflow.sh — add `_gitflow_push_off()` right above `_gitflow_push_branch`: rc 0 when `GITFLOW_NO_PUSH=1` OR `git config --bool --default true gitflow.autopush` is `false`. Comment: "GITFLOW_NO_PUSH=1 (throwaway test repos) or gitflow.autopush=false (manual-push mode, human-set: work machine, foreign clone)". Call it as the first line of `_gitflow_push_branch`. In `_gitflow_delete_remote` KEEP `[ "${GITFLOW_NO_PUSH:-0}" = 1 ] && return 0` as the first line (test repos stay silent), then replace the inline autopush line with `_gitflow_push_off && { ; return 0; }`. Grep claim, scoped: outside the hook-emitter heredocs (`_gitflow_emit_push_hook`, untouched per AC7) and that one documented NO_PUSH line, no inline reader of the two flags remains in lib/gitflow.sh. +- [ ] lib/gitflow.sh — `_gitflow_delete_remote`: when `_gitflow_push_off` fires (NO_PUSH already returned above, so this is autopush=false), origin exists, and `git rev-parse -q --verify "refs/remotes/origin/$br" >/dev/null` succeeds (no network), print to stderr `gitflow: origin/
left in place (manual push mode) — by hand: git push origin --delete
`; return 0 either way. Every `rev-parse --verify` probe added by this plan ends in `>/dev/null`: `gitflow_start`'s stdout is the branch name only (T11). +- [ ] lib/gitflow.sh — `gitflow_delete`: after `gitflow_merged_into_base` passes, check out the base that CONTAINS the branch: `if git merge-base --is-ancestor "$br" "$GITFLOW_DEVELOP" 2>/dev/null; then git checkout -q "$GITFLOW_DEVELOP"; else git checkout -q "$GITFLOW_MAIN"; fi` (replaces the current develop-else-main fallback at line ~195; T22j = merged into main only must stay deletable). Then `git branch -q --unset-upstream "$br" 2>/dev/null || true` BEFORE `git branch -q -d "$br"`. Comment citing LRN-161: `-d` judges against the upstream when one is set, against HEAD otherwise; the ancestor check is the real gate, so HEAD must be the containing base and the upstream must be out of the way. Keep the ≤25-logic-line budget: extract `_gitflow_checkout_containing_base
` if needed. +- [ ] lib/gitflow.sh — add `_gitflow_sync_base()` (≤10 lines) replacing the two `git pull --ff-only -q 2>/dev/null || true` lines (gitflow_start, _gitflow_merge_into): `_gitflow_timeout git pull --ff-only -q >/dev/null 2>&1 && return 0`; then if `git rev-parse -q --verify '@{u}'` succeeds and `git rev-list --count HEAD..@{u}` > 0 → stderr `gitflow: is behind origin/ by and cannot fast-forward — reconcile by hand (git pull, then push)`; always return 0 (never blocks). Silent when: no upstream (`@{u}` unresolvable), or offline with no RECORDED divergence (HEAD..@{u} = 0). Offline after an earlier fetch recorded the base as behind → still warns (the recorded fact is true). The `@{u}` probe ends in `>/dev/null`. +- [ ] hooks/unpushed-guard.sh — mode detection after `br=`: `raw=$(git config gitflow.autopush)`; `manual=0`; `[ "$(git config --bool --default true gitflow.autopush 2>/dev/null)" = false ] && manual=1`; `invalid=0`; `[ -n "$raw" ] && ! git config --bool gitflow.autopush >/dev/null 2>&1 && invalid=1`. Stop + manual → `exit 0` immediately (BDR-087: message only, and the user chose silence at Stop). ONE clause function kept (`unpushed_clause`), mode-aware: auto path unchanged byte for byte (T1–T9). Manual path: `n=$(git rev-list --count --branches --not --remotes)` (ALL local branches, not just HEAD — a session usually starts on develop after a local finish); `n -eq 0` → empty (so a fresh `start` branch with 0 commits is silent, LRN-091); else list the ahead branches via `git for-each-ref --format='%(refname:short)' refs/heads` filtered on `git rev-list --count --not --remotes` > 0, joined by `, ` → clause ` commit(s) not on origin (, ), push by hand: git push -u origin ` (never HEAD's name: HEAD may hold no unique commit); no origin remote → `no 'origin' remote, commit(s) on this disk only`. Prefix chosen at the single emit site: auto `⚠ unpushed work:`, manual `ℹ manual push mode:`. SessionStart keeps the `; uncommitted change(s) in ` clause in both modes (dirty-only manual → `ℹ manual push mode: uncommitted change(s) in `). `invalid=1` → SessionStart appends `; gitflow.autopush='' is not a boolean, treated as auto (pushes run)`. Header comment: +3 lines on manual mode. Functions ≤25 logic lines: extract `ahead_branches()`. +- [ ] CLAUDE.global.md — gitflow section: replace the two sentences `Foreign clone: \`git config gitflow.protect false\` / \`gitflow.autopush false\`; \`GITFLOW_NO_PUSH=1\` only for throwaway test repos. A branch ahead of its upstream is a defect, not a state.` (lines 186-188) with ONE statement: `Human-set opt-outs: \`git config gitflow.protect false\` (foreign clone) and \`gitflow.autopush false\` = manual-push mode (work machine): branches, commits and local merges run as usual, nothing is pushed, Claude never pushes (\`/close\` included) unless the user asks; \`GITFLOW_NO_PUSH=1\` only for throwaway test repos. Outside manual mode a branch ahead of its upstream is a defect, not a state.` Line 229 bullet: append ` Manual-push mode (above) is the one exception.` Net +3 to +4 lines (312 → ≤316, budget 320). No heading or bold label changes (doctrine-citers census unaffected). +- [ ] lib/gitflow-test.sh — NEW isolated block after T18g, before T19: `echo "T18m — manual-push mode: gitflow.autopush=false (human-set) → nothing pushed, finish still deletes"`; `newrepo manual; echo a>a; hookon; gitflow_init`; bare origin; `git push -q -u origin main develop` (`-u`: develop MUST track origin/develop for T18l/T18n — gitflow_init creates develop untracked, and manual mode never sets it); precondition chk `T18m0 develop tracks origin/develop`: `git rev-parse -q --verify 'develop@{u}' >/dev/null`; `git config gitflow.autopush false`. ORDER inside the block: T18i, T18j, T18k, T18o, T18n, T18l (T18l fetches `o` into refs/remotes/origin/develop and nothing reconciles it, so an offline test after it would warn — T18n runs first, while develop is ahead-only). + T18i: `gitflow_start feature manual` → `git rev-parse --verify -q refs/heads/feature/manual` AND `! git ls-remote --exit-code --heads origin feature/manual`. + T18j: `echo m>m.txt; git add m.txt; git commit -q -m m`; `# shellcheck disable=SC2034` + `dev_remote_before=$(git -C "$bare" rev-parse develop)`; `fin_rc=0; gitflow_finish >/dev/null 2>&1 || fin_rc=$?` → rc 0, `Merge feature/manual into develop` in local develop log, origin develop == dev_remote_before, branch deleted. + T18k (lagging upstream): `git config gitflow.autopush true; gitflow_start feature lag` (pushed -u); `git config gitflow.autopush false; echo l>l.txt; git add l.txt; git commit -q -m l`; `lag_out=$(gitflow_finish 2>&1); lag_rc=$?` → rc 0, `! git rev-parse --verify -q refs/heads/feature/lag`, origin/develop still == dev_remote_before, `lag_out` contains `left in place`, `git ls-remote --exit-code --heads origin feature/lag` still exists. + T18o (NO_PUSH stays silent on the remote copy): `git config gitflow.autopush true; gitflow_start feature np` (pushed -u); `git config gitflow.autopush false; echo n>n.txt; git add n.txt; git commit -q -m n`; `np_out=$(GITFLOW_NO_PUSH=1 gitflow_finish 2>&1); np_rc=$?` → rc 0, branch deleted, `np_out` does NOT contain `left in place`, origin/feature/np still exists. + T18n (offline, no recorded divergence → silent): `git remote set-url origin /nonexistent/x.git; off2_out=$(gitflow_start feature off2 2>&1)` → does NOT contain `behind`, `git rev-parse --verify -q refs/heads/feature/off2`; `git remote set-url origin "$bare"; git checkout -q develop`. + T18l (diverged base warning): `other="$WORK/manual-other"; git clone -q "$bare" "$other"`; in other: hooks off, identity, `git checkout -q develop; echo o>o.txt; git add o.txt; git commit -q -m o; git push -q origin develop`; local (on develop, ahead by the local merges): `div_err="$WORK/div.err"; div_out=$(gitflow_start feature div 2>"$div_err")` → stdout `[ "$div_out" = feature/div ]` (no SHA leak), stderr `grep -q 'behind origin/develop' "$div_err"`, branch exists. + Every `*_out`/`*_rc`/`dev_remote_before` read only inside chk evals gets `# shellcheck disable=SC2034` on the line above (lib/gitflow-test.sh idiom, lines 296/344/353). +- [ ] lib/tests/unpushed-guard.test.sh — append before the PASS line (repo has origin, upstream on main/master, in sync after T8's push; tree dirty from T7/T8 → `git checkout -q -- a` first): + `git config gitflow.autopush false` + T10 manual + clean + in sync: SessionStart → `silent`; Stop → `silent`. + T11 one local commit on HEAD, plus `git branch side HEAD; git checkout -q side; echo s>s; git add s; git commit -q -m s; git checkout -q -` (second ahead branch): Stop → `silent`; SessionStart → contains `manual push mode`, `2 commit(s)`, `side`, and NOT `unpushed work`. + T12 fresh branch with no upstream and 0 extra commits (`git checkout -q -b fresh`): SessionStart → still reports the 2 commits (they are reachable from other branches; count is repo-wide) — assert `2 commit(s)`; then `git checkout -q -` . + T13 dirty tree only (push the two commits by hand in the test: `git push -q origin HEAD side`, then `echo d>>a`): SessionStart → contains `manual push mode` and `uncommitted`, NOT `commit(s) not on origin`; Stop → silent. `git checkout -q -- a`. + T14 invalid value: `git config gitflow.autopush flase`; one more local commit; SessionStart → contains `not a boolean` AND `unpushed work` (treated as auto); Stop → contains `1 commit(s)` (auto behaviour). + T15 toggle back: `git config --unset gitflow.autopush`; Stop → contains `1 commit(s)` (positive control, auto path intact). + T16 no-origin manual (LAST, nothing restored after): `git config gitflow.autopush false; git remote remove origin`; SessionStart → contains `manual push mode` and `no 'origin' remote`; Stop → silent. + +## Edge cases +- `gitflow.autopush` set `--global` on the work machine: `git config --bool --default true` reads the merged value → every repo, no code difference. Toggle is human-set (static deny on `git config gitflow.*`, BDR-095 c); the deny is prefix-based and run B widens it (`git config * gitflow.*`, `git -c gitflow.*`, `GIT_CONFIG_COUNT=*`). +- Garbage value: `--bool` fails → auto mode (fail-open toward pushing, pre-existing in the emitted hooks, which run A may not edit — AC7); the guard now SAYS so at SessionStart. Fail-closed is a run B question (hook emitters). +- Count scope: manual mode counts every local branch (`--branches --not --remotes`); auto mode keeps the current-branch count (unchanged contract, T5/T6). +- Diverged base: warning only, never blocks `start`/`finish`; the user reconciles by hand. No upstream → silent; offline with no recorded divergence → silent; offline after a fetch already recorded the base as behind → warns (true fact). +- `gitflow_delete` now ends on the base that contains the branch (main for a main-only merge, develop otherwise) instead of always develop; no test asserts HEAD after a delete. +- No emitter (`_gitflow_emit_*`) touched → T19 drift gate needs no regeneration. +- Deployment order (contract): `gitflow.autopush false` must not be set on the work machine before runs B (push-guard, settings) and C (skills that push) are merged; until then `/close` STEP 5C still pushes develop. + +## Disposition (STEP 0.6 + challenge r1) +- honors BDR-095 by extending the existing `gitflow.autopush` opt-out (amendment c), not a new key. +- honors BDR-100 / LRN-113 by (1) one shared predicate `_gitflow_push_off` for every lib push site, (2) surface grep widened to `grep -rn "git push\|autopush\|GITFLOW_NO_PUSH" lib hooks githooks skills agents settings.json CLAUDE.global.md` — the skill/agent/settings hits are assigned to runs B and C in the contract, not silently dropped. +- honors LRN-161 by `--unset-upstream` before `-d` (the ancestor check is the gate; `-d` must judge against HEAD) and by re-reading the `--ff-only` pulls (now warn on divergence, wrapped in `_gitflow_timeout`). +- honors LRN-104 by locking every new output string in a test: manual line (T11), dirty-only (T13), invalid value (T14), no-origin (T16), "left in place" (T18k) and its NO_PUSH silence (T18o), "behind origin" (T18l) and its offline silence (T18n), stdout purity of `start` (T18l). +- honors LRN-091 / LRN-047 by silence at Stop and at `n=0` in manual mode. +- BDR-087: Stop hook stays systemMessage-only; no control flow. From afd607337122a84a529bb943fe2b4c5af349b004 Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 6 Oct 2026 18:03:35 +0200 Subject: [PATCH 004/547] =?UTF-8?q?docs(gitflow):=20manual-push=20mode=20?= =?UTF-8?q?=E2=80=94=20SETTINGS=20push=20discipline,=20gitflow=20skill=20r?= =?UTF-8?q?ows,=20CHANGELOG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 9 +++++++++ skills/gitflow/SKILL.md | 12 ++++++++---- templates/settings/SETTINGS.md | 17 +++++++++++------ 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a521455..1956865 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project ## [Unreleased] +### Added +- **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
` 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 `gitflow.autopush` value is named and treated as auto. Skills that push on their own do not honour the mode yet. Tests: `lib/gitflow-test.sh` T18m block, `lib/tests/unpushed-guard.test.sh` T10-T16. + +### Changed +- `gitflow start` and `finish` warn on stderr when a base is behind origin and cannot fast-forward, instead of a silent `git pull --ff-only || true` (T18l, T18n). + +### Fixed +- `gitflow delete` (and `finish`) land on the base that contains the branch and drop the branch's upstream before `git branch -d`, so a branch whose upstream lags (manual-push mode) is deleted instead of refused by git (T18k). + ## [2.0.0] — 2026-10-06 Upgrading from 1.x: see [MIGRATION.md](./MIGRATION.md#upgrading-an-existing-machine-to-200). diff --git a/skills/gitflow/SKILL.md b/skills/gitflow/SKILL.md index b5df56e..fd0bdd9 100644 --- a/skills/gitflow/SKILL.md +++ b/skills/gitflow/SKILL.md @@ -54,10 +54,12 @@ bash ~/.claude/lib/gitflow.sh protected-base [br] # rc 0 on main/develop — the `main`/`develop` (rc 6) and any branch not merged into develop or main (rc 5), and keeps the branch. The `origin/` copy is removed right after, once ITS tip passes the same check; a remote tip holding commits the bases lack is -kept, loudly (T24). Hand `git branch -d` is denied — with an auto-pushed -upstream it checks the wrong thing (T22a). A `reference-transaction` hook -vetoes any deletion or rename of `main`/`develop` at the ref layer, in every -repo. +kept, loudly (T24). In manual-push mode (`git config gitflow.autopush +false`, human-set) nothing is pushed: `start` and `finish` stay local, and +the `origin/` copy is left in place (T18i-T18k). Hand `git branch -d` is +denied — with an auto-pushed upstream it checks the wrong thing (T22a). A +`reference-transaction` hook vetoes any deletion or rename of +`main`/`develop` at the ref layer, in every repo. ## The finish gate — merge ONLY on an explicit human signal @@ -107,6 +109,8 @@ stays human-gated. | `delete`/`finish` rc=5 — branch not merged into develop or main | The branch still holds unmerged work: KEEP it, report it, never fall back to `git branch -d`/`-D`. Merge first (human gate), then re-run | | `delete` rc=6 — protected base | `main`/`develop` are never deleted. Stop; the request itself is the defect to report | | `delete`/`finish` warning "remote copy KEPT" or "NOT removed" | Non-fatal BY CONTRACT (remote cleanup is best-effort). KEPT = origin/
has a tip the bases lack: fetch, look, merge or leave it — never `git push --delete` by hand. NOT removed = origin unreachable or refused: report the printed command to the user | +| `delete`/`finish` warning "origin/
left in place (manual push mode)" | Expected in manual-push mode, not a failure. Pass the printed `git push origin --delete
` to the user; never run it (manual mode: no push unless the user asks, and `push --delete` is denied by settings) | +| `start`/`finish` warning " is behind origin/ by N and cannot fast-forward" | Non-fatal BY CONTRACT: the branch is still created and the merge still runs on the local base. The base has diverged from origin: report it to the user, who reconciles (`git pull`, then push). Never rebase or force-push a base | ## Common Mistakes diff --git a/templates/settings/SETTINGS.md b/templates/settings/SETTINGS.md index dadeaf8..1ce8b61 100644 --- a/templates/settings/SETTINGS.md +++ b/templates/settings/SETTINGS.md @@ -167,12 +167,17 @@ fourth hook, `reference-transaction`, vetoes any deletion or rename of reach every repo two ways: `make link` generates `githooks/` from the lib and sets git's global `core.hooksPath` to `~/.claude/githooks` (a repo's own local `core.hooksPath` wins, by git's rules), and `hooks/session-start.sh` -refreshes a repo's `.githooks/` when it lags the lib. Per-repo opt-outs for -a foreign clone: `git config gitflow.protect false` (branch model) and -`git config gitflow.autopush false` (push); `GITFLOW_NO_PUSH=1` for one -command in a throwaway repo. `make doctor` checks the global setting and -the generated dir. `hooks/unpushed-guard.sh` reports a branch ahead of its -upstream at session start and at each turn end. +refreshes a repo's `.githooks/` when it lags the lib. Per-repo opt-outs, set +by a human: `git config gitflow.protect false` (branch model, foreign clone) +and `git config gitflow.autopush false` (manual-push mode: the hooks, +`start` and `finish` push nothing, and `delete` leaves the `origin/` copy in +place, printing the command to remove it by hand); `GITFLOW_NO_PUSH=1` for +one command in a throwaway repo. `start` and `finish` warn when a base is +behind origin and cannot fast-forward. `make doctor` checks the global +setting and the generated dir. `hooks/unpushed-guard.sh` reports a branch +ahead of its upstream at session start and at each turn end; in manual-push +mode it stays silent at turn end and gives one `ℹ manual push mode:` line at +session start, counting unpushed commits across every local branch. ## managed-settings.json (enterprise) From 16c3dc8fbbba377d2a48622f50c65c48130440f6 Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 6 Oct 2026 18:03:36 +0200 Subject: [PATCH 005/547] =?UTF-8?q?chore(memory):=20BDR-111=20+=20LRN-191.?= =?UTF-8?q?.193=20=E2=80=94=20feat=20manual-push-mode=20run=20A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 7 +++++++ .claude/memory/learnings.md | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index e1cbe79..e5748b1 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1364,3 +1364,10 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: prepend coreutils/gnu-sed to PATH in Makefile+hooks; `grep X >/dev/null` (GNU grep treats /dev/null stdout like `-q`, race stays); broad `| grep -q` census (119 hits, fixtures, false confidence). - **Gates**: 3 lenses (FATAL 6 / CONCERNS 4 / FATAL 2) + confirmation CONCERNS(2), all closed r3; GATE 0 MET 8/8 ×2; verifier CONFORME 9/9; security PASS (1 MEDIUM hardened). Linux run `[deferred]`. - **Refs**: contract `.claude/tasks/contracts/2026-10-06-macos-portability-1105.md`, plan `.claude/tasks/plans/2026-10-06-macos-portability-1030.md`, commit 0efdff0 (bugfix/macos-portability), [[BLK-026]], [[LRN-189]], [[LRN-190]]. + +## BDR-111 — Manual-push mode = `gitflow.autopush false` end to end, no new key [accepted] (2026-10-06) +- **Decision**: user need (work machine): same flow, branches + commits + local merges, nothing pushed, push only by hand. Reuse existing human-set `gitflow.autopush` (static deny on `git config gitflow.*`), no `gitflow.mode`. Run A: lib `_gitflow_push_off` single reader for `start`/`finish`/`delete_remote`; `gitflow_delete` checks out CONTAINING base + `--unset-upstream` before `-d`; `_gitflow_sync_base` warns "behind origin, cannot fast-forward" instead of silent `|| true`; `unpushed-guard` silent at Stop, one `ℹ manual push mode:` SessionStart line counting ALL local branches; doctrine line CLAUDE.global.md. Run B (queued): PreToolUse `hooks/push-guard.sh` denies `git push` when autopush=false (user: block, `! git push` only), widen `gitflow.*` deny (`git config * gitflow.*`, `git -c`, `GIT_CONFIG_COUNT=`), settings prose, banner, fail-CLOSED on unparseable value in every reader at once. Run C (queued): skills that push alone (`/capitalize` STEP 5C `git push origin develop`, client-handover, release-candidate/tour claims). ORDER: no autopush=false at work before B+C. +- **Why**: `autopush false` already silenced hooks + remote delete; lib push sites ignored it (bug). Merge is NOT the user's concern (local merge wanted), push is. Fail-open on invalid value kept in A for consistency with untouched hook emitters (AC7). +- **Alternatives rejected**: new `gitflow.mode auto|manual` (duplicates autopush); tty-only lock on `finish` (user wants local merges); `-D` after ancestor gate (statically denied form, reviewers' red flag); fail-closed in lib only (hooks would still push → inconsistent). +- **Gates**: 3 lenses CONCERNS(1/2/2) + confirmation FATAL(4) → r2 fixes (T22j containing base, `-u` fixture, T18n before T18l); feater ×2; GATE 0 7/8 (AC6 = env red); verifier ECARTS(1) = AC6 only; security PASS ×2 (1 MEDIUM fail-open → run B). +- **Refs**: contract `.claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md`, plan `.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md`, commit 2fc8830 (feature/manual-push-mode, UNMERGED). Extends [[BDR-095]] (c); [[LRN-161]], [[LRN-191]], [[LRN-192]], [[LRN-193]], [[BLK-022]]. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 7ec9cb9..535faab 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1700,3 +1700,15 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s ## LRN-190 — Oracle hygiene: wrapped lines, baselines, no rm -rf via variable - **Context**: GATE 0 criterion 4 NOT-MET while code correct: executor wrapped `grep -q … \` + `<<<"$(…)"` at 80 cols (my own style rule), single-line regex missed it. Criterion 7 `shellcheck` bare would fail on pre-existing info notes outside Health Stack scope. Criterion 2 CHECK held `rm -rf "$d"` (destructive-tools rule), executor's copy refused by permission system. - **Apply**: join continuations first (`sed -e ':a' -e 'N' -e '$!ba' -e 's/\\\n[[:space:]]*/ /g'`); lint criteria compare counts against base ref (`git show base:file | shellcheck -`); planted fixtures cleaned with `rm -f file; rmdir dir`. Oracle edits after a red floor logged in CLARIFICATIONS as "oracle maintenance", criterion text never loosened. Extends [[LRN-188]]. + +## LRN-191 — `cmd | grep -q` under pipefail reintroduced one commit after BDR-110 banned it +- **Context**: feater wrote T18j as `git log develop --format=%s | grep -q …` in a `set -uo pipefail` suite. Green alone ×3, red once under load (3 suites + agents in parallel): `grep -q` exits early → SIGPIPE on `git log` → rc 141 → `&&` chain fails. Demo: `seq 1 200000 | grep -q 1` fails 300/300 under pipefail, `grep -q 1 < <(seq …)` 0/300. +- **Apply**: [[BDR-110]] form `grep -q PAT < <(cmd)` in tests, `<<<"$(cmd)"` in prod. Census can't catch it by text (BDR-110 chose no rule) → executor brief + verifier lens must name it: "no multi-line producer piped into `grep -q`". A flake seen ONCE under load is a bug, not noise: reproduce the mechanism before calling it flaky. Single-write `printf '%s' "$v" | grep -q` is safe. + +## LRN-192 — Turning auto-push off re-arms `git branch -d`'s upstream check (LRN-161 inverted) +- **Context**: [[LRN-161]]: auto-push kept upstream in sync → `-d` a no-op guard. Manual-push mode: upstream lags → `-d` REFUSES a branch merged into HEAD ("not yet merged to origin/
") → `finish` merges then rc 5 false "unmerged". First fix `--unset-upstream` then `-d` regressed T22j (hotfix merged into main only, HEAD=develop → `-d` refuses). +- **Apply**: after the explicit ancestor gate, checkout the base that CONTAINS the branch (`merge-base --is-ancestor br develop` ? develop : main), `--unset-upstream`, then `-d`. Any change to push/upstream config → re-read every `-d`, `--ff-only`, `@{u}` site AND the tests that assume upstream in sync (T22j class). Tests: gitflow-test T18k, T22j. + +## LRN-193 — A revised plan gets a fresh challenger, not a re-read: r2 found 3 BLOCKERs inside r1's fixes +- **Context**: manual-push-mode plan. r1 (3 lenses) → 2 MAJOR, I rewrote 5 checklist items. Confirmation pass (1 fresh correctness challenger on the REVISED file) → FATAL(4): my `--unset-upstream` fix broke T22j; my T18l fixture never set develop's upstream (`push` without `-u`, init creates develop untracked); my T18n/T18l order made offline silence vacuous. All three were in text I had just written and re-read. +- **Apply**: `challenge-plan.md` "re-challenge once if materially changed" is load-bearing, never skip it to save a dispatch. Brief the confirmation challenger on the NEW mechanics explicitly (state machine of new tests, fixture preconditions, ordering). Fixes to tests need the same fixture trace as the code (`-u`, upstream, what an earlier test leaves behind). From a2ac0189f715d8b2da7a4feca7a728a7654581b4 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 12:24:35 +0200 Subject: [PATCH 006/547] feat(gitflow): push-guard hook denies Claude's git push in manual-push mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run B of manual-push mode (BDR-111). With `gitflow.autopush false` nothing stops Claude from typing `git push` itself: the `ask` tier is inert under auto mode. This adds the mechanical block the user chose. - hooks/push-guard.sh (PreToolUse, matcher Bash|Monitor, timeout 10): detects a push in the command text (strict, quote-stripped loose and alias patterns; backslash-newline folded in bash, BSD sed/grep only), reads gitflow.autopush in the payload cwd and in every literal -C/cd dir the command names (global config counts outside a repo), denies with the documented JSON form and a reason that tells the user to run the command with `!`. Unparseable value = manual (fail closed); once a push is detected an EXIT trap emits a static deny on any internal error. jq missing = one stderr warning, allow (sibling-hook policy). - settings.json: hook wiring; 18 deny entries closing the write forms of the human-only toggle (any `git … config` spelling, section removal/rename, `-c`, config env overrides, direct edits of git config files); one soft_deny on pushing in manual mode in any form, with no per-turn clearance; the routing-around rule names hook refusals. - hooks/session-start.sh: `🔒 push : manual (autopush=false) — ! git push` banner line when the key reads false (padding in bytes). - lib/tests/push-guard.test.sh: 61 checks (push forms, over-blocks, invalid value, global key, fail-closed trap, no-jq, wiring, banner). Known limits are listed in the hook header; the soft_deny rule is the backstop. Run C (skills that push on their own) and run D (fail-closed readers everywhere) follow. Do not enable manual mode at work before C. --- hooks/push-guard.sh | 125 +++++++++++++++++++++ hooks/session-start.sh | 5 + lib/tests/push-guard.test.sh | 203 +++++++++++++++++++++++++++++++++++ settings.json | 37 ++++++- 4 files changed, 366 insertions(+), 4 deletions(-) create mode 100644 hooks/push-guard.sh create mode 100644 lib/tests/push-guard.test.sh diff --git a/hooks/push-guard.sh b/hooks/push-guard.sh new file mode 100644 index 0000000..a3c86f7 --- /dev/null +++ b/hooks/push-guard.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# push-guard.sh — PreToolUse (Bash|Monitor): refuse `git push` in manual +# push mode (BDR-111). Manual mode = `gitflow.autopush` reads false (or is +# unparseable: fail closed) in the payload cwd or in any literal -C / cd dir +# the command names; outside a repo `git config` reads global/system. +# +# Deny form: JSON on stdout, exit 0 (hookSpecificOutput.permissionDecision +# = "deny"). Silent in auto mode and on every non-push command. The guard +# sees the command TEXT only. Once a push is detected an EXIT trap emits a +# static deny (exit 0) unless a decision was recorded: internal error = +# push refused. jq missing: one stderr warning, allow (sibling hooks). +# +# OVER-BLOCKS in manual mode: any text carrying a later ` push` word after +# a `git` token (git subtree push, git stash push, git log -S "git push", +# grep -rn "git push" skills/, git config --get push.default, git add +# push.sh, git help push, a commit message quoting "git push"). +# MISSES: "git" push, git "push"; ~ / $VAR / $(...) in -C or cd (never +# resolved, never eval'd); --git-dir / GIT_DIR; a push hidden in a script, +# Makefile target or user alias (the soft_deny rule covers those). +set -u +unset CDPATH + +if ! command -v jq >/dev/null 2>&1; then + echo "push-guard: jq missing, guard inactive" >&2 + exit 0 +fi + +payload=$(cat 2>/dev/null) +field() { printf '%s' "$payload" | jq -r "$1 // empty" 2>/dev/null; } +cmd=$(field '.tool_input.command') +cwd=$(field '.cwd') +[ -n "$cmd" ] || exit 0 +[ -d "$cwd" ] || cwd=$PWD + +# Fold line breaks (backslash-newline first), then drop quoted spans. +one=${cmd//$'\\\n'/ } +one=${one//$'\n'/ } +bare=$(printf '%s' "$one" | sed -E "s/\"[^\"]*\"//g; s/'[^']*'//g") + +# is_push: strict (full text), loose (quotes removed), alias definition. +is_push() { + local strict loose alias_re + strict='(^|[^[:alnum:]_.-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^[:space:]-][^[:space:]]*)?)*[[:space:]]+(push|send-pack)([^[:alnum:]_-]|$)' + loose='(^|[^[:alnum:]_.-])git[[:space:]]+([^|;&()]*[[:space:]])?(push|send-pack)([^[:alnum:]_-]|$)' + alias_re='alias\.[^=[:space:]]+=[^[:space:]]*push' + printf '%s' "$one" | grep -qE "$strict" && return 0 + printf '%s' "$bare" | grep -qE "$loose" && return 0 + printf '%s' "$bare" | grep -qE "$alias_re" +} + +is_push || exit 0 + +# static_deny: the fixed fail-closed answer (no jq needed to build it). +static_deny() { + printf '%s' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"push-guard: internal error while checking manual push mode — push refused (fail closed). Run it yourself in the terminal with !"}}' +} +decided=0 +trap '[ "$decided" = 1 ] || static_deny; exit 0' EXIT + +# unquote : strip one pair of surrounding quotes. +unquote() { + local t=$1 + case "$t" in + \"*\") t=${t#\"}; t=${t%\"} ;; + \'*\') t=${t#\'}; t=${t%\'} ;; + esac + printf '%s' "$t" +} + +# arg_tokens: the directory argument of every `cd`/`pushd`/`-C` in the text. +arg_tokens() { + local arg='(--[[:space:]]+)?("[^"]*"|'"'[^']*'"'|[^[:space:];&|()]+)' + { + printf '%s' "$one" | grep -oE "(^|[[:space:];&|()])(cd|pushd)[[:space:]]+$arg" + printf '%s' "$one" | grep -oE "(^|[[:space:]])-C[[:space:]]+$arg" + } | sed -E 's/^[[:space:];&|()]*(cd|pushd|-C)[[:space:]]+(--[[:space:]]+)?//' +} + +# candidates: cwd, then each literal dir the command names (resolved from +# cwd; unresolvable ones are skipped, never an allow). +candidates() { + local tok dir + printf '%s\n' "$cwd" + arg_tokens | while IFS= read -r tok; do + tok=$(unquote "$tok") + case "$tok" in ''|-) continue ;; esac + dir=$( cd -- "$cwd" && cd -- "$tok" 2>/dev/null && pwd -P ) || continue + printf '%s\n' "$dir" + done +} + +# mode_in : prints `manual`, `invalid:` or nothing. +mode_in() { + ( + cd -- "$1" || exit 0 + raw=$(git config gitflow.autopush 2>/dev/null) + val=$(git config --bool --default true gitflow.autopush 2>/dev/null) + [ "$val" = false ] && echo manual + [ -n "$raw" ] && ! git config --bool gitflow.autopush >/dev/null 2>&1 \ + && echo "invalid:$raw" + exit 0 + ) +} + +# deny : emit the deny JSON, record the decision. +deny() { + local out + out=$(jq -cn --arg r "$1" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}') || out=$(static_deny) + printf '%s' "$out" + decided=1 + exit 0 +} + +while IFS= read -r dir; do + mode=$(mode_in "$dir" | head -n 1) + case "$mode" in + manual) + deny "push-guard: manual push mode (gitflow.autopush=false in $dir) — Claude never pushes. Run it yourself in the terminal: ! $cmd" ;; + invalid:*) + deny "push-guard: gitflow.autopush='${mode#invalid:}' is not a boolean in $dir — treated as manual push mode (fail closed). Fix the value by hand, or run it yourself: ! $cmd" ;; + esac +done < <(candidates) + +decided=1 +exit 0 diff --git a/hooks/session-start.sh b/hooks/session-start.sh index ef22f19..5bf9d67 100644 --- a/hooks/session-start.sh +++ b/hooks/session-start.sh @@ -230,6 +230,11 @@ if [ -n "$GF_REFRESHED" ]; then printf "│ 🪝 %-44s│\n" "${_gf_line:0:44}" unset _gf_line fi +# ── manual-push mode (BDR-111): one lock line when this repo never auto-pushes ── +# %-46s, not 44: bash printf pads by BYTES and "—" is 3 bytes (2 extra). +if [ "$(git config --bool --default true gitflow.autopush 2>/dev/null)" = false ]; then + printf "│ 🔒 %-46s│\n" "push : manual (autopush=false) — ! git push" +fi if [ -n "$GRAPHIFY_HINT" ]; then printf "│ 🕸️ %-44s│\n" "${GRAPHIFY_HINT:0:44}" printf "│ %-40s│\n" "→ /graphify (AST, seconds) — you decide" diff --git a/lib/tests/push-guard.test.sh b/lib/tests/push-guard.test.sh new file mode 100644 index 0000000..08549e2 --- /dev/null +++ b/lib/tests/push-guard.test.sh @@ -0,0 +1,203 @@ +#!/usr/bin/env bash +# lib/tests/push-guard.test.sh +# hooks/push-guard.sh (BDR-111): denies `git push` in manual push mode, +# silent otherwise. Also locks the settings.json wiring and the banner line. +set -u +export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +H="$ROOT/hooks/push-guard.sh" +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +pass=0; fail=0 +check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); else fail=$((fail+1)); + printf 'FAIL %s: got[%s] want[%s]\n' "$1" "$2" "$3"; fi; } + +# ── fixtures ── +mkrepo() { mkdir -p "$1" && git init -q "$1"; } +mkdir -p "$WORK/plain" +mkrepo "$WORK/auto" +mkrepo "$WORK/manual"; git -C "$WORK/manual" config gitflow.autopush false +mkdir -p "$WORK/manual/sub" "$WORK/manual/my dir" +mkrepo "$WORK/bad"; git -C "$WORK/bad" config gitflow.autopush flase +mkrepo "$WORK/manual2"; git -C "$WORK/manual2" config gitflow.autopush false +printf '[gitflow]\n\tautopush = false\n' > "$WORK/gconf" +mkdir -p "$WORK/shim" +cat > "$WORK/shim/jq" < + local payload + payload=$(jq -n --arg c "$1" --arg d "$2" \ + '{hook_event_name:"PreToolUse",tool_name:"Bash",tool_input:{command:$c},cwd:$d}') + OUT=$(printf '%s' "$payload" | bash "$H" 2>/dev/null); RC=$? +} +verdict() { + if [ "$RC" -ne 0 ]; then echo "error:$RC"; return; fi + if [ -z "$OUT" ]; then echo allow; return; fi + if [ "$(jq -r '.hookSpecificOutput.permissionDecision' <<<"$OUT" 2>/dev/null)" = deny ] + then echo deny; else echo "error:badjson"; fi +} +fire() { run "$1" "$2"; verdict; } +reason() { jq -r '.hookSpecificOutput.permissionDecisionReason' <<<"$OUT"; } + +M="$WORK/manual" + +# ── auto / none: silent ── +check T1-plain-allow "$(fire 'git push' "$WORK/plain")" allow +check T2-auto-allow "$(fire 'git push' "$WORK/auto")" allow +check T3-auto-upstream "$(fire 'git push -u origin feature/x' "$WORK/auto")" allow + +# ── manual: deny ── +run 'git push' "$M" +check T4-push "$(verdict)" deny +check T4b-one-line "$(printf '%s' "$OUT" | wc -l | tr -d ' ')" 0 +check T5-push-u "$(fire 'git push -u origin feature/x' "$M")" deny +check T6-dash-C "$(fire "git -C \"$M\" push" "$WORK/plain")" deny +check T7-cd-sub "$(fire 'cd sub && git push' "$M")" deny +check T8-dry-run "$(fire 'git push --dry-run' "$M")" deny +check T9-dash-c "$(fire 'git -c a=b push origin HEAD' "$M")" deny +check T10-subshell "$(fire '(cd sub && git push)' "$M")" deny +check T11-bash-c "$(fire "bash -c 'git push'" "$M")" deny +check T12-semicolon "$(fire 'git push; echo done' "$M")" deny +check T13-abs-git "$(fire '/usr/bin/git push' "$M")" deny +check T14-no-pager "$(fire 'git --no-pager push' "$M")" deny +check T15-quoted-dir "$(fire "cd \"$M/my dir\"; git push" "$WORK/plain")" deny +check T16-amp "$(fire 'git push&&echo ok' "$M")" deny +check T17-cd-dashdash "$(fire "cd -- $M && git push" "$WORK/plain")" deny +check T18-backslash-nl "$(fire $'git \\\n push' "$M")" deny +check T19-pipe "$(fire 'git push|tee /dev/null' "$M")" deny +check T20-subtree "$(fire 'git subtree push --prefix=x origin main' "$M")" deny +check T21-cd-amp "$(fire "(cd $M&&git push)" "$WORK/plain")" deny +check T22-alias "$(fire 'git -c alias.p=push p' "$M")" deny +check T23-send-pack "$(fire 'git send-pack origin' "$M")" deny +check T24-grep-overblock "$(fire 'grep -rn "git push" skills/' "$M")" deny +check T25-config-overblock "$(fire 'git config --get push.default' "$M")" deny + +# ── manual: allow ── +check T26-commit-msg "$(fire 'git status && git commit -m "fix push guard"' "$M")" allow +check T27-gitflow "$(fire 'bash ~/.claude/lib/gitflow.sh finish' "$M")" allow +check T28-pushd "$(fire 'git pushd' "$M")" allow +check T29-stash "$(fire 'git stash' "$M")" allow +check T30-echo "$(fire 'echo pushed' "$M")" allow +check T31-rg-C "$(fire 'rg -C 3 push src/' "$M")" allow +check T32-branch "$(fire 'git branch --show-current' "$M")" allow + +# ── invalid value: fail closed ── +run 'git push' "$WORK/bad" +check T33-invalid "$(verdict)" deny +R=$(reason) +check T33b-not-boolean "$(grep -c 'not a boolean' <<<"$R")" 1 +check T33c-raw-value "$(grep -c 'flase' <<<"$R")" 1 + +# ── global key ── +g() { # g : run with the global config pointing at gconf + local saved=$GIT_CONFIG_GLOBAL + GIT_CONFIG_GLOBAL="$WORK/gconf"; fire "$1" "$2" + GIT_CONFIG_GLOBAL=$saved +} +check T34a-global-auto-cwd "$(g 'git push' "$WORK/auto")" deny +check T34b-global-cd "$(g "cd \"$WORK/auto\" && git push" "$WORK/plain")" deny +check T34c-control "$(fire 'git push' "$WORK/auto")" allow + +# ── toggle control ── +check T35a-manual2 "$(fire 'git push' "$WORK/manual2")" deny +git -C "$WORK/manual2" config --unset gitflow.autopush +check T35b-unset "$(fire 'git push' "$WORK/manual2")" allow + +# ── fail closed on internal error ── +# T36: a jq shim that fails on `jq -cn` makes the guard's deny path error. +saved_path=$PATH; PATH="$WORK/shim:$PATH" +run 'git push' "$M" +PATH=$saved_path +check T36-static-deny "$(verdict)" deny +check T36b-internal "$(grep -c 'internal error' <<<"$(reason)")" 1 +check T36c-rc "$RC" 0 +run 'git push' "$M" +R=$(reason) +check T37a-bang "$(grep -c '! git push' <<<"$R")" 1 +check T37b-mode "$(grep -c 'manual push mode' <<<"$R")" 1 + +# T47: jq absent from PATH: guard warns on stderr and stays inactive. +mkdir -p "$WORK/nojq" +for tool in bash cat git grep sed tr dirname basename mktemp; do + real=$(command -v "$tool") || continue + case "$real" in /*) ln -sf "$real" "$WORK/nojq/$tool" ;; esac +done +payload47=$(jq -n --arg c 'git push' --arg d "$M" \ + '{tool_input:{command:$c},cwd:$d}') +out47=$(cd "$M" && printf '%s' "$payload47" \ + | PATH="$WORK/nojq" "$(command -v bash)" "$H" 2>"$WORK/nojq.err"); rc47=$? +check T47a-rc "$rc47" 0 +check T47b-stdout-empty "$out47" "" +check T47c-warn "$(grep -c 'jq missing' "$WORK/nojq.err")" 1 + +# ── payload edge cases ── +run_empty=$(printf '{}' | bash "$H" 2>/dev/null); rc=$? +check T38-empty-stdout "$run_empty" "" +check T38b-rc "$rc" 0 +nocwd=$(jq -n '{tool_input:{command:"git push"}}') +out=$(cd "$M" && printf '%s' "$nocwd" | bash "$H" 2>/dev/null) +check T39-no-cwd "$(jq -r '.hookSpecificOutput.permissionDecision' <<<"$out")" deny + +# ── settings.json wiring (file content only) ── +S="$ROOT/settings.json" +check T40-wiring "$(jq -e '.hooks.PreToolUse[] + | select(any(.hooks[]; .command=="bash ~/.claude/hooks/push-guard.sh")) + | .matcher=="Bash|Monitor" and .hooks[0].timeout==10' "$S" 2>&1)" true + +has_deny() { jq -e --arg e "$1" '.permissions.deny | index($e)' "$S" >/dev/null; } +missing="" +while IFS= read -r e; do + has_deny "$e" || missing="$missing [$e]" +done <<'EOF' +Bash(git *config *gitflow.*) +Bash(git *config *remove-section*gitflow*) +Bash(git *config *rename-section*gitflow*) +Bash(git -c gitflow.*) +Bash(git * -c gitflow.*) +Bash(*--config-env*gitflow*) +Bash(*GIT_CONFIG_PARAMETERS*) +Bash(*GIT_CONFIG_COUNT*) +Bash(* GIT_CONFIG_GLOBAL=*) +Bash(* GIT_CONFIG_SYSTEM=*) +Edit(**/.git/config) +Write(**/.git/config) +Edit(**/.gitconfig) +Write(**/.gitconfig) +Edit(~/.gitconfig) +Write(~/.gitconfig) +Edit(~/.config/git/config) +Write(~/.config/git/config) +EOF +check T41-new-deny-present "$missing" "" + +# Nothing removed: every deny entry of the pre-run-B settings is still there. +base=HEAD +lost=$(git -C "$ROOT" show "$base:settings.json" 2>/dev/null \ + | jq -r --slurpfile now "$S" \ + '.permissions.deny[] | select(. as $e | ($now[0].permissions.deny | index($e)) == null)') +check T42-nothing-removed "$lost" "" + +soft=$(jq -r '.autoMode.soft_deny[]' "$S") +check T43a-soft-rule "$(grep -c 'manual-push mode' <<<"$soft" | tr -d ' ')" 1 +check T43b-clearance "$(grep -c "does not clear it: the user types \`! git push\`" <<<"$soft")" 1 + +# ── session banner ── +banner() { # banner + (cd "$1" && SESSION_START_OFFLINE=1 bash "$ROOT/hooks/session-start.sh" \ + /dev/null) +} +out=$(banner "$M") +check T44-banner-control "$(grep -c 'Claude Code config' <<<"$out")" 1 +check T45-banner-manual "$(grep -c 'push : manual (autopush=false)' <<<"$out")" 1 +out=$(banner "$WORK/auto") +check T46a-auto-control "$(grep -c 'Claude Code config' <<<"$out")" 1 +check T46b-auto-silent "$(grep -c 'push : manual' <<<"$out")" 0 + +printf 'PASS=%s FAIL=%s\n' "$pass" "$fail"; [ "$fail" -eq 0 ] diff --git a/settings.json b/settings.json index bc35b4c..9af30b1 100644 --- a/settings.json +++ b/settings.json @@ -316,7 +316,25 @@ "Bash(git config --local core.hooksPath *)", "Bash(git config gitflow.*)", "Bash(git config --global gitflow.*)", - "Bash(git config --local gitflow.*)" + "Bash(git config --local gitflow.*)", + "Bash(git *config *gitflow.*)", + "Bash(git *config *remove-section*gitflow*)", + "Bash(git *config *rename-section*gitflow*)", + "Bash(git -c gitflow.*)", + "Bash(git * -c gitflow.*)", + "Bash(*--config-env*gitflow*)", + "Bash(*GIT_CONFIG_PARAMETERS*)", + "Bash(*GIT_CONFIG_COUNT*)", + "Bash(* GIT_CONFIG_GLOBAL=*)", + "Bash(* GIT_CONFIG_SYSTEM=*)", + "Edit(**/.git/config)", + "Write(**/.git/config)", + "Edit(**/.gitconfig)", + "Write(**/.gitconfig)", + "Edit(~/.gitconfig)", + "Write(~/.gitconfig)", + "Edit(~/.config/git/config)", + "Write(~/.config/git/config)" ], "ask": [ "Bash(bash -c *)", @@ -363,6 +381,16 @@ "command": "bash ~/.claude/hooks/rtk-rewrite.sh" } ] + }, + { + "matcher": "Bash|Monitor", + "hooks": [ + { + "type": "command", + "command": "bash ~/.claude/hooks/push-guard.sh", + "timeout": 10 + } + ] } ], "Notification": [ @@ -465,6 +493,7 @@ "Sending SIGKILL (`kill -9`) or killing processes by name (`killall`, `pkill`). These reach processes outside this session, including the user's editors, shells, dtach sessions and background jobs, and the target is chosen by a pattern, so a typo kills the wrong thing. Clear only when the user named the process in this turn.", "Editing more than one file in place in a single command: `sed -i` or `perl -pi` over a glob, or a loop over `git ls-files`. The damage is not loss, since git recovers it, but a diff spanning hundreds of files that nobody reads before committing. `sed -i` on a single named file passes. Clear only when the user asked for the sweep.", "Moving or renaming a directory inside the repo (`mv src/api src/api_old`, or any `mv` of a tree). It breaks imports and paths silently, and the breakage surfaces far from the command. Clear only when the user asked for that move.", + "Pushing in manual-push mode (`gitflow.autopush false`, set by the user): any git push by Claude — direct, scripted, aliased, inside a subshell, a Makefile target, a sub-agent, or after a HOME/GIT_CONFIG override that hides the key. The push-guard hook catches the direct forms; this rule covers the rest. A request to push in this turn does not clear it: the user types `! git push` in the terminal.", "An inline interpreter or `xargs` that deletes, or that writes outside the current working directory: `python3 -c`, `python -c` or `node -e` calling `rmtree`, `remove`, `unlink` or `truncate`; `xargs` feeding `rm`, `mv` or `dd`. `find ... | xargs rm` is the case that matters, since it routes around the `find * -exec rm` deny rule. Reading, computing, and editing a file inside the working directory pass untouched.", "Docker data destruction on this workstation: `docker rm -f` of a container, and `docker run` with a bind mount outside the current working directory or the session temp dir (volume drops, `system prune`, `compose down -v` and `--privileged` are static deny rules and cannot be cleared). Clear only when the user named the container or the mount in this turn.", "Discarding uncommitted work: `git checkout -- ` or `git checkout .`, `git restore` without `--staged`, `git stash pop` onto a dirty tree, or overwriting a modified tracked file with `cp` or `mv`. Git recovers a committed state, not this. Clear only when the user asked to discard those exact changes in this turn.", @@ -477,8 +506,8 @@ "Secret exfiltration: reading a `.env`, an SSH key, a token or a credentials file, and then sending what it contained outside this machine. That covers an HTTP request body or header, a paste or gist service, a file upload, an email, and a commit or push to any repository. The static deny rules match the reading tools by pattern and cannot see the second half of the chain; read and send are separate steps and may sit several turns apart. No instruction clears this.", "Production deployment: running a project's deploy script (`bin/deploy.sh` and its equivalents), any lftp, FTP, SFTP or rsync push to a hosting provider, and any action against a target whose name carries `prod` or `production` as a whole word or name segment. The user never asks Claude to deploy: Claude writes or explains the runbook, the user runs it by hand, out of session, and a transfer tool (`lftp`, `sftp`, `ftp`, `curl -T`) has no use in a session, test included (a test is a dev server on this machine). A green test suite, a finished feature, or a plan step that reads \"deploy\" is not an instruction to deploy. No in-session instruction clears this.", "Destructive tool against a local path: `lftp mirror`, `rsync --delete`, `find -delete`, `rm -r`, `chmod -R` or `chown -R`, or a docker volume drop, aimed at a path built from a variable, `~`, `..` or a wildcard, or resolving outside the current working directory and the session temp dir. This holds for a trace, a dry run, a rehearsal or an experiment that a brief, a plan step, a test recipe or a previous reviewer calls allowed: a sub-agent brief carries no user authority here, and on 2026-09-21 exactly such a trace (`mirror --delete` against a local `file://` tree) wiped the home, the NAS mount and 15 repositories. Tracing what such a tool would do is done by reading it. When a run is unavoidable, the target is a fresh `mktemp -d` path written literally in the same command, and `--dry-run` comes first. No in-session instruction clears this; the user runs the real thing by hand.", - "Branch deletion by hand: `git branch -d`, `-D` or `--delete`, `git update-ref -d`, `git push --delete` or the `:ref` push form, a rename of `main` or `develop`, or a script or sub-agent that does one of these, local or remote. The only sanctioned path is `gitflow.sh finish` or `gitflow.sh delete `, which refuses `main`/`develop` outright and any branch not merged into develop or main, then removes the `origin/` copy once its own tip passes the same check; `git branch -d` proves nothing once the branch has an auto-pushed upstream, which every branch has since BDR-095. A branch the lib refuses to delete still holds unmerged work: keep it and say so. No brief, plan step or cleanup routine authorizes a hand deletion.", - "Routing around a guardrail: a command the deny rules or this classifier refused is not run again through a wrapper script, an alias, a heredoc, a Makefile target written for the purpose, an env file, another shell, `make`/`python -c` indirection or another agent. That is the same action one step removed. A refusal ends the attempt: report the exact command and the rule that stopped it, then wait for the user. This binds every sub-agent whatever its brief says: a brief that orders a refused form is wrong, report it, do not comply. The legitimate hermetic test run is `make test` (optionally `suite=`); the export lives in the Makefile, never on the command line.", + "Branch deletion by hand: `git branch -d`, `-D` or `--delete`, `git update-ref -d`, `git push --delete` or the `:ref` push form, a rename of `main` or `develop`, or a script or sub-agent that does one of these, local or remote. The only sanctioned path is `gitflow.sh finish` or `gitflow.sh delete `, which refuses `main`/`develop` outright and any branch not merged into develop or main, then removes the `origin/` copy once its own tip passes the same check; `git branch -d` proves nothing once the branch has an auto-pushed upstream, which every branch has since BDR-095 (manual-push mode: the lib unsets the upstream itself before `-d`; the hand form stays banned). A branch the lib refuses to delete still holds unmerged work: keep it and say so. No brief, plan step or cleanup routine authorizes a hand deletion.", + "Routing around a guardrail: a command the deny rules, a PreToolUse hook or this classifier refused is not run again through a wrapper script, an alias, a heredoc, a Makefile target written for the purpose, an env file, another shell, `make`/`python -c` indirection or another agent. That is the same action one step removed. A refusal ends the attempt: report the exact command and the rule that stopped it, then wait for the user. This binds every sub-agent whatever its brief says: a brief that orders a refused form is wrong, report it, do not comply. The legitimate hermetic test run is `make test` (optionally `suite=`); the export lives in the Makefile, never on the command line.", "Disarming the guardrails: removing or weakening an entry in the `deny`, `soft_deny` or `hard_deny` lists of any settings.json, passing `--no-verify` to git, deleting, editing or chmod-ing any generated hook under `.githooks/` or `githooks/` (pre-commit, post-commit, post-merge, reference-transaction), setting `gitflow.protect` or `gitflow.autopush`, setting `disableAllHooks`, or switching `permissions.defaultMode` to `bypassPermissions`. Adding a restriction is fine; removing one is not. When a task is blocked by a guardrail, say so and stop, rather than widening the guardrail to get through. The user maintains these files by hand. No instruction clears this." ], "environment": [ @@ -496,7 +525,7 @@ "**Internal package registry**: none. Public npm and PyPI.", "**Host containment**: an ordinary developer workstation with open internet and no sandbox. Nothing is contained by the environment itself.", "**Data-loss history**: on 2026-09-21 a sub-agent's `lftp mirror --delete` trace against a local `file://` path wiped the home, the NAS mount and 15 repositories in 90 seconds; nothing had been pushed for four days. The deny rules on transfer and mirror tools, the hard_deny on destructive tools against local paths, and the gitflow push hooks exist because of it.", - "**Push discipline**: every branch is pushed at creation and every commit at once by the gitflow post-commit and post-merge hooks, so the remote holds the work. A branch ahead of its upstream is a defect to fix now, not a state to keep.", + "**Push discipline**: every branch is pushed at creation and every commit at once by the gitflow post-commit and post-merge hooks, so the remote holds the work. A branch ahead of its upstream is a defect to fix now, not a state to keep. Exception, manual-push mode (`gitflow.autopush false`, set by the user, work machine): nothing is pushed by Claude, in any form; the user pushes by hand with `! git push`.", "**Sensitive remote targets**: any namespace, host, database or container whose name carries `prod` or `production` as a whole word or name segment.", "**Sensitive data locations & audiences**: per-project `.env` files (gitignored) hold database, deploy and API credentials; some web projects store customer-submitted form data under a retention policy. Both are personal or client data — never send either to an external service." ] From 6468eda49533dd4de0aff942e874da0cbf1cd069 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 12:34:56 +0200 Subject: [PATCH 007/547] fix(push-guard): fail closed on token floods, git failures and quoted cd targets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hardening after the security gate on a2ac018 (3 MEDIUM, all closed and re-measured): - dir tokens are deduplicated and capped: more than 20 distinct cd/-C targets in one command denies before any git fork (20000 tokens: 0.15 s against the 10 s hook timeout that used to turn a flood into an allow) - a git or cd failure while reading gitflow.autopush denies instead of reading as auto (git absent, usage error, unenterable dir); the key being unset is the only "auto" answer; the decision is recorded only after one candidate was evaluated cleanly, else the EXIT trap denies - cd/pushd/-C targets that follow a quote or backtick (bash -c '…') are extracted; quote characters are excluded from unquoted tokens User decision (contract, gated): both fail-closed cases also fire in auto mode on such pathological commands; silence in auto mode holds for every ordinary push. Header limits list the residual misses (quotes or backslashes inside a token, cumulative relative cd, unparseable payload) backed by the soft_deny rule. Tests: 71 checks (T48–T50b added). --- hooks/push-guard.sh | 80 +++++++++++++++++++++++++----------- lib/tests/push-guard.test.sh | 36 ++++++++++++++++ 2 files changed, 92 insertions(+), 24 deletions(-) diff --git a/hooks/push-guard.sh b/hooks/push-guard.sh index a3c86f7..12f96ed 100644 --- a/hooks/push-guard.sh +++ b/hooks/push-guard.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # push-guard.sh — PreToolUse (Bash|Monitor): refuse `git push` in manual # push mode (BDR-111). Manual mode = `gitflow.autopush` reads false (or is -# unparseable: fail closed) in the payload cwd or in any literal -C / cd dir +# unparseable or unreadable: fail closed) in the payload cwd or in any literal -C / cd dir # the command names; outside a repo `git config` reads global/system. # # Deny form: JSON on stdout, exit 0 (hookSpecificOutput.permissionDecision @@ -14,9 +14,13 @@ # a `git` token (git subtree push, git stash push, git log -S "git push", # grep -rn "git push" skills/, git config --get push.default, git add # push.sh, git help push, a commit message quoting "git push"). -# MISSES: "git" push, git "push"; ~ / $VAR / $(...) in -C or cd (never -# resolved, never eval'd); --git-dir / GIT_DIR; a push hidden in a script, -# Makefile target or user alias (the soft_deny rule covers those). +# MISSES: "git" push, git "push", git pu\sh, git $'push', $g push; ~ / $VAR / +# $(...) in -C or cd (never resolved, never eval'd); --git-dir / GIT_DIR; a +# push hidden in a script, Makefile target, user alias or an alias planted +# by a redirect into .git/config; cumulative relative `cd a && cd b` (each +# dir is resolved from cwd, not from the previous cd). LIMITS: more than 20 +# distinct cd/-C dir tokens in one command is refused outright. The +# soft_deny rule covers every miss above. set -u unset CDPATH @@ -68,37 +72,53 @@ unquote() { } # arg_tokens: the directory argument of every `cd`/`pushd`/`-C` in the text. +# A quote or backtick may precede the command word (bash -c 'cd d && ...'). arg_tokens() { - local arg='(--[[:space:]]+)?("[^"]*"|'"'[^']*'"'|[^[:space:];&|()]+)' + local pre='[[:space:];&|()"'"'"'`]' + local arg='(--[[:space:]]+)?("[^"]*"|'"'[^']*'"'|[^[:space:];&|()"'"'"'`]+)' { - printf '%s' "$one" | grep -oE "(^|[[:space:];&|()])(cd|pushd)[[:space:]]+$arg" - printf '%s' "$one" | grep -oE "(^|[[:space:]])-C[[:space:]]+$arg" - } | sed -E 's/^[[:space:];&|()]*(cd|pushd|-C)[[:space:]]+(--[[:space:]]+)?//' + printf '%s' "$one" | grep -oE "(^|$pre)(cd|pushd)[[:space:]]+$arg" + printf '%s' "$one" | grep -oE "(^|$pre)-C[[:space:]]+$arg" + } | sed -E "s/^$pre*(cd|pushd|-C)[[:space:]]+(--[[:space:]]+)?//" } -# candidates: cwd, then each literal dir the command names (resolved from -# cwd; unresolvable ones are skipped, never an allow). +# resolve_dir : absolute dir for a literal token, from cwd. A missing +# dir yields nothing (skipped); an existing but unenterable one yields its +# path so mode_in fails closed on it. +resolve_dir() { + ( + cd -- "$cwd" 2>/dev/null || exit 1 + [ -d "$1" ] || exit 1 + if cd -- "$1" 2>/dev/null; then pwd -P; exit 0; fi + case "$1" in /*) printf '%s\n' "$1" ;; *) printf '%s/%s\n' "$PWD" "$1" ;; esac + ) +} + +# candidates: cwd, then each distinct literal dir of $tokens, deduplicated +# after resolution (unresolvable ones are skipped, never an allow). candidates() { - local tok dir + local tok printf '%s\n' "$cwd" - arg_tokens | while IFS= read -r tok; do + printf '%s\n' "$tokens" | while IFS= read -r tok; do tok=$(unquote "$tok") case "$tok" in ''|-) continue ;; esac - dir=$( cd -- "$cwd" && cd -- "$tok" 2>/dev/null && pwd -P ) || continue - printf '%s\n' "$dir" - done + resolve_dir "$tok" + done | sort -u } -# mode_in : prints `manual`, `invalid:` or nothing. +# mode_in : prints `manual`, `auto` (key unset or true), +# `invalid:` (not a boolean) or `failed:` (git or cd failed). mode_in() { ( - cd -- "$1" || exit 0 - raw=$(git config gitflow.autopush 2>/dev/null) - val=$(git config --bool --default true gitflow.autopush 2>/dev/null) - [ "$val" = false ] && echo manual - [ -n "$raw" ] && ! git config --bool gitflow.autopush >/dev/null 2>&1 \ - && echo "invalid:$raw" - exit 0 + cd -- "$1" 2>/dev/null || { echo "failed:cannot enter the directory"; exit 0; } + val=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? + case "$rc" in + 0) if [ "$val" = false ]; then echo manual; else echo auto; fi ;; + 1) echo auto ;; + *) raw=$(git config gitflow.autopush 2>/dev/null) + if [ -n "$raw" ]; then echo "invalid:$raw" + else echo "failed:git exited $rc"; fi ;; + esac ) } @@ -111,6 +131,14 @@ deny() { exit 0 } +# Cap the distinct dir tokens before resolving any (hook timeout is 10 s). +tokens=$(arg_tokens | sort -u) +ntok=$(printf '%s\n' "$tokens" | grep -c .) +if [ "$ntok" -gt 20 ]; then + deny "push-guard: too many directory tokens in one command ($ntok > 20) — push refused (fail closed). Split the command, or run it yourself: ! $cmd" +fi + +evaluated=0 while IFS= read -r dir; do mode=$(mode_in "$dir" | head -n 1) case "$mode" in @@ -118,8 +146,12 @@ while IFS= read -r dir; do deny "push-guard: manual push mode (gitflow.autopush=false in $dir) — Claude never pushes. Run it yourself in the terminal: ! $cmd" ;; invalid:*) deny "push-guard: gitflow.autopush='${mode#invalid:}' is not a boolean in $dir — treated as manual push mode (fail closed). Fix the value by hand, or run it yourself: ! $cmd" ;; + failed:*) + deny "push-guard: could not read gitflow.autopush in $dir (${mode#failed:}) — git failed, push refused (fail closed). Run it yourself in the terminal: ! $cmd" ;; + auto) evaluated=$((evaluated + 1)) ;; esac done < <(candidates) -decided=1 +# Zero cleanly evaluated candidates: leave decided=0, the EXIT trap denies. +[ "$evaluated" -gt 0 ] && decided=1 exit 0 diff --git a/lib/tests/push-guard.test.sh b/lib/tests/push-guard.test.sh index 08549e2..feef387 100644 --- a/lib/tests/push-guard.test.sh +++ b/lib/tests/push-guard.test.sh @@ -145,6 +145,42 @@ nocwd=$(jq -n '{tool_input:{command:"git push"}}') out=$(cd "$M" && printf '%s' "$nocwd" | bash "$H" 2>/dev/null) check T39-no-cwd "$(jq -r '.hookSpecificOutput.permissionDecision' <<<"$out")" deny +# ── hardening: candidate cap, git failure, quote-prefixed cd ── +cmd48=""; for i in $(seq 1 25); do cmd48="${cmd48}cd /x$i;"; done +run "$cmd48 git push" "$WORK/auto" +check T48-cap-deny "$(verdict)" deny +check T48-cap-reason "$(grep -c 'too many directory tokens' <<<"$(reason)")" 1 +cmd48b=""; for i in 1 2 3 4 5; do cmd48b="${cmd48b}cd \"$M\";"; done +run "$cmd48b git push" "$WORK/plain" +check T48b-dedup-detect "$(verdict)" deny +check T48b-manual-reason "$(grep -c 'manual push mode' <<<"$(reason)")" 1 + +# T49: git absent from PATH: the mode cannot be read, so deny (fail closed). +mkdir -p "$WORK/nogit" +for tool in bash cat grep sed tr jq dirname basename mktemp head sort wc; do + real=$(command -v "$tool") || continue + case "$real" in /*) ln -sf "$real" "$WORK/nogit/$tool" ;; esac +done +payload49=$(jq -n --arg c 'git push' --arg d "$M" \ + '{tool_input:{command:$c},cwd:$d}') +out49=$(printf '%s' "$payload49" | PATH="$WORK/nogit" "$(command -v bash)" "$H" 2>/dev/null); rc49=$? +check T49-rc "$rc49" 0 +check T49-deny "$(jq -r '.hookSpecificOutput.permissionDecision' <<<"$out49")" deny +check T49-reason "$(jq -r '.hookSpecificOutput.permissionDecisionReason' <<<"$out49" | grep -cE 'git|internal error')" 1 + +# T49b: an existing but unenterable candidate dir fails closed. +mkdir -p "$WORK/locked"; chmod 000 "$WORK/locked" +if [ -r "$WORK/locked" ] || (cd "$WORK/locked" 2>/dev/null); then + echo "SKIP T49b-unreadable (chmod 000 ineffective for this user)" +else + check T49b-unreadable "$(fire "cd \"$WORK/locked\" && git push" "$WORK/plain")" deny +fi +chmod 755 "$WORK/locked" + +# T50: a cd that follows a quote is still extracted. +check T50-bash-c-cd "$(fire "bash -c 'cd \"$M\" && git push'" "$WORK/plain")" deny +check T50b-unquoted-arg "$(fire "bash -c 'cd $M && git push'" "$WORK/plain")" deny + # ── settings.json wiring (file content only) ── S="$ROOT/settings.json" check T40-wiring "$(jq -e '.hooks.PreToolUse[] From 4630b625f7d8f4b3bbf107a320cb94b2ff7694c1 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 12:41:46 +0200 Subject: [PATCH 008/547] =?UTF-8?q?chore(memory):=20BDR-112=20+=20LRN-194.?= =?UTF-8?q?.196=20+=20journal=20=E2=80=94=20feat=20manual-push-guard=20run?= =?UTF-8?q?=20B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 7 +++ .claude/memory/journal.md | 4 ++ .claude/memory/learnings.md | 12 ++++ .claude/tasks/TODO.md | 5 +- .../2026-10-07-manual-push-guard-1003.md | 49 ++++++++++++++++ .../2026-10-07-manual-push-guard-1003.md | 57 +++++++++++++++++++ 6 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md create mode 100644 .claude/tasks/plans/2026-10-07-manual-push-guard-1003.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index e5748b1..c4bc03e 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1371,3 +1371,10 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: new `gitflow.mode auto|manual` (duplicates autopush); tty-only lock on `finish` (user wants local merges); `-D` after ancestor gate (statically denied form, reviewers' red flag); fail-closed in lib only (hooks would still push → inconsistent). - **Gates**: 3 lenses CONCERNS(1/2/2) + confirmation FATAL(4) → r2 fixes (T22j containing base, `-u` fixture, T18n before T18l); feater ×2; GATE 0 7/8 (AC6 = env red); verifier ECARTS(1) = AC6 only; security PASS ×2 (1 MEDIUM fail-open → run B). - **Refs**: contract `.claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md`, plan `.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md`, commit 2fc8830 (feature/manual-push-mode, UNMERGED). Extends [[BDR-095]] (c); [[LRN-161]], [[LRN-191]], [[LRN-192]], [[LRN-193]], [[BLK-022]]. + +## BDR-112 — push-guard: text-only PreToolUse deny of Claude's `git push` in manual-push mode, fail closed [accepted] (2026-10-07) +- **Decision**: run B of [[BDR-111]]. `hooks/push-guard.sh` (own PreToolUse group `Bash|Monitor`, timeout 10) reads `tool_input.command` + `cwd`; folds `\`-newline in bash (BSD sed unsafe, [[LRN-195]]); three ERE matches on `/usr/bin/grep`: STRICT (git + `-opt [arg]`* + push|send-pack, boundaries `[^[:alnum:]_.-]` / `[^[:alnum:]_-]`), LOOSE on quote-stripped text (any later ` push` word in the same simple command), ALIAS (`alias.x=…push`). Candidate dirs = cwd + literal `-C`/`cd`/`pushd` tokens (quotes stripped, never eval/expand), dedup `sort -u`, >20 distinct → deny before any fork. Mode per dir via `git config --bool gitflow.autopush` rc: 0 → value, 1 → auto, else → deny; NO work-tree gate (global key = work-machine deployment). Deny = JSON `permissionDecision=deny` exit 0, reason carries `! `; EXIT trap emits static deny + `exit 0` once a push is detected and nothing decided; jq missing → stderr + allow (sibling policy). User gated: fail-closed cases (cap, unenterable dir, git failure) fire in auto mode too. settings.json: 18 deny entries on WRITE forms of `gitflow.*` (any `git … config` spelling, remove/rename-section, `-c`, config env overrides, Edit/Write of git config files); soft_deny "pushing in manual-push mode, any form, no per-turn clearance"; routing-around hard_deny names hook refusals; banner `🔒 push : manual (autopush=false) — ! git push` (`%-46s`, bytes). +- **Why**: `ask` inert under auto ([[LRN-155]]); `hooks/guard-bash.sh` withheld ([[BLK-022]]) → one narrow rule instead. Trailing ` *` glob matches end-of-string ([[LRN-194]]) → no infix rule spares the bare read → Claude loses `git config … gitflow.autopush`; hooks/lib keep it; run C gets `gitflow.sh push-mode`. Text-only guard cannot see scripts/aliases → soft_deny is the declared backstop. +- **Alternatives rejected**: no-jq fallback (greps whole payload, denies in auto, untestable without shim; jq hard dep); `-C` dir unresolvable → allow (fail-open; now skipped, cwd still checked); `rev-parse` work-tree gate (drops the global key); `--default true` read (hides git failure); narrowing deny to spare the read (impossible with end-matching globs). +- **Gates**: 3 lenses CONCERNS(2)/CONCERNS(5)/FATAL(7) + confirmation FATAL(8) → r2 (BSD sed, oracle naming denied tokens, read loss); feater ×3 (58 → 61 → 71 checks); GATE 0 MET ×3; verifier CONFORME, then ECARTS(1) on hardening closed by gated clarification; security PASS ×2 (3 MEDIUM closed: 20k-token flood denied in 0.15 s, git absent → deny, `bash -c 'cd … && git push'` extracted; residuals → run D). +- **Refs**: contract `.claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md`, plan `.claude/tasks/plans/2026-10-07-manual-push-guard-1003.md`, commits a2ac018 + 6468eda (feature/manual-push-mode, UNMERGED). Links [[BDR-095]], [[BDR-100]], [[LRN-069]], [[LRN-196]]. Open: user probe `! git push --dry-run` under autopush=false (bang commands assumed hook-free). diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index a3e170d..e3460e0 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -569,3 +569,7 @@ rules: - /doc global audit 2026-10-06 (opus): 45 items, 6 docs. Applied 34 (24 AUTO + 9 HUMAN drafts + clone URL → Gitea): README components/slash/flow, Makefile help (11 profiles), USAGE /health→make doctor + GSD 3.0.0, ARCHITECTURE layout, MIGRATION retitled + "Upgrading to 2.0.0", SETTINGS package-install guard, CHANGELOG SemVer + default model + upgrade pointer → c6fb2e4. 10 deferred logged in TODO (LICENSE, Known-residual vs release, README restructure, USAGE narrative, templates/settings.json ask inert). - Release 2.0.0 cut (user go x3: release, tag push, MIT): bugfix merged 370f35a; develop merged into release/2.0.0 (b47bba7, CHANGELOG conflict resolved: upgrade pointer under [2.0.0]); suite 46/46 green on release; 9ef66e2 MIT LICENSE + README License + Linux residual reworded; gitflow finish by release-executor (BLK-018 did not fire) -> main 4093cca, tag v2.0.0 pushed on user go. Open after release: Linux make test (TODO), make plugin + .env on this machine (BLK-027). - /feat manual-push-mode run A (user: work machine, same flow, never push alone): `gitflow.autopush false` = manual-push mode end to end. Plan challenged 3 lenses + 1 confirm → 2 MAJOR (`-d` re-arms on lagging upstream LRN-161; /close STEP 5C pushes develop) + 3 BLOCKER in r2 (T22j regress, develop untracked in fixture, T18l/T18n order) all closed by named changes. feater ×2 (gaps: pipefail flake `git log | grep -q`, 9 SC2034 suppressions removed), GATE 0 7/8, verifier ECARTS(1) = AC6 env red only (design-tool-gate, 21st CLI present, same on develop fa67664), security PASS ×2. Commit 2fc8830 on feature/manual-push-mode, UNMERGED. Runs B (push-guard hook, settings deny widening, banner) + C (skills that push) queued in TODO; do NOT enable manual mode at work before B+C. + +## 2026-10-07 +- /feat manual-push-mode run B (user: "enchaine"): `hooks/push-guard.sh` PreToolUse denies Claude's `git push` when autopush false/unparseable/unreadable in cwd or literal -C/cd dirs (global config counts). Challenge: 3 lenses + robustness confirm FATAL(8) → BSD sed `N` fold empty on 1 line (hook dead), AC3 oracle naming denied tokens, glob trailing ` *` matches end → bare read lost, run C needs lib verb. feater ×3 (impl 58, no-jq test 61, hardening 71: cap 20 dirs, git rc → deny, quoted cd). GATE 0 MET ×3; verifier CONFORME then ECARTS(1) → user gated fail-closed also in auto for pathological commands; security PASS ×2 (3 MEDIUM closed, 2 residual → run D). Commits a2ac018 + 6468eda on feature/manual-push-mode, UNMERGED. settings.json live: 18 deny entries, soft_deny, Bash|Monitor hook group. User probe pending: `! git push --dry-run` bypasses hooks? + diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 535faab..ef32021 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1712,3 +1712,15 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s ## LRN-193 — A revised plan gets a fresh challenger, not a re-read: r2 found 3 BLOCKERs inside r1's fixes - **Context**: manual-push-mode plan. r1 (3 lenses) → 2 MAJOR, I rewrote 5 checklist items. Confirmation pass (1 fresh correctness challenger on the REVISED file) → FATAL(4): my `--unset-upstream` fix broke T22j; my T18l fixture never set develop's upstream (`push` without `-u`, init creates develop untracked); my T18n/T18l order made offline silence vacuous. All three were in text I had just written and re-read. - **Apply**: `challenge-plan.md` "re-challenge once if materially changed" is load-bearing, never skip it to save a dispatch. Brief the confirmation challenger on the NEW mechanics explicitly (state machine of new tests, fixture preconditions, ordering). Fixes to tests need the same fixture trace as the code (`-u`, upstream, what an earlier test leaves behind). + +## LRN-194 — Permission globs: trailing ` *` matches end-of-string; a denied token poisons every command that names it +- **Context**: push-guard deny widening. Planned `Bash(git *config *gitflow.* *)` to deny writes (key + value) and spare the bare read for run C. Evidence: `git config --local core.hooksPath` (no value) is denied by `Bash(git config --local core.hooksPath *)` → ` *` also matches end. Second effect: once `Bash(*GIT_CONFIG_COUNT*)` style rules landed (settings.json symlinked = live), a contract CHECK, a grep and a commit message naming the tokens would all be denied — including the oracle meant to verify the rules. +- **Apply**: (a) an infix/suffix glob cannot carve out a read of a denied key → give consumers a sanctioned reader (lib verb) instead; (b) a leading-`*` deny on a token makes the token unspeakable in command text → assertions about it live in test FILES (`make test`), never in CHECK commands, grep one-liners or commit subjects; (c) simplify: `Bash(git *config *gitflow.*)` already covers value writes, `--unset`, `--bool` forms. Links [[BDR-112]], [[BDR-100]]. + +## LRN-195 — BSD sed: `N` on the last line quits without printing → the `:a;N;$!ba` fold returns EMPTY on single-line input +- **Context**: push-guard plan folded `\`-newline with `sed -e ':a' -e 'N' -e '$!ba' -e 's/\\\n[[:space:]]*/ /g'` (the [[LRN-190]] idiom, written on GNU). `/usr/bin/sed` on macOS is BSD: `printf 'git push' | sed …` prints NOTHING. Every single-line command would have read as empty → guard dead in production, while a 2-line test passed. Caught by the confirmation challenger, not by tests. +- **Apply**: fold in bash (`one=${cmd//$'\\\n'/ }; one=${one//$'\n'/ }`) or `sed -e ':a' -e '$!N' -e '$!ba'`. Add a single-line positive control to any multi-line normaliser test. [[BDR-110]] census can't catch it (structural, not textual). Links [[LRN-190]], [[BDR-112]]. + +## LRN-196 — A fail-closed Claude Code hook: trap must `exit 0`, cap attacker-sized loops, read git's rc not its value +- **Context**: push-guard hardening (security gate, 3 MEDIUM). (1) EXIT trap printed the static deny but kept the non-zero rc → Claude Code parses hook JSON only on exit 0 → deny ignored = allow. (2) Each literal `cd`/`-C` token cost a subshell + 3 git execs: 600 tokens = 12 s > 10 s hook timeout → timeout = non-blocking = allow. (3) `git config --bool --default true` returns empty on git absent / old git / unreadable dir → read as "auto" → allow. +- **Apply**: `trap '… ; exit 0' EXIT`; deny path `out=$(jq …) || out=$STATIC; printf '%s' "$out"`; dedup (`sort -u`) + hard cap on command-controlled token counts, deny above the cap BEFORE any fork; distinguish `git config` rc 0/1/other (value / unset / failure → deny); record "decided" only after ≥1 clean evaluation. Lock each with a test (shim PATH without a tool, 25-token flood, chmod 000 dir with SKIP path). Measure the flood after the fix (20 000 tokens → 0.15 s). Links [[BDR-112]], [[BDR-087]], [[LRN-160]]. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 9910f02..8cb8517 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -2058,8 +2058,9 @@ dans un runner; capitalize reste main-loop. ## manual-push-mode (2026-10-06, /feat × 3) - [x] run A — `gitflow.autopush=false` honoured by `_gitflow_push_branch`, quiet unpushed-guard, doctrine line; plan `.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md` → commit 2fc8830 on feature/manual-push-mode; verifier ECARTS(1) = AC6 only (design-tool-gate env red, pre-existing on develop) → human waiver; merge human-gated -- [ ] run B — `hooks/push-guard.sh` PreToolUse (deny `git push` in manual mode) + test + settings.json (hook wiring, widen `gitflow.*` deny: `git config * gitflow.*`, `git -c gitflow.*`, `GIT_CONFIG_COUNT=*`; environment prose ~480/~499) + session-start banner push mode -- [ ] run C — skills that push on their own, gate on `gitflow.autopush`: capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims +- [x] run B — `hooks/push-guard.sh` PreToolUse (deny `git push` in manual mode) + 71-check test + settings.json (own hook group Bash|Monitor timeout 10; 18 write-form deny entries on the toggle; soft_deny on manual-mode pushes with no per-turn clearance; prose) + banner → a2ac018 + hardening commit; verifier CONFORME then ECARTS(1) closed by gated clarification (fail-closed cap/unenterable dir also in auto mode); security PASS ×2 +- [ ] run D also (push-guard residuals, security gate 2026-10-07): tokens with inner quotes/backslashes (`cd /m/'a b'`) resolve to the wrong dir → treat as unresolvable + deny or document; unparseable payload (lone surrogate) → jq fails → silent allow → grep raw payload for `push` and deny; `case "$mode"` default `*) deny`; up-front `command -v grep sed sort head jq` check; header line > 80 cols; T42 compares against HEAD (vacuous once committed) → compare against a pinned base or drop; no test sets the key to literal `true` +- [ ] run C — skills that push on their own, gate on the mode through a NEW lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (prints auto|manual|invalid; the bare `git config … gitflow.autopush` read is denied for Claude after run B — a trailing ` *` glob also matches end-of-string): capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims - [ ] run B also: fail-CLOSED on an unparseable `gitflow.autopush` value in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks, unpushed-guard) — run A keeps fail-open for consistency with the untouched emitters (security gate MEDIUM, 2026-10-06); `--end-of-options`/`--` on refname args and `printf %q` in copy-paste hints (LOW); `gitflow_delete`: check `_gitflow_checkout_containing_base` rc before `--unset-upstream` (LOW, 2nd gate) - [ ] ORDER: do not set `gitflow.autopush false` on the work machine before B + C are merged (until then `/close` still pushes develop) diff --git a/.claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md b/.claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md new file mode 100644 index 0000000..cac64a6 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md @@ -0,0 +1,49 @@ +# CONTRACT — manual-push-guard (run B of manual-push mode) +- date: 2026-10-07 | flow: feat | branch: feature/manual-push-mode (run A landed as 2fc8830; run C = skills that push, separate) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "ok enchaine sur le run B" +Run B as scoped in `.claude/tasks/contracts/2026-10-06-manual-push-mode-1632.md` CLARIFICATIONS and `.claude/tasks/TODO.md` "manual-push-mode": `hooks/push-guard.sh` PreToolUse (deny `git push` in manual mode) + test + settings.json (hook wiring, widen `gitflow.*` deny: `git config * gitflow.*`, `git -c gitflow.*`, `GIT_CONFIG_COUNT=*`; environment prose ~480/~499) + session-start banner push mode. User decisions (2026-10-06): mechanical block of `git push` chosen; only `! git push` (the user, in the terminal) passes; hook name `hooks/push-guard.sh` + `lib/tests/push-guard.test.sh`. + +## CLARIFICATIONS +Q: hook deny form / A: documented JSON on stdout, exit 0: `hookSpecificOutput.permissionDecision = "deny"` + `permissionDecisionReason` (code.claude.com/docs/en/hooks.md). Reason reaches Claude as the tool error. [orchestrator, internal] +Q: middle wildcards in `permissions.deny` Bash patterns / A: supported (`Bash(git * main)` documented), `*` matches any text incl. spaces, literal match on the whole command string. [orchestrator, verified via docs] +Q: fail-CLOSED on an unparseable `gitflow.autopush` value / A: user: refuse the push. In the GUARD only (deny, reason names the invalid value); lib and emitted hooks stay fail-open until run D (every reader at once, emitters included). [gated 2026-10-07] +Q: banner wording / A: user picked `push : manual`; final line (43 chars, fits the 44-char box): `🔒 push : manual (autopush=false) — ! git push`. [gated 2026-10-07] +Q: `git push --dry-run` / `-n` in manual mode / A: denied like any push (one rule, no carve-out; the user runs it). [orchestrator — simplest, stated] +Q: challenge r1 — deny widening vs run C's read / A: widen WRITE forms only (`git *config *gitflow.* *`, `*unset*`, `-c`, `--config-env`, `GIT_CONFIG_PARAMETERS`, `GIT_CONFIG_COUNT`, Edit/Write of `.git/config` and `.gitconfig`); the read `git config --bool --default true gitflow.autopush` stays reachable for run C. `Bash(env GIT_CONFIG_COUNT*)` dropped (covered by the existing `env GIT_CONFIG*`). [gated 2026-10-07, orchestrator — scope] +Q: challenge r1 — no-jq fallback / A: dropped; jq is a hard dependency (install-plugins.sh); the guard warns on stderr and allows, like every sibling hook. Fail-closed EXIT trap kept for internal errors once a push is detected. [orchestrator — internal] +Q: challenge r1 — mode read outside a repo / A: no work-tree gate; `git config` reads global/system there (work-machine `--global` deployment). Candidate dirs = cwd + literal `-C`/`cd` tokens; unresolvable → skipped, never an allow. [orchestrator — internal, fail-closed] +Q: challenge r1 — classifier coverage / A: one soft_deny entry added for pushes in manual mode in any form (scripts, aliases, subshells, sub-agents); env prose no longer names the hook as the whole defence. Matcher `Bash|Monitor` in its own hook group, timeout 10 s. [orchestrator] +Q: confirmation r2 — bare read / A: a trailing ` *` in a permission glob also matches end-of-string (evidence in plan Context), so the bare read `git config … gitflow.autopush` is denied for Claude after run B; hooks and lib keep it (not tool calls). Run C reads the mode through a lib verb (`gitflow.sh push-mode`), recorded in TODO. The deny list is simplified to `Bash(git *config *gitflow.*)` + section-level and env/edit forms (18 entries). [gated 2026-10-07, orchestrator — scope, surfaced to the user] +Q: confirmation r2 — oracles / A: settings.json assertions live in the test file (T40–T43), never in a CHECK command or a commit message: the new tokens would deny the command that names them. [orchestrator] +Q: hardening gate — two cases where the mode cannot be read safely (more than 20 distinct `cd`/`-C` dir tokens in one command; a named dir that exists but cannot be entered) deny the push even when the cwd is in auto mode; the verifier flagged this against criterion 2's "zero noise outside manual mode" / A: user: refuse the push (fail closed). Criterion 2 is read with this exception: auto-mode silence holds for every command whose named dirs can all be evaluated and number at most 20. [gated 2026-10-07] +Q: full-suite criterion / A: every suite except `lib/tests/design-tool-gate.test.sh`, a pre-existing environmental red on this machine (21st CLI present; reproduced on develop fa67664 without run A; TODO "test hermeticity"). Declared upfront, not loosened after a red. [orchestrator] + +## ACCEPTANCE CRITERIA +1. `hooks/push-guard.sh` (PreToolUse) denies any Bash command that runs `git push` — plain, `git -C push`, `git -c k=v push`, `--no-pager`, `--dry-run`/`-n`, inside `cd x && git push`, `(…)`, `bash -c '…'`, after `;`/`&&`/`|`, absolute `/usr/bin/git`, backslash-newline split — when `gitflow.autopush` reads false (or unparseable) in the payload cwd or in any literal `-C`/`cd` dir the command names (global config counts outside a repo). JSON deny form; the reason names manual push mode and tells the user to run it with `! `. + CHECK: out=$(make test suite=lib/tests/push-guard.test.sh 2>&1); printf '%s' "$out" | grep -q '^FAIL' && exit 1; printf '%s' "$out" | grep -qE 'PASS=(4[0-9]|[5-9][0-9]) FAIL=0' && echo PUSH-GUARD-OK + EXPECT: PUSH-GUARD-OK + EVIDENCE: MET exit=0 marker-found :: PUSH-GUARD-OK +2. Zero noise outside manual mode: auto mode (key unset or true, no global key) → the hook prints nothing and exits 0 for every command, `git push` included, except the two fail-closed cases gated in CLARIFICATIONS (more than 20 distinct dir tokens; a named dir that exists but cannot be entered) [gated 2026-10-07]; in manual mode every non-push command (`git status`, `git commit -m "fix push guard"`, `gitflow.sh finish`, `git pushd`, `git stash`, `echo pushed`) → nothing, exit 0. An unparseable value (e.g. `flase`) → deny, reason says the value is not a boolean. No jq → stderr warning, allow (sibling-hook behaviour, jq is a hard dependency). Locked by the same test file. +3. `settings.json`: (a) `hooks.PreToolUse` gains its own group `matcher "Bash|Monitor"` running `bash ~/.claude/hooks/push-guard.sh` with `timeout` 10; (b) `permissions.deny` gains the 18 entries listed in the plan (key writes in any `git … config` spelling, section removal/rename, `-c`/env overrides, direct edits of git config files); (c) one new soft_deny entry on pushing in manual-push mode in any form with the no-clearance clause, and the routing-around hard_deny names PreToolUse hook refusals; (d) prose: "Branch deletion by hand" stays unconditional with a manual-mode parenthetical, "**Push discipline**" gains the exception. Valid JSON; no existing entry removed, reworded or weakened. Locked by push-guard.test.sh T40–T43 (file-content assertions). + CHECK: jq . settings.json >/dev/null && out=$(make test suite=lib/tests/push-guard.test.sh 2>&1) && ! grep -qE '^FAIL T4[0-3]' <<<"$out" && grep -qE 'PASS=[0-9]+ FAIL=0' <<<"$out" && echo SETTINGS-OK + EXPECT: SETTINGS-OK + EVIDENCE: MET exit=0 marker-found :: SETTINGS-OK +4. `hooks/session-start.sh` banner: when `gitflow.autopush` reads false from the session cwd (local or global), one extra line `🔒 push : manual (autopush=false) — ! git push` inside the box, right border aligned (`%-46s`: bash pads by bytes, `—` is 3); nothing otherwise. Locked by push-guard.test.sh T44–T46 (fixture in the suite, `SESSION_START_OFFLINE=1`, positive control before the absence check). + CHECK: grep -q 'gitflow.autopush' hooks/session-start.sh && grep -q 'push : manual (autopush=false)' hooks/session-start.sh && grep -q '%-46s' hooks/session-start.sh && out=$(make test suite=lib/tests/push-guard.test.sh 2>&1) && ! grep -qE '^FAIL T4[4-6]' <<<"$out" && echo BANNER-OK + EXPECT: BANNER-OK + EVIDENCE: MET exit=0 marker-found :: BANNER-OK +5. shellcheck clean on `hooks/push-guard.sh`, `hooks/session-start.sh`, `lib/tests/push-guard.test.sh`; `bash -n` on all three. + CHECK: shellcheck hooks/push-guard.sh hooks/session-start.sh lib/tests/push-guard.test.sh && bash -n hooks/push-guard.sh hooks/session-start.sh lib/tests/push-guard.test.sh && echo SHELLCHECK-OK + EXPECT: SHELLCHECK-OK + EVIDENCE: MET exit=0 marker-found :: SHELLCHECK-OK +6. Every hermetic suite green except the declared environmental red `lib/tests/design-tool-gate.test.sh` (CLARIFICATIONS). + CHECK: fail=0; for t in $(ls lib/tests/*.test.sh lib/seo-data/*.test.sh lib/gitflow-test.sh lib/tests/run-*.sh | grep -v design-tool-gate.test.sh); do make test suite="$t" >/dev/null 2>&1 || { fail=1; echo "RED $t"; }; done; [ $fail -eq 0 ] && echo SUITES-OK + EXPECT: SUITES-OK + EVIDENCE: MET exit=0 marker-found :: SUITES-OK +7. No change to lib/gitflow.sh, hook emitters, githooks/, .githooks/, hooks/unpushed-guard.sh, skills/, CLAUDE.global.md; no new config key or env var; `hooks/rtk-rewrite.sh` untouched (integrity pin); no `eval` in the guard. Floor guard clean (no new suppression). + +## FILE SCOPE +hooks/push-guard.sh (new) · lib/tests/push-guard.test.sh (new) · settings.json · hooks/session-start.sh diff --git a/.claude/tasks/plans/2026-10-07-manual-push-guard-1003.md b/.claude/tasks/plans/2026-10-07-manual-push-guard-1003.md new file mode 100644 index 0000000..15c8595 --- /dev/null +++ b/.claude/tasks/plans/2026-10-07-manual-push-guard-1003.md @@ -0,0 +1,57 @@ +# PLAN — manual-push-guard (run B) — REVISED r2 (3 lenses + robustness confirmation) +Contract: .claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md + +## Context +Run A made `gitflow.autopush false` stop every lib push. Nothing yet stops Claude from typing `git push` itself: `Bash(git push *)` is on `ask`, inert under auto mode (BDR-095, LRN-155). `hooks/guard-bash.sh` does not exist (BLK-022); this guard is ONE narrow rule. The human-only toggle (`git config gitflow.*` deny) is prefix-only; run A widened its reach to the lib, so the bypass forms close now. A trailing ` *` in a permission glob also matches end-of-string (evidence: `git config --local core.hooksPath` with no value is denied by `Bash(git config --local core.hooksPath *)`), so NO infix rule can spare the bare read `git config … gitflow.autopush`: Claude loses the read, hooks and lib (not tool calls) keep it, and run C reads the mode through a lib verb (recorded in TODO). jq is a hard dependency (install-plugins.sh); sibling hooks fail open without it. `/usr/bin/sed` is BSD sed: no `N`-on-last-line idiom (an unconditional `N` on the last line quits WITHOUT printing → empty string on single-line input). + +## Checklist +- [ ] hooks/push-guard.sh (new, ≤100 lines, functions ≤25 logic lines, `set -u`, `unset CDPATH`): + Header: purpose, BDR-111, deny form (JSON `hookSpecificOutput.permissionDecision=deny`, exit 0), what it sees (command TEXT only), candidate dirs, fail-closed policy (unparseable value = manual; once a push is detected an EXIT trap emits the static deny with exit 0 unless a decision was recorded), limits: OVER-BLOCKS in manual mode (any command whose text carries a later ` push` word after a `git` token: `git subtree push`, `git stash push`, `git log -S "git push"`, `grep -rn "git push" skills/`, `git config --get push.default`, `git add push.sh`, `git help push`, a commit message containing "git push") and MISSES (`"git" push`, `git "push"`, `git send-pack` caught, `git -c alias.p=push p` caught by the alias pattern; expansions `~`/`$VAR`/`$(…)` in `-C`/`cd` never resolved; `--git-dir`/`GIT_DIR`; a push inside a script, Makefile target or user alias it runs → soft_deny rule). jq missing → one stderr warning, allow (sibling-hook behaviour). + Parse: `payload=$(cat 2>/dev/null)`; jq check; `field() { printf '%s' "$payload" | jq -r "$1 // empty" 2>/dev/null; }`; `cmd=$(field '.tool_input.command')`; `cwd=$(field '.cwd')`; `[ -n "$cmd" ] || exit 0`; `[ -d "$cwd" ] || cwd=$PWD`. + Normalize IN BASH, no sed: `one=${cmd//$'\\\n'/ }; one=${one//$'\n'/ }` (backslash-newline, then bare newlines → spaces); `bare=$(printf '%s' "$one" | sed -E "s/\"[^\"]*\"//g; s/'[^']*'//g")` (quoted spans removed; unbalanced quotes → documented limit). + `is_push()` (any of three, `grep -qE` on a single-write `printf '%s'`): + STRICT on `one`: `(^|[^[:alnum:]_.-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^[:space:]-][^[:space:]]*)?)*[[:space:]]+(push|send-pack)([^[:alnum:]_-]|$)` + LOOSE on `bare`: `(^|[^[:alnum:]_.-])git[[:space:]]+([^|;&()]*[[:space:]])?(push|send-pack)([^[:alnum:]_-]|$)` + ALIAS on `bare`: `alias\.[^=[:space:]]+=[^[:space:]]*push` + Not a push → `exit 0` silently (nothing armed yet). + Arm: `STATIC_DENY` = compact literal JSON (reason "push-guard: internal error while checking manual push mode — push refused (fail closed). Run it yourself in the terminal with !"); `decided=0; trap '[ "$decided" = 1 ] || printf "%s" "$STATIC_DENY"; exit 0' EXIT` (the trap forces exit 0 so Claude Code parses the JSON). + `candidates()`: start with `cwd`; `grep -oE` on `one` for `(^|[[:space:];&|()])(cd|pushd)[[:space:]]+(--[[:space:]]+)?("[^"]*"|'[^']*'|[^[:space:];&|()]+)` and `(^|[[:space:]])-C[[:space:]]+("[^"]*"|'[^']*'|[^[:space:];&|()]+)`; take the LAST field of each match, strip one pair of surrounding quotes, skip `-` and empty; resolve `( cd -- "$cwd" && cd -- "$tok" 2>/dev/null && pwd -P )`; unresolvable → skipped (never expands `~`, `$`, backticks; no eval). Over-inclusion (`rg -C 3`, `tar -C /tmp`) only adds dirs. Empty list is impossible (cwd always present). + `mode_in ` → prints `manual` / `invalid:` / nothing: `( cd -- "$dir" || exit 0; raw=$(git config gitflow.autopush 2>/dev/null); val=$(git config --bool --default true gitflow.autopush 2>/dev/null); [ "$val" = false ] && echo manual; [ -n "$raw" ] && ! git config --bool gitflow.autopush >/dev/null 2>&1 && echo "invalid:$raw" )`. NO work-tree gate: outside a repo `git config` reads global/system (work-machine `--global` deployment). + Decide: loop candidates; first `manual` → deny reason `push-guard: manual push mode (gitflow.autopush=false in ) — Claude never pushes. Run it yourself in the terminal: ! `; first `invalid:` → deny reason `push-guard: gitflow.autopush='' is not a boolean in — treated as manual push mode (fail closed). Fix the value by hand, or run it yourself: ! `; none → `decided=1; exit 0`. Deny: `out=$(jq -cn --arg r "$reason" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}') || out=$STATIC_DENY; printf '%s' "$out"; decided=1; exit 0`. `` = original command (jq --arg escapes it). +- [ ] lib/tests/push-guard.test.sh (new) — top: `set -u; export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null` (hermetic even when run directly; file content, not a command line), `ROOT`, `H="$ROOT/hooks/push-guard.sh"`, `WORK=$(mktemp -d)`, trap cleanup. Harness like rtk-rewrite.test.sh: `run(cmd, cwd)` pipes `jq -n '{hook_event_name:"PreToolUse",tool_name:"Bash",tool_input:{command:$c},cwd:$d}'` into `bash "$H"`, records stdout AND rc; `fire()` → `deny` iff rc=0 and stdout parses with `.hookSpecificOutput.permissionDecision=="deny"`, `allow` iff rc=0 and stdout empty, else `error:`; `reason()`. Multi-line producers never piped into `grep -q` (LRN-191): use `grep -q … <<<"$out"`. Fixtures: `plain/` (dir, not a repo), `auto/` (git init, no key), `manual/` (key false; `sub/`, `my dir/` inside), `bad/` (key `flase`), `manual2/` (toggle), `gconf` (file `[gitflow]` / `autopush = false`), `shim/` (dir with a `jq` script: `[ "$1" = -cn ] && exit 1; exec /usr/bin/jq "$@"`, resolved via `command -v jq` at test time). Cases (≥40): + auto/none: T1 plain `git push` allow; T2 auto `git push` allow; T3 auto `git push -u origin feature/x` allow. + manual deny (cwd manual unless stated): T4 `git push` (also asserts stdout is ONE JSON line); T5 `git push -u origin feature/x`; T6 (cwd plain) `git -C "$WORK/manual" push`; T7 `cd sub && git push`; T8 `git push --dry-run`; T9 `git -c a=b push origin HEAD`; T10 `(cd sub && git push)`; T11 `bash -c 'git push'`; T12 `git push; echo done`; T13 `/usr/bin/git push`; T14 `git --no-pager push`; T15 (cwd plain) `cd "$WORK/manual/my dir"; git push`; T16 `git push&&echo ok`; T17 (cwd plain) `cd -- $WORK/manual && git push` (literal expanded path, written by the test); T18 two-line `git \` + newline + ` push`; T19 `git push|tee /dev/null`; T20 `git subtree push --prefix=x origin main` (documented over-block); T21 (cwd plain) `(cd $WORK/manual&&git push)`; T22 `git -c alias.p=push p`; T23 `git send-pack origin`; T24 `grep -rn "git push" skills/` (documented over-block, locked); T25 `git config --get push.default` (documented over-block, locked). + manual allow: T26 `git status && git commit -m "fix push guard"`; T27 `bash ~/.claude/lib/gitflow.sh finish`; T28 `git pushd`; T29 `git stash`; T30 `echo pushed`; T31 `rg -C 3 push src/`; T32 `git branch --show-current`. + invalid: T33 bad `git push` → deny, reason contains `not a boolean` and `flase`. + global: T34a cwd auto, `GIT_CONFIG_GLOBAL=$WORK/gconf` for that one `run` (set inline inside the test function), `git push` → deny; T34b cwd plain, same env, `cd "$WORK/auto" && git push` → deny; T34c cwd auto, default env → allow (control). + control: T35 manual2 `git push` deny, then `git config --unset gitflow.autopush` in manual2 → allow. + fail-closed: T36 cwd manual, `PATH="$WORK/shim:$PATH"` for that run, `git push` → deny with rc 0 and reason contains `internal error` (jq -cn fails → static deny). T37 cwd manual `git push` under default PATH → reason contains `! git push` and `manual push mode`. + payload: T38 `{}` → allow, empty stdout, rc 0; T39 payload with `tool_input.command` but no `cwd` → uses PWD (run from manual/) → deny. + wiring (file-content assertions, never typed as a command): T40 `jq -e '.hooks.PreToolUse[] | select(any(.hooks[]; .command=="bash ~/.claude/hooks/push-guard.sh")) | .matcher=="Bash|Monitor" and .hooks[0].timeout==10' "$ROOT/settings.json"`; T41 every deny entry of settings (b) below present (loop over a literal list in the test file); T42 every deny entry of `git show HEAD:settings.json` still present (nothing removed); T43 soft_deny contains `manual-push mode` and the clearance clause `! git push`. + banner: `out=$(cd "$WORK/manual" && SESSION_START_OFFLINE=1 bash "$ROOT/hooks/session-start.sh" /dev/null)`; T44 positive control `grep -q 'Claude Code config' <<<"$out"`; T45 `grep -q 'push : manual (autopush=false)' <<<"$out"`; T46 same from `auto/`: positive control present AND no `push : manual`. +- [ ] settings.json (hand-formatted; text edits; `jq . settings.json >/dev/null`; `git diff settings.json` shows only these hunks; comma discipline: previous last element gains `,`, new last has none). NOTE for the executor and the orchestrator: once this lands, ~/.claude/settings.json (symlink) is live — never type the new tokens (`GIT_CONFIG_COUNT`, `GIT_CONFIG_PARAMETERS`, `--config-env`) in a Bash command or a commit message; they live in files only. + (a) `.hooks.PreToolUse` += NEW group `{"matcher": "Bash|Monitor", "hooks": [{"type": "command", "command": "bash ~/.claude/hooks/push-guard.sh", "timeout": 10}]}`. + (b) `.permissions.deny`, after `"Bash(git config --local gitflow.*)"`, 18 entries: `"Bash(git *config *gitflow.*)"`, `"Bash(git *config *remove-section*gitflow*)"`, `"Bash(git *config *rename-section*gitflow*)"`, `"Bash(git -c gitflow.*)"`, `"Bash(git * -c gitflow.*)"`, `"Bash(*--config-env*gitflow*)"`, `"Bash(*GIT_CONFIG_PARAMETERS*)"`, `"Bash(*GIT_CONFIG_COUNT*)"`, `"Bash(* GIT_CONFIG_GLOBAL=*)"`, `"Bash(* GIT_CONFIG_SYSTEM=*)"`, `"Edit(**/.git/config)"`, `"Write(**/.git/config)"`, `"Edit(**/.gitconfig)"`, `"Write(**/.gitconfig)"`, `"Edit(~/.gitconfig)"`, `"Write(~/.gitconfig)"`, `"Edit(~/.config/git/config)"`, `"Write(~/.config/git/config)"`. + (c) `.permissions.autoMode.soft_deny` += `"Pushing in manual-push mode (\`gitflow.autopush false\`, set by the user): any git push by Claude — direct, scripted, aliased, inside a subshell, a Makefile target, a sub-agent, or after a HOME/GIT_CONFIG override that hides the key. The push-guard hook catches the direct forms; this rule covers the rest. A request to push in this turn does not clear it: the user types \`! git push\` in the terminal."`; hard_deny "Routing around a guardrail": insert `a PreToolUse hook,` into the list of refusers (`a command the deny rules, a PreToolUse hook or this classifier refused`). Adding restrictions only. + (d) prose: hard_deny "Branch deletion by hand": keep `which every branch has since BDR-095` and append ` (manual-push mode: the lib unsets the upstream itself before \`-d\`; the hand form stays banned)`; environment **Push discipline**: append ` Exception, manual-push mode (\`gitflow.autopush false\`, set by the user, work machine): nothing is pushed by Claude, in any form; the user pushes by hand with \`! git push\`.` +- [ ] hooks/session-start.sh — after the 🪝 `GF_REFRESHED` block: + ``` + # ── manual-push mode (BDR-111): one lock line when this repo never auto-pushes ── + # %-46s, not 44: bash printf pads by BYTES and "—" is 3 bytes (2 extra). + if [ "$(git config --bool --default true gitflow.autopush 2>/dev/null)" = false ]; then + printf "│ 🔒 %-46s│\n" "push : manual (autopush=false) — ! git push" + fi + ``` + +## Edge cases +- Global key: shows the banner and denies everywhere, repo or not (truth on a work machine). +- Over-blocking in manual mode (loose match): listed in the header, two cases locked (T24, T25); never in auto mode. +- `Bash(*GIT_CONFIG_COUNT*)` ends the LRN-069 token-header idiom (`git -c http.extraHeader=…` stays). `Bash(* GIT_CONFIG_GLOBAL=*)` leaves `make test` untouched (the export lives inside the Makefile). +- Hook timeout 10 s → Claude Code treats a timeout as non-blocking (allow); the soft_deny and `ask` remain. +- `!` bang commands run in the user's terminal, outside the Bash tool — not hook-gated (belief): final report asks the user to probe once with `! git push --dry-run` in a scratch repo under `autopush=false`. +- Run C: the bare read is denied for Claude after (b); run C adds a lib verb (`gitflow.sh push-mode`, prints `auto|manual|invalid`) and gates skills on it — TODO updated by the orchestrator. + +## Disposition +- honors BDR-111 / BDR-095 (static deny first, prose second, `ask` entrusted with nothing; restrictions only added, nothing reworded or removed). +- honors BLK-022 (one narrow guard), LRN-069/LRN-155 (hook = gate under auto), LRN-047/LRN-091 (silent in auto and on non-push), LRN-104 (every reason, the wiring, matcher and timeout locked), LRN-191 (no multi-line producer into `grep -q`), BDR-110 (BSD sed/grep: bash folding, `/usr/bin/grep -E` semantics verified by the challengers), LRN-193 (fresh confirmation pass done: FATAL(8) → this revision). +- honors BDR-100 / LRN-113: surface grep after the change (file-content tokens only, via `make test` assertions T41/T42); readers outside this run → run D. From 472168d432aba466e193ed4a288361331c39e104 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 12:42:15 +0200 Subject: [PATCH 009/547] =?UTF-8?q?docs(gitflow):=20push-guard=20=E2=80=94?= =?UTF-8?q?=20SETTINGS=20push=20discipline=20+=20guardrails=20table,=20git?= =?UTF-8?q?flow=20skill,=20ARCHITECTURE,=20README,=20CHANGELOG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ARCHITECTURE.md | 2 +- CHANGELOG.md | 3 ++- README.md | 4 +++- skills/gitflow/SKILL.md | 9 +++++---- templates/settings/SETTINGS.md | 17 ++++++++++++++++- 5 files changed, 27 insertions(+), 8 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a063658..3c0d2d0 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -20,7 +20,7 @@ claude-config/ ├── update-all.sh # One-command update for all components ├── Makefile # Unified entry point: make install / doctor / update / test (make help) ├── plugins.lock.json # Version pinning for non-marketplace dependencies and vendored skills -├── hooks/ # Claude Code hooks: session start, statusline, RTK rewrite, ctx7 + design-toolchain reminders, attention notify, unpushed-work guard +├── hooks/ # Claude Code hooks: session start, statusline, RTK rewrite, ctx7 + design-toolchain reminders, attention notify, unpushed-work guard, manual-mode push guard ├── githooks/ # Generated git hooks (pre-commit, post-commit, post-merge, reference-transaction), git's global core.hooksPath ├── .githooks/ # This repo's own copy of the same hooks ├── rules/ # Rule files deployed to ~/.claude/rules (path-scoped or always-on) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1956865..545d3f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,10 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project ## [Unreleased] ### Added -- **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
` 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 `gitflow.autopush` value is named and treated as auto. Skills that push on their own do not honour the mode yet. Tests: `lib/gitflow-test.sh` T18m block, `lib/tests/unpushed-guard.test.sh` T10-T16. +- **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
` 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 `gitflow.autopush` value is named and treated as auto. `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 fails closed: for this hook a non-boolean value reads as manual, and a git failure while reading the key, an internal error or more than 20 distinct directory tokens in one command refuse the push (these pathological cases fire in auto mode too). In manual mode it over-blocks any command where a `push` word follows a `git` token; 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. Skills that push on their own do not honour the mode yet. Tests: `lib/gitflow-test.sh` T18m block, `lib/tests/unpushed-guard.test.sh` T10-T16, `lib/tests/push-guard.test.sh` (71 checks). ### Changed +- `settings.json` denies every write form of the human-only `gitflow.*` keys (18 entries): any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, and Edit/Write of `.git/config`, `.gitconfig` and `~/.config/git/config`. Side effect: Claude can no longer read `gitflow.autopush` through `git config` either; hooks and `lib/gitflow.sh` still read it. The `hard_deny` rule on routing around a guardrail now names PreToolUse hook refusals. - `gitflow start` and `finish` warn on stderr when a base is behind origin and cannot fast-forward, instead of a silent `git pull --ff-only || true` (T18l, T18n). ### Fixed diff --git a/README.md b/README.md index f36e86c..d37796f 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,9 @@ Not a collection of prompts — an operating layer on top of Claude Code: - **Hooks and permissions** are deterministic guardrails: gitflow enforced by a pre-commit hook in every repo (`make link` points git's global `core.hooksPath` at `~/.claude/githooks`), every commit pushed by - post-commit and post-merge hooks, `main`/`develop` undeletable by a reference-transaction hook, + post-commit and post-merge hooks (nothing pushed in a repo the user puts + in manual-push mode, where a PreToolUse hook also refuses Claude's own + `git push`), `main`/`develop` undeletable by a reference-transaction hook, deny-first permission rules, secrets kept in `~/.claude/.env` and never in config files. - **Templates and memory** seed every project with persistent registries diff --git a/skills/gitflow/SKILL.md b/skills/gitflow/SKILL.md index fd0bdd9..caee674 100644 --- a/skills/gitflow/SKILL.md +++ b/skills/gitflow/SKILL.md @@ -56,9 +56,10 @@ and keeps the branch. The `origin/` copy is removed right after, once ITS tip passes the same check; a remote tip holding commits the bases lack is kept, loudly (T24). In manual-push mode (`git config gitflow.autopush false`, human-set) nothing is pushed: `start` and `finish` stay local, and -the `origin/` copy is left in place (T18i-T18k). Hand `git branch -d` is -denied — with an auto-pushed upstream it checks the wrong thing (T22a). A -`reference-transaction` hook vetoes any deletion or rename of +the `origin/` copy is left in place (T18i-T18k). A `git push` Claude types is +refused by `hooks/push-guard.sh`; the user pushes with `! git push`. Hand +`git branch -d` is denied — with an auto-pushed upstream it checks the wrong +thing (T22a). A `reference-transaction` hook vetoes any deletion or rename of `main`/`develop` at the ref layer, in every repo. ## The finish gate — merge ONLY on an explicit human signal @@ -109,7 +110,7 @@ stays human-gated. | `delete`/`finish` rc=5 — branch not merged into develop or main | The branch still holds unmerged work: KEEP it, report it, never fall back to `git branch -d`/`-D`. Merge first (human gate), then re-run | | `delete` rc=6 — protected base | `main`/`develop` are never deleted. Stop; the request itself is the defect to report | | `delete`/`finish` warning "remote copy KEPT" or "NOT removed" | Non-fatal BY CONTRACT (remote cleanup is best-effort). KEPT = origin/
has a tip the bases lack: fetch, look, merge or leave it — never `git push --delete` by hand. NOT removed = origin unreachable or refused: report the printed command to the user | -| `delete`/`finish` warning "origin/
left in place (manual push mode)" | Expected in manual-push mode, not a failure. Pass the printed `git push origin --delete
` to the user; never run it (manual mode: no push unless the user asks, and `push --delete` is denied by settings) | +| `delete`/`finish` warning "origin/
left in place (manual push mode)" | Expected in manual-push mode, not a failure. Pass the printed `git push origin --delete
` to the user; never run it (manual mode: Claude never pushes, even when asked in the turn; the user runs it with `!`. `push --delete` is also denied by settings) | | `start`/`finish` warning " is behind origin/ by N and cannot fast-forward" | Non-fatal BY CONTRACT: the branch is still created and the merge still runs on the local base. The base has diverged from origin: report it to the user, who reconciles (`git pull`, then push). Never rebase or force-push a base | ## Common Mistakes diff --git a/templates/settings/SETTINGS.md b/templates/settings/SETTINGS.md index 1ce8b61..bda6696 100644 --- a/templates/settings/SETTINGS.md +++ b/templates/settings/SETTINGS.md @@ -145,6 +145,8 @@ local trace, and the brief had authorized it. What holds now, by tier: | `chmod`/`chown -R`, `sudo`/`doas`/`pkexec`, disk tools (`dd`, `mkfs`, `shred`…), `chattr` | `permissions.deny` | The user runs them by hand. | | Docker volume drops, `system prune`, `compose down -v`, `--privileged`, the docker socket, `-v /:` | `permissions.deny` | Promoted from `soft_deny`: no in-session clearance for data drops. | | Git history destruction (`push --delete`/`--mirror`/`:ref`/`--force-with-lease`, `branch -D`, `filter-branch`, `reflog expire`, `stash clear`/`drop`, `clean -f`), `--no-verify`, `core.hooksPath` | `permissions.deny` | A remote is the backup; nothing rewrites or deletes what it holds. | +| Writing the human-only `gitflow.*` toggles: any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, Edit/Write of git config files | `permissions.deny` | Claude never flips the mode that binds it. Side effect: the trailing glob also matches the bare read, so Claude cannot read `gitflow.autopush` through `git config`; hooks and `lib/gitflow.sh` still do. | +| Pushing in manual-push mode (`gitflow.autopush false`) | `hooks/push-guard.sh` (PreToolUse) + `autoMode.soft_deny` | `ask` is inert under auto mode. The hook denies the direct forms; the soft_deny covers scripted, aliased, subshell and sub-agent pushes, and a request in the turn does not clear it: the user types `! git push`. | | Destructive tool against a local path (variable, `~`, `..`, wildcard, outside cwd/tmp), even as a trace or a rehearsal a brief allows | `autoMode.hard_deny` | A pattern cannot express "the target resolves outside the project"; the classifier can. A sub-agent brief carries no user authority. | | `docker rm -f`, bind mount outside cwd; discarding uncommitted work | `autoMode.soft_deny` | Recoverable or user-intended in the turn. | @@ -152,7 +154,8 @@ Rules apply to sub-agents (auto mode is inherited) and to each segment of a compound command; a tool nested in another command (`docker compose run … lftp`) is not matched by a static rule. The PreToolUse guard hook that scans the whole command, its executable spec in `lib/tests/guard-bash.test.sh`, -is not shipped yet (BLK-022). +is not shipped yet (BLK-022). `hooks/push-guard.sh` scans the command text +for `git push` only, in manual-push mode (see below). Push discipline lives in `lib/gitflow.sh`: `start` pushes the branch, `finish` pushes each merge target, and the post-commit / post-merge hooks @@ -178,6 +181,18 @@ setting and the generated dir. `hooks/unpushed-guard.sh` reports a branch ahead of its upstream at session start and at each turn end; in manual-push mode it stays silent at turn end and gives one `ℹ manual push mode:` line at session start, counting unpushed commits across every local branch. +In manual-push mode `hooks/push-guard.sh` (PreToolUse, `Bash|Monitor`) also +refuses any `git push` Claude types, when the key 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 the push with +`! git push`, and the session banner adds a `🔒 push : manual` line. The hook +fails closed: a non-boolean value reads as manual, and a git failure while +reading the key or more than 20 directory tokens in one command refuses the +push, in auto mode too. In manual mode it over-blocks any command where a +`push` word follows a `git` token (`git stash push`, a grep for "git push"). +The misses listed in its header fall to an `autoMode.soft_deny` rule that no +request in the turn clears. Skills that push on their own are not adapted +yet. ## managed-settings.json (enterprise) From 5cf049d2351ab72993b0feb4f5c2a5a94c1916d9 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 13:39:01 +0200 Subject: [PATCH 010/547] feat(gitflow): push-mode verb; /close reports the push state instead of pushing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run C1 of manual-push mode (BDR-111/BDR-112). - lib/gitflow.sh: `gitflow.sh push-mode` prints auto | manual | invalid (rc 0; an invalid value is named on stderr). It is the one reader a skill may call: the bare `git config … gitflow.*` read is denied to Claude since run B. Ignores GITFLOW_NO_PUSH by design (documented). - skills/capitalize/SKILL.md STEP 5C: the explicit `git push origin develop` is gone — `finish` has pushed develop itself since BDR-095, mode-aware since run A. 5C is now three separate read-only calls (finish; push-mode; `git rev-list --count origin/develop..develop`) and prose outcomes keyed on the real ahead count: pushed / manual push mode, you push / not on origin / push FAILED / invalid value named, plus a finish-failure outcome (merge vs delete rc distinguished). STEP 6 closing lines and the recap carry every outcome; the `--no-push` line reads the branch's own ahead count ("this disk only" only when true). Invariant: no `git push` inside any Bash call; the user hints are prose. - skills/close/SKILL.md, lib/gitflow-aiguillage.md: "push" claims qualified "in auto-push mode". - lib/gitflow-test.sh T11b: six cases for the verb (default, true, false, non-boolean with stderr + rc 0, corrupt config, usage). Polish items from the gates are listed in TODO.md (C1 polish). --- lib/gitflow-aiguillage.md | 4 ++-- lib/gitflow-test.sh | 16 ++++++++++++++++ lib/gitflow.sh | 29 ++++++++++++++++++++++++++++- skills/capitalize/SKILL.md | 38 +++++++++++++++++++++++++------------- skills/close/SKILL.md | 4 ++-- 5 files changed, 73 insertions(+), 18 deletions(-) diff --git a/lib/gitflow-aiguillage.md b/lib/gitflow-aiguillage.md index 196f4b9..35235f7 100644 --- a/lib/gitflow-aiguillage.md +++ b/lib/gitflow-aiguillage.md @@ -37,8 +37,8 @@ exemption still lets a *manual* memory commit through on a protected base, but a skill-driven one now branches to `chore/*` first. **Integration is human-gated by default** — these flows commit, they do not merge. -EXCEPTION: `/capitalize` + `/close` auto-persist their memory-only commit (finish → -develop + push) when THEY branched a `chore/*` off develop this run (BDR-068 — a +EXCEPTION: `/capitalize` + `/close` auto-persist their memory-only commit (finish → develop; the lib pushes develop in auto-push mode only) +when THEY branched a `chore/*` off develop this run (BDR-068 — a scoped [[LRN-069]] exception; see the capitalize skill's STEP 5C). `/prune-memory` + `/reconcile` stay fully human-gated: never run `gitflow finish` from them. diff --git a/lib/gitflow-test.sh b/lib/gitflow-test.sh index 3579b83..0c2d82d 100644 --- a/lib/gitflow-test.sh +++ b/lib/gitflow-test.sh @@ -172,6 +172,22 @@ if bash "$HERE/gitflow.sh" protected-base main; then ok "cli protected-bas if bash "$HERE/gitflow.sh" protected-base feature/x; then no "cli protected-base feature (rc0?)"; else ok "cli protected-base feature → rc1"; fi chk "cli base-for hotfix=main" '[ "$(bash "$HERE/gitflow.sh" base-for hotfix)" = main ]' +echo "T11b — push-mode verb (the sanctioned reader for skills, BDR-112)" +newrepo pm; echo a>a +bash "$HERE/gitflow.sh" init >/dev/null 2>&1 +chk "cli push-mode default auto" '[ "$(bash "$HERE/gitflow.sh" push-mode)" = auto ]' +git config gitflow.autopush true +chk "cli push-mode true auto" '[ "$(bash "$HERE/gitflow.sh" push-mode)" = auto ]' +git config gitflow.autopush false +chk "cli push-mode manual" '[ "$(bash "$HERE/gitflow.sh" push-mode)" = manual ]' +git config gitflow.autopush flase +pm_out=$(bash "$HERE/gitflow.sh" push-mode 2>"$WORK/pm.err"); pm_rc=$? +chk "cli push-mode invalid, rc 0, value on stderr" "[ $pm_rc -eq 0 ] && [ \"$pm_out\" = invalid ] && grep -q flase \"$WORK/pm.err\"" +printf '[gitflow\n' >> .git/config +pm2_out=$(bash "$HERE/gitflow.sh" push-mode 2>/dev/null); pm2_rc=$? +chk "cli push-mode corrupt config → invalid, rc 0" "[ $pm2_rc -eq 0 ] && [ \"$pm2_out\" = invalid ]" +chk "cli usage lists push-mode" 'grep -q push-mode <<<"$(bash "$HERE/gitflow.sh" nope 2>&1)"' + echo "T12 — finish arg-guard (named branch must equal current, else refuse)" newrepo finargs; echo a>a; hookon; gitflow_init >/dev/null 2>&1 gitflow_start feature standon >/dev/null 2>&1; echo w>w.txt; git add w.txt; git commit -q -m w diff --git a/lib/gitflow.sh b/lib/gitflow.sh index 1ef2cd1..6732258 100644 --- a/lib/gitflow.sh +++ b/lib/gitflow.sh @@ -68,6 +68,32 @@ gitflow_release_open() { [ -n "$(git for-each-ref --format='%(refname:short)' 'refs/heads/release/*')" ] } +# gitflow_push_mode -> stdout auto | manual | invalid, rc 0 always. The ONE +# reader skills may call: `git config ... gitflow.*` is statically denied to +# Claude (BDR-112). manual = key reads false; auto = true or unset; invalid = +# anything else (unparseable value, git failure); the raw value goes to +# stderr so the caller can name it. Reads only. Ignores GITFLOW_NO_PUSH (a +# test-repo switch, not a mode): a caller that pushes must not rely on this +# verb alone, the lib's own push sites use _gitflow_push_off. +gitflow_push_mode() { + local val rc raw + val=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? + case "$rc:$val" in + 0:false) echo manual ;; + 0:true|1:*) echo auto ;; + *) raw=$(git config gitflow.autopush 2>/dev/null) + if [ -n "$raw" ]; then + echo "gitflow.sh push-mode: gitflow.autopush='$raw'" \ + "is not a boolean (git rc $rc)" >&2 + else + echo "gitflow.sh push-mode: could not read" \ + "gitflow.autopush (git rc $rc)" >&2 + fi + echo invalid ;; + esac + return 0 +} + # ── start ──────────────────────────────────────────────────────────────────── # rc 0 when pushing is off: GITFLOW_NO_PUSH=1 (throwaway test repos) or @@ -597,6 +623,7 @@ if [ "${BASH_SOURCE[0]}" = "${0}" ]; then delete) gitflow_delete "$@" ;; merged) [ -n "${1:-}" ] || { echo "usage: gitflow.sh merged " >&2; exit 2; } gitflow_merged_into_base "$1" ;; + push-mode) gitflow_push_mode ;; hooks) printf '%s\n' "${GITFLOW_HOOKS[@]}" ;; init) gitflow_init "$@" ;; reconcile) gitflow_reconcile_gitignore "$@" ;; @@ -606,6 +633,6 @@ if [ "${BASH_SOURCE[0]}" = "${0}" ]; then global-hooks) gitflow_global_hooks "$@" ;; emit-hook) _gitflow_emit_hook "${1:-pre-commit}" \ || { echo "gitflow.sh emit-hook {$(IFS='|'; echo "${GITFLOW_HOOKS[*]}")}" >&2; exit 2; } ;; - *) echo "usage: gitflow.sh {type|protected-base|base-for|release-open|start|finish|delete
|merged
|init|reconcile|purge-transient|install-hook|reconcile-hooks|global-hooks [value]|hooks|emit-hook }" >&2; exit 2 ;; + *) echo "usage: gitflow.sh {type|protected-base|base-for|release-open|start|finish|delete
|merged
|push-mode|init|reconcile|purge-transient|install-hook|reconcile-hooks|global-hooks [value]|hooks|emit-hook }" >&2; exit 2 ;; esac fi diff --git a/skills/capitalize/SKILL.md b/skills/capitalize/SKILL.md index 74b96fb..b421f33 100644 --- a/skills/capitalize/SKILL.md +++ b/skills/capitalize/SKILL.md @@ -10,7 +10,7 @@ description: | Triggers: "capitalize", "before clear/compact", "flush memory", "don't lose this", "avant de clear/compact", "capitalise ce qui manque", "close", "fin de journée", "checkpoint memory". -argument-hint: "[--ritual] [--no-push] (scans conversation + git + TODO against .claude/memory/; --ritual adds the 3-question reflection; --no-push holds memory on chore/: pushed to origin by the hooks, NOT merged (finish skipped), merge when ready; default = auto-finish into develop)" +argument-hint: "[--ritual] [--no-push] (scans conversation + git + TODO against .claude/memory/; --ritual adds the 3-question reflection; --no-push holds memory on chore/: pushed to origin by the hooks in auto-push mode, NOT merged (finish skipped), merge when ready; default = auto-finish into develop)" allowed-tools: - Read - Edit @@ -332,17 +332,22 @@ pre-BDR-068 behavior): branch the memory already rides feature/bugfix — never auto-merge it), AND - `--no-push` was NOT passed (the hold escape hatch). -Then, from the `chore/` branch: +Skip this step entirely (go to STEP 6, which prints the hold note) on +`--no-push`, on a WORKING branch, or when STEP 5B returned rc 3. - bash "$HOME/.claude/lib/gitflow.sh" finish chore # merge → develop, delete branch - git push origin develop +Otherwise, from the `chore/` branch, THREE separate Bash calls, never combined. INVARIANT: no `git push` inside any Bash call of this skill (push-guard reads command text; the lib pushes develop itself in auto-push mode). The hints that tell the USER what to type (`! git push …`) are prose, kept on single lines. -- **finish + push OK** → surface `develop pushed` in STEP 6. -- **push fails** (offline / rejected) → the merge to develop ALREADY happened - locally; report `merged to develop, push FAILED — push manually`. Do NOT retry - or reset the merge. -- **`--no-push` / WORKING branch / rc 3** → skip this step; the commit stays where - it is. STEP 6 prints the manual-merge note. +1. `bash "$HOME/.claude/lib/gitflow.sh" finish chore ` — merge → develop, delete branch, push develop in auto-push mode. rc≠0 → skip calls 2-3, go to STEP 6 with the `finish failed` line: rc 4 = conflict, develop mid-merge, `chore/` kept, NOT merged; rc 1 = checkout failed, NOT merged; rc 5/2/6 come from the delete AFTER the merge: check `git merge-base --is-ancestor chore/ develop` and report `merged, branch not deleted (rc )` when it holds, `NOT merged` otherwise. Never say "merged" without that check. +2. `bash "$HOME/.claude/lib/gitflow.sh" push-mode` → `auto | manual | invalid` (stderr names an invalid value). +3. `git rev-list --count origin/develop..develop 2>/dev/null || echo unknown` → `ahead` (0 = on origin; `unknown` = no origin/develop ref, e.g. no origin remote). + +Outcomes, evaluated IN THIS ORDER (all require finish rc 0): + +- **push mode `invalid`** → `merged to develop — gitflow.autopush= is not a boolean: the lib and hooks still push on an invalid value until run D (origin/develop is commit(s) behind, or unknown); fix the value by hand`. +- **`ahead` = 0** → `develop pushed` (auto-push mode did it). +- **`ahead` = unknown** → `merged to develop — not on origin (no origin/develop ref; no remote or never fetched)`; push mode manual → add `You: ! git push origin develop once a remote exists`. +- **`ahead` > 0, push mode `manual`** → `merged to develop — manual push mode: not pushed. You: ! git push origin develop`. +- **`ahead` > 0, push mode `auto`** → `merged to develop — push FAILED (see finish stderr); push manually`. Do NOT retry or reset the merge. ## STEP 6 — FINAL OUTPUT + HANDOFF @@ -355,7 +360,7 @@ CAPITALIZE COMPLETE — () TODO.md : checked , added journal.md : +1 line under ## committed : (chore(memory): …) | ⚠️ NOT committed (rc 3 — see closing line) - persisted : develop pushed | on chore/, not merged (--no-push) | merged, push FAILED + persisted : develop pushed | merged, manual push mode: not pushed | merged, not on origin (no origin/develop) | merged, push FAILED | merged, gitflow.autopush invalid ( behind) | finish rc , not merged | merged, branch not deleted (rc ) | on chore/, not merged (--no-push) dropped as already-captured: LRN-023, BLK-006 ignored as noise: push/tag release ``` @@ -364,8 +369,15 @@ Then the closing line — pick by the STEP 5C persist result (`` = `Contex flushed` for pre-wipe, `Session closed` for ritual): - **auto-persisted (default — branched off develop, pushed)** → `✅ + persisted to origin/develop (). Next session: read .claude/memory/ at startup.` -- **--no-push (held on branch)** → `✅ + committed on chore/ — pushed to origin by the hooks, NOT merged (--no-push: finish skipped). Merge when ready.` +On the `--no-push` path (and on any 5B-committed path where 5C did not run) read TWO facts first, each its own Bash call: `bash "$HOME/.claude/lib/gitflow.sh" push-mode` and `git rev-list --count origin/chore/..chore/ 2>/dev/null || echo unknown` (`branch_ahead`). `` below is the verb's word. + +- **--no-push, `branch_ahead` = 0** → `✅ + committed on chore/ — pushed to origin by the hooks (auto-push mode), NOT merged (--no-push). Merge when ready.` +- **--no-push, `branch_ahead` > 0 or unknown** → `✅ + committed on chore/ — this disk only, not pushed (), NOT merged. You: ! git push -u origin chore/; merge when ready.` With push mode `invalid`, append ` gitflow.autopush= is not a boolean: fix it by hand`. +- **manual (merged, `ahead` > 0)** → `✅ + merged to develop — manual push mode: not pushed. You: ! git push origin develop` +- **not on origin (merged, `ahead` unknown)** → `✅ + merged to develop — not on origin (no origin/develop ref).` +- **invalid (merged)** → `⚠️ + merged to develop — gitflow.autopush= is not a boolean; lib/hooks still push on it until run D (origin/develop behind). Fix the value by hand.` - **push failed after merge** → `✅ + merged to develop — ⚠️ push FAILED (); merged locally, push manually.` +- **finish failed** → `⚠️ + finish rc : — chore/ kept, NOT merged (or: merged, branch not deleted); resolve by hand.` - **WORKING branch (rode a feature branch)** → `✅ + committed on . Integrates when the branch merges.` - **commit skipped (rc 3)** → keep the ✅ on the WRITE but make the gap loud, never buried: `✅ — ⚠️ NOT committed (); entries safe on disk, commit manually.` @@ -400,7 +412,7 @@ manual commit (rc 3). always produces a commit; only an unsafe git state (rc 3) skips it. - **Auto-persist the flush (STEP 5C, BDR-068)** — a memory-only commit on a `chore/` branch THIS run created off develop auto-finishes → develop + - pushes; a scoped exception to LRN-069. `--no-push` holds it on the branch; a + pushes (the lib pushes develop in auto-push mode only; manual mode merges and leaves the push to the user); a scoped exception to LRN-069. `--no-push` holds it on the branch; a WORKING branch (memory rides feature/bugfix) or rc 3 skips it. NEVER auto-finish a branch the run did not create. - **Skip trivial** for the 4 ID registries; journal excepted. diff --git a/skills/close/SKILL.md b/skills/close/SKILL.md index af68e3b..28e2192 100644 --- a/skills/close/SKILL.md +++ b/skills/close/SKILL.md @@ -9,7 +9,7 @@ description: | (that is /prune-memory). Triggers: "close", "end session", "ferme la session", "session close", "checkpoint memory", "what did we learn", "retro rapide", "fin de journée". -argument-hint: "[--no-push] (runs capitalize in ritual mode; --no-push holds memory on chore/: pushed to origin by the hooks, NOT merged (finish skipped), merge when ready; default = auto-finish into develop)" +argument-hint: "[--no-push] (runs capitalize in ritual mode; --no-push holds memory on chore/: pushed to origin by the hooks in auto-push mode, NOT merged (finish skipped), merge when ready; default = auto-finish into develop)" allowed-tools: - Read - Edit @@ -28,7 +28,7 @@ allowed-tools: Invoke the `capitalize` skill now and run it in **ritual mode**: the full pipeline (STEP 0 precheck → STEP 1 auto-scan → STEP 2 dedup → STEP 2B TODO reconcile → STEP 3 approval gate → STEP 4 write → STEP 5 journal → STEP 5B -memory commit → STEP 5C auto-persist: finish + push, BDR-068 — pass +memory commit → STEP 5C auto-persist: finish (push rides it in auto-push mode), BDR-068 — pass `--no-push` through to hold the chore branch instead → STEP 6 handoff), PLUS STEP 1B's explicit 3-question reflection (what did you decide / learn / block). From 6104545e76b51c7230dbba9080eb02aee9b47dac Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 14:02:51 +0200 Subject: [PATCH 011/547] feat(skills): push state read from facts, never pushed by the skills MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run C2 of manual-push mode (BDR-111/BDR-112). The four flows that pushed on their own, or claimed the branch was on origin, now read the truth after the fact and hand the user the exact command: - client-handover-writer: the "Push to origin now?" question and its push block are gone (the hooks had already pushed in auto-push mode; push-guard denies it in manual mode). A reusable PUSH STATE READ (branch, origin probe, `git rev-list --count origin/
..
`, the verb only to word the reason) runs after commit-change, at the top of the deploy pause, after "Deployed" and before each end report. The branch name is validated against an allowlist before it is placed in any command or hint (a hostile branch name is otherwise a shell injection). Pending → the user pushes BEFORE the deploy pause; the deploy brief says "after your push". `Push:` line in both reports. - release-candidate STEP 6: two ahead counts + the verb; anything other than auto with both counts 0 prints one user command `! git push --atomic origin main develop v` and stops; the tag gate stays for auto mode; `hold` notes --follow-tags; version regex. - release-executor: push claims qualified (auto-push mode, best effort). - tour: mode-agnostic rule; STEP 3 reads one `git -C ` fact per project (suffix-aware branch, --remotes=origin, origin probe) and the summary row says on origin / local only with the user command. --- agents/client-handover-writer.md | 92 +++++++++++++++++++------------ agents/release-executor.md | 16 +++--- skills/client-handover/SKILL.md | 2 +- skills/release-candidate/SKILL.md | 32 ++++++++--- skills/tour/SKILL.md | 21 +++++-- 5 files changed, 108 insertions(+), 55 deletions(-) diff --git a/agents/client-handover-writer.md b/agents/client-handover-writer.md index 1ba9c0c..c9a7271 100644 --- a/agents/client-handover-writer.md +++ b/agents/client-handover-writer.md @@ -62,7 +62,7 @@ and degrading Google's NAP-consistency signal. Pipeline (each step gates the next): 1. Baseline audits: SEO+GEO and security hardening in parallel. 2. Fix loops: apply each audit's bundle (AUTO items, ONE gate for GATED ones) and re-audit until ≥17/20 or `MAX_ITERATIONS` hit. -3. Commit + push if files changed. +3. Commit if files changed (the hooks push in auto-push mode; the push state is read, never assumed). 4. Deploy pause: list deploy artifacts + process, wait for user confirmation. 5. Live-site validation against the deployed URL. 6. Per-axis gate: every score ≥17/20 OR stop + roadmap. @@ -567,40 +567,45 @@ If `PENDING_CHANGES` non-empty → invoke /commit-change skill via subagent: > commit). Use Conventional Commits format. After committing, return the > SHA list." -Then, **before pushing, STOP and ask for an explicit GO** — the push is an -outward-facing action and never fires autonomously: +**PUSH STATE READ.** Three separate Bash calls, never combined, read-only: +`git branch --show-current` → `
`; +`git remote get-url origin >/dev/null 2>&1 && echo origin || echo no-origin`; +`git rev-list --count origin/
..
2>/dev/null || echo unknown` → +`ahead`. Validate `
` against `^[A-Za-z0-9._/-]+$` before using it +anywhere (git accepts shell metacharacters in branch names). On mismatch: +state = `unknown (branch name contains characters this pipeline refuses to +interpolate: push by hand after renaming the branch)`, interpolate NOTHING, +skip the rev-list and the verb. The validated `
` is the only name ever +placed in a `! git push -u origin
` hint (STEP 5, deploy brief, +reports); every re-run of PUSH STATE READ inherits this rule. +If `ahead` ≠ 0 and origin exists: +`bash "$HOME/.claude/lib/gitflow.sh" push-mode` → anything other than `auto` +is treated like `manual` (stderr line kept verbatim when `invalid`). +State, first match wins, in this order: (1) no commits were made this run +or the gitflow fallback left changes uncommitted → +`nothing to push (no commits this run)` / `uncommitted changes (no gitflow +model): publish by hand`, stop; (2) `
` invalid → the unknown state +above; (3) `no-origin` → `not on origin (no origin remote: add one first)`; +(4) `ahead` = 0 → `on origin`; (5) otherwise (`ahead` > 0 or `unknown`) +→ `pending — you: ! git push -u origin
` + reason: push mode `manual` → +`(manual push mode)`, `auto` → `(not on origin: no remote-tracking ref or +the hook push did not land)`, `invalid` → `()`. +The pipeline never runs `git push` itself. -> AskUserQuestion — "Changes committed on ``. Push to origin now? -> - A) Yes — push `` to origin -> - B) No — I'll push manually before confirming deploy" +`pending` → tell the user NOW: `Commits are local only. Push first: +! git push -u origin
`. -Only on **A** run the push; on **B** skip it and note "push deferred to user" -in the STEP 8 summary, then continue. - -> **Red flag — STOP:** never `git push` without option-A GO; never -> `gitflow finish`/`merge`. This pipeline commits and (on GO) pushes a working -> branch — it never integrates into a protected branch. - -```bash -CURRENT_BRANCH=$(git branch --show-current) -git push origin "$CURRENT_BRANCH" 2>&1 -``` - -If push fails (no remote, auth issue, conflict): capture error, report to -user via AskUserQuestion: - -``` -"Push failed: . Pipeline needs the changes published before deploy. -Options: -- A) Retry push (after I fix it manually) -- B) Skip push — I'll publish manually before confirming deploy -- C) Abort pipeline" -``` +> **Red flag — STOP:** never `git push` (the hooks push in auto-push mode; +> otherwise the user does); never `gitflow finish`/`merge`. This pipeline +> commits a working branch — it never integrates into a protected branch. --- ## STEP 6 — DEPLOY PAUSE +Re-run PUSH STATE READ (every path reaches STEP 6, some without STEP 5's +read). + Skip if `PROJECT_TYPE != web` (non-web has no deploy-then-validate flow — set `VALIDATE_SKIPPED=true` and jump to STEP 8). @@ -625,10 +630,15 @@ Commits added in this session: Tailor to project deploy method (use DEPLOY_HINTS): -- **Vercel/Netlify/Cloudflare Pages auto-deploy from git**: "Push has been - done. The platform deploys automatically — usually 1-3 min. Watch the - dashboard. Tell me when the new version is live." -- **GitHub Actions / GitLab CI**: "Workflow `` should run on push. +When the state is `pending`, the brief OPENS with +`First push: ! git push -u origin
`. When `on origin`, keep "Push has +been done. …". + +- **Vercel/Netlify/Cloudflare Pages auto-deploy from git**: "The platform + deploys automatically after your push (a working branch gives a preview + at most; production builds from the production branch) — usually 1-3 + min. Watch the dashboard. Tell me when the new version is live." +- **GitHub Actions / GitLab CI**: "Workflow `` runs on your push. Watch CI status. Tell me when it's green and live." - **Manual upload (FTP / SSH)**: "Upload these files to the server: ``. If using rsync, here's a template: `rsync -avz dist/ user@server:/path`." @@ -650,6 +660,9 @@ AskUserQuestion: - C) Skip /web-validate — proceed to handover doc with VALIDATE marked SKIPPED ``` +After option A "Deployed": re-run PUSH STATE READ; still `pending` → ask +again (the live site cannot hold these commits). + If A → proceed to STEP 7. If B → exit cleanly with state report. If C → mark `VALIDATE_SKIPPED=true` and jump to STEP 8. @@ -683,8 +696,8 @@ SCORE_VALIDATE_AFTER=$(extract_score .claude/audits/VALIDATE.md) Note: VALIDATE has no `_BEFORE` (first run is post-deploy). The before/after table for VALIDATE shows `—` for before, `` for after. -If /web-validate produced new fixes in source code, run STEP 5 again (mini-commit -+ push) BEFORE moving to STEP 8 — but DO NOT loop /web-validate. The remaining +If /web-validate produced new fixes in source code, run STEP 5 again (mini-commit; +push state read, never assumed) BEFORE moving to STEP 8 — but DO NOT loop /web-validate. The remaining deploy of those fixes is mentioned to the user in the final doc. --- @@ -806,9 +819,14 @@ Below-threshold audits: Roadmap written to .claude/audits/HANDOVER-ROADMAP.md. Tasks appended to .claude/tasks/TODO.md. +Push: + Resolve P0 items, then re-run /client-handover. ``` +Re-run PUSH STATE READ right before printing this report (never reuse +the STEP 5 snapshot). + If `ALL_PASS = true` → proceed to STEP 9 (memory load + doc generation). ### Roadmap structure (when gate fails) @@ -1170,9 +1188,13 @@ Parse the returned `HANDOVER-DOC REPORT`: - `STATUS: DONE` → report the `MD` / `HTML` / `PDF` paths to the user, plus the `GATES` line and any `NOTES` caveats (e.g. `[À COMPLÉTER]` markers left in NAP, deploy chapter included/skipped). + Re-run PUSH STATE READ right before printing, then add the bullet: + - Push: - `STATUS: BLOCKED` → surface the report verbatim (including which PACKAGE field the doc-writer flagged) and stop — do not retry or - patch the PACKAGE silently. + patch the PACKAGE silently. Re-run PUSH STATE READ and add the same + bullet: + - Push: In BOTH branches, then clean the transient draft: `rm -f ".audit/handover-draft-${RUNID}.md"` (run-scoped, gitignored — diff --git a/agents/release-executor.md b/agents/release-executor.md index f33a180..b86aa05 100644 --- a/agents/release-executor.md +++ b/agents/release-executor.md @@ -77,15 +77,17 @@ actual branch; never finish whatever happens to be checked out. output verbatim; do not attempt to resolve it yourself. 2. **Tag AFTER finish, on `main`** — never before: `git tag -a v main -m "release "` (annotated, so it lands on - main's release-merge commit). Finish has already pushed `main` and - `develop` through the lib's hooks (BDR-095); the tag stays local until - the dispatcher's tag-push gate. + main's release-merge commit). In auto-push mode finish pushes `main` + and `develop` (best effort: the lib warns and returns 0 on a failed + push; the dispatcher re-verifies with ahead counts) (BDR-095); in + manual push mode they stay local. The tag stays local until the + dispatcher's tag-push gate. ### Forbidden in this span -`git push` (any remote, any ref — `main`/`develop` ride the lib's hook -pushes during finish; the dispatcher owns the tag-push gate), deciding the -version number, the when-to-release decision, attribution trailers of any -kind. +`git push` (any remote, any ref — `main`/`develop` ride the lib's +pushes during finish in auto-push mode; the dispatcher owns the tag-push +gate), deciding the version number, the when-to-release decision, +attribution trailers of any kind. --- diff --git a/skills/client-handover/SKILL.md b/skills/client-handover/SKILL.md index 73ebfaf..d7df8f0 100644 --- a/skills/client-handover/SKILL.md +++ b/skills/client-handover/SKILL.md @@ -45,7 +45,7 @@ The agent runs a **ship-and-handover pipeline** with explicit gates: - Re-invoke the audit subagent in audit mode: it re-scores and returns the next FIX BUNDLE; it applies nothing (a dispatched child cannot hold a gate). - Repeat up to `MAX_ITERATIONS` (default 5). - If still < 17/20 after cap → escalate to user with concrete remaining issues; user decides continue / stop / manual intervention. -4. **COMMIT + PUSH** — If files changed during fix loops, run /commit-change (atomic logical commits) then `git push`. +4. **COMMIT + PUSH** — If files changed during fix loops, run /commit-change (atomic logical commits); the gitflow hooks push in auto-push mode, otherwise (manual push mode, or a hook push that failed) the agent tells the user to push with `! git push -u origin ` BEFORE the deploy pause. 5. **DEPLOY PAUSE** — List exact deploy artifacts: changed files since baseline, deploy hints from project (vercel.json, netlify.toml, Dockerfile, .github/workflows/deploy.yml, etc.), and the deploy process in plain words. Use AskUserQuestion: "Deploy done? (Yes / Not yet / Skip validate)". Block until Yes or Skip. 6. **/web-validate (live site)** — Run validator-analyzer against the deployed URL. Capture `SCORE_VALIDATE`. 7. **GATE — per-axis threshold ≥17/20** — Compute final `SCORE_*_AFTER` for SEO classique, GEO (IA), HARDEN, VALIDATE. If ANY < 17/20: STOP. Generate `.claude/audits/HANDOVER-ROADMAP.md` with prioritized analysis of what's blocking each below-threshold axis. Do NOT write the client deliverable. Report to user. diff --git a/skills/release-candidate/SKILL.md b/skills/release-candidate/SKILL.md index 7eddd35..4437664 100644 --- a/skills/release-candidate/SKILL.md +++ b/skills/release-candidate/SKILL.md @@ -25,8 +25,9 @@ The two mechanical spans (prep, finish+tag) run on the sonnet-pinned gate needed here, dispatch does the job. This dispatcher keeps everything the executor must never own: the version-NUMBER decision (judgment — derives from semver change nature), and the two human gates (when to release, and -the tag push). A human gate sits BETWEEN the two spans by construction, so the -executor is never dispatched twice in one call. +the tag push (auto-push mode; in manual push mode the user pushes main, +develop and the tag in one command)). A human gate sits BETWEEN the two +spans by construction, so the executor is never dispatched twice in one call. ## When to use - `develop` is ahead of `main` and you want to publish a version. @@ -54,6 +55,8 @@ Read the `## [Unreleased]` section of `CHANGELOG.md` and the commits on `develop` since `main`. Apply the Versioning rule above (breaking → MAJOR, features → MINOR, fixes → PATCH) and settle `` before dispatching anything — the executor never derives or second-guesses this number. +The version must match `^[0-9]+\.[0-9]+\.[0-9]+$` before it is placed in +any command or tag; anything else stops the run. ### STEP 3 — Dispatch: prep ``` @@ -93,10 +96,22 @@ Parse the `RELEASE-EXEC REPORT`: not an auto-retry. ### STEP 6 — Tag push GATE (ASK) -`main` and `develop` are already on origin: the lib pushes every merge as -it lands (`_gitflow_merge_into` + the post-merge hook, BDR-095). Only the -tag is left. STOP. On explicit go only ([[LRN-069]]) — run the tag push -HERE, in this dispatcher, never delegated to the executor: +Read the state, separate Bash calls: +`git rev-list --count origin/main..main 2>/dev/null || echo unknown`, +`git rev-list --count origin/develop..develop 2>/dev/null || echo unknown`, +`bash "$HOME/.claude/lib/gitflow.sh" push-mode`. +- Anything other than `auto` from the verb (manual, invalid, empty, usage + error) OR either count ≠ 0 or `unknown` → Claude pushes nothing + (push-guard would refuse it in manual mode; a failed lib push is the + user's call, BDR-095). Print ONE command for the user and STOP, no + question: `! git push --atomic origin main develop v` (invalid: + quote the verb's stderr line verbatim; auto with a count ≠ 0 or unknown: + say `main/develop not on origin (no remote-tracking ref or the lib's push + did not land)`; no origin remote (`git remote get-url origin` fails): say + `add an origin remote first`). +- Push mode `auto` and both counts 0 → main and develop are on origin; only + the tag is left. STOP. On explicit go only ([[LRN-069]]) — run the tag + push HERE, never delegated: ``` AskUserQuestion: Push tag v to origin? — go / hold @@ -105,13 +120,16 @@ Go → ```bash git push origin v ``` -`hold` → stop; the release is on origin (main + develop), the tag stays local. +`hold` → stop; the release is on origin (main + develop), the tag stays +local until the next push of main (`--follow-tags` on every lib and hook +push). ## Common mistakes - Tagging before `gitflow finish` → tag wouldn't sit on main's merge commit. Tag AFTER, on main. - Auto-firing finish because tests pass → finish is a HUMAN gate. - Restarting the tag at v1.0.0 → desyncs from the CHANGELOG lineage. Continue it. - Pushing the tag without the ASK gate → [[LRN-069]]. +- Pushing anything in manual push mode → print the one user command, push nothing. ## Validation `RC_WORK=$(mktemp -d) RC_TAG=1 bash lib/tests/run-release-candidate.sh` → 5/5 (fan-out + tag on main). `RC_TAG=0` reds the tag assertion — proves the lib alone never tags (the gap this skill fills). diff --git a/skills/tour/SKILL.md b/skills/tour/SKILL.md index 3f7ca46..9f88245 100644 --- a/skills/tour/SKILL.md +++ b/skills/tour/SKILL.md @@ -237,6 +237,16 @@ order: and says so in the summary. 4. Confirm `git status --porcelain` is clean (runtime junk the sandbox cannot delete, e.g. `__pycache__/`, becomes a report residual line). +5. Push state, only when a branch exists (report-only, skipped or + dirty-tree projects have none: their row keeps `no branch`, no push + column). Two read-only calls, probe first: + `git -C remote get-url origin >/dev/null 2>&1 || echo no-origin` + then + `git -C rev-list --count --not --remotes=origin 2>/dev/null || echo unknown` + (`` = the name `gitflow start` returned, suffixed `-2`/`-3` on a + same-day re-run — never the bare `chore/tour-`). 0 → `on origin`; + else `local only → ! git -C push -u origin ` (probe + printed `no-origin` → `local only (no origin remote)`). ```markdown ## Tour 2026-07-04 — branch chore/tour-2026-07-04 — 2 iterations — CONVERGED @@ -255,8 +265,8 @@ any project line with contract-changing fixes left open for decision): ``` TOUR COMPLETE — 2026-07-04 - ~/proj/api : CONVERGED (2 it.) — 3 fixed, 1 suggested | chore/tour-2026-07-04, 4 commits - ~/proj/site : NOT CONVERGED (3 it.) — 2 open residuals | chore/tour-2026-07-04, 6 commits + ~/proj/api : CONVERGED (2 it.) — 3 fixed, 1 suggested | chore/tour-2026-07-04, 4 commits | on origin + ~/proj/site : NOT CONVERGED (3 it.) — 2 open residuals | chore/tour-2026-07-04, 6 commits | local only → ! git -C ~/proj/site push -u origin chore/tour-2026-07-04 ~/proj/lib : report-only (dirty tree) | no branch Branches left UNMERGED — review each, then `gitflow finish` on your GO. Reconcile suggestions pending — apply via /reconcile. @@ -270,9 +280,10 @@ without that approval — neither this repo's nor any target project's. - Branch via the gitflow lib; **never `gitflow finish`, never merge, never push `main`/`develop`** — "the tour is green" is not a signal. - The chore branch's own commits are pushed by the gitflow hooks - (BDR-095); a `push FAILED` hook warning is a report residual, fixed - with a plain `git push -u origin chore/tour-`. + The gitflow hooks push the chore branch in auto-push mode only; when it + is not on origin (manual push mode, or a `push FAILED` warning) the USER + pushes it — `! git -C push -u origin ` — the tour + never pushes or retries. - Scoped pathspecs only; `git add -A` is forbidden. - Target TODO.md and target `.claude/memory/` are READ-ONLY. Reconcile produces suggestions, not edits. From 3881f462c68a66a7ffde8df23992f5804225c1ae Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 14:35:08 +0200 Subject: [PATCH 012/547] =?UTF-8?q?fix(gitflow):=20run=20C=20polish=20?= =?UTF-8?q?=E2=80=94=205C=20coherence,=20sanitized=20verb=20stderr,=20herm?= =?UTF-8?q?etic=20suite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the non-gap observations the gates left on runs C1/C2: - capitalize STEP 5C/6: heading no longer says "+ push"; the --no-push fact read is its own paragraph and scoped to that path; the auto-persisted line requires finish rc 0 AND ahead = 0; rc 5/2/6 (merged, branch not deleted) still report the push state; the "not on origin" line carries the once-a-remote-exists hint. - gitflow.sh push-mode: the raw config value echoed on stderr is reduced to printable characters (LC_ALL=C, BSD tr safe) and capped at 64. - gitflow-test.sh exports the hermetic git config env in the file, so a bare run on a global-manual machine stays green. - client-handover-writer: the branch allowlist refuses a leading dash. --- agents/client-handover-writer.md | 2 +- lib/gitflow-test.sh | 1 + lib/gitflow.sh | 3 ++- skills/capitalize/SKILL.md | 15 ++++++++------- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/agents/client-handover-writer.md b/agents/client-handover-writer.md index c9a7271..0273722 100644 --- a/agents/client-handover-writer.md +++ b/agents/client-handover-writer.md @@ -571,7 +571,7 @@ If `PENDING_CHANGES` non-empty → invoke /commit-change skill via subagent: `git branch --show-current` → `
`; `git remote get-url origin >/dev/null 2>&1 && echo origin || echo no-origin`; `git rev-list --count origin/
..
2>/dev/null || echo unknown` → -`ahead`. Validate `
` against `^[A-Za-z0-9._/-]+$` before using it +`ahead`. Validate `
` against `^[A-Za-z0-9._/][A-Za-z0-9._/-]*$` before using it anywhere (git accepts shell metacharacters in branch names). On mismatch: state = `unknown (branch name contains characters this pipeline refuses to interpolate: push by hand after renaming the branch)`, interpolate NOTHING, diff --git a/lib/gitflow-test.sh b/lib/gitflow-test.sh index 0c2d82d..c6bdd67 100644 --- a/lib/gitflow-test.sh +++ b/lib/gitflow-test.sh @@ -6,6 +6,7 @@ # (the chk helper EVALs its second arg; single-quoted assertion strings are # intentional — they must not expand at definition time.) set -uo pipefail +export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null HERE="$(cd "$(dirname "$0")" && pwd)" # Do NOT override GITFLOW_GITIGNORE_TEMPLATE: the lib self-resolves it from its # own location (../templates), which is correct in both the repo and installed. diff --git a/lib/gitflow.sh b/lib/gitflow.sh index 6732258..db008b6 100644 --- a/lib/gitflow.sh +++ b/lib/gitflow.sh @@ -81,7 +81,8 @@ gitflow_push_mode() { case "$rc:$val" in 0:false) echo manual ;; 0:true|1:*) echo auto ;; - *) raw=$(git config gitflow.autopush 2>/dev/null) + *) raw=$(git config gitflow.autopush 2>/dev/null | LC_ALL=C tr -cd '[:print:]' 2>/dev/null) + raw=${raw:0:64} if [ -n "$raw" ]; then echo "gitflow.sh push-mode: gitflow.autopush='$raw'" \ "is not a boolean (git rc $rc)" >&2 diff --git a/skills/capitalize/SKILL.md b/skills/capitalize/SKILL.md index b421f33..1045007 100644 --- a/skills/capitalize/SKILL.md +++ b/skills/capitalize/SKILL.md @@ -317,7 +317,7 @@ journal-only example. Surgical scope is the helper's (stages ONLY `.claude/memory` + `.claude/tasks`, changed-paths-filtered, never `git add -A`). Do NOT hand-roll git here. -## STEP 5C — AUTO-PERSIST THE MEMORY (finish + push) +## STEP 5C — AUTO-PERSIST THE MEMORY (finish; the lib pushes in auto-push mode) Memory's value is cross-session persistence — a commit stranded on an unmerged `chore/` branch is invisible to the next session sitting on develop, so the @@ -337,11 +337,11 @@ Skip this step entirely (go to STEP 6, which prints the hold note) on Otherwise, from the `chore/` branch, THREE separate Bash calls, never combined. INVARIANT: no `git push` inside any Bash call of this skill (push-guard reads command text; the lib pushes develop itself in auto-push mode). The hints that tell the USER what to type (`! git push …`) are prose, kept on single lines. -1. `bash "$HOME/.claude/lib/gitflow.sh" finish chore ` — merge → develop, delete branch, push develop in auto-push mode. rc≠0 → skip calls 2-3, go to STEP 6 with the `finish failed` line: rc 4 = conflict, develop mid-merge, `chore/` kept, NOT merged; rc 1 = checkout failed, NOT merged; rc 5/2/6 come from the delete AFTER the merge: check `git merge-base --is-ancestor chore/ develop` and report `merged, branch not deleted (rc )` when it holds, `NOT merged` otherwise. Never say "merged" without that check. +1. `bash "$HOME/.claude/lib/gitflow.sh" finish chore ` — merge → develop, delete branch, push develop in auto-push mode. rc≠0 → go to STEP 6 with the `finish failed` line (rc 1/4 skip calls 2-3; rc 5/2/6 with the ancestor check true still run them so the push state is reported): rc 4 = conflict, develop mid-merge, `chore/` kept, NOT merged; rc 1 = checkout failed, NOT merged; rc 5/2/6 come from the delete AFTER the merge: check `git merge-base --is-ancestor chore/ develop` and report `merged, branch not deleted (rc )` when it holds, `NOT merged` otherwise. Never say "merged" without that check. 2. `bash "$HOME/.claude/lib/gitflow.sh" push-mode` → `auto | manual | invalid` (stderr names an invalid value). 3. `git rev-list --count origin/develop..develop 2>/dev/null || echo unknown` → `ahead` (0 = on origin; `unknown` = no origin/develop ref, e.g. no origin remote). -Outcomes, evaluated IN THIS ORDER (all require finish rc 0): +Outcomes, evaluated IN THIS ORDER (finish rc 0, or rc 5/2/6 with the branch merged — the wording then starts with `merged, branch not deleted (rc ) —` instead of `merged to develop —`): - **push mode `invalid`** → `merged to develop — gitflow.autopush= is not a boolean: the lib and hooks still push on an invalid value until run D (origin/develop is commit(s) behind, or unknown); fix the value by hand`. - **`ahead` = 0** → `develop pushed` (auto-push mode did it). @@ -368,16 +368,17 @@ CAPITALIZE COMPLETE — () Then the closing line — pick by the STEP 5C persist result (`` = `Context flushed` for pre-wipe, `Session closed` for ritual): -- **auto-persisted (default — branched off develop, pushed)** → `✅ + persisted to origin/develop (). Next session: read .claude/memory/ at startup.` -On the `--no-push` path (and on any 5B-committed path where 5C did not run) read TWO facts first, each its own Bash call: `bash "$HOME/.claude/lib/gitflow.sh" push-mode` and `git rev-list --count origin/chore/..chore/ 2>/dev/null || echo unknown` (`branch_ahead`). `` below is the verb's word. +- **auto-persisted (5C: finish rc 0 AND `ahead` = 0)** → `✅ + persisted to origin/develop (). Next session: read .claude/memory/ at startup.` + +On the `--no-push` path ONLY read TWO facts first, each its own Bash call: `bash "$HOME/.claude/lib/gitflow.sh" push-mode` and `git rev-list --count origin/chore/..chore/ 2>/dev/null || echo unknown` (`branch_ahead`). `` below is the verb's word. The WORKING-branch and rc 3 paths have no `chore/` and never use the mode. - **--no-push, `branch_ahead` = 0** → `✅ + committed on chore/ — pushed to origin by the hooks (auto-push mode), NOT merged (--no-push). Merge when ready.` - **--no-push, `branch_ahead` > 0 or unknown** → `✅ + committed on chore/ — this disk only, not pushed (), NOT merged. You: ! git push -u origin chore/; merge when ready.` With push mode `invalid`, append ` gitflow.autopush= is not a boolean: fix it by hand`. - **manual (merged, `ahead` > 0)** → `✅ + merged to develop — manual push mode: not pushed. You: ! git push origin develop` -- **not on origin (merged, `ahead` unknown)** → `✅ + merged to develop — not on origin (no origin/develop ref).` +- **not on origin (merged, `ahead` unknown)** → `✅ + merged to develop — not on origin (no origin/develop ref).` Push mode manual → add `You: ! git push origin develop once a remote exists`. - **invalid (merged)** → `⚠️ + merged to develop — gitflow.autopush= is not a boolean; lib/hooks still push on it until run D (origin/develop behind). Fix the value by hand.` - **push failed after merge** → `✅ + merged to develop — ⚠️ push FAILED (); merged locally, push manually.` -- **finish failed** → `⚠️ + finish rc : — chore/ kept, NOT merged (or: merged, branch not deleted); resolve by hand.` +- **finish failed** → `⚠️ + finish rc : — chore/ kept, NOT merged; resolve by hand.` (rc 1/4 only; rc 5/2/6 with the branch merged use the outcome lines above with the `merged, branch not deleted (rc )` prefix, so the push state is still reported.) - **WORKING branch (rode a feature branch)** → `✅ + committed on . Integrates when the branch merges.` - **commit skipped (rc 3)** → keep the ✅ on the WRITE but make the gap loud, never buried: `✅ — ⚠️ NOT committed (); entries safe on disk, commit manually.` From 0b08ceda97038d6d07c4de54f3704b8eb9fabea0 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 14:48:07 +0200 Subject: [PATCH 013/547] =?UTF-8?q?chore(memory):=20BDR-113=20+=20LRN-197.?= =?UTF-8?q?.199=20+=20journal=20=E2=80=94=20feat=20manual-push-mode=20run?= =?UTF-8?q?=20C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 7 ++ .claude/memory/journal.md | 1 + .claude/memory/learnings.md | 12 +++ .claude/tasks/TODO.md | 6 +- .../2026-10-07-manual-push-skills-c1-1304.md | 41 ++++++++++ .../2026-10-07-manual-push-skills-c2-1325.md | 43 ++++++++++ .../2026-10-07-manual-push-skills-c1-1304.md | 79 +++++++++++++++++++ .../2026-10-07-manual-push-skills-c2-1325.md | 33 ++++++++ 8 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-07-manual-push-skills-c1-1304.md create mode 100644 .claude/tasks/contracts/2026-10-07-manual-push-skills-c2-1325.md create mode 100644 .claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md create mode 100644 .claude/tasks/plans/2026-10-07-manual-push-skills-c2-1325.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index c4bc03e..8a3f2ee 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1378,3 +1378,10 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: no-jq fallback (greps whole payload, denies in auto, untestable without shim; jq hard dep); `-C` dir unresolvable → allow (fail-open; now skipped, cwd still checked); `rev-parse` work-tree gate (drops the global key); `--default true` read (hides git failure); narrowing deny to spare the read (impossible with end-matching globs). - **Gates**: 3 lenses CONCERNS(2)/CONCERNS(5)/FATAL(7) + confirmation FATAL(8) → r2 (BSD sed, oracle naming denied tokens, read loss); feater ×3 (58 → 61 → 71 checks); GATE 0 MET ×3; verifier CONFORME, then ECARTS(1) on hardening closed by gated clarification; security PASS ×2 (3 MEDIUM closed: 20k-token flood denied in 0.15 s, git absent → deny, `bash -c 'cd … && git push'` extracted; residuals → run D). - **Refs**: contract `.claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md`, plan `.claude/tasks/plans/2026-10-07-manual-push-guard-1003.md`, commits a2ac018 + 6468eda (feature/manual-push-mode, UNMERGED). Links [[BDR-095]], [[BDR-100]], [[LRN-069]], [[LRN-196]]. Open: user probe `! git push --dry-run` under autopush=false (bang commands assumed hook-free). + +## BDR-113 — Skills never push; truth from `rev-list` facts, mode verb only words the reason [accepted] (2026-10-07) +- **Decision**: run C of [[BDR-111]]. New lib verb `gitflow.sh push-mode` (stdout `auto|manual|invalid`, rc 0, raw value on stderr, printable ≤64 chars; ignores GITFLOW_NO_PUSH) = the one reader skills may call (bare `git config … gitflow.*` denied, [[BDR-112]]). Skills push NOTHING on their own except the release tag in auto mode on explicit go. Every "on origin / not pushed" line comes from `git rev-list --count origin/
..
` (or `
--not --remotes=origin` for the tour) read AFTER the action, in its own Bash call; the verb only words the reason (manual vs push FAILED vs invalid). Removed as redundant since BDR-095: `/close` STEP 5C `git push origin develop` (finish pushes develop itself, mode-aware since run A) and `/client-handover`'s "Push to origin now?" question + push block (hooks had pushed; push-guard denies in manual). User hints are complete `! git …` commands (`-u`, `--atomic origin main develop vX`, `-C `), branch name allowlisted `^[A-Za-z0-9._/][A-Za-z0-9._/-]*$` before any interpolation. `/release-candidate` manual/invalid or any count ≠ 0 → one user command, STOP, no question; tag gate kept for auto with both counts 0. `/tour`: one `-C` fact per project after the report commit, suffix-aware branch name, summary row `on origin | local only → cmd`. +- **Why**: a shell gate `[ "$mode" = auto ] && git push …` is denied WHOLE by the text-only push-guard and `$mode` dies between Bash calls ([[LRN-199]]); the push it gated was redundant anyway ([[LRN-197]]); invalid value: lib/hooks still push (fail-open until run D) so "not pushed" from the mode word would lie — the count tells the truth. +- **Alternatives rejected**: gate the existing push on the verb (denied/stateless); keep the GO question (gated nothing); word invalid as manual (false in the lib); per-skill `git config` read (denied). +- **Gates**: C1: 3 lenses (1 BLOCKER: shell gate) + confirm CONCERNS(3); feater; GATE 0 MET; verifier CONFORME; security PASS. C2: 3 lenses (BLOCKER: deploy brief said "push done") + confirm CONCERNS(4); feater; verifier CONFORME; security BLOCK(1) branch-name injection ([[LRN-198]]) → fixed → CONFORME + PASS. Polish pass: CONFORME + PASS. +- **Refs**: contracts `.claude/tasks/contracts/2026-10-07-manual-push-skills-c1-1304.md`, `…-c2-1325.md`; plans same slugs; commits 5cf049d, 6104545, 3881f46 (feature/manual-push-mode, UNMERGED). Links [[BDR-068]], [[BDR-095]], [[BDR-042]], [[LRN-069]]. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index e3460e0..2b3e474 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -572,4 +572,5 @@ rules: ## 2026-10-07 - /feat manual-push-mode run B (user: "enchaine"): `hooks/push-guard.sh` PreToolUse denies Claude's `git push` when autopush false/unparseable/unreadable in cwd or literal -C/cd dirs (global config counts). Challenge: 3 lenses + robustness confirm FATAL(8) → BSD sed `N` fold empty on 1 line (hook dead), AC3 oracle naming denied tokens, glob trailing ` *` matches end → bare read lost, run C needs lib verb. feater ×3 (impl 58, no-jq test 61, hardening 71: cap 20 dirs, git rc → deny, quoted cd). GATE 0 MET ×3; verifier CONFORME then ECARTS(1) → user gated fail-closed also in auto for pathological commands; security PASS ×2 (3 MEDIUM closed, 2 residual → run D). Commits a2ac018 + 6468eda on feature/manual-push-mode, UNMERGED. settings.json live: 18 deny entries, soft_deny, Bash|Monitor hook group. User probe pending: `! git push --dry-run` bypasses hooks? +- /feat manual-push-mode run C (user: "enchaine"), split C1+C2. C1: lib verb `gitflow.sh push-mode` (auto|manual|invalid, value on stderr, rc 0) + T11b; /close STEP 5C `git push origin develop` REMOVED (finish has pushed develop since BDR-095; shell gate would be denied whole by push-guard, `$mode` dies between Bash calls) → finish, verb, `rev-list --count origin/develop..develop`, prose outcomes incl. finish-failure; `--no-push` line from the branch's own count. Challenge 3 lenses (1 BLOCKER) + confirm CONCERNS(3); verifier CONFORME; security PASS. C2: client-handover GO question + push block removed (hooks pushed already in auto; guard denies in manual) → PUSH STATE READ re-run before every claim, branch-name allowlist (security BLOCK(1) → fixed, PASS); release-candidate: two counts + verb, `! git push --atomic origin main develop vX`, tag gate kept for auto/0/0; tour: `-C` fact per project, suffix-aware branch, `--remotes=origin`. Verifier CONFORME ×2. Commits 5cf049d + 6104545, UNMERGED. Polish pass in flight. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index ef32021..69293c0 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1724,3 +1724,15 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s ## LRN-196 — A fail-closed Claude Code hook: trap must `exit 0`, cap attacker-sized loops, read git's rc not its value - **Context**: push-guard hardening (security gate, 3 MEDIUM). (1) EXIT trap printed the static deny but kept the non-zero rc → Claude Code parses hook JSON only on exit 0 → deny ignored = allow. (2) Each literal `cd`/`-C` token cost a subshell + 3 git execs: 600 tokens = 12 s > 10 s hook timeout → timeout = non-blocking = allow. (3) `git config --bool --default true` returns empty on git absent / old git / unreadable dir → read as "auto" → allow. - **Apply**: `trap '… ; exit 0' EXIT`; deny path `out=$(jq …) || out=$STATIC; printf '%s' "$out"`; dedup (`sort -u`) + hard cap on command-controlled token counts, deny above the cap BEFORE any fork; distinguish `git config` rc 0/1/other (value / unset / failure → deny); record "decided" only after ≥1 clean evaluation. Lock each with a test (shim PATH without a tool, 25-token flood, chmod 000 dir with SKIP path). Measure the flood after the fix (20 000 tokens → 0.15 s). Links [[BDR-112]], [[BDR-087]], [[LRN-160]]. + +## LRN-197 — A skill's own `git push` after a lib finish or a hook-pushed commit is redundant since BDR-095: delete it, don't gate it +- **Context**: `/close` STEP 5C ran `gitflow finish` then `git push origin develop` (added 2026-07-16); the lib push landed 2026-09-22 and 5C was never revisited. `/client-handover` asked "Push to origin now?" after commit-change, whose commits the post-commit hook had already pushed. Both runs' first plan GATED the push on the mode; the simplicity lens found both pushes redundant. +- **Apply**: before gating an action, ask whether it still does anything. Grep every `git push` in skills/agents after any change to hooks/lib push behaviour (BDR-100 surface rule); replace a redundant push + its question by a FACT read afterwards (`git rev-list --count origin/
..
`) and a user hint. Links [[BDR-113]], [[BDR-095]], [[LRN-113]]. + +## LRN-198 — Text read from git and pasted into a later Bash call is an injection sink: allowlist before interpolating +- **Context**: C2 replaced one Bash block (`CURRENT_BRANCH=$(git branch --show-current); git push origin "$CURRENT_BRANCH"`, quoted variable, safe) by three separate calls where the branch name is pasted as text into `git rev-list --count origin/
..
` and into `! git push -u origin
`. `git check-ref-format --branch 'x$(id)y'` rc 0: a hostile branch (PR checkout, crafted remote) runs its payload. Security gate BLOCK(1). +- **Apply**: any name an agent READS (branch, tag, path from repo state) and later WRITES into command text must pass an allowlist first (`^[A-Za-z0-9._/][A-Za-z0-9._/-]*$`; leading `-` excluded = option injection); on mismatch interpolate nothing and say so. Prefer a quoted shell variable inside ONE call when the flow allows; when prose branching forces multi-call, the allowlist replaces the quotes. `` from user args: same class, lower trust gap. Links [[BDR-113]], [[LRN-196]]. + +## LRN-199 — Agent-level branching is prose on a printed word: shell state dies between Bash calls, and a text guard denies the whole call +- **Context**: plan wrote `mode=$(gitflow.sh push-mode)` then `[ "$mode" = auto ] && git push origin develop`. Two failures: (a) separate calls → `$mode` empty → silent skip, rc 1 misread as "push FAILED"; (b) one call → push-guard's STRICT regex matches `&& git push origin` in the TEXT and denies the WHOLE call, so even `finish` never runs. Three lenses hit it independently. +- **Apply**: a skill reads a word from a command's visible stdout, then branches in PROSE ("printed `auto` → run X as its own call; anything else → never issue X"). Never a shell variable across calls, never a conditional that contains a guarded token. Any text-only PreToolUse guard turns `cmd-you-wanted-to-avoid` inside a conditional into a denial of the surrounding command. Links [[BDR-112]], [[BDR-113]], [[LRN-191]]. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 8cb8517..76bb3c5 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -2060,9 +2060,11 @@ dans un runner; capitalize reste main-loop. - [x] run A — `gitflow.autopush=false` honoured by `_gitflow_push_branch`, quiet unpushed-guard, doctrine line; plan `.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md` → commit 2fc8830 on feature/manual-push-mode; verifier ECARTS(1) = AC6 only (design-tool-gate env red, pre-existing on develop) → human waiver; merge human-gated - [x] run B — `hooks/push-guard.sh` PreToolUse (deny `git push` in manual mode) + 71-check test + settings.json (own hook group Bash|Monitor timeout 10; 18 write-form deny entries on the toggle; soft_deny on manual-mode pushes with no per-turn clearance; prose) + banner → a2ac018 + hardening commit; verifier CONFORME then ECARTS(1) closed by gated clarification (fail-closed cap/unenterable dir also in auto mode); security PASS ×2 - [ ] run D also (push-guard residuals, security gate 2026-10-07): tokens with inner quotes/backslashes (`cd /m/'a b'`) resolve to the wrong dir → treat as unresolvable + deny or document; unparseable payload (lone surrogate) → jq fails → silent allow → grep raw payload for `push` and deny; `case "$mode"` default `*) deny`; up-front `command -v grep sed sort head jq` check; header line > 80 cols; T42 compares against HEAD (vacuous once committed) → compare against a pinned base or drop; no test sets the key to literal `true` -- [ ] run C — skills that push on their own, gate on the mode through a NEW lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (prints auto|manual|invalid; the bare `git config … gitflow.autopush` read is denied for Claude after run B — a trailing ` *` glob also matches end-of-string): capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims +- [x] run C (C1 5cf049d, C2 6104545; split C1: lib verb `push-mode` + T11 tests + capitalize STEP 5C + close hint, plan `.claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md`; C2: client-handover skill+agent, release-candidate STEP 6, tour rule) — skills that push on their own, gate on the mode through a NEW lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (prints auto|manual|invalid; the bare `git config … gitflow.autopush` read is denied for Claude after run B — a trailing ` *` glob also matches end-of-string): capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims - [ ] run B also: fail-CLOSED on an unparseable `gitflow.autopush` value in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks, unpushed-guard) — run A keeps fail-open for consistency with the untouched emitters (security gate MEDIUM, 2026-10-06); `--end-of-options`/`--` on refname args and `printf %q` in copy-paste hints (LOW); `gitflow_delete`: check `_gitflow_checkout_containing_base` rc before `--unset-upstream` (LOW, 2nd gate) -- [ ] ORDER: do not set `gitflow.autopush false` on the work machine before B + C are merged (until then `/close` still pushes develop) +- [x] C1/C2 polish pass → 3881f46 (verifier CONFORME, security PASS; items were: capitalize STEP 5C heading still says "(finish + push)"; :372 paragraph glued to the :371 bullet and tells the WORKING-branch path to read `origin/chore/..` (no such ref there; that path never uses the mode); on finish rc 5/2/6 calls 2-3 are skipped so a manual-mode user gets no `! git push origin develop` hint; the "unknown + manual" closing line (:377) lacks the `once a remote exists` hint present in 5C (:348); STEP 6 "auto-persisted … pushed" bullet (:371) not tied to `ahead = 0` (security MEDIUM); verb stderr: cap `raw` to 64 printable chars; T11b "default auto" relies on the Makefile's hermetic env (fine under `make test`, spurious when run bare on a global-manual machine) → export in the suite header like line 257. C2 polish (verifier non-gaps): client-handover-writer PUSH STATE READ states need explicit precedence (uncommitted/no-commits first, then no-origin, then ahead); tour STEP 3 item 5 only when a branch exists (report-only / dirty-tree rows have none); 9.7 `STATUS: BLOCKED` branch lacks the `- Push:` bullet; release-executor:85-86 line > 80 cols +- [x] ORDER constraint lifted: A + B + C all on feature/manual-push-mode; merge (human gate) then the work machine may set `gitflow.autopush false`. Still pending before relying on it at work: user probe `! git push --dry-run` in a scratch repo under autopush=false (bang commands assumed hook-free); run D below. +- [ ] run D — fail-CLOSED on an unparseable `gitflow.autopush` in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks + githooks regen, unpushed-guard) so the "invalid → lib/hooks still push" caveat in CHANGELOG/SETTINGS/skills can be removed; push-guard residuals (inner-quote/backslash tokens, lone-surrogate payload, `*) deny` default, up-front tool check, T42 base, literal `true` test); verb stderr: `LC_ALL=C` done, truncation marker + sanitizer test; client-handover: stale "COMMIT + PUSH" headings, `` quoting in tour hints; release-executor own version regex ## test hermeticity (2026-10-06, found during manual-push-mode run A) - [ ] `lib/tests/design-tool-gate.test.sh` reds on any machine with the 21st CLI installed ("FAIL precondition: system-wide 21st present, CLI_ABSENT case not hermetic") — pre-existing on develop (fa67664), independent of the diff. Make the CLI_ABSENT case hermetic (PATH shim / stubbed probe) so `make test` is green on a design-profile machine. Until then full-suite oracles (`make test` exit 0) cannot be MET here. diff --git a/.claude/tasks/contracts/2026-10-07-manual-push-skills-c1-1304.md b/.claude/tasks/contracts/2026-10-07-manual-push-skills-c1-1304.md new file mode 100644 index 0000000..dc3d321 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-07-manual-push-skills-c1-1304.md @@ -0,0 +1,41 @@ +# CONTRACT — manual-push-skills-c1 (run C1 of manual-push mode) +- date: 2026-10-07 | flow: feat | branch: feature/manual-push-mode (runs A 2fc8830, B a2ac018+6468eda landed; C2 = client-handover ×2, release-candidate, tour follows) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "ok enchaine sur le run C" +Run C as scoped in `.claude/tasks/TODO.md` "manual-push-mode": skills that push on their own, gate on the mode through a NEW lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (prints auto|manual|invalid; the bare `git config … gitflow.autopush` read is denied for Claude after run B): capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims. User's framing (2026-10-06): "Il faut tout faire pareil, juste rien push seul. Mais faire les branches localement, faire les commits localement etc. Juste il faut pas push. seulement manuel". + +## CLARIFICATIONS +Q: scope split / A: C1 (this contract) = lib verb + its test + `/capitalize` STEP 5C + the `--no-push` hints in capitalize and close; C2 = client-handover skill + agent, release-candidate STEP 6, tour rule. 8 files > the /feat cap of 5. [orchestrator — scope, surfaced] +Q: does `/close` still merge the memory chore branch into develop in manual mode? / A: yes — local merges are part of "tout faire pareil"; only the push is withheld, and the handoff line says so. [orchestrator, from the user's own words] +Q: `invalid` mode in STEP 5C / A: challenge r1 — the lib and hooks still PUSH on an invalid value (fail-open until run D), so the handoff never claims "not pushed" from the mode alone: it reports the real `origin/develop..develop` count and names the value from the verb's stderr. [orchestrator, revised] +Q: challenge r1 — explicit `git push origin develop` in STEP 5C / A: removed. `finish` has pushed develop itself since BDR-095 (mode-aware since run A); a shell gate containing `git push` would be denied whole by push-guard in manual mode and `$mode` does not persist across Bash calls. 5C = finish, then two read-only facts (verb, ahead count), then prose. [orchestrator — internal] +Q: challenge r1 — scope / A: `lib/gitflow-aiguillage.md` (one line, "finish → develop + push") joins FILE SCOPE (5 files). [orchestrator — scope] +Q: `_gitflow_push_off` refactor onto the new verb / A: no — unchanged this run (run D owns every reader's fail-closed semantics). [orchestrator — internal] + +## ACCEPTANCE CRITERIA +1. `bash ~/.claude/lib/gitflow.sh push-mode` prints exactly one word on stdout: `manual` when `git config --bool gitflow.autopush` returns false, `auto` when it returns true or the key is unset (rc 1), `invalid` for any other rc (unparseable value, corrupt config, git failure) with the raw value named on stderr; rc 0 in all cases; the usage line lists the verb; the verb never writes config. Locked by the new T11b block. + CHECK: out=$(make test suite=lib/gitflow-test.sh 2>&1); printf '%s' "$out" | grep -q ' FAIL ' && exit 1; for t in "cli push-mode default auto" "cli push-mode true auto" "cli push-mode manual" "cli push-mode invalid, rc 0, value on stderr" "cli push-mode corrupt config" "cli usage lists push-mode"; do grep -qF "ok $t" <<<"$out" || exit 1; done; echo PUSH-MODE-OK + EXPECT: PUSH-MODE-OK + EVIDENCE: MET exit=0 marker-found :: PUSH-MODE-OK +2. `skills/capitalize/SKILL.md` STEP 5C contains NO `git push` text and no `git config` read: three separate calls (finish; `gitflow.sh push-mode`; `git rev-list --count origin/develop..develop`), a finish failure outcome (rc≠0 → kept, NOT merged, no "merged" wording), and outcomes keyed on the ahead count + mode (`develop pushed` / `manual push mode: not pushed, you: ! git push origin develop` / `push FAILED` / invalid value named from stderr with the real ahead count). STEP 6 reads the mode on every 5B-committed path and the `--no-push` closing line has a manual-mode variant ("this disk only, not pushed"); the recap carries the new values. The `--no-push` argument-hint in capitalize AND close says "in auto-push mode"; `lib/gitflow-aiguillage.md` no longer says "+ push" unconditionally. + CHECK: grep -q 'gitflow.sh" push-mode' skills/capitalize/SKILL.md && grep -q 'manual push mode: not pushed' skills/capitalize/SKILL.md && grep -q 'rev-list --count origin/develop..develop' skills/capitalize/SKILL.md && grep -q 'this disk only' skills/capitalize/SKILL.md && ! grep -q 'git config.*gitflow' skills/capitalize/SKILL.md skills/close/SKILL.md && grep -q 'auto-push mode' skills/capitalize/SKILL.md && grep -q 'auto-push mode' skills/close/SKILL.md && grep -q 'auto-push mode' lib/gitflow-aiguillage.md && echo CAPITALIZE-OK + EXPECT: CAPITALIZE-OK + EVIDENCE: MET exit=0 marker-found :: CAPITALIZE-OK +3. Doctrine citers census green (skill prose changed). + CHECK: make test suite=lib/tests/doctrine-citers.test.sh >/dev/null 2>&1 && echo CITERS-OK + EXPECT: CITERS-OK + EVIDENCE: MET exit=0 marker-found :: CITERS-OK +4. shellcheck clean on lib/gitflow.sh and lib/gitflow-test.sh; no `# shellcheck disable` added; floor guard clean. + CHECK: shellcheck lib/gitflow.sh lib/gitflow-test.sh && [ "$(git diff -- lib/gitflow.sh lib/gitflow-test.sh | grep -c '^+.*shellcheck disable')" -eq 0 ] && echo SHELLCHECK-OK + EXPECT: SHELLCHECK-OK + EVIDENCE: MET exit=0 marker-found :: SHELLCHECK-OK +5. Every hermetic suite green except the declared environmental red `lib/tests/design-tool-gate.test.sh`. + CHECK: fail=0; for t in $(ls lib/tests/*.test.sh lib/seo-data/*.test.sh lib/gitflow-test.sh lib/tests/run-*.sh | grep -v design-tool-gate.test.sh); do make test suite="$t" >/dev/null 2>&1 || { fail=1; echo "RED $t"; }; done; [ $fail -eq 0 ] && echo SUITES-OK + EXPECT: SUITES-OK + EVIDENCE: MET exit=0 marker-found :: SUITES-OK +6. No behaviour change elsewhere in lib/gitflow.sh (`_gitflow_push_off`, hooks emitters, start/finish/delete untouched; T18/T19/T22/T24 green — covered by criterion 1's FAIL grep); no edits outside FILE SCOPE; the verb never writes config. INVARIANT judged by reading (a negative grep would itself carry the denied text): no `git push` inside any Bash call in skills/capitalize/SKILL.md or skills/close/SKILL.md — the `! git push …` user hints are prose on single lines; every 5C outcome (invalid first, ahead 0, unknown, >0 manual, >0 auto; finish rc 1/4 vs 5/2/6) has a STEP 6 line and a recap value. + +## FILE SCOPE +lib/gitflow.sh · lib/gitflow-test.sh · skills/capitalize/SKILL.md · skills/close/SKILL.md · lib/gitflow-aiguillage.md diff --git a/.claude/tasks/contracts/2026-10-07-manual-push-skills-c2-1325.md b/.claude/tasks/contracts/2026-10-07-manual-push-skills-c2-1325.md new file mode 100644 index 0000000..ae34ee6 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-07-manual-push-skills-c2-1325.md @@ -0,0 +1,43 @@ +# CONTRACT — manual-push-skills-c2 (run C2 of manual-push mode) +- date: 2026-10-07 | flow: feat | branch: feature/manual-push-mode (after C1: lib verb `gitflow.sh push-mode`) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "ok enchaine sur le run C" +Run C as scoped in `.claude/tasks/TODO.md` "manual-push-mode": skills that push on their own, gate on the mode through the lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (auto|manual|invalid): client-handover SKILL:48 + agents/client-handover-writer.md (STEP 5 push GO), release-candidate STEP 6 ("main and develop are already on origin", tag push), tour rule ("pushed by the gitflow hooks … fixed with a plain git push -u"). User's framing (2026-10-06): "tout faire pareil, juste rien push seul … seulement manuel". + +## CLARIFICATIONS +Q: scope / A: C2 = the four remaining sites + the one-line claim in agents/release-executor.md ("ride the lib's hook pushes"). 5 files. Prose only, no shell code change; the verb is read in its own Bash call and the decision is prose. [orchestrator — scope] +Q: invalid mode in these flows / A: push-guard denies Claude's push on an invalid value (fail closed, run B), while the lib/hooks still push on it (fail-open until run D): the skills treat `invalid` like `manual` for what CLAUDE does (no push attempt, the user runs the command), and name the value from the verb's stderr. [orchestrator] +Q: release in manual mode / A: no push at all by Claude: main, develop and the tag are left local; the skill prints ONE user command `! git push origin main develop v` and stops (no AskUserQuestion, nothing to gate). The `hold` wording for auto mode stays. [orchestrator — visible wording derived from the user's rule] +Q: challenge r1 — truth source / A: every "on origin" / "not pushed" statement in these flows comes from `git rev-list --count origin/
..
` (or `
--not --remotes` for the tour), read in its own Bash call; the verb only words the reason. Invalid: the verb's stderr is quoted verbatim, never a templated value. [orchestrator] +Q: challenge r1 — client-handover push GO question / A: removed (it gated nothing: the hooks had already pushed in auto mode; push-guard denies it in manual mode). The pipeline never runs `git push`; the user is told to push BEFORE the deploy pause, and the deploy brief says "after your push". `Push:` line added to both end reports. [orchestrator — visible wording derived from the user's rule] +Q: challenge r1 — release command / A: `! git push --atomic origin main develop v`; also used in auto mode when a lib push did not reach origin. Tag-push gate kept for auto mode with both counts 0. `hold` wording notes `--follow-tags` publishes the held tag on the next push of main. [orchestrator] +Q: confirmation r2 / A: PUSH STATE READ is one reusable paragraph, re-run at the top of STEP 6, after "Deployed", and right before every `Push:` line (states: on origin / nothing to push / uncommitted (gitflow fallback) / not on origin, no origin remote / pending + reason); the red-flag box is kept and reworded, not deleted; anything other than `auto` from the verb is treated like manual; the tour uses the branch name `gitflow start` returned (suffix-aware) and reads the fact after the report commit; multi-line Edit anchors given to the executor. [orchestrator] +Q: tour `push FAILED` residual / A: in every mode the USER fixes it (BDR-095: a rejected push warns, the user decides); the rule no longer reads as Claude retrying. [orchestrator] + +## ACCEPTANCE CRITERIA +1. agents/client-handover-writer.md: the GO question and the push block are gone; a reusable PUSH STATE READ (branch, origin check, `git rev-list --count origin/
..
`, the verb when ahead ≠ 0) is defined in STEP 5 and re-run at the top of STEP 6, after "Deployed", and before every `Push:` line; `pending` tells the user `! git push -u origin
` BEFORE STEP 6 and the deploy brief opens with it and says "after your push"; `Push:` line (column 0) in the PIPELINE STOPPED template and a `- Push:` bullet in the 9.7 report; the red-flag box is kept and says the pipeline never pushes. No `git config` read. + CHECK: grep -q 'gitflow.sh" push-mode' agents/client-handover-writer.md && grep -q 'rev-list --count origin/
..
' agents/client-handover-writer.md && grep -q 'First push:' agents/client-handover-writer.md && [ "$(grep -c '^Push: ' agents/client-handover-writer.md)" -ge 1 ] && grep -q 'after your push' agents/client-handover-writer.md && grep -q 'PUSH STATE READ' agents/client-handover-writer.md && grep -q 'Red flag' agents/client-handover-writer.md && ! grep -q 'git config.*gitflow' agents/client-handover-writer.md && ! grep -q 'Push to origin now' agents/client-handover-writer.md && echo HANDOVER-AGENT-OK + EXPECT: HANDOVER-AGENT-OK + EVIDENCE: MET exit=0 marker-found :: HANDOVER-AGENT-OK +2. skills/client-handover/SKILL.md step 4 says the hooks push in auto-push mode and that otherwise the agent tells the user to push BEFORE the deploy pause. + CHECK: grep -q 'auto-push mode' skills/client-handover/SKILL.md && grep -q 'manual push mode' skills/client-handover/SKILL.md && grep -q 'BEFORE the deploy pause' skills/client-handover/SKILL.md && echo HANDOVER-SKILL-OK + EXPECT: HANDOVER-SKILL-OK + EVIDENCE: MET exit=0 marker-found :: HANDOVER-SKILL-OK +3. skills/release-candidate/SKILL.md STEP 6: reads two ahead counts + the verb (separate calls); manual/invalid or any count ≠ 0 → prints `! git push --atomic origin main develop v` and stops (no question; invalid quotes the verb's stderr); auto with both counts 0 → the existing tag-push gate; `hold` notes `--follow-tags`. Overview and common-mistakes qualified. agents/release-executor.md: both push claims (step 2 and the forbidden-span note) say "in auto-push mode". + CHECK: grep -q 'gitflow.sh" push-mode' skills/release-candidate/SKILL.md && grep -q -- '--atomic origin main develop v' skills/release-candidate/SKILL.md && grep -q 'rev-list --count origin/main..main' skills/release-candidate/SKILL.md && grep -q 'follow-tags' skills/release-candidate/SKILL.md && [ "$(grep -c 'auto-push mode' agents/release-executor.md)" -ge 2 ] && echo RELEASE-OK + EXPECT: RELEASE-OK + EVIDENCE: MET exit=0 marker-found :: RELEASE-OK +4. skills/tour/SKILL.md: the rule is mode-agnostic (hooks push in auto-push mode; otherwise the USER pushes with `! git -C push -u origin `; the tour never pushes or retries); STEP 3 item 5 reads one `git -C rev-list --count --not --remotes` fact per project after the report commit, with `` = the name gitflow start returned (suffix-aware); the summary row carries `on origin` / `local only → …`. + CHECK: grep -q 'auto-push mode' skills/tour/SKILL.md && grep -q 'manual push mode' skills/tour/SKILL.md && grep -q 'git -C push -u origin' skills/tour/SKILL.md && grep -q 'local only' skills/tour/SKILL.md && grep -q -- '--not --remotes' skills/tour/SKILL.md && echo TOUR-OK + EXPECT: TOUR-OK + EVIDENCE: MET exit=0 marker-found :: TOUR-OK +5. Doctrine citers census green; floor guard clean; every hermetic suite green except the declared environmental red. + CHECK: make test suite=lib/tests/doctrine-citers.test.sh >/dev/null 2>&1 && bash ~/.claude/lib/floor-guard.sh develop -- skills/client-handover/SKILL.md agents/client-handover-writer.md skills/release-candidate/SKILL.md skills/tour/SKILL.md agents/release-executor.md >/dev/null 2>&1 && fail=0 && for t in $(ls lib/tests/*.test.sh lib/seo-data/*.test.sh lib/gitflow-test.sh lib/tests/run-*.sh | grep -v design-tool-gate.test.sh); do make test suite="$t" >/dev/null 2>&1 || fail=1; done && [ $fail -eq 0 ] && echo SUITES-OK + EXPECT: SUITES-OK + EVIDENCE: MET exit=0 marker-found :: SUITES-OK +6. Judged by reading: the only `git push` left inside a Bash block in the five files is release-candidate's tag push, reached only in auto mode with both counts 0 on explicit go; every other push is a `! git …` user hint in prose (complete: `-u`, `--atomic`, `-C ` where needed); no "on origin" / "not pushed" claim derives from the mode word alone; no file outside FILE SCOPE changes; frontmatter, agent pins and headings unchanged (release-candidate description + STEP 6 heading accepted residuals). + +## FILE SCOPE +skills/client-handover/SKILL.md · agents/client-handover-writer.md · skills/release-candidate/SKILL.md · agents/release-executor.md · skills/tour/SKILL.md diff --git a/.claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md b/.claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md new file mode 100644 index 0000000..d2f0d7d --- /dev/null +++ b/.claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md @@ -0,0 +1,79 @@ +# PLAN — manual-push-skills-c1 — REVISED r2 (3 lenses + correctness confirmation) +Contract: .claude/tasks/contracts/2026-10-07-manual-push-skills-c1-1304.md + +## Context +`/close` STEP 5C runs `gitflow.sh finish chore ` then `git push origin develop`. Since BDR-095 (9da5d8d, 2026-09-22) `finish` already pushes develop itself (`_gitflow_merge_into` → `_gitflow_push_branch`, mode-aware since run A), so the explicit push has been redundant for two weeks; in manual mode push-guard (run B) would deny it, and a shell gate `[ "$mode" = auto ] && git push …` is denied as a whole by the text-only guard while `$mode` does not survive between Bash calls. Fix = remove the push text entirely and REPORT from facts read after finish. Skills can no longer read `gitflow.autopush` via `git config` (BDR-112) → the lib verb `push-mode` is the sanctioned reader. Invalid value: lib/hooks still push (fail-open until run D), so the wording must not claim "not pushed" — the ahead count tells the truth. + +## Checklist +- [ ] lib/gitflow.sh — `gitflow_push_mode()` in the predicates section (after `gitflow_release_open`): + ``` + # gitflow_push_mode → stdout auto | manual | invalid, rc 0 always. The ONE + # reader skills may call: `git config … gitflow.*` is statically denied to + # Claude (BDR-112). manual = key reads false; auto = true or unset; invalid = + # anything else (unparseable value, git failure) — the raw value goes to + # stderr so the caller can name it. Reads only. Ignores GITFLOW_NO_PUSH (a + # test-repo switch, not a mode): a caller that pushes must not rely on this + # verb alone — the lib's own push sites use _gitflow_push_off. + gitflow_push_mode() { + local val rc raw + val=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? + case "$rc:$val" in + 0:false) echo manual ;; + 0:true|1:*) echo auto ;; + *) raw=$(git config gitflow.autopush 2>/dev/null) + if [ -n "$raw" ]; then + echo "gitflow.sh push-mode: gitflow.autopush='$raw' is not a boolean (git rc $rc)" >&2 + else + echo "gitflow.sh push-mode: could not read gitflow.autopush (git rc $rc)" >&2 + fi + echo invalid ;; + esac + return 0 + } + ``` + CLI dispatcher: `push-mode) gitflow_push_mode ;;` after `merged`; add `push-mode` to the usage string. `_gitflow_push_off` UNCHANGED (run D). +- [ ] lib/gitflow-test.sh — NEW block after T11, own repo (hooks on from init, irrelevant: config reads/writes only): `echo "T11b — push-mode verb (the sanctioned reader for skills, BDR-112)"`; `newrepo pm; echo a>a; bash "$HERE/gitflow.sh" init >/dev/null 2>&1`; + `chk "cli push-mode default auto" '[ "$(bash "$HERE/gitflow.sh" push-mode)" = auto ]'`; + `git config gitflow.autopush true` → `chk "cli push-mode true auto" …= auto`; + `git config gitflow.autopush false` → `chk "cli push-mode manual" …= manual`; + `git config gitflow.autopush flase` → `pm_out=$(bash "$HERE/gitflow.sh" push-mode 2>"$WORK/pm.err"); pm_rc=$?` (same line) → `chk "cli push-mode invalid, rc 0, value on stderr" "[ $pm_rc -eq 0 ] && [ \"$pm_out\" = invalid ] && grep -q flase \"$WORK/pm.err\""`; + corrupt config: `printf '[gitflow\n' >> .git/config` → `pm2_out=$(bash "$HERE/gitflow.sh" push-mode 2>/dev/null); pm2_rc=$?` → `chk "cli push-mode corrupt config → invalid, rc 0" "[ $pm2_rc -eq 0 ] && [ \"$pm2_out\" = invalid ]"`; + `chk "cli usage lists push-mode" 'grep -q push-mode <<<"$(bash "$HERE/gitflow.sh" nope 2>&1)"'`. + Variables read in double-quoted assertions (no SC2034 suppression). Config writes live in the test FILE only. +- [ ] skills/capitalize/SKILL.md — STEP 5C (heading UNCHANGED; repo-wide grep shows no citer; the citers census does not cover skill headings). Body rewrite below the three fire-conditions: + "Skip this step entirely (go to STEP 6, which prints the hold note) on `--no-push`, on a WORKING branch, or when STEP 5B returned rc 3. + Otherwise, from the `chore/` branch, THREE separate Bash calls, never combined. INVARIANT: no `git push` inside any Bash call of this skill (push-guard reads command text; the lib pushes develop itself in auto-push mode). The hints that tell the USER what to type (`! git push …`) are prose, kept on single lines. + 1. `bash "$HOME/.claude/lib/gitflow.sh" finish chore ` — merge → develop, delete branch, push develop in auto-push mode. rc≠0 → skip calls 2-3, go to STEP 6 with the `finish failed` line: rc 4 = conflict, develop mid-merge, `chore/` kept, NOT merged; rc 1 = checkout failed, NOT merged; rc 5/2/6 come from the delete AFTER the merge: check `git merge-base --is-ancestor chore/ develop` and report `merged, branch not deleted (rc )` when it holds, `NOT merged` otherwise. Never say "merged" without that check. + 2. `bash "$HOME/.claude/lib/gitflow.sh" push-mode` → `auto | manual | invalid` (stderr names an invalid value). + 3. `git rev-list --count origin/develop..develop 2>/dev/null || echo unknown` → `ahead` (0 = on origin; `unknown` = no origin/develop ref, e.g. no origin remote). + Outcomes, evaluated IN THIS ORDER (all require finish rc 0): + - push mode `invalid` → `merged to develop — gitflow.autopush= is not a boolean: the lib and hooks still push on an invalid value until run D (origin/develop is commit(s) behind, or unknown); fix the value by hand`. + - `ahead` = 0 → `develop pushed` (auto-push mode did it). + - `ahead` = unknown → `merged to develop — not on origin (no origin/develop ref; no remote or never fetched)`; push mode manual → add `You: ! git push origin develop once a remote exists`. + - `ahead` > 0, push mode `manual` → `merged to develop — manual push mode: not pushed. You: ! git push origin develop`. + - `ahead` > 0, push mode `auto` → `merged to develop — push FAILED (see finish stderr); push manually`. Do NOT retry or reset the merge." + Keep the three existing bullets' intent inside the list above (the first qualified as auto-push mode). Recap line ~358 `persisted :` values → `develop pushed | merged, manual push mode: not pushed | merged, not on origin (no origin/develop) | merged, push FAILED | merged, gitflow.autopush invalid ( behind) | finish rc , not merged | merged, branch not deleted (rc ) | on chore/, not merged (--no-push)`. + STEP 6 (lines ~366-368): `` stays the session label (`Context flushed` / `Session closed`); the conditions below say "push mode". On the `--no-push` path (and on any 5B-committed path where 5C did not run) read TWO facts, each its own call: `bash "$HOME/.claude/lib/gitflow.sh" push-mode` and `git rev-list --count origin/chore/..chore/ 2>/dev/null || echo unknown` (`branch_ahead`). Lines (single-line bullets, as the existing ones): + - auto-persisted (ahead 0) — unchanged. + - `--no-push`, `branch_ahead` = 0 → `✅ + committed on chore/ — pushed to origin by the hooks (auto-push mode), NOT merged (--no-push). Merge when ready.` + - `--no-push`, `branch_ahead` > 0 or unknown → `✅ + committed on chore/ — this disk only, not pushed (), NOT merged. You: ! git push -u origin chore/; merge when ready.` With push mode `invalid`, append ` gitflow.autopush= is not a boolean: fix it by hand`. + - manual (merged, `ahead` > 0) → `✅ + merged to develop — manual push mode: not pushed. You: ! git push origin develop`. + - not on origin (merged, `ahead` unknown) → `✅ + merged to develop — not on origin (no origin/develop ref).` + - invalid (merged) → `⚠️ + merged to develop — gitflow.autopush= is not a boolean; lib/hooks still push on it until run D (origin/develop behind). Fix the value by hand.` + - push failed — unchanged. + - finish failed → `⚠️ + finish rc : — chore/ kept, NOT merged (or: merged, branch not deleted); resolve by hand.` + argument-hint (line 13): `pushed to origin by the hooks` → `pushed to origin by the hooks in auto-push mode`. Rules line ~403: append ` — the lib pushes develop in auto-push mode only; manual mode merges and leaves the push to the user`. +- [ ] skills/close/SKILL.md — argument-hint (line 12): same `in auto-push mode` wording; line 31 `STEP 5C auto-persist: finish + push, BDR-068` → `STEP 5C auto-persist: finish (push rides it in auto-push mode), BDR-068`. +- [ ] lib/gitflow-aiguillage.md — lines 40-42: `(finish → develop + push)` → `(finish → develop; the lib pushes develop in auto-push mode only)`. One line. + +## Edge cases +- INVARIANT: no `git push` inside any Bash CALL of capitalize/close (the user-facing `! git push …` hints are prose on single lines) → push-guard never fires on /close. The verifier judges it by reading; a negative grep would itself carry `git push` and be denied in manual mode (LRN-194 b). +- `origin/develop` ref absent (no origin, never fetched) → `unknown` → its own outcome ("not on origin"), never "push FAILED" (in auto mode without origin the lib is silently a no-op, lib/gitflow.sh:90). +- Invalid value: truth comes from `ahead`, not from the mode; wording never says "not pushed" without `ahead` > 0. +- The verb ignores GITFLOW_NO_PUSH by design (documented in its comment); 5C never runs in a test repo; C2 callers that push must gate on the verb AND respect push-guard (they will not contain `git push` text in manual mode anyway). +- Heading kept → no citer risk; BDR-100 census does not apply to skill headings (manual repo-wide grep done: none). + +## Disposition +- honors BDR-068 (auto-persist: merge always, push rides finish in auto mode) and BDR-111/BDR-112 (verb = sanctioned reader; zero `git config` in skills; zero `git push` inside Bash calls). +- honors BDR-095 (truth from the remote state, never from intent: `ahead` count) and LRN-104 (every new output string lives in the skill text; the verb's outputs locked in T11b incl. stderr and rc). +- honors LRN-191 (`grep -q … <<<"$(…)"`), LRN-194 (fixtures in files), LRN-193 (fresh confirmation pass after this revision). diff --git a/.claude/tasks/plans/2026-10-07-manual-push-skills-c2-1325.md b/.claude/tasks/plans/2026-10-07-manual-push-skills-c2-1325.md new file mode 100644 index 0000000..856e976 --- /dev/null +++ b/.claude/tasks/plans/2026-10-07-manual-push-skills-c2-1325.md @@ -0,0 +1,33 @@ +# PLAN — manual-push-skills-c2 — REVISED r2 (3 lenses + correctness confirmation) +Contract: .claude/tasks/contracts/2026-10-07-manual-push-skills-c2-1325.md + +## Context +Same pattern as C1: since BDR-095 the hooks push every commit in auto-push mode, so a skill's own `git push` (and the question that gates it) gates nothing in auto mode, and in manual/invalid mode push-guard denies it. Truth about "on origin" comes from a FACT read after the fact — `git rev-list --count origin/
..
` (0 = on origin; >0 = not; `unknown` = no remote-tracking ref) — never from the mode word (the lib still pushes on an invalid value until run D). The verb `gitflow.sh push-mode` (C1) only WORDS the explanation (manual vs push FAILED) and is read in its own Bash call; no shell variable crosses calls. Where a user must push, the hint is a complete `! git …` command with `-u` and, for multi-repo flows, `-C `. + +## Checklist +- [ ] agents/client-handover-writer.md — define ONE reusable paragraph "PUSH STATE READ" (insert it once, right after the commit-change dispatch in STEP 5, and REFER to it elsewhere): "Three separate Bash calls, never combined, read-only: `git branch --show-current` → `
`; `git remote get-url origin >/dev/null 2>&1 && echo origin || echo no-origin`; `git rev-list --count origin/
..
2>/dev/null || echo unknown` → `ahead`. If `ahead` ≠ 0 and origin exists: `bash "$HOME/.claude/lib/gitflow.sh" push-mode` → anything other than `auto` is treated like `manual` (stderr line kept verbatim when `invalid`). State: `ahead` = 0 → `on origin`; no commits were made this run or the gitflow fallback left changes uncommitted → `nothing to push (no commits this run)` / `uncommitted changes (no gitflow model): publish by hand`; `no-origin` → `not on origin (no origin remote: add one first)`; `ahead` > 0 or `unknown` → `pending — you: ! git push -u origin
` + reason: push mode `manual` → `(manual push mode)`, `auto` → `(not on origin: no remote-tracking ref or the hook push did not land)`, `invalid` → `()`. The pipeline never runs `git push` itself." Then: + STEP 5: replace ONLY lines ~570-578 (from "Then, **before pushing, STOP and ask for an explicit GO**" through the "Only on **A** … then continue." paragraph) with the PUSH STATE READ paragraph followed by: "`pending` → tell the user NOW: `Commits are local only. Push first: ! git push -u origin
`." KEEP the red-flag box (~580-582) and reword it (multi-line old_string, exact current text: `> **Red flag — STOP:** never \`git push\` without option-A GO; never\n> \`gitflow finish\`/\`merge\`. This pipeline commits and (on GO) pushes a working\n> branch — it never integrates into a protected branch.`) → `> **Red flag — STOP:** never \`git push\` (the hooks push in auto-push mode;\n> otherwise the user does); never \`gitflow finish\`/\`merge\`. This pipeline\n> commits a working branch — it never integrates into a protected branch.` Then DELETE lines ~584-598 (the `CURRENT_BRANCH=…/git push origin` bash block and the "If push fails …" AskUserQuestion block). + STEP 6: FIRST line of STEP 6 (before "Skip if PROJECT_TYPE != web"): "Re-run PUSH STATE READ (every path reaches STEP 6, some without STEP 5's read)." Deploy brief (lines ~626-631, multi-line anchors: `"Push has been\n done. The platform deploys automatically — usually 1-3 min. Watch the\n dashboard.`): when the state is `pending` the brief OPENS with `First push: ! git push -u origin
`; the Vercel/Netlify/Cloudflare line reads "The platform deploys automatically after your push (a working branch gives a preview at most; production builds from the production branch) — usually 1-3 min…"; the CI line "Workflow `` runs on your push…"; when `on origin`, keep "Push has been done. …". After option A "Deployed" (~648): "Re-run PUSH STATE READ; still `pending` → ask again (the live site cannot hold these commits)." + Reports: PIPELINE STOPPED template (~795-810) gains a line at column 0 `Push: ` after the Score table; the 9.7 user report gains a bullet `- Push: `; both re-run PUSH STATE READ right before printing (never a STEP 5 snapshot). Line ~65 `3. Commit + push if files changed.` → `3. Commit if files changed (the hooks push in auto-push mode; the push state is read, never assumed).`; lines ~686-687 `(mini-commit\n+ push)` → `(mini-commit; push state read, never assumed)`. +- [ ] skills/client-handover/SKILL.md step 4 — `run /commit-change (atomic logical commits) then \`git push\`.` → `run /commit-change (atomic logical commits); the gitflow hooks push in auto-push mode, otherwise (manual push mode, or a hook push that failed) the agent tells the user to push with \`! git push -u origin \` BEFORE the deploy pause.` +- [ ] skills/release-candidate/SKILL.md STEP 6 — replace the paragraph from "`main` and `develop` are already on origin" through the `hold` line (lines ~96-108) with: + "Read the state, separate Bash calls: `git rev-list --count origin/main..main 2>/dev/null || echo unknown`, `git rev-list --count origin/develop..develop 2>/dev/null || echo unknown`, `bash "$HOME/.claude/lib/gitflow.sh" push-mode`. + - anything other than `auto` from the verb (manual, invalid, empty, usage error) OR either count ≠ 0 or `unknown` → Claude pushes nothing (push-guard would refuse it in manual mode; a failed lib push is the user's call, BDR-095). Print ONE command for the user and STOP, no question: `! git push --atomic origin main develop v` (invalid: quote the verb's stderr line verbatim; auto with a count ≠ 0 or unknown: say `main/develop not on origin (no remote-tracking ref or the lib's push did not land)`; no origin remote (`git remote get-url origin` fails): say `add an origin remote first`). + - push mode `auto` and both counts 0 → main and develop are on origin; only the tag is left. STOP. On explicit go only ([[LRN-069]]) — run the tag push HERE, never delegated: `AskUserQuestion: Push tag v to origin? — go / hold`. Go → ```bash\ngit push origin v\n```. `hold` → stop; the release is on origin (main + develop), the tag stays local until the next push of main (`--follow-tags` on every lib and hook push)." + Overview lines ~27-28 (multi-line anchor `and the two human gates (when to release, and\nthe tag push).`) → append " (auto-push mode; in manual push mode the user pushes main, develop and the tag in one command)". Common-mistakes bullet list: add `- Pushing anything in manual push mode → print the one user command, push nothing.` Frontmatter description ("tag it, and push") and the STEP 6 heading stay (frozen, residuals). +- [ ] agents/release-executor.md — lines ~80-82 (multi-line anchor: `Finish has already pushed \`main\` and\n \`develop\` through the lib's hooks (BDR-095); the tag stays local until\n the dispatcher's tag-push gate.`) → "In auto-push mode finish has already pushed `main` and `develop` through the lib (BDR-095); in manual push mode they stay local. The tag stays local"; lines ~85-86 (anchor `\`main\`/\`develop\` ride the lib's hook\npushes during finish;`) → "`main`/`develop` ride the lib's pushes during finish in auto-push mode". +- [ ] skills/tour/SKILL.md — Rules (lines ~273-275, multi-line anchor: ` The chore branch's own commits are pushed by the gitflow hooks\n (BDR-095); a \`push FAILED\` hook warning is a report residual, fixed\n with a plain \`git push -u origin chore/tour-\`.`) → " The gitflow hooks push the chore branch in auto-push mode only; when it is not on origin (manual push mode, or a `push FAILED` warning) the USER pushes it — `! git -C push -u origin ` — the tour never pushes or retries." STEP 3 per-project closing list (~228-239): add item 5 AFTER the `docs(tour): report` commit (3.3, the last commit): "5. Push state, one read-only call: `git -C rev-list --count --not --remotes 2>/dev/null || echo unknown` (`` = the name `gitflow start` returned, suffixed `-2`/`-3` on a same-day re-run — never the bare `chore/tour-`). 0 → `on origin`; else `local only → ! git -C push -u origin ` (no origin remote → `local only (no origin remote)`)." Summary row format (~258-259): after `, commits` append ` | on origin` or ` | local only → ! git -C push -u origin `. Runner prompt (~92-100) unchanged: the row format carries the field and the runner already returns `BRANCH: `. No verb read in the tour. + +## Edge cases +- `unknown` (never fetched) → "not on origin (no remote-tracking ref)"; no origin remote → "add an origin remote first" (the `! git push … origin …` hint would fail); never "push FAILED". `ahead` = 0 → "on origin" with no claim about WHO pushed (in manual mode it was the user). +- Every `Push:`/deploy-brief statement re-reads the fact right before it prints (a STEP 5 snapshot is stale once the user pushed); STEP 6 reads it first because three paths reach STEP 6 without STEP 5's read (no pending changes; gitflow fallback; `--skip-audits`). +- AC substrings must each sit on ONE physical line (line-based greps); `Push:` at column 0 inside the PIPELINE STOPPED fence; `auto-push mode` on two distinct lines in release-executor.md. +- Invalid value: never "not pushed" from the mode; the counts decide; the verb's stderr is quoted verbatim (it may say "could not read" without a value). +- Release command is `--atomic`: a non-fast-forward on main rejects the whole set, so the tag never lands without its merge. +- client-handover-writer runs INLINE in the main loop (SKILL.md:29-33): the prose reaches the pusher. commit-change and handover-doc-writer never push. +- Tour runners are sub-agents using `git -C `: the fact call uses `-C` too; the user hint carries the path (same branch name across projects). +- Removed gates (client-handover GO question, release "on origin" claim) were gating nothing in auto mode: the hooks had pushed already (same redundancy C1 removed in /close). LRN-069's push gate now means: Claude never pushes in these flows except the release tag on explicit go in auto mode. +- Residual (frozen by AC6): release-candidate frontmatter "tag it, and push", STEP 6 heading "Tag push GATE (ASK)" — true in auto mode; listed in the CHANGELOG at doc-sync. + +## Disposition +- honors BDR-095 (truth from the remote state; a failed push is the user's decision), BDR-111/BDR-112 (verb for wording only, read in its own call; zero `git config` in skills; zero `git push` inside a Bash call reachable in manual mode), BDR-042 (tag + its gate stay in the dispatcher), LRN-069 (explicit go kept for the one push Claude still makes: the tag, auto mode), LRN-193 (fresh confirmation pass after this revision), LRN-104 (every user-facing string is in the skill text; no runtime test exists for prose — AC6 is the reading gate). From e4bc6212efc169ba1ae94ccf735cfd0186b5fdc2 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 14:48:27 +0200 Subject: [PATCH 014/547] =?UTF-8?q?docs(gitflow):=20run=20C=20=E2=80=94=20?= =?UTF-8?q?push-mode=20verb,=20skills=20never=20push;=20CHANGELOG,=20SETTI?= =?UTF-8?q?NGS,=20gitflow=20skill,=20README,=20USAGE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 6 +++++- README.md | 2 +- USAGE.md | 2 +- skills/gitflow/SKILL.md | 1 + templates/settings/SETTINGS.md | 12 +++++++++--- 5 files changed, 17 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 545d3f0..6ad6729 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,15 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project ## [Unreleased] ### Added -- **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
` 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 `gitflow.autopush` value is named and treated as auto. `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 fails closed: for this hook a non-boolean value reads as manual, and a git failure while reading the key, an internal error or more than 20 distinct directory tokens in one command refuse the push (these pathological cases fire in auto mode too). In manual mode it over-blocks any command where a `push` word follows a `git` token; 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. Skills that push on their own do not honour the mode yet. Tests: `lib/gitflow-test.sh` T18m block, `lib/tests/unpushed-guard.test.sh` T10-T16, `lib/tests/push-guard.test.sh` (71 checks). +- **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
` 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 `gitflow.autopush` value is named and treated as auto. `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 fails closed: for this hook a non-boolean value reads as manual, and a git failure while reading the key, an internal error or more than 20 distinct directory tokens in one command refuse the push (these pathological cases fire in auto mode too). In manual mode it over-blocks any command where a `push` word follows a `git` token; 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. 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/
..
` read after the fact, with the complete `! git …` command when something is left for the user to push. An invalid value is named, but the lib and the git hooks still push on it as auto. Tests: `lib/gitflow-test.sh` T11b (push-mode verb) and T18m block, `lib/tests/unpushed-guard.test.sh` T10-T16, `lib/tests/push-guard.test.sh` (71 checks). ### Changed - `settings.json` denies every write form of the human-only `gitflow.*` keys (18 entries): any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, and Edit/Write of `.git/config`, `.gitconfig` and `~/.config/git/config`. Side effect: Claude can no longer read `gitflow.autopush` through `git config` either; hooks and `lib/gitflow.sh` still read it. The `hard_deny` rule on routing around a guardrail now names PreToolUse hook refusals. - `gitflow start` and `finish` warn on stderr when a base is behind origin and cannot fast-forward, instead of a silent `git pull --ff-only || true` (T18l, T18n). +- `/close` (`/capitalize` STEP 5C) no longer runs its own push of develop: `gitflow finish` already pushes develop in auto-push mode (BDR-095). The closing line reports the real state, read after the merge: pushed, manual push mode with the `! git push origin develop` to run, not on origin, push failed, or an invalid `gitflow.autopush` value named. A finish whose merge landed but whose branch delete failed (rc 5/2/6) still reports the push state. +- `/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 ` 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`. 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. +- `/tour`: each summary row says `on origin` or `local only` with the `! git -C push -u origin ` to run. The tour never pushes or retries. ### Fixed - `gitflow delete` (and `finish`) land on the base that contains the branch and drop the branch's upstream before `git branch -d`, so a branch whose upstream lags (manual-push mode) is deleted instead of refused by git (T18k). diff --git a/README.md b/README.md index d37796f..1c47c19 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ a different package, ships its own conflicting `graphify` bin) — see | `/impeccable` | Design verbs (audit, polish, bolder…) + deterministic anti-slop detector (`npx impeccable detect`) | | `/commit-change` | Smart commit grouping from staged/unstaged changes | | `/gitflow` | Gitflow branch operations — bootstrap main+develop, start a typed branch, directed merge | -| `/release-candidate` | Cut a versioned release — finalize version.txt + CHANGELOG, merge develop→main, tag, push | +| `/release-candidate` | Cut a versioned release — finalize version.txt + CHANGELOG, merge develop→main, tag, push (auto-push mode, tag on your go; manual push mode: one `! git push --atomic` command you run) | | `/deploy` | Compose the deploy checklist from a project's committed runbook (delta only); you run it, the skill resumes cold on your report | | `/graphify` | Codebase knowledge graph — navigation for large-scope tasks | | `/plugin-check` | Check active plugins vs project needs — recommend enable/disable | diff --git a/USAGE.md b/USAGE.md index b6ae6ad..24a2c54 100644 --- a/USAGE.md +++ b/USAGE.md @@ -146,7 +146,7 @@ Tu veux... | `/geo` | Audit GEO uniquement (IA) | Visibilité ChatGPT, Perplexity, Claude, Gemini… | | `/commit-change` | Commits bien structurés | Groupe les changements par unité logique | | `/gitflow` | Opérations de branches gitflow | Bootstrap main+develop, branche typée, merge dirigé | -| `/release-candidate` | Couper une release versionnée (develop en avance sur main) | Finalise version.txt + CHANGELOG, merge develop→main, tag, push | +| `/release-candidate` | Couper une release versionnée (develop en avance sur main) | Finalise version.txt + CHANGELOG, merge develop→main, tag, push (mode auto-push, tag sur ton feu vert ; mode push manuel : une commande `! git push --atomic` que tu lances) | | `/deploy` | Déployer via le runbook du projet | Instancie le delta depuis le dernier deploy, reprend à froid ; tu exécutes la checklist, Claude ne déploie jamais | | `/graphify` | Navigation codebase large-scope | Knowledge graph, pour tâches multi-fichiers | | `/skills-perso` | Lister ses skills personnels | Skills créés dans ~/.claude/skills/ | diff --git a/skills/gitflow/SKILL.md b/skills/gitflow/SKILL.md index caee674..b401393 100644 --- a/skills/gitflow/SKILL.md +++ b/skills/gitflow/SKILL.md @@ -40,6 +40,7 @@ bash ~/.claude/lib/gitflow.sh start # branch from the correct base bash ~/.claude/lib/gitflow.sh finish # directed merge of the CURRENT branch — HUMAN-GATED (below) bash ~/.claude/lib/gitflow.sh delete # delete a merged branch, local + origin copy — refuses main/develop + anything unmerged bash ~/.claude/lib/gitflow.sh protected-base [br] # rc 0 on main/develop — the shared predicate +bash ~/.claude/lib/gitflow.sh push-mode # auto | manual | invalid on stdout, rc 0: the only way a skill reads gitflow.autopush; pushes nothing ``` `finish` merges by the current branch's type: diff --git a/templates/settings/SETTINGS.md b/templates/settings/SETTINGS.md index bda6696..0066799 100644 --- a/templates/settings/SETTINGS.md +++ b/templates/settings/SETTINGS.md @@ -145,7 +145,7 @@ local trace, and the brief had authorized it. What holds now, by tier: | `chmod`/`chown -R`, `sudo`/`doas`/`pkexec`, disk tools (`dd`, `mkfs`, `shred`…), `chattr` | `permissions.deny` | The user runs them by hand. | | Docker volume drops, `system prune`, `compose down -v`, `--privileged`, the docker socket, `-v /:` | `permissions.deny` | Promoted from `soft_deny`: no in-session clearance for data drops. | | Git history destruction (`push --delete`/`--mirror`/`:ref`/`--force-with-lease`, `branch -D`, `filter-branch`, `reflog expire`, `stash clear`/`drop`, `clean -f`), `--no-verify`, `core.hooksPath` | `permissions.deny` | A remote is the backup; nothing rewrites or deletes what it holds. | -| Writing the human-only `gitflow.*` toggles: any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, Edit/Write of git config files | `permissions.deny` | Claude never flips the mode that binds it. Side effect: the trailing glob also matches the bare read, so Claude cannot read `gitflow.autopush` through `git config`; hooks and `lib/gitflow.sh` still do. | +| Writing the human-only `gitflow.*` toggles: any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, Edit/Write of git config files | `permissions.deny` | Claude never flips the mode that binds it. Side effect: the trailing glob also matches the bare read, so Claude cannot read `gitflow.autopush` through `git config`; hooks and `lib/gitflow.sh` still do, and skills read it through `gitflow.sh push-mode`. | | Pushing in manual-push mode (`gitflow.autopush false`) | `hooks/push-guard.sh` (PreToolUse) + `autoMode.soft_deny` | `ask` is inert under auto mode. The hook denies the direct forms; the soft_deny covers scripted, aliased, subshell and sub-agent pushes, and a request in the turn does not clear it: the user types `! git push`. | | Destructive tool against a local path (variable, `~`, `..`, wildcard, outside cwd/tmp), even as a trace or a rehearsal a brief allows | `autoMode.hard_deny` | A pattern cannot express "the target resolves outside the project"; the classifier can. A sub-agent brief carries no user authority. | | `docker rm -f`, bind mount outside cwd; discarding uncommitted work | `autoMode.soft_deny` | Recoverable or user-intended in the turn. | @@ -191,8 +191,14 @@ reading the key or more than 20 directory tokens in one command refuses the push, in auto mode too. In manual mode it over-blocks any command where a `push` word follows a `git` token (`git stash push`, a grep for "git push"). The misses listed in its header fall to an `autoMode.soft_deny` rule that no -request in the turn clears. Skills that push on their own are not adapted -yet. +request in the turn clears. Skills read the mode through +`bash ~/.claude/lib/gitflow.sh push-mode` (`auto`, `manual` or `invalid`, +rc 0) and push nothing themselves, except the `/release-candidate` tag in +auto-push mode on an explicit go. What they report as on origin or not +pushed comes from `git rev-list --count origin/
..
` read afterwards, +and a pending push is handed to the user as a complete `! git …` command. +An invalid value is named, but the lib and the git hooks still push on it +as auto; only push-guard fails closed on it. ## managed-settings.json (enterprise) From 472cccbc52b2fa46cb3419b6f488678e00cfd5ec Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 16:45:31 +0200 Subject: [PATCH 015/547] fix(gitflow): every autopush reader fails closed and names an invalid value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run D1 of manual-push mode (BDR-114). `git config --bool --default true gitflow.autopush` only covered a MISSING key: an unparseable value made git die with empty output, the `= false` test failed, and every push ran again. A typo on a work machine silently re-enabled the pushes it was meant to stop. - lib/gitflow.sh: `_gitflow_push_off` reads the mode through the lib verb (`push-mode`); anything but `auto` is push-off, and the verb's stderr line names an invalid value during start/finish. - Emitted post-commit/post-merge hooks (POSIX sh, standalone): push only when the key reads `true` or is unset; `false` exits quietly; any other result prints one stderr line ("NOT pushed, treated as manual push mode") and exits 0. Mirrors gitflow_push_mode. - .githooks/ and githooks/ regenerated files-only through `emit-hook` (no config read or write; .git/config hash unchanged). - hooks/unpushed-guard.sh: mode from the lib verb (absolute lib path resolved before any cd, no temp file); anything but auto is manual; the SessionStart line names an invalid or unreadable value. - Tests: gitflow-test T18q block (invalid → start, hook and finish push nothing and say so; `true` → the hook pushes; emitted hook is POSIX-clean), unpushed-guard T14 rewritten. --- .githooks/post-commit | 11 +++++++++-- .githooks/post-merge | 11 +++++++++-- githooks/post-commit | 11 +++++++++-- githooks/post-merge | 11 +++++++++-- hooks/unpushed-guard.sh | 22 +++++++++++++++------- lib/gitflow-test.sh | 24 ++++++++++++++++++++++++ lib/gitflow.sh | 28 +++++++++++++++++++--------- lib/tests/unpushed-guard.test.sh | 6 ++++-- 8 files changed, 98 insertions(+), 26 deletions(-) diff --git a/.githooks/post-commit b/.githooks/post-commit index 417fecf..08d9954 100755 --- a/.githooks/post-commit +++ b/.githooks/post-commit @@ -5,8 +5,15 @@ hook=post-commit # holds. Never fails the commit: no origin / offline / refused → warning only. # Opt out for one command with GITFLOW_NO_PUSH=1 (throwaway repos, tests). [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && exit 0 -# Per-repo opt-out (no push rights on a foreign clone): git config gitflow.autopush false -[ "$(git config --bool --default true gitflow.autopush)" = false ] && exit 0 +# Manual-push mode (human-set): git config gitflow.autopush false. Fail closed: +# an unparseable value or a config read failure also means "no push", named. +# Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4. +v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? +case "$rc:$v" in + 0:true|1:*) ;; + 0:false) exit 0 ;; + *) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;; +esac git remote get-url origin >/dev/null 2>&1 || exit 0 br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 # detached HEAD — nothing to track if command -v timeout >/dev/null 2>&1; then t="timeout ${GITFLOW_PUSH_TIMEOUT:-30}"; else t=""; fi diff --git a/.githooks/post-merge b/.githooks/post-merge index 69a9f65..853eda0 100755 --- a/.githooks/post-merge +++ b/.githooks/post-merge @@ -5,8 +5,15 @@ hook=post-merge # holds. Never fails the commit: no origin / offline / refused → warning only. # Opt out for one command with GITFLOW_NO_PUSH=1 (throwaway repos, tests). [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && exit 0 -# Per-repo opt-out (no push rights on a foreign clone): git config gitflow.autopush false -[ "$(git config --bool --default true gitflow.autopush)" = false ] && exit 0 +# Manual-push mode (human-set): git config gitflow.autopush false. Fail closed: +# an unparseable value or a config read failure also means "no push", named. +# Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4. +v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? +case "$rc:$v" in + 0:true|1:*) ;; + 0:false) exit 0 ;; + *) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;; +esac git remote get-url origin >/dev/null 2>&1 || exit 0 br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 # detached HEAD — nothing to track if command -v timeout >/dev/null 2>&1; then t="timeout ${GITFLOW_PUSH_TIMEOUT:-30}"; else t=""; fi diff --git a/githooks/post-commit b/githooks/post-commit index 417fecf..08d9954 100755 --- a/githooks/post-commit +++ b/githooks/post-commit @@ -5,8 +5,15 @@ hook=post-commit # holds. Never fails the commit: no origin / offline / refused → warning only. # Opt out for one command with GITFLOW_NO_PUSH=1 (throwaway repos, tests). [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && exit 0 -# Per-repo opt-out (no push rights on a foreign clone): git config gitflow.autopush false -[ "$(git config --bool --default true gitflow.autopush)" = false ] && exit 0 +# Manual-push mode (human-set): git config gitflow.autopush false. Fail closed: +# an unparseable value or a config read failure also means "no push", named. +# Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4. +v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? +case "$rc:$v" in + 0:true|1:*) ;; + 0:false) exit 0 ;; + *) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;; +esac git remote get-url origin >/dev/null 2>&1 || exit 0 br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 # detached HEAD — nothing to track if command -v timeout >/dev/null 2>&1; then t="timeout ${GITFLOW_PUSH_TIMEOUT:-30}"; else t=""; fi diff --git a/githooks/post-merge b/githooks/post-merge index 69a9f65..853eda0 100755 --- a/githooks/post-merge +++ b/githooks/post-merge @@ -5,8 +5,15 @@ hook=post-merge # holds. Never fails the commit: no origin / offline / refused → warning only. # Opt out for one command with GITFLOW_NO_PUSH=1 (throwaway repos, tests). [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && exit 0 -# Per-repo opt-out (no push rights on a foreign clone): git config gitflow.autopush false -[ "$(git config --bool --default true gitflow.autopush)" = false ] && exit 0 +# Manual-push mode (human-set): git config gitflow.autopush false. Fail closed: +# an unparseable value or a config read failure also means "no push", named. +# Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4. +v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? +case "$rc:$v" in + 0:true|1:*) ;; + 0:false) exit 0 ;; + *) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;; +esac git remote get-url origin >/dev/null 2>&1 || exit 0 br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 # detached HEAD — nothing to track if command -v timeout >/dev/null 2>&1; then t="timeout ${GITFLOW_PUSH_TIMEOUT:-30}"; else t=""; fi diff --git a/hooks/unpushed-guard.sh b/hooks/unpushed-guard.sh index 1c464c2..5a83e5b 100755 --- a/hooks/unpushed-guard.sh +++ b/hooks/unpushed-guard.sh @@ -12,9 +12,13 @@ # # Manual-push mode (git config gitflow.autopush false, human-set): unpushed # work is expected, so Stop stays silent; SessionStart gives one info line -# counting every local branch, with the branches to push by hand. +# counting every local branch, with the branches to push by hand. An +# unparseable value is treated as manual too (fail closed, BDR-114); the mode +# comes from the lib verb, the one reader the hooks share. set -u +# Resolved before any cd: the hook may be invoked by a relative path. +_lib="$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" 2>/dev/null && pwd)/gitflow.sh" payload=$(cat 2>/dev/null) field() { printf '%s' "$payload" | jq -r "$1 // empty" 2>/dev/null; } event=$(field '.hook_event_name') @@ -23,10 +27,10 @@ cd "$cwd" 2>/dev/null || exit 0 git rev-parse --is-inside-work-tree >/dev/null 2>&1 || exit 0 br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 -raw=$(git config gitflow.autopush 2>/dev/null) -manual=0; invalid=0 -[ "$(git config --bool --default true gitflow.autopush 2>/dev/null)" = false ] && manual=1 -[ -n "$raw" ] && ! git config --bool gitflow.autopush >/dev/null 2>&1 && invalid=1 +# The verb writes its stderr line BEFORE its stdout word: the last line is the mode. +out=$(bash "$_lib" push-mode 2>&1); mode=${out##*$'\n'} +mode_err=${out%"$mode"}; mode_err=${mode_err%$'\n'} +manual=0; [ "$mode" = auto ] || manual=1 # fail closed: anything but auto [ "$manual" = 1 ] && [ "$event" != SessionStart ] && exit 0 # BDR-087: info at start only # Local branches holding commits no remote has, one per line. @@ -73,8 +77,12 @@ if [ "$event" = "SessionStart" ]; then dirty=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ') [ "$dirty" -gt 0 ] && msg="${msg:+$msg; }$dirty uncommitted change(s) in $cwd" fi -if [ "$invalid" = 1 ] && [ "$event" = "SessionStart" ]; then - msg="${msg:+$msg; }gitflow.autopush='$raw' is not a boolean, treated as auto (pushes run)" +if [ "$event" = "SessionStart" ]; then + case "$mode" in + invalid) msg="${msg:+$msg; }${mode_err#gitflow.sh push-mode: } — treated as manual push mode (nothing pushes); fix the value by hand" ;; + manual|auto) ;; + *) msg="${msg:+$msg; }push mode unreadable (lib verb printed '${mode:-nothing}') — treated as manual push mode" ;; + esac fi [ -n "$msg" ] || exit 0 diff --git a/lib/gitflow-test.sh b/lib/gitflow-test.sh index c6bdd67..fa2c3fd 100644 --- a/lib/gitflow-test.sh +++ b/lib/gitflow-test.sh @@ -406,6 +406,30 @@ div_err="$WORK/div.err" div_out=$(gitflow_start feature div 2>"$div_err") chk "T18l diverged base → warns on stderr, stdout stays the branch name" "[ \"$div_out\" = feature/div ] && grep -q 'behind origin/develop' \"$div_err\" && git rev-parse --verify -q refs/heads/feature/div >/dev/null" +echo "T18q — fail closed: unparseable gitflow.autopush → nothing pushes, named (BDR-114)" +newrepo badval; echo a>a; hookon; gitflow_init >/dev/null 2>&1 +bare="$WORK/badval.git"; git init -q --bare "$bare"; git remote add origin "$bare" +git push -q -u origin main develop 2>/dev/null +git config gitflow.autopush flase +gitflow_start feature bad >/dev/null 2>"$WORK/q1.err" +chk "T18q1 start → branch local, not on origin, value named" "git rev-parse --verify -q refs/heads/feature/bad >/dev/null && ! git ls-remote --exit-code --heads origin feature/bad >/dev/null 2>&1 && grep -q 'not a boolean' \"$WORK/q1.err\"" +echo b>b.txt; git add b.txt; git commit -q -m b 2>"$WORK/q2.err" +chk "T18q2 commit → not pushed, hook says NOT pushed" "! git ls-remote --exit-code --heads origin feature/bad >/dev/null 2>&1 && grep -q 'NOT pushed' \"$WORK/q2.err\"" +dev_before=$(git -C "$bare" rev-parse develop) +gitflow_finish >/dev/null 2>&1; q_rc=$? +chk "T18q3 finish → merged locally, origin develop unchanged" "[ $q_rc -eq 0 ] && [ \"\$(git -C \"$bare\" rev-parse develop)\" = \"$dev_before\" ] && ! git rev-parse --verify -q refs/heads/feature/bad >/dev/null" +git config gitflow.autopush true +gitflow_start feature good >/dev/null 2>&1 +echo g>g.txt; git add g.txt; git commit -q -m g 2>/dev/null +chk "T18q4 true → post-commit pushed (tips equal)" '[ "$(git rev-parse HEAD)" = "$(git -C "$bare" rev-parse feature/good)" ]' +_gitflow_emit_push_hook post-commit > "$WORK/pc.sh" +chk "T18q5a emitted hook carries the rc:value case" "[ -s \"$WORK/pc.sh\" ] && grep -qF 'case \"\$rc:\$v\"' \"$WORK/pc.sh\"" +if command -v shellcheck >/dev/null 2>&1; then + chk "T18q5 emitted hook is POSIX-clean" "shellcheck -s sh \"$WORK/pc.sh\"" +else + ok "T18q5 skipped (no shellcheck)" +fi + echo "T19 — installed hooks == emitted hooks in the config repo (LRN-114 drift gate)" if [ -d "$HERE/../.githooks" ]; then chk "T19a pre-commit installed == emitted" 'diff -q <(_gitflow_emit_pre_commit) "$HERE/../.githooks/pre-commit" >/dev/null' diff --git a/lib/gitflow.sh b/lib/gitflow.sh index db008b6..9cabaa8 100644 --- a/lib/gitflow.sh +++ b/lib/gitflow.sh @@ -97,12 +97,14 @@ gitflow_push_mode() { # ── start ──────────────────────────────────────────────────────────────────── -# rc 0 when pushing is off: GITFLOW_NO_PUSH=1 (throwaway test repos) or -# gitflow.autopush=false (manual-push mode, human-set: work machine, foreign -# clone). The single reader of both flags for the lib's own push sites. +# rc 0 when pushing is off: GITFLOW_NO_PUSH=1 (throwaway test repos), or +# gitflow.autopush not readable as `true`/unset — manual-push mode (false, +# human-set) AND fail closed on an unparseable value or a config read +# failure (BDR-114). The verb's stderr passes through: it names an invalid +# value and is silent for auto/manual. Single reader for the lib's push sites. _gitflow_push_off() { [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && return 0 - [ "$(git config --bool --default true gitflow.autopush)" = false ] + [ "$(gitflow_push_mode)" != auto ] } # gitflow_start → checkout -b / from the correct base. @@ -192,8 +194,9 @@ gitflow_merged_into_base() { return 1 } -# _gitflow_note_remote_left
→ manual mode never deletes origin/
; say -# so when a remote-tracking ref shows a copy exists (no network call). +# _gitflow_note_remote_left
→ push off (manual mode or invalid value) never +# deletes origin/
; say so when a remote-tracking ref shows a copy exists +# (no network call). _gitflow_note_remote_left() { local br="$1" gitflow_protected_base "$br" && return 0 @@ -203,7 +206,7 @@ _gitflow_note_remote_left() { # _gitflow_delete_remote
→ remove origin/
once the LOCAL copy is gone. # Same contract as the pushes (BDR-095): best effort, warn never fail; skipped -# under GITFLOW_NO_PUSH=1, gitflow.autopush=false or no origin. The REMOTE tip +# when push is off (see _gitflow_push_off) or no origin. The REMOTE tip # is re-checked against develop/main before the delete: a commit pushed from # elsewhere that never reached a base (or that this clone has never fetched) # keeps the remote branch alive, loudly. Never a base, by construction and by @@ -507,8 +510,15 @@ cat <<'HOOK' # holds. Never fails the commit: no origin / offline / refused → warning only. # Opt out for one command with GITFLOW_NO_PUSH=1 (throwaway repos, tests). [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && exit 0 -# Per-repo opt-out (no push rights on a foreign clone): git config gitflow.autopush false -[ "$(git config --bool --default true gitflow.autopush)" = false ] && exit 0 +# Manual-push mode (human-set): git config gitflow.autopush false. Fail closed: +# an unparseable value or a config read failure also means "no push", named. +# Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4. +v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? +case "$rc:$v" in + 0:true|1:*) ;; + 0:false) exit 0 ;; + *) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;; +esac git remote get-url origin >/dev/null 2>&1 || exit 0 br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 # detached HEAD — nothing to track if command -v timeout >/dev/null 2>&1; then t="timeout ${GITFLOW_PUSH_TIMEOUT:-30}"; else t=""; fi diff --git a/lib/tests/unpushed-guard.test.sh b/lib/tests/unpushed-guard.test.sh index 6b4c9c0..d5a60d5 100755 --- a/lib/tests/unpushed-guard.test.sh +++ b/lib/tests/unpushed-guard.test.sh @@ -66,8 +66,10 @@ git config gitflow.autopush flase echo i>i; git add i; git commit -q -m i out=$(fire SessionStart "$PWD") check T14-invalid-named "$(has "$out" "not a boolean")" yes -check T14-invalid-treated-auto "$(has "$out" "unpushed work")" yes -check T14-invalid-stop-auto "$(has "$(fire Stop "$PWD")" "1 commit(s)")" yes +check T14-invalid-prefix "$(has "$out" "ℹ manual push mode:")" yes +check T14-invalid-treated "$(has "$out" "treated as manual")" yes +check T14-invalid-no-warn "$(has "$out" "unpushed work")" no +check T14-invalid-stop-silent "$(fire Stop "$PWD")" silent git config --unset gitflow.autopush check T15-unset-auto-intact "$(has "$(fire Stop "$PWD")" "1 commit(s)")" yes git config gitflow.autopush false; git remote remove origin From 3c59333fcf6b4cc86c8d8f3840d3c7bdf29de6ba Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 17:11:56 +0200 Subject: [PATCH 016/547] fix(push-guard): single reader, whole-word dir tokens, payload fallback, bad-value banner Run D2 of manual-push mode (BDR-114). - push-guard sources lib/gitflow.sh once (absolute path) and reads each candidate dir through gitflow_push_mode; a missing lib denies. - Dir tokens are extracted as whole shell words: a fully quoted token (inner apostrophe allowed) is resolved, a backslash-escaped space is unescaped deterministically, a token mixing quoted and unquoted parts is refused (fail closed) instead of resolving to its parent. - A payload jq cannot parse is scanned as raw text with its JSON escapes folded; a push-looking one gets the static deny through the trap. - The 20-token cap runs before any per-token classification (a flood of 20 000 tokens is refused in 0.13 s; T58 locks it under 5 s). - `case "$mode"` has a deny default; missing core tools warn and allow. - T42 compares the deny list against main (the last release) instead of HEAD; literal-true, mixed-token, broken-payload, lib-missing and banner-on-bad-value cases added (98 checks). - session-start banner reads the mode through the verb and shows `push : manual (autopush bad)` on an unparseable value. - tour hints quote "". --- hooks/push-guard.sh | 107 +++++++++++++++++++++++++++-------- hooks/session-start.sh | 10 ++-- lib/tests/push-guard.test.sh | 101 +++++++++++++++++++++++++++++++-- skills/tour/SKILL.md | 8 +-- 4 files changed, 187 insertions(+), 39 deletions(-) diff --git a/hooks/push-guard.sh b/hooks/push-guard.sh index 12f96ed..0b92954 100644 --- a/hooks/push-guard.sh +++ b/hooks/push-guard.sh @@ -2,14 +2,22 @@ # push-guard.sh — PreToolUse (Bash|Monitor): refuse `git push` in manual # push mode (BDR-111). Manual mode = `gitflow.autopush` reads false (or is # unparseable or unreadable: fail closed) in the payload cwd or in any literal -C / cd dir -# the command names; outside a repo `git config` reads global/system. +# the command names; outside a repo `git config` reads global/system. The +# mode is read by the sourced lib verb gitflow_push_mode (single reader). # # Deny form: JSON on stdout, exit 0 (hookSpecificOutput.permissionDecision # = "deny"). Silent in auto mode and on every non-push command. The guard # sees the command TEXT only. Once a push is detected an EXIT trap emits a # static deny (exit 0) unless a decision was recorded: internal error = -# push refused. jq missing: one stderr warning, allow (sibling hooks). +# push refused. jq, cat, grep, sed, sort or head missing: one stderr +# warning, allow (sibling hooks; PATH is not command-controlled). # +# DENIED beyond a manual-mode push: a cd/-C dir token mixing quoted and +# unquoted parts ("/m"/x"/y", a/'../b'); a cd argument touching a closing +# quote followed by another quote on the line (bash -c 'cd /x' && bash -c +# 'git push' reads as one mixed token, accepted, fail closed); a payload jq +# cannot parse whose raw text (JSON escapes folded) looks like a push: static +# deny, mode-blind, so a description naming a push also denies there. # OVER-BLOCKS in manual mode: any text carrying a later ` push` word after # a `git` token (git subtree push, git stash push, git log -S "git push", # grep -rn "git push" skills/, git config --get push.default, git add @@ -24,14 +32,29 @@ set -u unset CDPATH +# Absolute lib path, before anything else; sourced once (functions only). +_src=${BASH_SOURCE[0]} +case "$_src" in */*) _dir=${_src%/*} ;; *) _dir=. ;; esac +LIB="$(cd -P "$_dir/../lib" 2>/dev/null && pwd)/gitflow.sh" +# shellcheck source=/dev/null +if [ -r "$LIB" ]; then . "$LIB"; LIB_OK=1; else LIB_OK=0; fi + if ! command -v jq >/dev/null 2>&1; then echo "push-guard: jq missing, guard inactive" >&2 exit 0 fi +for t in cat grep sed sort head; do + command -v "$t" >/dev/null 2>&1 || { + echo "push-guard: $t missing, guard inactive" >&2 + exit 0 + } +done payload=$(cat 2>/dev/null) field() { printf '%s' "$payload" | jq -r "$1 // empty" 2>/dev/null; } -cmd=$(field '.tool_input.command') +# jq's rc is field's rc: a payload that does not parse becomes the text to scan. +unparsed=0 +cmd=$(field '.tool_input.command') || { cmd=$payload; unparsed=1; } cwd=$(field '.cwd') [ -n "$cmd" ] || exit 0 [ -d "$cwd" ] || cwd=$PWD @@ -39,7 +62,12 @@ cwd=$(field '.cwd') # Fold line breaks (backslash-newline first), then drop quoted spans. one=${cmd//$'\\\n'/ } one=${one//$'\n'/ } +if [ "$unparsed" = 1 ]; then + one=${one//\\n/ }; one=${one//\\r/ }; one=${one//\\t/ }; one=${one//\\\\/ } +fi bare=$(printf '%s' "$one" | sed -E "s/\"[^\"]*\"//g; s/'[^']*'//g") +# JSON quotes are syntax, not shell quoting: keep them for the loose regexes. +[ "$unparsed" = 1 ] && bare=$one # is_push: strict (full text), loose (quotes removed), alias definition. is_push() { @@ -60,22 +88,35 @@ static_deny() { } decided=0 trap '[ "$decided" = 1 ] || static_deny; exit 0' EXIT +# Unparseable payload that looks like a push: the trap answers (mode-blind). +[ "$unparsed" = 1 ] && exit 0 -# unquote : strip one pair of surrounding quotes. -unquote() { - local t=$1 +# classify_tok : prints the literal dir of a raw dir token, rc 1 when it +# mixes quoted and unquoted parts. A token enclosed in one quote pair is +# stripped (the other quote kind inside is fine); backslashes of an unquoted +# token are unescaped (a\ b -> a b), deterministic, never eval'd. +classify_tok() { + local t=$1 q= case "$t" in - \"*\") t=${t#\"}; t=${t%\"} ;; - \'*\') t=${t#\'}; t=${t%\'} ;; + \"*\") q='"' ;; + \'*\') q="'" ;; esac - printf '%s' "$t" + if [ -n "$q" ]; then + t=${t#"$q"}; t=${t%"$q"} + case "$t" in *"$q"*) return 1 ;; esac + printf '%s' "$t" + return 0 + fi + case "$t" in *\"*|*\'*) return 1 ;; esac + printf '%s' "$t" | sed -E 's/\\(.)/\1/g' } -# arg_tokens: the directory argument of every `cd`/`pushd`/`-C` in the text. +# arg_tokens: the directory argument of every `cd`/`pushd`/`-C` in the text, +# one shell word each (adjacent quoted and unquoted segments, \x escapes). # A quote or backtick may precede the command word (bash -c 'cd d && ...'). arg_tokens() { local pre='[[:space:];&|()"'"'"'`]' - local arg='(--[[:space:]]+)?("[^"]*"|'"'[^']*'"'|[^[:space:];&|()"'"'"'`]+)' + local arg='(--[[:space:]]+)?((\\.|"[^"]*"|'"'[^']*'"'|[^[:space:];&|()"'"'"'`\\]+)+)' { printf '%s' "$one" | grep -oE "(^|$pre)(cd|pushd)[[:space:]]+$arg" printf '%s' "$one" | grep -oE "(^|$pre)-C[[:space:]]+$arg" @@ -94,30 +135,30 @@ resolve_dir() { ) } -# candidates: cwd, then each distinct literal dir of $tokens, deduplicated +# candidates: cwd, then each distinct literal dir of $literals, deduplicated # after resolution (unresolvable ones are skipped, never an allow). candidates() { local tok printf '%s\n' "$cwd" - printf '%s\n' "$tokens" | while IFS= read -r tok; do - tok=$(unquote "$tok") + printf '%s\n' "$literals" | while IFS= read -r tok; do case "$tok" in ''|-) continue ;; esac resolve_dir "$tok" done | sort -u } # mode_in : prints `manual`, `auto` (key unset or true), -# `invalid:` (not a boolean) or `failed:` (git or cd failed). +# `invalid:` (not a boolean, unreadable) or `failed:`. mode_in() { ( cd -- "$1" 2>/dev/null || { echo "failed:cannot enter the directory"; exit 0; } - val=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? - case "$rc" in - 0) if [ "$val" = false ]; then echo manual; else echo auto; fi ;; - 1) echo auto ;; - *) raw=$(git config gitflow.autopush 2>/dev/null) - if [ -n "$raw" ]; then echo "invalid:$raw" - else echo "failed:git exited $rc"; fi ;; + [ "$LIB_OK" = 1 ] || { echo "failed:gitflow lib missing"; exit 0; } + out=$(gitflow_push_mode 2>&1); m=${out##*$'\n'} + why=$(printf '%s\n' "$out" | grep -m1 '^gitflow.sh push-mode: ' \ + | sed 's/^gitflow.sh push-mode: //') + case "$m" in + manual|auto) echo "$m" ;; + invalid) echo "invalid:${why:-unreadable}" ;; + *) echo "$m" ;; esac ) } @@ -131,12 +172,26 @@ deny() { exit 0 } -# Cap the distinct dir tokens before resolving any (hook timeout is 10 s). +# literal_dirs: fills $literals from $tokens; a mixed token denies, naming +# it. Runs in the main shell (deny must end the hook, not a subshell). +literal_dirs() { + local raw lit + literals="" + while IFS= read -r raw; do + [ -n "$raw" ] || continue + lit=$(classify_tok "$raw") || deny "push-guard: directory token $raw mixes quoted and unquoted parts — this guard refuses to interpolate it (fail closed). Quote the whole path, or run it yourself: ! $cmd" + literals="$literals$lit"$'\n' + done <<<"$tokens" +} + +# Cap the distinct dir tokens before resolving or classifying any (hook +# timeout is 10 s). tokens=$(arg_tokens | sort -u) ntok=$(printf '%s\n' "$tokens" | grep -c .) if [ "$ntok" -gt 20 ]; then deny "push-guard: too many directory tokens in one command ($ntok > 20) — push refused (fail closed). Split the command, or run it yourself: ! $cmd" fi +literal_dirs evaluated=0 while IFS= read -r dir; do @@ -145,10 +200,12 @@ while IFS= read -r dir; do manual) deny "push-guard: manual push mode (gitflow.autopush=false in $dir) — Claude never pushes. Run it yourself in the terminal: ! $cmd" ;; invalid:*) - deny "push-guard: gitflow.autopush='${mode#invalid:}' is not a boolean in $dir — treated as manual push mode (fail closed). Fix the value by hand, or run it yourself: ! $cmd" ;; + deny "push-guard: ${mode#invalid:} in $dir — treated as manual push mode (fail closed). Fix the value by hand, or run it yourself: ! $cmd" ;; failed:*) - deny "push-guard: could not read gitflow.autopush in $dir (${mode#failed:}) — git failed, push refused (fail closed). Run it yourself in the terminal: ! $cmd" ;; + deny "push-guard: push mode unreadable in $dir (${mode#failed:}) — push refused (fail closed). Run it yourself: ! $cmd" ;; auto) evaluated=$((evaluated + 1)) ;; + *) + deny "push-guard: unexpected push mode '$mode' in $dir — push refused (fail closed). Run it yourself: ! $cmd" ;; esac done < <(candidates) diff --git a/hooks/session-start.sh b/hooks/session-start.sh index 5bf9d67..a7c7698 100644 --- a/hooks/session-start.sh +++ b/hooks/session-start.sh @@ -53,7 +53,6 @@ _gf_lib="$(dirname "${BASH_SOURCE[0]}")/../lib/gitflow.sh" if [ -f "$_gf_lib" ] && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then GF_REFRESHED=$(bash "$_gf_lib" reconcile-hooks 2>/dev/null | sed -n 's/^gitflow hooks refreshed: *//p') fi -unset _gf_lib # ── graphify threshold signal (BDR-097) ── # Informs, never acts: one banner line when the repo holds ≥ 200 tracked code @@ -232,9 +231,12 @@ if [ -n "$GF_REFRESHED" ]; then fi # ── manual-push mode (BDR-111): one lock line when this repo never auto-pushes ── # %-46s, not 44: bash printf pads by BYTES and "—" is 3 bytes (2 extra). -if [ "$(git config --bool --default true gitflow.autopush 2>/dev/null)" = false ]; then - printf "│ 🔒 %-46s│\n" "push : manual (autopush=false) — ! git push" -fi +_pm=$( [ -r "$_gf_lib" ] && bash "$_gf_lib" push-mode 2>/dev/null ) +case "$_pm" in + manual) printf "│ 🔒 %-46s│\n" "push : manual (autopush=false) — ! git push" ;; + invalid) printf "│ 🔒 %-46s│\n" "push : manual (autopush bad) — ! git push" ;; +esac +unset _pm _gf_lib if [ -n "$GRAPHIFY_HINT" ]; then printf "│ 🕸️ %-44s│\n" "${GRAPHIFY_HINT:0:44}" printf "│ %-40s│\n" "→ /graphify (AST, seconds) — you decide" diff --git a/lib/tests/push-guard.test.sh b/lib/tests/push-guard.test.sh index feef387..11c2054 100644 --- a/lib/tests/push-guard.test.sh +++ b/lib/tests/push-guard.test.sh @@ -150,6 +150,14 @@ cmd48=""; for i in $(seq 1 25); do cmd48="${cmd48}cd /x$i;"; done run "$cmd48 git push" "$WORK/auto" check T48-cap-deny "$(verdict)" deny check T48-cap-reason "$(grep -c 'too many directory tokens' <<<"$(reason)")" 1 +cmd58=""; for i in $(seq 1 2000); do cmd58="${cmd58}cd /x$i;"; done +t58=$SECONDS +run "$cmd58 git push" "$WORK/auto" +t58=$((SECONDS - t58)) +echo "T58 elapsed: ${t58}s" +check T58-flood-deny "$(verdict)" deny +check T58-flood-reason "$(grep -c 'too many directory tokens' <<<"$(reason)")" 1 +check T58-flood-fast "$([ "$t58" -lt 5 ] && echo yes || echo no)" yes cmd48b=""; for i in 1 2 3 4 5; do cmd48b="${cmd48b}cd \"$M\";"; done run "$cmd48b git push" "$WORK/plain" check T48b-dedup-detect "$(verdict)" deny @@ -181,6 +189,69 @@ chmod 755 "$WORK/locked" check T50-bash-c-cd "$(fire "bash -c 'cd \"$M\" && git push'" "$WORK/plain")" deny check T50b-unquoted-arg "$(fire "bash -c 'cd $M && git push'" "$WORK/plain")" deny +# T51: a literal `true` is auto mode. +mkrepo "$WORK/truerepo"; git -C "$WORK/truerepo" config gitflow.autopush true +check T51-literal-true "$(fire 'git push' "$WORK/truerepo")" allow + +# T52: tokens that mix quoted and unquoted parts are refused, named. +run "cd $WORK/auto'/../manual' && git push" "$WORK/plain" +check T52-mixed-deny "$(verdict)" deny +check T52-mixed-reason "$(grep -c 'mixes quoted and unquoted' <<<"$(reason)")" 1 +run "cd \"$WORK/manual/my dir\" && git push" "$WORK/plain" +check T52b-quoted-deny "$(verdict)" deny +check T52b-quoted-reason "$(grep -c 'manual push mode' <<<"$(reason)")" 1 +mkdir -p "$WORK/auto/bob's" +check T52c-apostrophe-nopush "$(fire "cd \"$WORK/auto/bob's\" && git status" "$WORK/plain")" allow +check T52c-apostrophe-auto "$(fire "cd \"$WORK/auto/bob's\" && git push" "$WORK/plain")" allow + +# T53: a backslash-escaped space is one word, unescaped and resolved. +run "cd $WORK/manual/my\\ dir && git push" "$WORK/plain" +check T53-escaped-space "$(verdict)" deny +check T53-escaped-reason "$(grep -c 'manual push mode' <<<"$(reason)")" 1 +run "cd \"$WORK/manual\"/sub\"\" && git push" "$WORK/plain" +check T53b-enclosed-mixed "$(verdict)" deny +check T53b-mixed-reason "$(grep -c 'mixes quoted and unquoted' <<<"$(reason)")" 1 + +# T54: a payload jq cannot parse (lone surrogate escape in cwd). +bad54() { # bad54 : broken payload on stdout + printf '{"tool_input":{"command":"%s"},"cwd":"\\ud800"}' "$1" +} +bad54 'git status' > "$WORK/bad.json" +if jq -e . <"$WORK/bad.json" >/dev/null 2>&1; then + check T54-precondition-unparseable parsed unparsed +fi +out54=$(cd "$WORK/auto" && bad54 'git push' | bash "$H" 2>/dev/null); rc54=$? +check T54-deny "$(jq -r '.hookSpecificOutput.permissionDecision' <<<"$out54")" deny +check T54-internal "$(grep -c 'internal error' <<<"$out54")" 1 +check T54-rc "$rc54" 0 +out54=$(cd "$WORK/auto" && bad54 'git status' | bash "$H" 2>/dev/null) +check T54b-no-push-allow "$out54" "" +out54=$(cd "$WORK/auto" && bad54 'git add -A\ngit push' | bash "$H" 2>/dev/null) +check T54c-escaped-newline "$(grep -c 'permissionDecision":"deny"' <<<"$out54")" 1 +out54=$(cd "$WORK/auto" \ + && bad54 'git subtree push --prefix=x origin main' | bash "$H" 2>/dev/null) +check T54d-loose "$(grep -c 'permissionDecision":"deny"' <<<"$out54")" 1 + +# T55: a missing core tool (grep) warns on stderr and stays inactive. +mkdir -p "$WORK/nogrep" +for tool in bash cat jq git sed sort head; do + real=$(command -v "$tool") || continue + case "$real" in /*) ln -sf "$real" "$WORK/nogrep/$tool" ;; esac +done +out55=$(cd "$M" && printf '%s' "$payload47" \ + | PATH="$WORK/nogrep" "$(command -v bash)" "$H" 2>"$WORK/nogrep.err"); rc55=$? +check T55a-rc "$rc55" 0 +check T55b-stdout-empty "$out55" "" +check T55c-warn "$(grep -c 'grep missing' "$WORK/nogrep.err")" 1 + +# T56: lib missing (hook copied away from its lib/) denies, own reason. +mkdir -p "$WORK/alone/hooks"; cp "$ROOT/hooks/push-guard.sh" "$WORK/alone/hooks/" +saved_h=$H; H="$WORK/alone/hooks/push-guard.sh" +run 'git push' "$M" +H=$saved_h +check T56-lib-missing "$(verdict)" deny +check T56-reason "$(grep -c 'gitflow lib missing' <<<"$(reason)")" 1 + # ── settings.json wiring (file content only) ── S="$ROOT/settings.json" check T40-wiring "$(jq -e '.hooks.PreToolUse[] @@ -213,12 +284,28 @@ Write(~/.config/git/config) EOF check T41-new-deny-present "$missing" "" -# Nothing removed: every deny entry of the pre-run-B settings is still there. -base=HEAD -lost=$(git -C "$ROOT" show "$base:settings.json" 2>/dev/null \ - | jq -r --slurpfile now "$S" \ - '.permissions.deny[] | select(. as $e | ($now[0].permissions.deny | index($e)) == null)') -check T42-nothing-removed "$lost" "" +# Nothing removed: every deny entry of the fresher of origin/main and main +# (the last release) is still there. Neither ref resolves: SKIP, no count. +rv() { git -C "$ROOT" rev-parse -q --verify "$1" >/dev/null 2>&1; } +base="" +if rv origin/main && rv main; then + if git -C "$ROOT" merge-base --is-ancestor main origin/main; then + base=origin/main; else base=main; fi +elif rv origin/main; then base=origin/main +elif rv main; then base=main +fi +if [ -z "$base" ]; then + echo "SKIP T42 (no main ref)" +else + echo "T42 base: $base" + basedeny=$(git -C "$ROOT" show "$base:settings.json" 2>/dev/null \ + | jq -r '.permissions.deny[]' 2>/dev/null) + check T42-base-nonempty "$([ -n "$basedeny" ] && echo yes || echo no)" yes + lost=$(git -C "$ROOT" show "$base:settings.json" 2>/dev/null \ + | jq -r --slurpfile now "$S" \ + '.permissions.deny[] | select(. as $e | ($now[0].permissions.deny | index($e)) == null)') + check T42-nothing-removed "$lost" "" +fi soft=$(jq -r '.autoMode.soft_deny[]' "$S") check T43a-soft-rule "$(grep -c 'manual-push mode' <<<"$soft" | tr -d ' ')" 1 @@ -235,5 +322,7 @@ check T45-banner-manual "$(grep -c 'push : manual (autopush=false)' <<<"$out")" out=$(banner "$WORK/auto") check T46a-auto-control "$(grep -c 'Claude Code config' <<<"$out")" 1 check T46b-auto-silent "$(grep -c 'push : manual' <<<"$out")" 0 +out=$(banner "$WORK/bad") +check T57-banner-invalid "$(grep -c 'push : manual (autopush bad)' <<<"$out")" 1 printf 'PASS=%s FAIL=%s\n' "$pass" "$fail"; [ "$fail" -eq 0 ] diff --git a/skills/tour/SKILL.md b/skills/tour/SKILL.md index 9f88245..a486a4d 100644 --- a/skills/tour/SKILL.md +++ b/skills/tour/SKILL.md @@ -240,12 +240,12 @@ order: 5. Push state, only when a branch exists (report-only, skipped or dirty-tree projects have none: their row keeps `no branch`, no push column). Two read-only calls, probe first: - `git -C remote get-url origin >/dev/null 2>&1 || echo no-origin` + `git -C "" remote get-url origin >/dev/null 2>&1 || echo no-origin` then - `git -C rev-list --count --not --remotes=origin 2>/dev/null || echo unknown` + `git -C "" rev-list --count --not --remotes=origin 2>/dev/null || echo unknown` (`` = the name `gitflow start` returned, suffixed `-2`/`-3` on a same-day re-run — never the bare `chore/tour-`). 0 → `on origin`; - else `local only → ! git -C push -u origin ` (probe + else `local only → ! git -C "" push -u origin ` (probe printed `no-origin` → `local only (no origin remote)`). ```markdown @@ -282,7 +282,7 @@ without that approval — neither this repo's nor any target project's. never push `main`/`develop`** — "the tour is green" is not a signal. The gitflow hooks push the chore branch in auto-push mode only; when it is not on origin (manual push mode, or a `push FAILED` warning) the USER - pushes it — `! git -C push -u origin ` — the tour + pushes it — `! git -C "" push -u origin ` — the tour never pushes or retries. - Scoped pathspecs only; `git add -A` is forbidden. - Target TODO.md and target `.claude/memory/` are READ-ONLY. Reconcile From 64ca0f8e09e9c5ef45cb8fb2ed8c5dd9f2f2f30f Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 17:11:58 +0200 Subject: [PATCH 017/547] docs(skills): invalid autopush value is fail-closed everywhere; prose aligned Run D3 of manual-push mode (BDR-114). With every reader now failing closed, the skill prose stops saying the lib and hooks still push on an invalid value: - capitalize STEP 5C / STEP 6: the invalid outcome is split on the ahead count (nothing pushed vs pushed anyway by a stale fail-open hook or a manual push); the verb's stderr line is quoted verbatim; neighbouring closing lines carry push-mode qualifiers so none shadows the invalid case; the --no-push lines follow the same rule. - client-handover: "COMMIT + PUSH" labels become "COMMIT + PUSH STATE READ"; the STEP 5 residual sentences no longer imply the pipeline pushes; the invalid value is named as a case where the user pushes. - release-executor: prep span checks the version format by reading the string (never in a Bash command); manual mode and an invalid value both leave main/develop local. --- agents/client-handover-writer.md | 14 +++++++------- agents/release-executor.md | 5 ++++- skills/capitalize/SKILL.md | 16 +++++++++------- skills/client-handover/SKILL.md | 2 +- 4 files changed, 21 insertions(+), 16 deletions(-) diff --git a/agents/client-handover-writer.md b/agents/client-handover-writer.md index 0273722..c608bed 100644 --- a/agents/client-handover-writer.md +++ b/agents/client-handover-writer.md @@ -533,7 +533,7 @@ After loops finish (success, stall, or override), capture: --- -## STEP 5 — COMMIT + PUSH (only if files changed) +## STEP 5 — COMMIT + PUSH STATE READ (only if files changed) ```bash CHANGED_DURING_PIPELINE=$(git diff --name-only "$PIPELINE_BASE_SHA"..HEAD) @@ -542,18 +542,18 @@ PENDING_CHANGES=$(git status --porcelain) If both empty → skip to STEP 6. -**Gitflow precondition (report-only fallback).** Before any commit or push, -confirm this is a gitflow repo: +**Gitflow precondition (report-only fallback).** Before any commit, +confirm this is a gitflow repo (the pipeline never pushes): ```bash git rev-parse --verify -q develop >/dev/null 2>&1 && echo DEVELOP_OK [ -f "$HOME/.claude/lib/gitflow.sh" ] && echo LIB_OK ``` -If `develop` is missing OR the gitflow lib is unavailable → **do NOT commit, -do NOT push.** Leave the changes in the working tree and record in the STEP 8 -summary: "Commit/push skipped — no gitflow model in this repo; publish the -listed changes manually before deploy." Continue to STEP 6. +If `develop` is missing OR the gitflow lib is unavailable → **do NOT commit +(and never push).** Leave the changes in the working tree and record in the +STEP 8 summary: "Commit skipped — no gitflow model in this repo; publish the +listed changes by hand before deploy." Continue to STEP 6. If `PENDING_CHANGES` non-empty → invoke /commit-change skill via subagent: diff --git a/agents/release-executor.md b/agents/release-executor.md index b86aa05..a102923 100644 --- a/agents/release-executor.md +++ b/agents/release-executor.md @@ -31,6 +31,9 @@ stop and report — never chain into the other span yourself. ### Input ``: the version number, already decided by the dispatcher before dispatch — you never derive it, never second-guess it, never bump it. +Format check only, by reading the string (never inside a Bash command): + must match ^[0-9]+\.[0-9]+\.[0-9]+$ (literal regex text, single +backslashes); anything else → STATUS: BLOCKED, nothing created. ### Steps 1. `bash "$HOME/.claude/lib/gitflow.sh" start release ` — forks from @@ -80,7 +83,7 @@ actual branch; never finish whatever happens to be checked out. main's release-merge commit). In auto-push mode finish pushes `main` and `develop` (best effort: the lib warns and returns 0 on a failed push; the dispatcher re-verifies with ahead counts) (BDR-095); in - manual push mode they stay local. The tag stays local until the + manual push mode, or with an invalid gitflow.autopush, they stay local. The tag stays local until the dispatcher's tag-push gate. ### Forbidden in this span diff --git a/skills/capitalize/SKILL.md b/skills/capitalize/SKILL.md index 1045007..5037ea7 100644 --- a/skills/capitalize/SKILL.md +++ b/skills/capitalize/SKILL.md @@ -343,7 +343,8 @@ Otherwise, from the `chore/` branch, THREE separate Bash calls, never comb Outcomes, evaluated IN THIS ORDER (finish rc 0, or rc 5/2/6 with the branch merged — the wording then starts with `merged, branch not deleted (rc ) —` instead of `merged to develop —`): -- **push mode `invalid`** → `merged to develop — gitflow.autopush= is not a boolean: the lib and hooks still push on an invalid value until run D (origin/develop is commit(s) behind, or unknown); fix the value by hand`. +- **push mode `invalid`, `ahead` > 0 or unknown** → `merged to develop — : treated as manual push mode by every reader, nothing pushed (origin/develop is commit(s) behind, or unknown). Fix the value by hand, then: ! git push origin develop` (append ` once a remote exists` when `ahead` is unknown). +- **push mode `invalid`, `ahead` = 0** → `merged to develop — : pushed anyway, a hook in this repo still fails open (likely a stale .githooks/: a session-start reconcile refreshes it, commit the refresh) or a manual push. Fix the value by hand.` - **`ahead` = 0** → `develop pushed` (auto-push mode did it). - **`ahead` = unknown** → `merged to develop — not on origin (no origin/develop ref; no remote or never fetched)`; push mode manual → add `You: ! git push origin develop once a remote exists`. - **`ahead` > 0, push mode `manual`** → `merged to develop — manual push mode: not pushed. You: ! git push origin develop`. @@ -360,7 +361,7 @@ CAPITALIZE COMPLETE — () TODO.md : checked , added journal.md : +1 line under ## committed : (chore(memory): …) | ⚠️ NOT committed (rc 3 — see closing line) - persisted : develop pushed | merged, manual push mode: not pushed | merged, not on origin (no origin/develop) | merged, push FAILED | merged, gitflow.autopush invalid ( behind) | finish rc , not merged | merged, branch not deleted (rc ) | on chore/, not merged (--no-push) + persisted : develop pushed | merged, manual push mode: not pushed | merged, not on origin (no origin/develop) | merged, push FAILED | merged, autopush invalid, nothing pushed ( behind) | merged, autopush invalid, pushed anyway (stale hook or manual push) | finish rc , not merged | merged, branch not deleted (rc ) | on chore/, not merged (--no-push) dropped as already-captured: LRN-023, BLK-006 ignored as noise: push/tag release ``` @@ -368,15 +369,16 @@ CAPITALIZE COMPLETE — () Then the closing line — pick by the STEP 5C persist result (`` = `Context flushed` for pre-wipe, `Session closed` for ritual): -- **auto-persisted (5C: finish rc 0 AND `ahead` = 0)** → `✅ + persisted to origin/develop (). Next session: read .claude/memory/ at startup.` +- **auto-persisted (push mode `auto`, finish rc 0 AND `ahead` = 0)** → `✅ + persisted to origin/develop (). Next session: read .claude/memory/ at startup.` On the `--no-push` path ONLY read TWO facts first, each its own Bash call: `bash "$HOME/.claude/lib/gitflow.sh" push-mode` and `git rev-list --count origin/chore/..chore/ 2>/dev/null || echo unknown` (`branch_ahead`). `` below is the verb's word. The WORKING-branch and rc 3 paths have no `chore/` and never use the mode. -- **--no-push, `branch_ahead` = 0** → `✅ + committed on chore/ — pushed to origin by the hooks (auto-push mode), NOT merged (--no-push). Merge when ready.` -- **--no-push, `branch_ahead` > 0 or unknown** → `✅ + committed on chore/ — this disk only, not pushed (), NOT merged. You: ! git push -u origin chore/; merge when ready.` With push mode `invalid`, append ` gitflow.autopush= is not a boolean: fix it by hand`. +- **--no-push, `branch_ahead` = 0** → `✅ + committed on chore/ — pushed to origin by the hooks (auto-push mode), NOT merged (--no-push). Merge when ready.` With push mode `invalid`, replace `(auto-push mode)` with `(: pushed anyway, a hook still fails open, likely stale, or a manual push; fix the value by hand, commit the .githooks refresh)`. +- **--no-push, `branch_ahead` > 0 or unknown** → `✅ + committed on chore/ — this disk only, not pushed (), NOT merged. You: ! git push -u origin chore/; merge when ready.` With push mode `invalid`, append ` : treated as manual push mode, nothing pushed; fix the value by hand`. - **manual (merged, `ahead` > 0)** → `✅ + merged to develop — manual push mode: not pushed. You: ! git push origin develop` -- **not on origin (merged, `ahead` unknown)** → `✅ + merged to develop — not on origin (no origin/develop ref).` Push mode manual → add `You: ! git push origin develop once a remote exists`. -- **invalid (merged)** → `⚠️ + merged to develop — gitflow.autopush= is not a boolean; lib/hooks still push on it until run D (origin/develop behind). Fix the value by hand.` +- **not on origin (push mode not `invalid`, merged, `ahead` unknown)** → `✅ + merged to develop — not on origin (no origin/develop ref).` Push mode manual → add `You: ! git push origin develop once a remote exists`. +- **invalid (merged, ahead > 0 or unknown)** → `⚠️ + merged to develop — : treated as manual push mode by every reader, nothing pushed (origin/develop behind). Fix the value by hand, then: ! git push origin develop` (+ ` once a remote exists` when unknown) +- **invalid (merged, ahead = 0)** → `⚠️ + merged to develop — : pushed anyway, a hook still fails open, likely stale (refreshed by the next session-start reconcile; commit the refresh) or a manual push. Fix the value by hand.` - **push failed after merge** → `✅ + merged to develop — ⚠️ push FAILED (); merged locally, push manually.` - **finish failed** → `⚠️ + finish rc : — chore/ kept, NOT merged; resolve by hand.` (rc 1/4 only; rc 5/2/6 with the branch merged use the outcome lines above with the `merged, branch not deleted (rc )` prefix, so the push state is still reported.) - **WORKING branch (rode a feature branch)** → `✅ + committed on . Integrates when the branch merges.` diff --git a/skills/client-handover/SKILL.md b/skills/client-handover/SKILL.md index d7df8f0..fa4acc3 100644 --- a/skills/client-handover/SKILL.md +++ b/skills/client-handover/SKILL.md @@ -45,7 +45,7 @@ The agent runs a **ship-and-handover pipeline** with explicit gates: - Re-invoke the audit subagent in audit mode: it re-scores and returns the next FIX BUNDLE; it applies nothing (a dispatched child cannot hold a gate). - Repeat up to `MAX_ITERATIONS` (default 5). - If still < 17/20 after cap → escalate to user with concrete remaining issues; user decides continue / stop / manual intervention. -4. **COMMIT + PUSH** — If files changed during fix loops, run /commit-change (atomic logical commits); the gitflow hooks push in auto-push mode, otherwise (manual push mode, or a hook push that failed) the agent tells the user to push with `! git push -u origin ` BEFORE the deploy pause. +4. **COMMIT + PUSH STATE READ** — If files changed during fix loops, run /commit-change (atomic logical commits); the gitflow hooks push in auto-push mode, otherwise (manual push mode, an invalid gitflow.autopush, or a hook push that failed) the agent tells the user to push with `! git push -u origin ` BEFORE the deploy pause. 5. **DEPLOY PAUSE** — List exact deploy artifacts: changed files since baseline, deploy hints from project (vercel.json, netlify.toml, Dockerfile, .github/workflows/deploy.yml, etc.), and the deploy process in plain words. Use AskUserQuestion: "Deploy done? (Yes / Not yet / Skip validate)". Block until Yes or Skip. 6. **/web-validate (live site)** — Run validator-analyzer against the deployed URL. Capture `SCORE_VALIDATE`. 7. **GATE — per-axis threshold ≥17/20** — Compute final `SCORE_*_AFTER` for SEO classique, GEO (IA), HARDEN, VALIDATE. If ANY < 17/20: STOP. Generate `.claude/audits/HANDOVER-ROADMAP.md` with prioritized analysis of what's blocking each below-threshold axis. Do NOT write the client deliverable. Report to user. From 4a747c8144b018ba0b08b9573810531258aafe66 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 17:24:29 +0200 Subject: [PATCH 018/547] =?UTF-8?q?docs(doctrine):=20manual-push=20mode=20?= =?UTF-8?q?=E2=80=94=20invalid=20value=20counts=20as=20manual;=20Claude=20?= =?UTF-8?q?never=20pushes,=20even=20when=20asked?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.global.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/CLAUDE.global.md b/CLAUDE.global.md index 59969d0..c784bb1 100644 --- a/CLAUDE.global.md +++ b/CLAUDE.global.md @@ -186,9 +186,11 @@ that ran `gitflow init` (new/onboarded projects) keeps its own `.githooks/`, refreshed at session start. Human-set opt-outs: `git config gitflow.protect false` (foreign clone) and `gitflow.autopush false` = manual-push mode (work machine): branches, commits and local merges run as -usual, nothing is pushed, Claude never pushes (`/close` included) unless -the user asks; `GITFLOW_NO_PUSH=1` only for throwaway test repos. Outside -manual mode a branch ahead of its upstream is a defect, not a state. +usual, nothing is pushed, Claude never pushes (`/close` included), even +when asked: the user runs `! git push`. An invalid value counts as manual, +nothing pushes and the stop is named. `GITFLOW_NO_PUSH=1` only for +throwaway test repos. Outside manual mode a branch ahead of its upstream +is a defect, not a state. ## Security — non-negotiable defaults Apply at every step: design, scaffolding, implementation, review. From 1203a9a735d57dc947ef9cad3d511f3c278fb61c Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 17:24:30 +0200 Subject: [PATCH 019/547] =?UTF-8?q?docs(gitflow):=20run=20D=20=E2=80=94=20?= =?UTF-8?q?invalid=20autopush=20value=20fails=20closed=20everywhere;=20CHA?= =?UTF-8?q?NGELOG,=20SETTINGS,=20gitflow=20skill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 9 +++++---- skills/gitflow/SKILL.md | 9 ++++++--- templates/settings/SETTINGS.md | 21 ++++++++++++++------- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ad6729..26db705 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,18 +7,19 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project ## [Unreleased] ### Added -- **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
` 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 `gitflow.autopush` value is named and treated as auto. `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 fails closed: for this hook a non-boolean value reads as manual, and a git failure while reading the key, an internal error or more than 20 distinct directory tokens in one command refuse the push (these pathological cases fire in auto mode too). In manual mode it over-blocks any command where a `push` word follows a `git` token; 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. 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/
..
` read after the fact, with the complete `! git …` command when something is left for the user to push. An invalid value is named, but the lib and the git hooks still push on it as auto. Tests: `lib/gitflow-test.sh` T11b (push-mode verb) and T18m block, `lib/tests/unpushed-guard.test.sh` T10-T16, `lib/tests/push-guard.test.sh` (71 checks). +- **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
` 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. In manual mode it over-blocks any command where a `push` word follows a `git` token; 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/
..
` 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). ### Changed - `settings.json` denies every write form of the human-only `gitflow.*` keys (18 entries): any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, and Edit/Write of `.git/config`, `.gitconfig` and `~/.config/git/config`. Side effect: Claude can no longer read `gitflow.autopush` through `git config` either; hooks and `lib/gitflow.sh` still read it. The `hard_deny` rule on routing around a guardrail now names PreToolUse hook refusals. - `gitflow start` and `finish` warn on stderr when a base is behind origin and cannot fast-forward, instead of a silent `git pull --ff-only || true` (T18l, T18n). -- `/close` (`/capitalize` STEP 5C) no longer runs its own push of develop: `gitflow finish` already pushes develop in auto-push mode (BDR-095). The closing line reports the real state, read after the merge: pushed, manual push mode with the `! git push origin develop` to run, not on origin, push failed, or an invalid `gitflow.autopush` value named. A finish whose merge landed but whose branch delete failed (rc 5/2/6) still reports the push state. +- `/close` (`/capitalize` STEP 5C) no longer runs its own push of develop: `gitflow finish` already pushes develop in auto-push mode (BDR-095). The closing line reports the real state, read after the merge: pushed, manual push mode with the `! git push origin develop` to run, not on origin, push failed, or an invalid `gitflow.autopush` value named and treated as manual push mode. A finish whose merge landed but whose branch delete failed (rc 5/2/6) still reports the push state. - `/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 ` 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`. 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. -- `/tour`: each summary row says `on origin` or `local only` with the `! git -C push -u origin ` to run. The tour never pushes or retries. +- `/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`. 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 "" push -u origin ` to run. The tour never pushes or retries. ### Fixed - `gitflow delete` (and `finish`) land on the base that contains the branch and drop the branch's upstream before `git branch -d`, so a branch whose upstream lags (manual-push mode) is deleted instead of refused by git (T18k). +- An invalid `gitflow.autopush` value (not a boolean, or a config read that fails) no longer pushes. The post-commit / post-merge hooks and every push site of `lib/gitflow.sh` (`start`, `finish`, the `origin/` cleanup of `delete`) read it as auto and pushed; they now push nothing and say why. Each hook run prints `gitflow post-commit: gitflow.autopush unreadable (git rc ) — NOT pushed, treated as manual push mode; fix the value by hand` (post-merge likewise), and the lib passes through the `push-mode` verb's line, `gitflow.sh push-mode: gitflow.autopush='' is not a boolean (git rc )`. A repo with its own committed `.githooks/` (onboarded projects) keeps running its old hooks, which still push on an invalid value, until a session start runs `reconcile-hooks` and rewrites them; commit that refresh so other clones get it. Tests: `lib/gitflow-test.sh` T18q block. ## [2.0.0] — 2026-10-06 diff --git a/skills/gitflow/SKILL.md b/skills/gitflow/SKILL.md index b401393..7976d64 100644 --- a/skills/gitflow/SKILL.md +++ b/skills/gitflow/SKILL.md @@ -57,8 +57,10 @@ and keeps the branch. The `origin/` copy is removed right after, once ITS tip passes the same check; a remote tip holding commits the bases lack is kept, loudly (T24). In manual-push mode (`git config gitflow.autopush false`, human-set) nothing is pushed: `start` and `finish` stay local, and -the `origin/` copy is left in place (T18i-T18k). A `git push` Claude types is -refused by `hooks/push-guard.sh`; the user pushes with `! git push`. Hand +the `origin/` copy is left in place (T18i-T18k). An invalid value (not a +boolean, or a failed read) is manual push mode too: nothing is pushed and the +stop is named on stderr (T18q). A `git push` Claude types is refused by +`hooks/push-guard.sh`; the user pushes with `! git push`. Hand `git branch -d` is denied — with an auto-pushed upstream it checks the wrong thing (T22a). A `reference-transaction` hook vetoes any deletion or rename of `main`/`develop` at the ref layer, in every repo. @@ -111,7 +113,8 @@ stays human-gated. | `delete`/`finish` rc=5 — branch not merged into develop or main | The branch still holds unmerged work: KEEP it, report it, never fall back to `git branch -d`/`-D`. Merge first (human gate), then re-run | | `delete` rc=6 — protected base | `main`/`develop` are never deleted. Stop; the request itself is the defect to report | | `delete`/`finish` warning "remote copy KEPT" or "NOT removed" | Non-fatal BY CONTRACT (remote cleanup is best-effort). KEPT = origin/
has a tip the bases lack: fetch, look, merge or leave it — never `git push --delete` by hand. NOT removed = origin unreachable or refused: report the printed command to the user | -| `delete`/`finish` warning "origin/
left in place (manual push mode)" | Expected in manual-push mode, not a failure. Pass the printed `git push origin --delete
` to the user; never run it (manual mode: Claude never pushes, even when asked in the turn; the user runs it with `!`. `push --delete` is also denied by settings) | +| `delete`/`finish` warning "origin/
left in place (manual push mode)" | Expected in manual-push mode or with an invalid `gitflow.autopush` (the verb's `gitflow.sh push-mode:` line precedes it), not a failure. Pass the printed `git push origin --delete
` to the user; never run it (manual mode: Claude never pushes, even when asked in the turn; the user runs it with `!`. `push --delete` is also denied by settings) | +| Hook stderr "gitflow post-commit: gitflow.autopush unreadable (git rc ) — NOT pushed, treated as manual push mode" (post-merge likewise), or `start`/`finish`/`delete` stderr "gitflow.sh push-mode: gitflow.autopush='' is not a boolean" / "could not read gitflow.autopush" | Fail closed BY CONTRACT: the value is invalid, so nothing was pushed. Report the line to the user, who fixes the value by hand (`git config` on the key is denied to Claude); hand any pending push to the user as `! git push …`. Never retry the push | | `start`/`finish` warning " is behind origin/ by N and cannot fast-forward" | Non-fatal BY CONTRACT: the branch is still created and the merge still runs on the local base. The base has diverged from origin: report it to the user, who reconciles (`git pull`, then push). Never rebase or force-push a base | ## Common Mistakes diff --git a/templates/settings/SETTINGS.md b/templates/settings/SETTINGS.md index 0066799..7e43059 100644 --- a/templates/settings/SETTINGS.md +++ b/templates/settings/SETTINGS.md @@ -146,7 +146,7 @@ local trace, and the brief had authorized it. What holds now, by tier: | Docker volume drops, `system prune`, `compose down -v`, `--privileged`, the docker socket, `-v /:` | `permissions.deny` | Promoted from `soft_deny`: no in-session clearance for data drops. | | Git history destruction (`push --delete`/`--mirror`/`:ref`/`--force-with-lease`, `branch -D`, `filter-branch`, `reflog expire`, `stash clear`/`drop`, `clean -f`), `--no-verify`, `core.hooksPath` | `permissions.deny` | A remote is the backup; nothing rewrites or deletes what it holds. | | Writing the human-only `gitflow.*` toggles: any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, Edit/Write of git config files | `permissions.deny` | Claude never flips the mode that binds it. Side effect: the trailing glob also matches the bare read, so Claude cannot read `gitflow.autopush` through `git config`; hooks and `lib/gitflow.sh` still do, and skills read it through `gitflow.sh push-mode`. | -| Pushing in manual-push mode (`gitflow.autopush false`) | `hooks/push-guard.sh` (PreToolUse) + `autoMode.soft_deny` | `ask` is inert under auto mode. The hook denies the direct forms; the soft_deny covers scripted, aliased, subshell and sub-agent pushes, and a request in the turn does not clear it: the user types `! git push`. | +| Pushing in manual-push mode (`gitflow.autopush false`, or any invalid value) | `hooks/push-guard.sh` (PreToolUse) + `autoMode.soft_deny` | `ask` is inert under auto mode. The hook denies the direct forms; the soft_deny covers scripted, aliased, subshell and sub-agent pushes, and a request in the turn does not clear it: the user types `! git push`. | | Destructive tool against a local path (variable, `~`, `..`, wildcard, outside cwd/tmp), even as a trace or a rehearsal a brief allows | `autoMode.hard_deny` | A pattern cannot express "the target resolves outside the project"; the classifier can. A sub-agent brief carries no user authority. | | `docker rm -f`, bind mount outside cwd; discarding uncommitted work | `autoMode.soft_deny` | Recoverable or user-intended in the turn. | @@ -186,10 +186,12 @@ refuses any `git push` Claude types, when the key 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 the push with `! git push`, and the session banner adds a `🔒 push : manual` line. The hook -fails closed: a non-boolean value reads as manual, and a git failure while -reading the key or more than 20 directory tokens in one command refuses the -push, in auto mode too. In manual mode it over-blocks any command where a -`push` word follows a `git` token (`git stash push`, a grep for "git push"). +fails closed: an invalid value reads as manual, and a `cd`/`-C` directory +token mixing quoted and unquoted parts, an unparseable payload that looks like +a push, a missing `lib/gitflow.sh` or more than 20 directory tokens in one +command refuses the push, in auto mode too. In manual mode it over-blocks any +command where a `push` word follows a `git` token (`git stash push`, a grep +for "git push"). The misses listed in its header fall to an `autoMode.soft_deny` rule that no request in the turn clears. Skills read the mode through `bash ~/.claude/lib/gitflow.sh push-mode` (`auto`, `manual` or `invalid`, @@ -197,8 +199,13 @@ rc 0) and push nothing themselves, except the `/release-candidate` tag in auto-push mode on an explicit go. What they report as on origin or not pushed comes from `git rev-list --count origin/
..
` read afterwards, and a pending push is handed to the user as a complete `! git …` command. -An invalid value is named, but the lib and the git hooks still push on it -as auto; only push-guard fails closed on it. +An invalid value (not a boolean, or a read that fails) is manual push mode +for every reader: the hooks, `start`, `finish` and `delete` push nothing and +say why on stderr, push-guard refuses, the banner shows +`🔒 push : manual (autopush bad)` and the SessionStart line names the value. +Exception: a repo with its own committed `.githooks/` runs its old hooks, +which still push on an invalid value, until a session start refreshes them; +commit the refresh. ## managed-settings.json (enterprise) From 3721cf522a57a8b8a3f457af729b02a8d5bd52e2 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 17:24:31 +0200 Subject: [PATCH 020/547] =?UTF-8?q?chore(memory):=20BDR-114=20+=20LRN-200.?= =?UTF-8?q?.202=20+=20journal=20=E2=80=94=20feat=20manual-push-mode=20run?= =?UTF-8?q?=20D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 7 +++ .claude/memory/journal.md | 1 + .claude/memory/learnings.md | 12 ++++ .claude/tasks/TODO.md | 5 +- ...26-10-07-manual-push-failclosed-d1-1522.md | 41 +++++++++++++ ...-07-manual-push-guard-residuals-d2-1526.md | 40 ++++++++++++ .../2026-10-07-manual-push-prose-d3-1530.md | 36 +++++++++++ ...26-10-07-manual-push-failclosed-d1-1522.md | 61 +++++++++++++++++++ ...-07-manual-push-guard-residuals-d2-1526.md | 35 +++++++++++ .../2026-10-07-manual-push-prose-d3-1530.md | 24 ++++++++ 10 files changed, 260 insertions(+), 2 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-07-manual-push-failclosed-d1-1522.md create mode 100644 .claude/tasks/contracts/2026-10-07-manual-push-guard-residuals-d2-1526.md create mode 100644 .claude/tasks/contracts/2026-10-07-manual-push-prose-d3-1530.md create mode 100644 .claude/tasks/plans/2026-10-07-manual-push-failclosed-d1-1522.md create mode 100644 .claude/tasks/plans/2026-10-07-manual-push-guard-residuals-d2-1526.md create mode 100644 .claude/tasks/plans/2026-10-07-manual-push-prose-d3-1530.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 8a3f2ee..a8a6232 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1385,3 +1385,10 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: gate the existing push on the verb (denied/stateless); keep the GO question (gated nothing); word invalid as manual (false in the lib); per-skill `git config` read (denied). - **Gates**: C1: 3 lenses (1 BLOCKER: shell gate) + confirm CONCERNS(3); feater; GATE 0 MET; verifier CONFORME; security PASS. C2: 3 lenses (BLOCKER: deploy brief said "push done") + confirm CONCERNS(4); feater; verifier CONFORME; security BLOCK(1) branch-name injection ([[LRN-198]]) → fixed → CONFORME + PASS. Polish pass: CONFORME + PASS. - **Refs**: contracts `.claude/tasks/contracts/2026-10-07-manual-push-skills-c1-1304.md`, `…-c2-1325.md`; plans same slugs; commits 5cf049d, 6104545, 3881f46 (feature/manual-push-mode, UNMERGED). Links [[BDR-068]], [[BDR-095]], [[BDR-042]], [[LRN-069]]. + +## BDR-114 — Every `gitflow.autopush` reader fails closed and names the stop; the lib verb is the single reader [accepted] (2026-10-07) +- **Decision**: run D of [[BDR-111]]. Rule for every reader: unset or `true` → auto (push); `false` → manual (no push, silent); anything else (unparseable value, corrupt config, git failure) → NO push and one named line. Readers: lib `_gitflow_push_off` = `[ "$(gitflow_push_mode)" != auto ]` (verb stderr passes through); emitted post-commit/post-merge hooks (standalone POSIX sh, mirror of the verb: `case "$rc:$v" in 0:true|1:*) ;; 0:false) exit 0 ;; *) echo "… NOT pushed, treated as manual push mode" >&2; exit 0 ;; esac`); unpushed-guard, session-start banner (`autopush bad` lock line) and push-guard (sources the lib once, `gitflow_push_mode` per candidate) all read the verb. push-guard residuals: whole-word dir tokens (mixed quoting → deny; fully quoted + inner other-quote and `\ ` escapes resolved), payload jq cannot parse → raw scan with JSON escapes folded → static deny, cap BEFORE any per-token fork, T42 base = main. Skill prose: invalid outcome split on the ahead count (0 → "pushed anyway, likely a stale fail-open hook or a manual push"), labels COMMIT + PUSH STATE READ, release-executor version format check by reading. Doctrine: invalid = manual; "never pushes, even when asked". +- **Why**: `--bool --default true` covers a MISSING key only; a typo re-enabled every push silently (the 21-09 hazard class on a work machine). The user chose fail-closed for the guard in run B; D extends it everywhere and keeps a terminal signal (git's own "fatal: bad boolean" used to be the only one; the hooks now print theirs). +- **Alternatives rejected**: regen via `install-hook` (writes a LOCAL hooks-path entry) or `global-hooks` (writes the GLOBAL config when the value is missing — it was, [[LRN-200]]) → `emit-hook > file` only; temp file for the verb's stderr in a hook (fail-open on a full TMPDIR, predictable path) → `2>&1` capture ([[LRN-202]]); classification before the token cap (13 s flood) → cap first ([[LRN-201]]); shell check of the release version string (interpolation sink) → by reading. +- **Gates**: D1 3 lenses + confirm FATAL(1) (global-config write) → emit-hook; feater; GATE 0 MET; verifier CONFORME; security PASS. D2 3 lenses + confirm FATAL(3) (escape alternative, same-quote-inside, `bare=$one` when unparsed); feater; GATE 0 MET; verifier CONFORME; security BLOCK(1) cap-after-fork → fixed (20k tokens 0.13 s) → CONFORME + PASS. D3 3 lenses + confirm CONCERNS(3); feater; CONFORME + PASS. +- **Refs**: contracts/plans `2026-10-07-manual-push-failclosed-d1-1522`, `…-guard-residuals-d2-1526`, `…-prose-d3-1530`; commits 472cccb, 3c59333, 64ca0f8 (feature/manual-push-mode, UNMERGED). Supersedes the "fail-open on invalid value" line of [[BDR-111]]. Links [[BDR-112]], [[BDR-113]], [[LRN-114]], [[LRN-196]]. Residuals: TODO "post-run-D residuals" (soft_deny names only `false`; stale `.githooks/` in onboarded repos until reconcile). diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 2b3e474..826087e 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -573,4 +573,5 @@ rules: ## 2026-10-07 - /feat manual-push-mode run B (user: "enchaine"): `hooks/push-guard.sh` PreToolUse denies Claude's `git push` when autopush false/unparseable/unreadable in cwd or literal -C/cd dirs (global config counts). Challenge: 3 lenses + robustness confirm FATAL(8) → BSD sed `N` fold empty on 1 line (hook dead), AC3 oracle naming denied tokens, glob trailing ` *` matches end → bare read lost, run C needs lib verb. feater ×3 (impl 58, no-jq test 61, hardening 71: cap 20 dirs, git rc → deny, quoted cd). GATE 0 MET ×3; verifier CONFORME then ECARTS(1) → user gated fail-closed also in auto for pathological commands; security PASS ×2 (3 MEDIUM closed, 2 residual → run D). Commits a2ac018 + 6468eda on feature/manual-push-mode, UNMERGED. settings.json live: 18 deny entries, soft_deny, Bash|Monitor hook group. User probe pending: `! git push --dry-run` bypasses hooks? - /feat manual-push-mode run C (user: "enchaine"), split C1+C2. C1: lib verb `gitflow.sh push-mode` (auto|manual|invalid, value on stderr, rc 0) + T11b; /close STEP 5C `git push origin develop` REMOVED (finish has pushed develop since BDR-095; shell gate would be denied whole by push-guard, `$mode` dies between Bash calls) → finish, verb, `rev-list --count origin/develop..develop`, prose outcomes incl. finish-failure; `--no-push` line from the branch's own count. Challenge 3 lenses (1 BLOCKER) + confirm CONCERNS(3); verifier CONFORME; security PASS. C2: client-handover GO question + push block removed (hooks pushed already in auto; guard denies in manual) → PUSH STATE READ re-run before every claim, branch-name allowlist (security BLOCK(1) → fixed, PASS); release-candidate: two counts + verb, `! git push --atomic origin main develop vX`, tag gate kept for auto/0/0; tour: `-C` fact per project, suffix-aware branch, `--remotes=origin`. Verifier CONFORME ×2. Commits 5cf049d + 6104545, UNMERGED. Polish pass in flight. +- /feat manual-push-mode run D (user: "enchaine"), split D1/D2/D3, 9 lenses + 3 confirmations. D1: every autopush reader fails closed AND names an invalid value (lib `_gitflow_push_off` via the verb; emitted hooks POSIX `case "$rc:$v"` + stderr line; unpushed-guard via the verb, no temp file); regen files-only via `emit-hook >` after the confirmation showed `install-hook` writes a local hooks-path and `global-hooks` writes the GLOBAL config when it lacks the value — which it did: user's dotfiles installer had overwritten `~/.gitconfig` (@USER@ placeholders, no hooksPath) + `~/.zshrc` at 15:39; user confirmed (own machine setup) and restored from the installer's backup before execution. D2: push-guard sources the lib, whole-word tokens (mixed quoting → deny), payload fallback, cap BEFORE classification (security BLOCK(1) caught the reorder: 1,600 tokens = 13 s > 10 s timeout → fixed, 20k tokens 0.13 s), T42 base main, banner `autopush bad`. D3: prose aligned (invalid outcome split on the ahead count, labels COMMIT + PUSH STATE READ, executor version check by reading). Commits 472cccb, 3c59333, 64ca0f8 on feature/manual-push-mode, UNMERGED. Residuals in TODO. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 69293c0..c3b2bb9 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1736,3 +1736,15 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s ## LRN-199 — Agent-level branching is prose on a printed word: shell state dies between Bash calls, and a text guard denies the whole call - **Context**: plan wrote `mode=$(gitflow.sh push-mode)` then `[ "$mode" = auto ] && git push origin develop`. Two failures: (a) separate calls → `$mode` empty → silent skip, rc 1 misread as "push FAILED"; (b) one call → push-guard's STRICT regex matches `&& git push origin` in the TEXT and denies the WHOLE call, so even `finish` never runs. Three lenses hit it independently. - **Apply**: a skill reads a word from a command's visible stdout, then branches in PROSE ("printed `auto` → run X as its own call; anything else → never issue X"). Never a shell variable across calls, never a conditional that contains a guarded token. Any text-only PreToolUse guard turns `cmd-you-wanted-to-avoid` inside a conditional into a denial of the surrounding command. Links [[BDR-112]], [[BDR-113]], [[LRN-191]]. + +## LRN-200 — `install-hook` and `global-hooks` write git config as a side effect; only `emit-hook > file` regenerates hooks config-free +- **Context**: D1 planned `install-hook` (= write hooks + a LOCAL hooks-path entry this repo must not gain: it runs on the global hooks) then `global-hooks ` ("returns before any write because the global value already matches"). The confirmation challenger read `~/.gitconfig`: rewritten 2 min earlier by the user's dotfiles installer (`@USER@` placeholders, no hooks path) → `global-hooks` WOULD have written the global config through a lib call, and `md5 .git/config` could not see it. User confirmed (own machine setup) and restored from the installer's backup; commits waited. +- **Apply**: regenerate generated hooks with `bash lib/gitflow.sh emit-hook > /` (no config read/write, mode preserved); never `install-hook`/`global-hooks` from a flow. Evidence = md5 of `.git/config` AND a Read of `~/.gitconfig` before/after. Before any commit, check `git var GIT_COMMITTER_IDENT` is not a placeholder: an external installer can rewrite dotfiles mid-session. Links [[BDR-114]], [[LRN-114]], [[BLK-027]]. + +## LRN-201 — A flood cap must run before ANY per-token fork; a reorder reopened the timeout fail-open and only a timed 2 000-token test catches it +- **Context**: run B put the 20-token cap before resolution (20k tokens 0.15 s). D2 added `classify_tok` (one subshell + sed per token) and the executor ran it BEFORE the cap: 1,600 tokens = 13 s > the 10 s hook timeout = allow. Verifier CONFORME (suite max 21 tokens), security re-scan BLOCK(1). Fix: `arg_tokens | sort -u | grep -c .` then `> 20` deny, then classification on ≤20 survivors; T58 = 2,000 tokens, deny, `$SECONDS` < 5. +- **Apply**: in any guard, order = count → cap → everything else; a cap without a timed flood test in the suite is a comment, not a guard. Re-measure the flood after every change to the token pipeline (security gate did: 0.13 s at 20k). Links [[BDR-114]], [[LRN-196]], [[LRN-104]]. + +## LRN-202 — Reading a stderr-then-stdout verb from a hook: `out=$(cmd 2>&1)`, last line = word, prefix line = reason; no temp file; lib path absolute before any cd +- **Context**: unpushed-guard plan used `2>"${TMPDIR:-/tmp}/x.$$"` + cat + rm: fail-OPEN when TMPDIR is full (`|| mode=auto`), predictable path, symlink-followable on shared /tmp, leaked on kill; `mode=$(cmd 2>&1 >/dev/null)` captures ONLY stderr. push-guard's `mktemp` variant added `set -u` trap hazards. The verb writes its stderr line BEFORE its stdout word in one process, so `${out##*$'\n'}` is the word and the `gitflow.sh push-mode:` line is the reason (select by prefix, not `head -1`: a bash startup warning could precede it). Resolve the lib path to an absolute one BEFORE the hook's `cd "$cwd"` (a relative invocation otherwise resolves into the target repo). +- **Apply**: hooks never touch temp files for a one-line capture; anything but the expected word is treated as the fail-closed state, never as the default. Links [[BDR-114]], [[LRN-196]], [[LRN-199]]. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 76bb3c5..fd5102a 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -2059,12 +2059,13 @@ dans un runner; capitalize reste main-loop. ## manual-push-mode (2026-10-06, /feat × 3) - [x] run A — `gitflow.autopush=false` honoured by `_gitflow_push_branch`, quiet unpushed-guard, doctrine line; plan `.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md` → commit 2fc8830 on feature/manual-push-mode; verifier ECARTS(1) = AC6 only (design-tool-gate env red, pre-existing on develop) → human waiver; merge human-gated - [x] run B — `hooks/push-guard.sh` PreToolUse (deny `git push` in manual mode) + 71-check test + settings.json (own hook group Bash|Monitor timeout 10; 18 write-form deny entries on the toggle; soft_deny on manual-mode pushes with no per-turn clearance; prose) + banner → a2ac018 + hardening commit; verifier CONFORME then ECARTS(1) closed by gated clarification (fail-closed cap/unenterable dir also in auto mode); security PASS ×2 -- [ ] run D also (push-guard residuals, security gate 2026-10-07): tokens with inner quotes/backslashes (`cd /m/'a b'`) resolve to the wrong dir → treat as unresolvable + deny or document; unparseable payload (lone surrogate) → jq fails → silent allow → grep raw payload for `push` and deny; `case "$mode"` default `*) deny`; up-front `command -v grep sed sort head jq` check; header line > 80 cols; T42 compares against HEAD (vacuous once committed) → compare against a pinned base or drop; no test sets the key to literal `true` +- [x] run D also (closed in D2 3c59333 — push-guard residuals, security gate 2026-10-07): tokens with inner quotes/backslashes (`cd /m/'a b'`) resolve to the wrong dir → treat as unresolvable + deny or document; unparseable payload (lone surrogate) → jq fails → silent allow → grep raw payload for `push` and deny; `case "$mode"` default `*) deny`; up-front `command -v grep sed sort head jq` check; header line > 80 cols; T42 compares against HEAD (vacuous once committed) → compare against a pinned base or drop; no test sets the key to literal `true` - [x] run C (C1 5cf049d, C2 6104545; split C1: lib verb `push-mode` + T11 tests + capitalize STEP 5C + close hint, plan `.claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md`; C2: client-handover skill+agent, release-candidate STEP 6, tour rule) — skills that push on their own, gate on the mode through a NEW lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (prints auto|manual|invalid; the bare `git config … gitflow.autopush` read is denied for Claude after run B — a trailing ` *` glob also matches end-of-string): capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims - [ ] run B also: fail-CLOSED on an unparseable `gitflow.autopush` value in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks, unpushed-guard) — run A keeps fail-open for consistency with the untouched emitters (security gate MEDIUM, 2026-10-06); `--end-of-options`/`--` on refname args and `printf %q` in copy-paste hints (LOW); `gitflow_delete`: check `_gitflow_checkout_containing_base` rc before `--unset-upstream` (LOW, 2nd gate) - [x] C1/C2 polish pass → 3881f46 (verifier CONFORME, security PASS; items were: capitalize STEP 5C heading still says "(finish + push)"; :372 paragraph glued to the :371 bullet and tells the WORKING-branch path to read `origin/chore/..` (no such ref there; that path never uses the mode); on finish rc 5/2/6 calls 2-3 are skipped so a manual-mode user gets no `! git push origin develop` hint; the "unknown + manual" closing line (:377) lacks the `once a remote exists` hint present in 5C (:348); STEP 6 "auto-persisted … pushed" bullet (:371) not tied to `ahead = 0` (security MEDIUM); verb stderr: cap `raw` to 64 printable chars; T11b "default auto" relies on the Makefile's hermetic env (fine under `make test`, spurious when run bare on a global-manual machine) → export in the suite header like line 257. C2 polish (verifier non-gaps): client-handover-writer PUSH STATE READ states need explicit precedence (uncommitted/no-commits first, then no-origin, then ahead); tour STEP 3 item 5 only when a branch exists (report-only / dirty-tree rows have none); 9.7 `STATUS: BLOCKED` branch lacks the `- Push:` bullet; release-executor:85-86 line > 80 cols - [x] ORDER constraint lifted: A + B + C all on feature/manual-push-mode; merge (human gate) then the work machine may set `gitflow.autopush false`. Still pending before relying on it at work: user probe `! git push --dry-run` in a scratch repo under autopush=false (bang commands assumed hook-free); run D below. -- [ ] run D — fail-CLOSED on an unparseable `gitflow.autopush` in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks + githooks regen, unpushed-guard) so the "invalid → lib/hooks still push" caveat in CHANGELOG/SETTINGS/skills can be removed; push-guard residuals (inner-quote/backslash tokens, lone-surrogate payload, `*) deny` default, up-front tool check, T42 base, literal `true` test); verb stderr: `LC_ALL=C` done, truncation marker + sanitizer test; client-handover: stale "COMMIT + PUSH" headings, `` quoting in tour hints; release-executor own version regex +- [x] run D (D1 472cccb, D2 3c59333, D3 64ca0f8 — all verifier CONFORME + security PASS; split 2026-10-07: D1 fail-closed readers — lib `_gitflow_push_off` via the verb, emitted push hooks POSIX rule + regen, unpushed-guard via the verb, plan `.claude/tasks/plans/2026-10-07-manual-push-failclosed-d1-1522.md`; D2 push-guard residuals + session-start banner on invalid + tour `` quoting; D3 skill/agent prose: drop the "until run D" caveats, stale COMMIT + PUSH headings, release-executor version regex, + doc-sync) — fail-CLOSED on an unparseable `gitflow.autopush` in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks + githooks regen, unpushed-guard) so the "invalid → lib/hooks still push" caveat in CHANGELOG/SETTINGS/skills can be removed; push-guard residuals (inner-quote/backslash tokens, lone-surrogate payload, `*) deny` default, up-front tool check, T42 base, literal `true` test); verb stderr: `LC_ALL=C` done, truncation marker + sanitizer test; client-handover: stale "COMMIT + PUSH" headings, `` quoting in tour hints; release-executor own version regex ## test hermeticity (2026-10-06, found during manual-push-mode run A) - [ ] `lib/tests/design-tool-gate.test.sh` reds on any machine with the 21st CLI installed ("FAIL precondition: system-wide 21st present, CLI_ABSENT case not hermetic") — pre-existing on develop (fa67664), independent of the diff. Make the CLI_ABSENT case hermetic (PATH shim / stubbed probe) so `make test` is green on a design-profile machine. Until then full-suite oracles (`make test` exit 0) cannot be MET here. +- [ ] post-run-D residuals (gates, 2026-10-07): settings.json soft_deny names only `gitflow.autopush false` → add "or an unparseable value" (restriction only, settings run); capitalize STEP 6: manual mode with `ahead` = 0 (user pushed by hand between merge and read) matches no closing line, and the 5C `ahead` = 0 bullet still says "(auto-push mode did it)"; release-executor:86 line > 80 cols; push-guard header line 4 > 80 cols (pre-existing); unpushed-guard Stop silence now also covers a missing lib (SessionStart names it) — accepted diff --git a/.claude/tasks/contracts/2026-10-07-manual-push-failclosed-d1-1522.md b/.claude/tasks/contracts/2026-10-07-manual-push-failclosed-d1-1522.md new file mode 100644 index 0000000..8d9b0e3 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-07-manual-push-failclosed-d1-1522.md @@ -0,0 +1,41 @@ +# CONTRACT — manual-push-failclosed-d1 (run D1 of manual-push mode) +- date: 2026-10-07 | flow: feat | branch: feature/manual-push-mode (runs A, B, C landed) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "ok enchaine sur le run D" +Run D as consolidated in `.claude/tasks/TODO.md`: "fail-CLOSED on an unparseable `gitflow.autopush` in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks + githooks regen, unpushed-guard) so the \"invalid → lib/hooks still push\" caveat in CHANGELOG/SETTINGS/skills can be removed; push-guard residuals (inner-quote/backslash tokens, lone-surrogate payload, `*) deny` default, up-front tool check, T42 base, literal `true` test); verb stderr: `LC_ALL=C` done, truncation marker + sanitizer test; client-handover: stale \"COMMIT + PUSH\" headings, `` quoting in tour hints; release-executor own version regex". + +## CLARIFICATIONS +Q: scope split / A: D1 (this contract) = fail-closed readers: lib `_gitflow_push_off`, the emitted push hooks (+ regenerated `.githooks/` and `githooks/`), `hooks/unpushed-guard.sh`, their tests. D2 = push-guard residuals + session-start banner on an invalid value + tour hint quoting. D3 = skill/agent prose (remove the "until run D" caveats, stale headings, release-executor version regex) + doc-sync. [orchestrator — scope] +Q: semantics / A: for every reader, `gitflow.autopush` unset or `true` → auto (push); `false` → manual (no push); anything else (unparseable, corrupt config, git failure) → NO push, reported as "invalid, treated as manual push mode". The lib verb `push-mode` already prints `invalid`; `_gitflow_push_off` reuses it (`!= auto` → off). The emitted hooks stay standalone `#!/bin/sh` (foreign repos, no lib): same rule inline. [orchestrator — the user chose fail-closed for the guard in run B; this extends it to every reader] +Q: regeneration of installed hooks / A: files only, with no config read or write: `bash lib/gitflow.sh emit-hook > /` for post-commit and post-merge under `.githooks/` and `githooks/`, in the same step as the emitter edit. NOT `install-hook` (writes a local hooks-path entry) and NOT `global-hooks` (writes the GLOBAL config when `~/.gitconfig` lacks the value — true since a dotfiles installer overwrote it at 15:39 today). `.git/config` hash unchanged and `~/.gitconfig` untouched are part of the evidence. [orchestrator — revised twice] +Q: run precondition / A: the user's `~/.gitconfig` must be restored first (identity + hooksPath); the executor checks `name =` is not `@USER@` by reading, else BLOCKED. [orchestrator] +Q: silence vs naming / A: a stopped push is NAMED on stderr by every reader (hook: one line per commit; lib: the verb's line passes through `_gitflow_push_off`): D1 must not remove the terminal user's only signal. [orchestrator — revised after challenge] +Q: unpushed-guard mode source / A: the guard reads the mode through the lib verb (`$(dirname "${BASH_SOURCE[0]}")/../lib/gitflow.sh push-mode`, the same relative path session-start uses), one reader for hooks that live next to the lib; its invalid line becomes "treated as manual push mode (nothing pushes); fix the value by hand". [orchestrator — internal] + +## ACCEPTANCE CRITERIA +1. Lib: with `gitflow.autopush` set to an unparseable value, `gitflow start` creates the branch locally without pushing and prints the verb's `not a boolean` line, a commit on it is not pushed by the post-commit hook which prints a `NOT pushed` line, `gitflow finish` merges locally and origin/develop is unchanged; with `true` the post-commit hook pushes (tips equal, positive control). `_gitflow_push_off` reads the mode through `gitflow_push_mode`. Locked by the new isolated gitflow-test block T18q1–T18q5 (q5 skipped with `ok` when shellcheck is absent). + CHECK: out=$(make test suite=lib/gitflow-test.sh 2>&1); printf '%s' "$out" | grep -q ' FAIL ' && exit 1; for t in "T18q1" "T18q2" "T18q3" "T18q4" "T18q5"; do grep -qF "ok $t" <<<"$out" || exit 1; done; echo FAILCLOSED-LIB-OK + EXPECT: FAILCLOSED-LIB-OK + EVIDENCE: MET exit=0 marker-found :: FAILCLOSED-LIB-OK +2. Emitted hooks (`_gitflow_emit_push_hook`): `#!/bin/sh`-portable rule — push only when `git config --bool gitflow.autopush` returns rc 0 `true` or rc 1 (unset); `false` exits 0 silently; any other result prints one stderr line (`NOT pushed, treated as manual push mode`) and exits 0. `.githooks/` and `githooks/` regenerated (files only) and identical to the emitters (T19a–e green); no `--default true gitflow.autopush` left in the four regenerated files; auto-mode T18a–h and manual T18m green. + CHECK: out=$(make test suite=lib/gitflow-test.sh 2>&1); printf '%s' "$out" | grep -q ' FAIL ' && exit 1; for t in T19a T19b T19c T19e T19d T18a T18b T18h T18i T18j T18k; do grep -q "ok $t" <<<"$out" || exit 1; done; ! grep -q -- '--default true gitflow.autopush' .githooks/post-commit .githooks/post-merge githooks/post-commit githooks/post-merge && grep -q 'NOT pushed' .githooks/post-commit && echo HOOKS-OK + EXPECT: HOOKS-OK + EVIDENCE: MET exit=0 marker-found :: HOOKS-OK +3. `hooks/unpushed-guard.sh`: mode read through the lib verb (absolute lib path resolved before any `cd`; no temp file); anything other than `auto` behaves as manual (silent at Stop; SessionStart `ℹ manual push mode:` line); `invalid` names the value and says "treated as manual push mode (nothing pushes)"; an unreadable verb result says so. Auto and manual behaviour unchanged (T1–T13, T15–T16 green); T14 rewritten for the new semantics. + CHECK: out=$(make test suite=lib/tests/unpushed-guard.test.sh 2>&1); printf '%s' "$out" | grep -q '^FAIL' && exit 1; grep -qE 'PASS=(2[8-9]|[3-9][0-9]) FAIL=0' <<<"$out" && grep -q 'treated as manual push mode' hooks/unpushed-guard.sh && grep -q 'gitflow.sh" push-mode\|gitflow.sh push-mode\|push-mode' hooks/unpushed-guard.sh && ! grep -q -- '--default true' hooks/unpushed-guard.sh && echo GUARD-OK + EXPECT: GUARD-OK + EVIDENCE: MET exit=0 marker-found :: GUARD-OK +4. No `--default true gitflow.autopush` read remains in lib/gitflow.sh or hooks/unpushed-guard.sh (the `gitflow.protect` reads keep `--default true`; `hooks/session-start.sh` is D2). shellcheck clean on lib/gitflow.sh, lib/gitflow-test.sh, hooks/unpushed-guard.sh; no new suppression; floor guard clean. + CHECK: ! grep -q -- '--default true gitflow.autopush' lib/gitflow.sh hooks/unpushed-guard.sh && shellcheck lib/gitflow.sh lib/gitflow-test.sh hooks/unpushed-guard.sh && [ "$(git diff -- lib/gitflow.sh lib/gitflow-test.sh hooks/unpushed-guard.sh lib/tests/unpushed-guard.test.sh | grep -c '^+.*shellcheck disable')" -eq 0 ] && echo SHELLCHECK-OK + EXPECT: SHELLCHECK-OK + EVIDENCE: MET exit=0 marker-found :: SHELLCHECK-OK +5. Every hermetic suite green except the declared environmental red `lib/tests/design-tool-gate.test.sh`. + CHECK: fail=0; for t in $(ls lib/tests/*.test.sh lib/seo-data/*.test.sh lib/gitflow-test.sh lib/tests/run-*.sh | grep -v design-tool-gate.test.sh); do make test suite="$t" >/dev/null 2>&1 || { fail=1; echo "RED $t"; }; done; [ $fail -eq 0 ] && echo SUITES-OK + EXPECT: SUITES-OK + EVIDENCE: MET exit=0 marker-found :: SUITES-OK +6. Judged by reading: `GITFLOW_NO_PUSH=1` semantics unchanged; `gitflow_push_mode` stdout contract unchanged; the emitted hooks remain standalone POSIX sh (no bash-isms, no lib dependency); no file outside FILE SCOPE changed except the regenerated `.githooks/{post-commit,post-merge}` and `githooks/{post-commit,post-merge}`; `pre-commit` and `reference-transaction` emitted files unchanged byte for byte; `.git/config` unchanged (hash before/after in the executor report); the `left in place` note text unchanged. + +## FILE SCOPE +lib/gitflow.sh · lib/gitflow-test.sh · hooks/unpushed-guard.sh · lib/tests/unpushed-guard.test.sh · generated: .githooks/post-commit, .githooks/post-merge, githooks/post-commit, githooks/post-merge diff --git a/.claude/tasks/contracts/2026-10-07-manual-push-guard-residuals-d2-1526.md b/.claude/tasks/contracts/2026-10-07-manual-push-guard-residuals-d2-1526.md new file mode 100644 index 0000000..005cf50 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-07-manual-push-guard-residuals-d2-1526.md @@ -0,0 +1,40 @@ +# CONTRACT — manual-push-guard-residuals-d2 (run D2 of manual-push mode) +- date: 2026-10-07 | flow: feat | branch: feature/manual-push-mode (after D1) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "ok enchaine sur le run D" +Run D as consolidated in `.claude/tasks/TODO.md`; D2 slice: "push-guard residuals (inner-quote/backslash tokens, lone-surrogate payload, `*) deny` default, up-front tool check, T42 base, literal `true` test)", session-start banner on an invalid value, tour `` quoting in hints. + +## CLARIFICATIONS +Q: single reader / A: push-guard SOURCES the lib once (absolute path resolved at the top) and calls `gitflow_push_mode` per candidate (no bash spawn per candidate); lib missing → deny with its own reason. The banner calls the verb through the existing `_gf_lib`; lib missing → no lock line. [orchestrator — revised] +Q: inner-quote/backslash tokens / A: challenge r1 — the extraction regex must capture the whole shell word (adjacent quoted and unquoted segments). A token fully enclosed in one quote pair is stripped and resolved (an inner apostrophe inside `"…"` is fine); a token that MIXES quoted and unquoted parts is DENIED (fail closed, user-gated rule for pathological commands); a backslash-escaped space in an unquoted token is unescaped deterministically (no eval) and resolved, not denied. [orchestrator — revised] +Q: unparseable payload / A: `field` fails → the raw payload is the text to scan, with the two-character JSON escapes folded to spaces, through the unchanged `is_push`; a match → static deny via the EXIT trap (mode-blind); no match → allow. Accepted limit: a `description` mentioning a push also denies on a broken payload. [orchestrator — revised] +Q: missing core tools (grep, sed, sort, head) / A: same policy as jq: one stderr warning, allow — a guard that denies every Bash call when PATH is broken makes the session unusable; PATH is not command-controlled. Documented. [orchestrator] +Q: T42 base / A: compare the deny list against `main:settings.json` (the last release; `git describe --tags` fails here because v2.0.0 is not an ancestor of the branch) instead of HEAD: "no deny entry present on main was removed" stays meaningful after the branch merges into develop. Fallback `origin/main:settings.json`; neither readable → the check prints SKIP, never FAIL. [orchestrator] + +## ACCEPTANCE CRITERIA +1. push-guard: `mode_in` reads the mode through the sourced lib verb (manual/auto/invalid + its stderr line), lib missing → deny with its own reason; the `case "$mode"` has a `*)` deny default; a dir token mixing quoted and unquoted parts → deny naming it, a fully-quoted token with an inner apostrophe or a backslash-escaped space → resolved normally; unparseable payload with push-looking raw text (JSON escapes folded) → static deny, without → allow; missing core tools → stderr warning + allow; a repo with `gitflow.autopush = true` → allow. All existing cases stay green. Locked by the suite (new cases T51–T57, incl. T52b/c, T54b/c). + CHECK: out=$(make test suite=lib/tests/push-guard.test.sh 2>&1); printf '%s' "$out" | grep -q '^FAIL' && exit 1; grep -qE 'PASS=(8[0-9]|9[0-9]|[1-9][0-9]{2}) FAIL=0' <<<"$out" && grep -q 'push-mode' hooks/push-guard.sh && ! grep -q -- '--default true' hooks/push-guard.sh && echo PUSH-GUARD-OK + EXPECT: PUSH-GUARD-OK + EVIDENCE: MET exit=0 marker-found :: PUSH-GUARD-OK +2. T42 compares the current deny list against the fresher of `origin/main` and `main` (SKIP if neither resolves; FAIL if the base deny list is empty): every entry present there is still present; the test prints `T42 base: `. + CHECK: grep -q 'T42 base' lib/tests/push-guard.test.sh && ! grep -q 'base=HEAD' lib/tests/push-guard.test.sh && grep -q 'SKIP T42' lib/tests/push-guard.test.sh && echo T42-OK + EXPECT: T42-OK + EVIDENCE: MET exit=0 marker-found :: T42-OK +3. session-start banner reads the mode through the lib verb: `manual` → existing line; `invalid` → `🔒 push : manual (autopush bad) — ! git push` (41 chars, fits the box); `auto` or lib missing → nothing. No `--default true gitflow.autopush` read left in hooks/session-start.sh or hooks/push-guard.sh (hooks/unpushed-guard.sh is D1's; the whole-hooks grep is run after D1's commit). Locked by push-guard.test.sh banner cases (T44–T46 + new T57). + CHECK: grep -q 'push-mode' hooks/session-start.sh && grep -q 'autopush bad' hooks/session-start.sh && ! grep -q -- '--default true gitflow.autopush' hooks/session-start.sh hooks/push-guard.sh && out=$(make test suite=lib/tests/push-guard.test.sh 2>&1) && ! grep -qE '^FAIL T(4[4-6]|57)' <<<"$out" && echo BANNER-OK + EXPECT: BANNER-OK + EVIDENCE: MET exit=0 marker-found :: BANNER-OK +4. skills/tour/SKILL.md: every `` inside a command or hint is double-quoted (`git -C ""`). + CHECK: [ "$(grep -c 'git -C ' skills/tour/SKILL.md)" = 0 ] && [ "$(grep -c 'git -C ""' skills/tour/SKILL.md)" -ge 3 ] && echo TOUR-OK + EXPECT: TOUR-OK + EVIDENCE: MET exit=0 marker-found :: TOUR-OK +5. shellcheck clean on hooks/push-guard.sh, hooks/session-start.sh, lib/tests/push-guard.test.sh; no new suppression; floor guard clean; doctrine citers green; every hermetic suite green except the declared environmental red. + CHECK: shellcheck hooks/push-guard.sh hooks/session-start.sh lib/tests/push-guard.test.sh && [ "$(git diff -- hooks/push-guard.sh hooks/session-start.sh lib/tests/push-guard.test.sh | grep -c '^+.*shellcheck disable')" -eq 0 ] && make test suite=lib/tests/doctrine-citers.test.sh >/dev/null 2>&1 && fail=0 && for t in $(ls lib/tests/*.test.sh lib/seo-data/*.test.sh lib/gitflow-test.sh lib/tests/run-*.sh | grep -v design-tool-gate.test.sh); do make test suite="$t" >/dev/null 2>&1 || fail=1; done && [ $fail -eq 0 ] && echo SUITES-OK + EXPECT: SUITES-OK + EVIDENCE: MET exit=0 marker-found :: SUITES-OK +6. Judged by reading: no `eval`; the strict/loose/alias regexes unchanged; the 20-token cap unchanged; `bash -n` clean; sourcing the lib brings no `set -e`/`set -o pipefail` into the hook; the header DENIED/MISSES/LIMITS list updated; no file outside FILE SCOPE; the tour example row with `~/proj/site` stays unquoted. + +## FILE SCOPE +hooks/push-guard.sh · lib/tests/push-guard.test.sh · hooks/session-start.sh · skills/tour/SKILL.md diff --git a/.claude/tasks/contracts/2026-10-07-manual-push-prose-d3-1530.md b/.claude/tasks/contracts/2026-10-07-manual-push-prose-d3-1530.md new file mode 100644 index 0000000..ebfb283 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-07-manual-push-prose-d3-1530.md @@ -0,0 +1,36 @@ +# CONTRACT — manual-push-prose-d3 (run D3 of manual-push mode) +- date: 2026-10-07 | flow: feat | branch: feature/manual-push-mode (after D1 + D2: every reader fails closed) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "ok enchaine sur le run D" +Run D as consolidated in `.claude/tasks/TODO.md`; D3 slice: skill/agent prose — drop the "until run D" caveats now that every reader fails closed, stale "COMMIT + PUSH" headings in client-handover, release-executor own version regex; then doc-sync (CHANGELOG, SETTINGS "still push on an invalid value" sentences). + +## CLARIFICATIONS +Q: heading rename "COMMIT + PUSH" / A: agents/client-handover-writer.md `## STEP 5 — COMMIT + PUSH (only if files changed)` → `## STEP 5 — COMMIT + PUSH STATE READ (only if files changed)`; skills/client-handover/SKILL.md step 4 bold label `**COMMIT + PUSH**` → `**COMMIT + PUSH STATE READ**` (the agent's own term for the sub-step; "PUSH STATE" alone could read as "push the state"). Repo-wide grep shows no other citer of either string (checked 2026-10-07: only those two lines). [orchestrator — public-name-ish label, surfaced in the final report] +Q: invalid-value wording after D1 / A: challenge r1 — the ahead count DECIDES the wording: `ahead` > 0 or unknown → "treated as manual push mode by every reader, nothing pushed"; `ahead` = 0 → "pushed anyway: a hook in this repo still fails open (stale .githooks/, refreshed next session)". The verb's stderr line is quoted verbatim (never a templated value). [orchestrator] +Q: executor version check / A: prep span only (finish's branch precondition already depends on prep), checked by reading the string, never inside a Bash command. [orchestrator — revised] +Q: D1/D2 precondition / A: the executor's first step greps for any surviving `--default true gitflow.autopush` reader; a hit → BLOCKED. [orchestrator] +Q: release-executor version check / A: SUPERSEDED by the "revised" entry below (prep span only, by reading). [orchestrator] + +## ACCEPTANCE CRITERIA +1. skills/capitalize/SKILL.md: no "until run D" text; the invalid-mode outcome is split on the ahead count in 5C and in STEP 6 (`> 0`/unknown → treated as manual by every reader, nothing pushed, user command with the `once a remote exists` qualifier when unknown; `= 0` → pushed anyway, stale fail-open hook named); the verb's stderr line is quoted verbatim; the `--no-push` ahead-0 line carries the invalid qualifier. + CHECK: [ "$(grep -c 'until run D' skills/capitalize/SKILL.md)" = 0 ] && [ "$(grep -c 'treated as manual push mode by every reader' skills/capitalize/SKILL.md)" -ge 2 ] && [ "$(grep -c 'still fails open' skills/capitalize/SKILL.md)" -ge 2 ] && [ "$(grep -c 'verb stderr line verbatim' skills/capitalize/SKILL.md)" -ge 5 ] && grep -q 'pushed anyway' skills/capitalize/SKILL.md && grep -q 'push mode `auto`, finish rc 0' skills/capitalize/SKILL.md && echo CAPITALIZE-OK + EXPECT: CAPITALIZE-OK + EVIDENCE: MET exit=0 marker-found :: CAPITALIZE-OK +2. client-handover: both labels renamed to "COMMIT + PUSH STATE READ"; the STEP 5 residual lines ("Before any commit or push", "do NOT commit, do NOT push", "Commit/push skipped") no longer imply the pipeline pushes; the skill's step 4 names the invalid value. + CHECK: grep -q 'COMMIT + PUSH STATE READ' agents/client-handover-writer.md && grep -q 'COMMIT + PUSH STATE READ' skills/client-handover/SKILL.md && [ "$(grep -h 'COMMIT + PUSH' agents/client-handover-writer.md skills/client-handover/SKILL.md | grep -vc 'COMMIT + PUSH STATE READ')" = 0 ] && ! grep -q 'Commit/push skipped' agents/client-handover-writer.md && grep -q 'invalid gitflow.autopush' skills/client-handover/SKILL.md && echo HANDOVER-OK + EXPECT: HANDOVER-OK + EVIDENCE: MET exit=0 marker-found :: HANDOVER-OK +3. agents/release-executor.md: the prep span's Input carries the format-check sentence (by reading, never in a Bash command) with the literal regex; the manual-mode line also names an invalid value. + CHECK: grep -qF '^[0-9]+\.[0-9]+\.[0-9]+$' agents/release-executor.md && grep -q 'by reading the string' agents/release-executor.md && grep -q 'invalid gitflow.autopush' agents/release-executor.md && echo EXECUTOR-OK + EXPECT: EXECUTOR-OK + EVIDENCE: MET exit=0 marker-found :: EXECUTOR-OK +4. Doctrine citers census green; floor guard clean; every hermetic suite green except the declared environmental red. + CHECK: make test suite=lib/tests/doctrine-citers.test.sh >/dev/null 2>&1 && bash ~/.claude/lib/floor-guard.sh develop -- skills/capitalize/SKILL.md skills/client-handover/SKILL.md agents/client-handover-writer.md agents/release-executor.md >/dev/null 2>&1 && fail=0 && for t in $(ls lib/tests/*.test.sh lib/seo-data/*.test.sh lib/gitflow-test.sh lib/tests/run-*.sh | grep -v design-tool-gate.test.sh); do make test suite="$t" >/dev/null 2>&1 || fail=1; done && [ $fail -eq 0 ] && echo SUITES-OK + EXPECT: SUITES-OK + EVIDENCE: MET exit=0 marker-found :: SUITES-OK +5. Judged by reading: no `git push` entered any Bash call; frontmatter and agent pins unchanged; no file outside FILE SCOPE (doc-sync handles CHANGELOG/SETTINGS afterwards, through its own gate). + +## FILE SCOPE +skills/capitalize/SKILL.md · skills/client-handover/SKILL.md · agents/client-handover-writer.md · agents/release-executor.md diff --git a/.claude/tasks/plans/2026-10-07-manual-push-failclosed-d1-1522.md b/.claude/tasks/plans/2026-10-07-manual-push-failclosed-d1-1522.md new file mode 100644 index 0000000..77e0392 --- /dev/null +++ b/.claude/tasks/plans/2026-10-07-manual-push-failclosed-d1-1522.md @@ -0,0 +1,61 @@ +# PLAN — manual-push-failclosed-d1 — REVISED r2 (3 lenses + correctness confirmation) +Contract: .claude/tasks/contracts/2026-10-07-manual-push-failclosed-d1-1522.md + +## Context +Every lib/hook reader of `gitflow.autopush` uses `git config --bool --default true … = false`. `--default` only covers a MISSING key: an unparseable value makes git die with empty output, `[ "" = false ]` is false, and the push runs — a typo silently re-enables every push on a work machine. push-guard (run B) already fails closed; the lib verb `push-mode` (run C) already prints `invalid`. D1 makes the lib, the two emitted push hooks and unpushed-guard agree: unset/true → auto, false → manual, anything else → NO push AND one stderr line naming it (the terminal user keeps a signal: today git's own `fatal: bad boolean` is that signal, and D1 must not remove it silently). `~/.claude/lib` and `~/.claude/githooks` are symlinks into this checkout: lib edits are live machine-wide at once, so tests run against the SOURCED emitter before the installed copies are regenerated, and regeneration comes last. + +## Checklist (in this order) +- [ ] lib/gitflow-test.sh FIRST — NEW isolated block after T18m (before T19): `echo "T18q — fail closed: unparseable gitflow.autopush → nothing pushes, named (BDR-114)"`; `newrepo badval; echo a>a; hookon; gitflow_init`; bare origin; `git push -q -u origin main develop`; `git config gitflow.autopush flase`. + T18q1 `gitflow_start feature bad >/dev/null 2>"$WORK/q1.err"` → local branch exists AND `! git ls-remote --exit-code --heads origin feature/bad` AND `grep -q 'not a boolean' "$WORK/q1.err"` (the verb's stderr passes through `_gitflow_push_off`). + T18q2 `echo b>b.txt; git add b.txt; git commit -q -m b 2>"$WORK/q2.err"` → `! git ls-remote --exit-code --heads origin feature/bad` AND `grep -q 'NOT pushed' "$WORK/q2.err"` (the hook names it; hooks ON via hookon — note: the installed `.githooks/` in the throwaway repo is written by `gitflow_init` from the SOURCED emitter, so this tests the new text before any regen). + T18q3 `dev_before=$(git -C "$bare" rev-parse develop)`; `gitflow_finish >/dev/null 2>&1; q_rc=$?` → `[ $q_rc -eq 0 ] && [ "$(git -C "$bare" rev-parse develop)" = "$dev_before" ] && ! git rev-parse --verify -q refs/heads/feature/bad`. + T18q4 positive control for the hook's `0:true` arm: `git config gitflow.autopush true; gitflow_start feature good; echo g>g.txt; git add g.txt; git commit -q -m g` → `[ "$(git rev-parse HEAD)" = "$(git -C "$bare" rev-parse feature/good)" ]` (tips equal: the post-commit hook pushed; `ls-remote` alone would pass from the start's push). + T18q5 POSIX-clean emitted hook: `_gitflow_emit_push_hook post-commit > "$WORK/pc.sh"` (SOURCED function, never a relative lib path from a fixture cwd); `[ -s "$WORK/pc.sh" ] && grep -qF 'case "$rc:$v"' "$WORK/pc.sh"`; then `if command -v shellcheck >/dev/null 2>&1; then chk "T18q5 emitted hook is POSIX-clean" 'shellcheck -s sh "$WORK/pc.sh"'; else ok "T18q5 skipped (no shellcheck)"; fi` (first shellcheck use in a hermetic suite → guarded). + Variables read in double-quoted assertions (no SC2034 suppression). Config writes live in the test FILE. No T18q0 (duplicate of T11b). +- [ ] lib/gitflow.sh — `_gitflow_push_off`: + ``` + # rc 0 when pushing is off: GITFLOW_NO_PUSH=1 (throwaway test repos), or + # gitflow.autopush not readable as `true`/unset — manual-push mode (false, + # human-set) AND fail closed on an unparseable value or a config read + # failure (BDR-114). The verb's stderr passes through: it names an invalid + # value and is silent for auto/manual. Single reader for the lib's push sites. + _gitflow_push_off() { + [ "${GITFLOW_NO_PUSH:-0}" = 1 ] && return 0 + [ "$(gitflow_push_mode)" != auto ] + } + ``` + Comments: line ~195 ("manual mode never deletes origin/
") → "push off (manual mode or invalid value) never deletes origin/
"; line ~206 ("skipped under GITFLOW_NO_PUSH=1, gitflow.autopush=false or no origin") → "skipped when push is off (see _gitflow_push_off) or no origin". `_gitflow_note_remote_left`'s message UNCHANGED ("manual push mode" is the doctrine name for the off state; skills/gitflow/SKILL.md:114 quotes it). +- [ ] lib/gitflow.sh — `_gitflow_emit_push_hook` heredoc: replace the two opt-out lines (`# Per-repo opt-out (no push rights on a foreign clone): git config gitflow.autopush false` / `[ "$(git config --bool --default true gitflow.autopush)" = false ] && exit 0`) with: + ``` + # Manual-push mode (human-set): git config gitflow.autopush false. Fail closed: + # an unparseable value or a config read failure also means "no push", named. + # Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4. + v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$? + case "$rc:$v" in + 0:true|1:*) ;; + 0:false) exit 0 ;; + *) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;; + esac + ``` + POSIX sh only. pre-commit and reference-transaction emitters untouched (byte for byte). +- [ ] hooks/unpushed-guard.sh — at the TOP (before `payload=$(cat …)` and before `cd "$cwd"`): `_lib="$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" 2>/dev/null && pwd)/gitflow.sh"`. Replace lines 26-29 (the four lines `raw=`, `manual=0; invalid=0`, the `manual=` test, the `invalid=` test) AND lines 76-78 (the old invalid clause) — no `invalid` variable survives (SC2034 otherwise) — with: + ``` + out=$(bash "$_lib" push-mode 2>&1); mode=${out##*$'\n'}; mode_err=${out%"$mode"} + manual=0; [ "$mode" = auto ] || manual=1 # fail closed: anything but auto + ``` + (the verb writes its stderr line BEFORE its stdout word, so the last line is the mode; no temp file, no delete). Invalid/unreadable clause (SessionStart only): `case "$mode" in invalid) msg="${msg:+$msg; }${mode_err#gitflow.sh push-mode: } — treated as manual push mode (nothing pushes); fix the value by hand" ;; manual|auto) ;; *) msg="${msg:+$msg; }push mode unreadable (lib verb printed '${mode:-nothing}') — treated as manual push mode" ;; esac` (strip the trailing newline of `mode_err`). Stop + manual=1 → silent (unchanged early exit). Header comment: "+ an unparseable value is treated as manual (fail closed, BDR-114); the mode comes from the lib verb". Functions ≤25 logic lines. +- [ ] lib/tests/unpushed-guard.test.sh — T14 rewrite (same fixture, key `flase`, one unpushed commit): T14-invalid-named → SessionStart contains `not a boolean`; T14-invalid-prefix → contains `ℹ manual push mode:`; T14-invalid-treated → contains `treated as manual`; T14-invalid-no-warn → NOT `unpushed work`; T14-invalid-stop-silent → Stop → `silent`. T15 unchanged. +- [ ] regenerate in the SAME step as the emitter edit (a SessionStart `reconcile-hooks` between the two would run `install-hook` and write a local hooks-path entry), files only, with NO config read or write of any kind: `bash lib/gitflow.sh emit-hook post-commit > .githooks/post-commit`, `… emit-hook post-merge > .githooks/post-merge`, `… emit-hook post-commit > githooks/post-commit`, `… emit-hook post-merge > githooks/post-merge` (writing into the existing files keeps mode 755). NOT `install-hook` (local config write) and NOT `global-hooks` (writes the GLOBAL config when `~/.gitconfig` lacks the hooksPath — which is the case right now: the user's gitconfig was overwritten by a dotfiles installer at 15:39 and must be restored by the user first). Evidence: `md5 -q .git/config` identical before/after; `~/.gitconfig` untouched (the executor never reads it); `git diff --stat` shows only the four hook files. If a command is refused, STOP and report; never hand-edit generated hooks. +- [ ] then run `make test suite=lib/gitflow-test.sh` again: T19a–e green = installed == emitted. + +## Edge cases +- `GITFLOW_NO_PUSH=1` still short-circuits before any mode read (T18o). +- Terminal user with a typo: every commit prints the hook's one-line stderr and pushes nothing; `gitflow start`/`finish` print the verb's line. Inside Claude: unpushed-guard names it at SessionStart; the banner shows the lock line after D2. +- Lib path for the guard resolved before any `cd` (relative invocation safe). +- Onboarded projects keep their committed fail-open `.githooks/` until a session-start `reconcile-hooks` runs there and the user commits the refresh: documented at doc-sync (CHANGELOG scope note), not solvable from this repo. +- Skills/docs still carrying "until run D" (capitalize :346/:379, CHANGELOG, SETTINGS) become stale the moment D1 lands: D3 + doc-sync follow on the same branch before merge. +- Hooks in throwaway test repos are written by `gitflow_init` from the sourced emitter → T18q runs against the NEW hook text before regeneration. + +## Disposition +- honors BDR-111/BDR-112 (fail-closed semantics chosen by the user, now every reader), BDR-095 (push every commit — unchanged in auto mode; T18b/T18q4 positive controls; a stopped push is always NAMED on stderr), LRN-114 (edit the generator → regenerate installed copies through the lib → T19 drift gate), LRN-113 (grep `--default true gitflow.autopush` across lib/ hooks/ githooks/ .githooks/ ends at zero after D1+D2), LRN-191, LRN-194, LRN-196 (read git's rc), BDR-087 (Stop stays message-only), LRN-193 (fresh confirmation after this revision). +- New BDR-114 proposed at capitalize: "every autopush reader fails closed and names the value; unset/true auto, false manual, else no push". diff --git a/.claude/tasks/plans/2026-10-07-manual-push-guard-residuals-d2-1526.md b/.claude/tasks/plans/2026-10-07-manual-push-guard-residuals-d2-1526.md new file mode 100644 index 0000000..ae75b1c --- /dev/null +++ b/.claude/tasks/plans/2026-10-07-manual-push-guard-residuals-d2-1526.md @@ -0,0 +1,35 @@ +# PLAN — manual-push-guard-residuals-d2 — REVISED r2 (3 lenses + correctness confirmation) +Contract: .claude/tasks/contracts/2026-10-07-manual-push-guard-residuals-d2-1526.md + +## Context +push-guard (run B, hardened) is live on every Bash|Monitor call (`~/.claude/hooks` is a symlink into this tree: every edit above `is_push || exit 0` runs machine-wide at once → `bash -n` after each edit). Residuals: `arg_tokens`' unquoted alternative stops at the first quote, so `cd /m/'a b'` yields `/m/` and the wrong dir is checked (fail-open toward the parent); an unparseable payload allows silently; the mode `case` has no default; missing core tools allow silently; T42 is vacuous once committed; no literal-`true` test; the banner shows nothing on an invalid value. After D1 the lib verb is the single reader: push-guard sources the lib once and calls `gitflow_push_mode` per candidate; the banner calls the verb. + +## Checklist (bash -n hooks/push-guard.sh after every edit) +- [ ] hooks/push-guard.sh + a. Top: `LIB="$(cd -P "$(dirname "${BASH_SOURCE[0]}")/../lib" 2>/dev/null && pwd)/gitflow.sh"` (absolute, before anything else). Tools: after the jq check, `for t in cat grep sed sort head; do command -v "$t" >/dev/null 2>&1 || { echo "push-guard: $t missing, guard inactive" >&2; exit 0; }; done` (jq policy; documented). + b. Payload fallback (no regex hoist, no early `static_deny` call): `unparsed=0; cmd=$(field '.tool_input.command') || { cmd=$payload; unparsed=1; }` (jq's rc is the rc of `field`; a parse failure → the raw payload becomes the text to scan). In the fold step, when `unparsed=1`, also replace the two-character JSON escapes `\n`, `\r`, `\t`, `\\` by spaces: `one=${one//\\n/ }; one=${one//\\r/ }; one=${one//\\t/ }; one=${one//\\\\/ }`. `is_push` runs unchanged on it. When `unparsed=1`, also set `bare=$one` (JSON quotes are syntax, not shell quoting: deleting every `"…"` span would blind the loose and alias regexes). Right after the EXIT trap is installed: `[ "$unparsed" = 1 ] && exit 0` → the trap emits the static deny (mode-blind, fail closed). Accepted limit (header): on a broken payload the whole JSON text is scanned, so a `description` mentioning a push also denies. + c. Source the lib once: after LIB: `# shellcheck source=/dev/null` then `if [ -r "$LIB" ]; then . "$LIB"; LIB_OK=1; else LIB_OK=0; fi` (the `source=/dev/null` directive is the only clean way to source a path variable; it is not a `disable`) (sourcing defines functions only; the CLI dispatcher runs only when executed). `mode_in `: `( cd -- "$1" 2>/dev/null || { echo "failed:cannot enter the directory"; exit 0; }; [ "$LIB_OK" = 1 ] || { echo "failed:gitflow lib missing"; exit 0; }; out=$(gitflow_push_mode 2>&1); m=${out##*$'\n'}; why=$(printf '%s\n' "$out" | grep -m1 '^gitflow.sh push-mode: ' | sed 's/^gitflow.sh push-mode: //'); case "$m" in manual|auto) echo "$m" ;; invalid) echo "invalid:${why:-unreadable}" ;; *) echo "$m" ;; esac )`. No temp file. Reason for `invalid:*`: `push-guard: ${mode#invalid:} in $dir — treated as manual push mode (fail closed). Fix the value by hand, or run it yourself: ! $cmd` (the verb's line already says "gitflow.autopush='x' is not a boolean (git rc N)" or "could not read …"). Reason for `failed:*`: `push-guard: push mode unreadable in $dir (${mode#failed:}) — push refused (fail closed). Run it yourself: ! $cmd`. + d. `case "$mode"` gains `*) deny "push-guard: unexpected push mode '$mode' in $dir — push refused (fail closed). Run it yourself: ! $cmd" ;;`. + e. Tokens: `arg_tokens`' argument alternative becomes a REPETITION of segments so adjacent quoted and unquoted parts form one shell word: `arg='(--[[:space:]]+)?((\\.|"[^"]*"|'"'"'[^'"'"']*'"'"'|[^[:space:];&|()"'"'"'`\\]+)+)'` — an escape alternative `\\.` and the backslash removed from the unquoted class, so `my\ dir` is one word (verified on BSD grep: `/W/manual/my\ dir`, `a\ b\ c`, `/a'/../b'`, `"Bob's"`). Keep the `--` optional prefix and the same `pre` class. Then a `classify_tok` step in the MAIN shell, before the 20-token cap: for each raw token — if it starts and ends with the same quote → strip that pair, then if the inner text still contains THAT same quote character → deny (mixed: `"/m"/x"/y"`, `'/u/Bob'\''s repo'`); inner quotes of the OTHER kind are fine (`"Bob's repo"`); a token not enclosed that contains any quote → deny: `push-guard: directory token $tok mixes quoted and unquoted parts — this guard refuses to interpolate it (fail closed). Quote the whole path, or run it yourself: ! $cmd`; else unescape backslashes in the unquoted token with ONE mechanism: `tok=$(printf '%s' "$tok" | sed -E 's/\\(.)/\1/g')` (BSD sed verified: `a\\b` → `a\b`, `my\ dir` → `my dir`; deterministic, no eval). Resolution and dedup unchanged after that. Drop the old `unquote` helper if `classify_tok` replaces it. + f. Header: DENIED now lists mixed-quote tokens and the case where a `cd` argument touches a closing quote followed by another quote on the line (`bash -c 'cd /x' && bash -c 'git push'` → one mixed token → denied; accepted, fail closed); MISSES drops inner-quote tokens, keeps `~`/`$VAR`/`$(…)`; add "payload jq cannot parse → raw text scanned (JSON escapes folded), static deny on a push match; grep/sed/sort/head/cat or jq missing → stderr warning, allow"; LIMITS unchanged (20 tokens). +- [ ] lib/tests/push-guard.test.sh + T51 `truerepo` fixture (key `true`) `git push` → allow. + T52 (cwd plain) `cd $WORK/auto'/../manual' && git push` (test writes the expanded `$WORK`) → deny, reason contains `mixes quoted and unquoted`. T52b (cwd plain) `cd "$WORK/manual/my dir" && git push` → deny, reason `manual push mode` (fully quoted, resolved). T52c (cwd auto) fixture dir `$WORK/auto/bob's` → `cd "$WORK/auto/bob's" && git status` → allow (no push) and `cd "$WORK/auto/bob's" && git push` → allow (auto; inner apostrophe inside a fully-quoted token is fine). + T53 (cwd plain) `cd $WORK/manual/my\ dir && git push` → deny, reason `manual push mode` (backslash unescaped, resolved). T53b (cwd plain) `cd "$WORK/manual"/sub"" && git push` → deny, reason `mixes quoted and unquoted`. + T54 unparseable payload: fixture written with `printf '%s'` holding the 6-char escape `\ud800` in `cwd`; precondition `! jq -e . <"$WORK/bad.json"` (FAIL the test if jq parses it); run from `$WORK/auto` with command `git push` → stdout contains `"permissionDecision":"deny"`, reason contains `internal error`, rc 0; T54b same broken payload with `git status` → empty stdout; T54c broken payload whose command is `git add -A\ngit push` (two-char escape) → deny. T54d broken payload whose command is `git subtree push --prefix=x origin main` → deny (loose regex must still see it: `bare=$one` when unparsed). + T55 missing core tool: shim with bash, cat, jq, git, sed, sort, head but NO grep → rc 0, empty stdout, stderr `grep missing`. + T56 lib missing: `mkdir -p "$WORK/alone/hooks" && cp "$ROOT/hooks/push-guard.sh" "$WORK/alone/hooks/"` (copy; no `$WORK/alone/lib`), run with a temporary `H="$WORK/alone/hooks/push-guard.sh"` then restore `H`, cwd manual → deny, reason `gitflow lib missing`. + T57 banner invalid: reuse the existing `banner` helper → `banner "$WORK/bad"` contains `push : manual (autopush bad)`. + T42 → base: whichever of `origin/main` / `main` resolves (`git -C "$ROOT" rev-parse -q --verify`); both → the fresher by ancestry (`merge-base --is-ancestor main origin/main` → origin/main, else main); neither → print `SKIP T42 (no main ref)` and count nothing; assert the base deny count > 0 (FAIL otherwise); print `T42 base: `. +- [ ] hooks/session-start.sh — replace the `--default true` test with: `_pm=$( [ -r "$_gf_lib" ] && bash "$_gf_lib" push-mode 2>/dev/null )` (reuse `_gf_lib`, computed at line ~52 — move its `unset` after this block); `case "$_pm" in manual) printf "│ 🔒 %-46s│\n" "push : manual (autopush=false) — ! git push" ;; invalid) printf "│ 🔒 %-46s│\n" "push : manual (autopush bad) — ! git push" ;; esac` (41 chars + 2 bytes for `—` → fits the box); `unset _pm`. Keep the byte-padding comment. +- [ ] skills/tour/SKILL.md — `git -C ` → `git -C ""` at every placeholder site (~243, 245, 248, 285); the `~/proj/site` example row stays unquoted (a quoted `~` would not expand). + +## Edge cases +- Sourcing `lib/gitflow.sh` inside the hook: functions only; `set -uo pipefail` is NOT set by sourcing (the lib sets it only in its CLI branch) — verify by reading the lib's last block; the hook keeps its own `set -u`. +- `gitflow_push_mode` inside `$(…)` in a subshell: one git call per candidate, no bash spawn (BASH_ENV irrelevant). +- Broken payload: the static deny is mode-blind by design (the mode cannot be read without a command); documented. +- Mixed-quote tokens are denied in auto mode too (user-gated fail-closed for pathological commands, run B); fully-quoted tokens with inner apostrophes and backslash-escaped spaces are resolved, not denied. +- D1 owns hooks/unpushed-guard.sh; D2 is verified after D1's commit, so AC3's `--default true` grep over hooks/ is run then (contract says so). + +## Disposition +- honors BDR-112 (fail-closed guard; user-gated pathological cases), BDR-113/BDR-114 (single reader = the verb, sourced), LRN-196 (trap exit 0 unchanged; caps; read rc), LRN-198 (quoted paths; no eval, deterministic unescape), LRN-104 (every new string locked), LRN-191, LRN-194, LRN-193 (fresh confirmation after this revision), BDR-100 (`--default true gitflow.autopush` grep across hooks/ ends at zero after D1+D2). diff --git a/.claude/tasks/plans/2026-10-07-manual-push-prose-d3-1530.md b/.claude/tasks/plans/2026-10-07-manual-push-prose-d3-1530.md new file mode 100644 index 0000000..bfb669c --- /dev/null +++ b/.claude/tasks/plans/2026-10-07-manual-push-prose-d3-1530.md @@ -0,0 +1,24 @@ +# PLAN — manual-push-prose-d3 — REVISED r2 (3 lenses + correctness confirmation) +Contract: .claude/tasks/contracts/2026-10-07-manual-push-prose-d3-1530.md + +## Context +After D1 and D2 every reader of `gitflow.autopush` in THIS checkout (lib, emitted hooks, unpushed-guard, push-guard, banner) treats an unparseable value as manual: nothing pushes, and the stop is named. Two caveats remain: (a) onboarded projects keep their committed `.githooks/` until a session-start reconcile refreshes them, so a stale per-repo hook can still push on an invalid value — the ahead count tells; (b) the soft_deny backstop names only `gitflow.autopush false` (settings.json is outside D3; TODO). The skill prose written during run C still says "the lib and hooks still push on an invalid value until run D". Two labels say "COMMIT + PUSH" although the step reads the push state. The release executor trusts the dispatcher's version regex alone. + +## Checklist +- [ ] PRECONDITION (executor's first step): `grep -l -- '--default true gitflow.autopush' lib/gitflow.sh hooks/unpushed-guard.sh hooks/session-start.sh githooks/post-commit githooks/post-merge .githooks/post-commit .githooks/post-merge` must print nothing (D1 + D2 landed); any hit → STATUS: BLOCKED, nothing edited. +- [ ] skills/capitalize/SKILL.md — line ~346 (5C invalid outcome) becomes TWO lines, both single-line bullets, placed where the one line is (still evaluated first): + `- **push mode \`invalid\`, \`ahead\` > 0 or unknown** → \`merged to develop — : treated as manual push mode by every reader, nothing pushed (origin/develop is commit(s) behind, or unknown). Fix the value by hand, then: ! git push origin develop\` (append \` once a remote exists\` when \`ahead\` is unknown).` + `- **push mode \`invalid\`, \`ahead\` = 0** → \`merged to develop — : pushed anyway, likely a stale fail-open hook (a session-start reconcile refreshes a stale .githooks/; commit the refresh) or a manual push. Fix the value by hand.\`` + Line ~379 (STEP 6 invalid closing line) becomes two matching lines: `- **invalid (merged, ahead > 0 or unknown)** → \`⚠️ + merged to develop — : treated as manual push mode by every reader, nothing pushed (origin/develop behind). Fix the value by hand, then: ! git push origin develop\` (+ \` once a remote exists\` when unknown)` and `- **invalid (merged, ahead = 0)** → \`⚠️ + merged to develop — : pushed anyway, likely a stale fail-open hook (refreshed by the next session-start reconcile; commit the refresh) or a manual push. Fix the value by hand.\``. STEP 6 is picked by the 5C result, not evaluated in order, so disambiguate the neighbours: line ~371 `**auto-persisted (5C: finish rc 0 AND \`ahead\` = 0)**` → `**auto-persisted (push mode \`auto\`, finish rc 0 AND \`ahead\` = 0)**`; line ~378 `**not on origin (merged, \`ahead\` unknown)**` → `**not on origin (push mode not \`invalid\`, merged, \`ahead\` unknown)**`. Recap line ~363: `merged, gitflow.autopush invalid ( behind)` → `merged, autopush invalid, nothing pushed ( behind) | merged, autopush invalid, pushed anyway (stale hook or manual push)`. Line ~375 (`--no-push`, `branch_ahead` = 0): add after the template, as an instruction like the :376 precedent: `With push mode \`invalid\`, replace \`(auto-push mode)\` with \`(: pushed anyway, likely a stale fail-open hook or a manual push; fix the value by hand, commit the .githooks refresh)\`.` Line ~376 (`--no-push`, `branch_ahead` > 0 or unknown): its existing `With push mode \`invalid\`, append \` gitflow.autopush= is not a boolean: fix it by hand\`` → `With push mode \`invalid\`, append \` : treated as manual push mode, nothing pushed; fix the value by hand\``. No "until run D" text remains; no templated ``: the verb's stderr line is quoted verbatim (it may say "could not read"). No period right after a `! git …` command. +- [ ] agents/client-handover-writer.md — heading `## STEP 5 — COMMIT + PUSH (only if files changed)` → `## STEP 5 — COMMIT + PUSH STATE READ (only if files changed)`. Residual push claims in the same step — the current text WRAPS across lines and carries bold markers; use the Read tool and multi-line old_strings: ~545-546 `Before any commit or push,⏎confirm this is a gitflow repo:` → `Before any commit, confirm this is a gitflow repo (the pipeline never pushes):`; ~553-554 `**do NOT commit,⏎do NOT push.**` → `**do NOT commit (and never push).**`; ~555-556 `Commit/push skipped — no gitflow model in this repo; publish the⏎listed changes manually before deploy.` → `Commit skipped — no gitflow model in this repo; publish the listed changes by hand before deploy.` (re-wrap as the file does). Line ~700 (C2-qualified "mini-commit; push state read, never assumed") stays. Verify with the Grep tool (pattern `push`), never a Bash grep carrying the push word. +- [ ] skills/client-handover/SKILL.md — step 4 label `**COMMIT + PUSH**` → `**COMMIT + PUSH STATE READ**`; in the same sentence `otherwise (manual push mode, or a hook push that failed)` → `otherwise (manual push mode, an invalid gitflow.autopush, or a hook push that failed)`. +- [ ] agents/release-executor.md — prep span, `### Input` paragraph: after "never bump it." add on its own line: `Format check only, by reading the string (never inside a Bash command): must match ^[0-9]+\.[0-9]+\.[0-9]+$ (literal regex text, single backslashes); anything else → STATUS: BLOCKED, nothing created.` (prep only: finish's existing `### Preconditions` already requires the `release/` branch that only prep creates). Lines ~80-83: `in manual push mode they stay local` → `in manual push mode, or with an invalid gitflow.autopush, they stay local` — keep `invalid gitflow.autopush` and `by reading the string` unbroken on one physical line each (line-based greps). + +## Edge cases +- Label rename: repo-wide grep for "COMMIT + PUSH" (skills, agents, lib, hooks, rules, README, USAGE, templates, CLAUDE.global.md, CHANGELOG, docs) → only the two renamed lines; in-file references are by step number. +- "Pushed anyway" diagnosis: after D1, an invalid value with `ahead` = 0 can only come from a stale per-repo hook (or a human push); the line says so instead of asserting "nothing pushes". +- Doc-sync afterwards owns: CHANGELOG `[Unreleased]` three sites ("treated as auto", "for this hook a non-boolean value reads as manual", "still push on it as auto"), SETTINGS Push discipline "still push on it as auto; only push-guard fails closed", with the stale-`.githooks/` scope note. +- TODO (outside D3): settings.json soft_deny names only `gitflow.autopush false` — add "or an unparseable value" (restriction only) in a later settings run. + +## Disposition +- honors BDR-114 (fail-closed everywhere → prose must stop saying otherwise, but never claims more than the facts: the ahead count decides), BDR-100/LRN-113 (label rename with citer grep; precondition grep for D1/D2 before any prose change), LRN-104, LRN-198 (version string checked by reading, never interpolated into a check command), BDR-042 (dispatcher decides the number; the executor only formats-checks). From 6b528dc85feda5a3a9aa4968d5f2421161441cbe Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 17:37:57 +0200 Subject: [PATCH 021/547] =?UTF-8?q?chore(memory):=20journal=20+=20TODO=20?= =?UTF-8?q?=E2=80=94=20manual-push-mode=20merged=20into=20develop=20(669db?= =?UTF-8?q?06)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 826087e..162e3da 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -574,4 +574,5 @@ rules: - /feat manual-push-mode run B (user: "enchaine"): `hooks/push-guard.sh` PreToolUse denies Claude's `git push` when autopush false/unparseable/unreadable in cwd or literal -C/cd dirs (global config counts). Challenge: 3 lenses + robustness confirm FATAL(8) → BSD sed `N` fold empty on 1 line (hook dead), AC3 oracle naming denied tokens, glob trailing ` *` matches end → bare read lost, run C needs lib verb. feater ×3 (impl 58, no-jq test 61, hardening 71: cap 20 dirs, git rc → deny, quoted cd). GATE 0 MET ×3; verifier CONFORME then ECARTS(1) → user gated fail-closed also in auto for pathological commands; security PASS ×2 (3 MEDIUM closed, 2 residual → run D). Commits a2ac018 + 6468eda on feature/manual-push-mode, UNMERGED. settings.json live: 18 deny entries, soft_deny, Bash|Monitor hook group. User probe pending: `! git push --dry-run` bypasses hooks? - /feat manual-push-mode run C (user: "enchaine"), split C1+C2. C1: lib verb `gitflow.sh push-mode` (auto|manual|invalid, value on stderr, rc 0) + T11b; /close STEP 5C `git push origin develop` REMOVED (finish has pushed develop since BDR-095; shell gate would be denied whole by push-guard, `$mode` dies between Bash calls) → finish, verb, `rev-list --count origin/develop..develop`, prose outcomes incl. finish-failure; `--no-push` line from the branch's own count. Challenge 3 lenses (1 BLOCKER) + confirm CONCERNS(3); verifier CONFORME; security PASS. C2: client-handover GO question + push block removed (hooks pushed already in auto; guard denies in manual) → PUSH STATE READ re-run before every claim, branch-name allowlist (security BLOCK(1) → fixed, PASS); release-candidate: two counts + verb, `! git push --atomic origin main develop vX`, tag gate kept for auto/0/0; tour: `-C` fact per project, suffix-aware branch, `--remotes=origin`. Verifier CONFORME ×2. Commits 5cf049d + 6104545, UNMERGED. Polish pass in flight. - /feat manual-push-mode run D (user: "enchaine"), split D1/D2/D3, 9 lenses + 3 confirmations. D1: every autopush reader fails closed AND names an invalid value (lib `_gitflow_push_off` via the verb; emitted hooks POSIX `case "$rc:$v"` + stderr line; unpushed-guard via the verb, no temp file); regen files-only via `emit-hook >` after the confirmation showed `install-hook` writes a local hooks-path and `global-hooks` writes the GLOBAL config when it lacks the value — which it did: user's dotfiles installer had overwritten `~/.gitconfig` (@USER@ placeholders, no hooksPath) + `~/.zshrc` at 15:39; user confirmed (own machine setup) and restored from the installer's backup before execution. D2: push-guard sources the lib, whole-word tokens (mixed quoting → deny), payload fallback, cap BEFORE classification (security BLOCK(1) caught the reorder: 1,600 tokens = 13 s > 10 s timeout → fixed, 20k tokens 0.13 s), T42 base main, banner `autopush bad`. D3: prose aligned (invalid outcome split on the ahead count, labels COMMIT + PUSH STATE READ, executor version check by reading). Commits 472cccb, 3c59333, 64ca0f8 on feature/manual-push-mode, UNMERGED. Residuals in TODO. +- Merge (user go "tu peux merge dans develop"): final full suite green (46 suites minus the declared env red) + Health Stack shellcheck clean on the branch tip → `gitflow finish feature manual-push-mode` → develop 669db06, pushed, branch removed local + origin. 19 commits (runs A, B, C1/C2, D1/D2/D3 + docs + memory). User answered: only pushes change; commits/branches/local merges untouched; invalid value now fail-closed everywhere. User plan: dotfiles installer prompts for `gitflow.autopush` (default false) — told them the gitconfig template also needs `core.hooksPath` (the install wiped it). Open: user probe `! git push --dry-run` under autopush=false; AC6 env red (design-tool-gate); post-run-D residuals in TODO. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index fd5102a..dfac095 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -2056,14 +2056,14 @@ dans un runner; capitalize reste main-loop. - [ ] P34 USAGE + agents/plugin-advisor.md "gstack ON/OFF", "context7 ON" vocabulary — gstack is per-profile, ctx7 is a CLI; move both together - [ ] P41 templates/settings/settings.json: `permissions.ask` entries (npx, docker rm, make deploy, psql…) inert under defaultMode auto → config fix, not doc -## manual-push-mode (2026-10-06, /feat × 3) +## manual-push-mode (2026-10-06, /feat × 3) — MERGED into develop 669db06 (2026-10-07, user go) - [x] run A — `gitflow.autopush=false` honoured by `_gitflow_push_branch`, quiet unpushed-guard, doctrine line; plan `.claude/tasks/plans/2026-10-06-manual-push-mode-1632.md` → commit 2fc8830 on feature/manual-push-mode; verifier ECARTS(1) = AC6 only (design-tool-gate env red, pre-existing on develop) → human waiver; merge human-gated - [x] run B — `hooks/push-guard.sh` PreToolUse (deny `git push` in manual mode) + 71-check test + settings.json (own hook group Bash|Monitor timeout 10; 18 write-form deny entries on the toggle; soft_deny on manual-mode pushes with no per-turn clearance; prose) + banner → a2ac018 + hardening commit; verifier CONFORME then ECARTS(1) closed by gated clarification (fail-closed cap/unenterable dir also in auto mode); security PASS ×2 - [x] run D also (closed in D2 3c59333 — push-guard residuals, security gate 2026-10-07): tokens with inner quotes/backslashes (`cd /m/'a b'`) resolve to the wrong dir → treat as unresolvable + deny or document; unparseable payload (lone surrogate) → jq fails → silent allow → grep raw payload for `push` and deny; `case "$mode"` default `*) deny`; up-front `command -v grep sed sort head jq` check; header line > 80 cols; T42 compares against HEAD (vacuous once committed) → compare against a pinned base or drop; no test sets the key to literal `true` - [x] run C (C1 5cf049d, C2 6104545; split C1: lib verb `push-mode` + T11 tests + capitalize STEP 5C + close hint, plan `.claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md`; C2: client-handover skill+agent, release-candidate STEP 6, tour rule) — skills that push on their own, gate on the mode through a NEW lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (prints auto|manual|invalid; the bare `git config … gitflow.autopush` read is denied for Claude after run B — a trailing ` *` glob also matches end-of-string): capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims - [ ] run B also: fail-CLOSED on an unparseable `gitflow.autopush` value in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks, unpushed-guard) — run A keeps fail-open for consistency with the untouched emitters (security gate MEDIUM, 2026-10-06); `--end-of-options`/`--` on refname args and `printf %q` in copy-paste hints (LOW); `gitflow_delete`: check `_gitflow_checkout_containing_base` rc before `--unset-upstream` (LOW, 2nd gate) - [x] C1/C2 polish pass → 3881f46 (verifier CONFORME, security PASS; items were: capitalize STEP 5C heading still says "(finish + push)"; :372 paragraph glued to the :371 bullet and tells the WORKING-branch path to read `origin/chore/..` (no such ref there; that path never uses the mode); on finish rc 5/2/6 calls 2-3 are skipped so a manual-mode user gets no `! git push origin develop` hint; the "unknown + manual" closing line (:377) lacks the `once a remote exists` hint present in 5C (:348); STEP 6 "auto-persisted … pushed" bullet (:371) not tied to `ahead = 0` (security MEDIUM); verb stderr: cap `raw` to 64 printable chars; T11b "default auto" relies on the Makefile's hermetic env (fine under `make test`, spurious when run bare on a global-manual machine) → export in the suite header like line 257. C2 polish (verifier non-gaps): client-handover-writer PUSH STATE READ states need explicit precedence (uncommitted/no-commits first, then no-origin, then ahead); tour STEP 3 item 5 only when a branch exists (report-only / dirty-tree rows have none); 9.7 `STATUS: BLOCKED` branch lacks the `- Push:` bullet; release-executor:85-86 line > 80 cols -- [x] ORDER constraint lifted: A + B + C all on feature/manual-push-mode; merge (human gate) then the work machine may set `gitflow.autopush false`. Still pending before relying on it at work: user probe `! git push --dry-run` in a scratch repo under autopush=false (bang commands assumed hook-free); run D below. +- [x] MERGED 669db06 (user go, final suite green, shellcheck clean). Work machine: the user's dotfiles installer will set `git config --global gitflow.autopush` with a prompt, default false; its gitconfig template must also carry `core.hooksPath = ~/.claude/githooks` (the 15:39 install wiped it). Still pending before relying on it at work: user probe `! git push --dry-run` in a scratch repo under autopush=false (bang commands assumed hook-free); run D below. - [x] run D (D1 472cccb, D2 3c59333, D3 64ca0f8 — all verifier CONFORME + security PASS; split 2026-10-07: D1 fail-closed readers — lib `_gitflow_push_off` via the verb, emitted push hooks POSIX rule + regen, unpushed-guard via the verb, plan `.claude/tasks/plans/2026-10-07-manual-push-failclosed-d1-1522.md`; D2 push-guard residuals + session-start banner on invalid + tour `` quoting; D3 skill/agent prose: drop the "until run D" caveats, stale COMMIT + PUSH headings, release-executor version regex, + doc-sync) — fail-CLOSED on an unparseable `gitflow.autopush` in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks + githooks regen, unpushed-guard) so the "invalid → lib/hooks still push" caveat in CHANGELOG/SETTINGS/skills can be removed; push-guard residuals (inner-quote/backslash tokens, lone-surrogate payload, `*) deny` default, up-front tool check, T42 base, literal `true` test); verb stderr: `LC_ALL=C` done, truncation marker + sanitizer test; client-handover: stale "COMMIT + PUSH" headings, `` quoting in tour hints; release-executor own version regex ## test hermeticity (2026-10-06, found during manual-push-mode run A) From f24682b3f386bb4ed5028ff9be941896d491be92 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 7 Oct 2026 17:45:01 +0200 Subject: [PATCH 022/547] =?UTF-8?q?chore(memory):=20BDR-112=20amendment=20?= =?UTF-8?q?=E2=80=94=20manual-push=20mode=20user-tested,=20dotfiles=20prom?= =?UTF-8?q?pt=20handed=20over?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 3 ++- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index a8a6232..4082f09 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1377,7 +1377,8 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Why**: `ask` inert under auto ([[LRN-155]]); `hooks/guard-bash.sh` withheld ([[BLK-022]]) → one narrow rule instead. Trailing ` *` glob matches end-of-string ([[LRN-194]]) → no infix rule spares the bare read → Claude loses `git config … gitflow.autopush`; hooks/lib keep it; run C gets `gitflow.sh push-mode`. Text-only guard cannot see scripts/aliases → soft_deny is the declared backstop. - **Alternatives rejected**: no-jq fallback (greps whole payload, denies in auto, untestable without shim; jq hard dep); `-C` dir unresolvable → allow (fail-open; now skipped, cwd still checked); `rev-parse` work-tree gate (drops the global key); `--default true` read (hides git failure); narrowing deny to spare the read (impossible with end-matching globs). - **Gates**: 3 lenses CONCERNS(2)/CONCERNS(5)/FATAL(7) + confirmation FATAL(8) → r2 (BSD sed, oracle naming denied tokens, read loss); feater ×3 (58 → 61 → 71 checks); GATE 0 MET ×3; verifier CONFORME, then ECARTS(1) on hardening closed by gated clarification; security PASS ×2 (3 MEDIUM closed: 20k-token flood denied in 0.15 s, git absent → deny, `bash -c 'cd … && git push'` extracted; residuals → run D). -- **Refs**: contract `.claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md`, plan `.claude/tasks/plans/2026-10-07-manual-push-guard-1003.md`, commits a2ac018 + 6468eda (feature/manual-push-mode, UNMERGED). Links [[BDR-095]], [[BDR-100]], [[LRN-069]], [[LRN-196]]. Open: user probe `! git push --dry-run` under autopush=false (bang commands assumed hook-free). +- **Refs**: contract `.claude/tasks/contracts/2026-10-07-manual-push-guard-1003.md`, plan `.claude/tasks/plans/2026-10-07-manual-push-guard-1003.md`, commits a2ac018 + 6468eda (feature/manual-push-mode, UNMERGED). Links [[BDR-095]], [[BDR-100]], [[LRN-069]], [[LRN-196]]. +- **Amendment 2026-10-07**: user probe done on their machine (`autopush=false` repo): no auto push, the bang-prefixed dry-run passes → `!` commands bypass the PreToolUse guard, design confirmed. Dotfiles installer will prompt for the key (default false) and carry `core.hooksPath` in the gitconfig template. ## BDR-113 — Skills never push; truth from `rev-list` facts, mode verb only words the reason [accepted] (2026-10-07) - **Decision**: run C of [[BDR-111]]. New lib verb `gitflow.sh push-mode` (stdout `auto|manual|invalid`, rc 0, raw value on stderr, printable ≤64 chars; ignores GITFLOW_NO_PUSH) = the one reader skills may call (bare `git config … gitflow.*` denied, [[BDR-112]]). Skills push NOTHING on their own except the release tag in auto mode on explicit go. Every "on origin / not pushed" line comes from `git rev-list --count origin/
..
` (or `
--not --remotes=origin` for the tour) read AFTER the action, in its own Bash call; the verb only words the reason (manual vs push FAILED vs invalid). Removed as redundant since BDR-095: `/close` STEP 5C `git push origin develop` (finish pushes develop itself, mode-aware since run A) and `/client-handover`'s "Push to origin now?" question + push block (hooks had pushed; push-guard denies in manual). User hints are complete `! git …` commands (`-u`, `--atomic origin main develop vX`, `-C `), branch name allowlisted `^[A-Za-z0-9._/][A-Za-z0-9._/-]*$` before any interpolation. `/release-candidate` manual/invalid or any count ≠ 0 → one user command, STOP, no question; tag gate kept for auto with both counts 0. `/tour`: one `-C` fact per project after the report commit, suffix-aware branch name, summary row `on origin | local only → cmd`. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 162e3da..d59a38e 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -575,4 +575,5 @@ rules: - /feat manual-push-mode run C (user: "enchaine"), split C1+C2. C1: lib verb `gitflow.sh push-mode` (auto|manual|invalid, value on stderr, rc 0) + T11b; /close STEP 5C `git push origin develop` REMOVED (finish has pushed develop since BDR-095; shell gate would be denied whole by push-guard, `$mode` dies between Bash calls) → finish, verb, `rev-list --count origin/develop..develop`, prose outcomes incl. finish-failure; `--no-push` line from the branch's own count. Challenge 3 lenses (1 BLOCKER) + confirm CONCERNS(3); verifier CONFORME; security PASS. C2: client-handover GO question + push block removed (hooks pushed already in auto; guard denies in manual) → PUSH STATE READ re-run before every claim, branch-name allowlist (security BLOCK(1) → fixed, PASS); release-candidate: two counts + verb, `! git push --atomic origin main develop vX`, tag gate kept for auto/0/0; tour: `-C` fact per project, suffix-aware branch, `--remotes=origin`. Verifier CONFORME ×2. Commits 5cf049d + 6104545, UNMERGED. Polish pass in flight. - /feat manual-push-mode run D (user: "enchaine"), split D1/D2/D3, 9 lenses + 3 confirmations. D1: every autopush reader fails closed AND names an invalid value (lib `_gitflow_push_off` via the verb; emitted hooks POSIX `case "$rc:$v"` + stderr line; unpushed-guard via the verb, no temp file); regen files-only via `emit-hook >` after the confirmation showed `install-hook` writes a local hooks-path and `global-hooks` writes the GLOBAL config when it lacks the value — which it did: user's dotfiles installer had overwritten `~/.gitconfig` (@USER@ placeholders, no hooksPath) + `~/.zshrc` at 15:39; user confirmed (own machine setup) and restored from the installer's backup before execution. D2: push-guard sources the lib, whole-word tokens (mixed quoting → deny), payload fallback, cap BEFORE classification (security BLOCK(1) caught the reorder: 1,600 tokens = 13 s > 10 s timeout → fixed, 20k tokens 0.13 s), T42 base main, banner `autopush bad`. D3: prose aligned (invalid outcome split on the ahead count, labels COMMIT + PUSH STATE READ, executor version check by reading). Commits 472cccb, 3c59333, 64ca0f8 on feature/manual-push-mode, UNMERGED. Residuals in TODO. - Merge (user go "tu peux merge dans develop"): final full suite green (46 suites minus the declared env red) + Health Stack shellcheck clean on the branch tip → `gitflow finish feature manual-push-mode` → develop 669db06, pushed, branch removed local + origin. 19 commits (runs A, B, C1/C2, D1/D2/D3 + docs + memory). User answered: only pushes change; commits/branches/local merges untouched; invalid value now fail-closed everywhere. User plan: dotfiles installer prompts for `gitflow.autopush` (default false) — told them the gitconfig template also needs `core.hooksPath` (the install wiped it). Open: user probe `! git push --dry-run` under autopush=false; AC6 env red (design-tool-gate); post-run-D residuals in TODO. +- User tested manual-push mode on their machine: works (no auto push under `false`, bang-prefixed dry-run passes). Prompt handed over for the dotfiles repo: gitconfig template gets `core.hooksPath = ~/.claude/githooks` + `[gitflow] autopush = @AUTOPUSH@` rendered from an install question (default false, true/false only, unrendered placeholder = render failure). BDR-112 amended. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index dfac095..c624d12 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -2063,7 +2063,7 @@ dans un runner; capitalize reste main-loop. - [x] run C (C1 5cf049d, C2 6104545; split C1: lib verb `push-mode` + T11 tests + capitalize STEP 5C + close hint, plan `.claude/tasks/plans/2026-10-07-manual-push-skills-c1-1304.md`; C2: client-handover skill+agent, release-candidate STEP 6, tour rule) — skills that push on their own, gate on the mode through a NEW lib verb `bash ~/.claude/lib/gitflow.sh push-mode` (prints auto|manual|invalid; the bare `git config … gitflow.autopush` read is denied for Claude after run B — a trailing ` *` glob also matches end-of-string): capitalize STEP 5C (`git push origin develop`), client-handover SKILL:48 + agents/client-handover-writer.md:586, release-candidate:96 + tour:273 "already on origin" claims - [ ] run B also: fail-CLOSED on an unparseable `gitflow.autopush` value in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks, unpushed-guard) — run A keeps fail-open for consistency with the untouched emitters (security gate MEDIUM, 2026-10-06); `--end-of-options`/`--` on refname args and `printf %q` in copy-paste hints (LOW); `gitflow_delete`: check `_gitflow_checkout_containing_base` rc before `--unset-upstream` (LOW, 2nd gate) - [x] C1/C2 polish pass → 3881f46 (verifier CONFORME, security PASS; items were: capitalize STEP 5C heading still says "(finish + push)"; :372 paragraph glued to the :371 bullet and tells the WORKING-branch path to read `origin/chore/..` (no such ref there; that path never uses the mode); on finish rc 5/2/6 calls 2-3 are skipped so a manual-mode user gets no `! git push origin develop` hint; the "unknown + manual" closing line (:377) lacks the `once a remote exists` hint present in 5C (:348); STEP 6 "auto-persisted … pushed" bullet (:371) not tied to `ahead = 0` (security MEDIUM); verb stderr: cap `raw` to 64 printable chars; T11b "default auto" relies on the Makefile's hermetic env (fine under `make test`, spurious when run bare on a global-manual machine) → export in the suite header like line 257. C2 polish (verifier non-gaps): client-handover-writer PUSH STATE READ states need explicit precedence (uncommitted/no-commits first, then no-origin, then ahead); tour STEP 3 item 5 only when a branch exists (report-only / dirty-tree rows have none); 9.7 `STATUS: BLOCKED` branch lacks the `- Push:` bullet; release-executor:85-86 line > 80 cols -- [x] MERGED 669db06 (user go, final suite green, shellcheck clean). Work machine: the user's dotfiles installer will set `git config --global gitflow.autopush` with a prompt, default false; its gitconfig template must also carry `core.hooksPath = ~/.claude/githooks` (the 15:39 install wiped it). Still pending before relying on it at work: user probe `! git push --dry-run` in a scratch repo under autopush=false (bang commands assumed hook-free); run D below. +- [x] MERGED 669db06 (user go, final suite green, shellcheck clean). Work machine: the user's dotfiles installer will set `git config --global gitflow.autopush` with a prompt, default false; its gitconfig template must also carry `core.hooksPath = ~/.claude/githooks` (the 15:39 install wiped it). User probe DONE 2026-10-07 (bang commands bypass the guard, no auto push under false); run D below. - [x] run D (D1 472cccb, D2 3c59333, D3 64ca0f8 — all verifier CONFORME + security PASS; split 2026-10-07: D1 fail-closed readers — lib `_gitflow_push_off` via the verb, emitted push hooks POSIX rule + regen, unpushed-guard via the verb, plan `.claude/tasks/plans/2026-10-07-manual-push-failclosed-d1-1522.md`; D2 push-guard residuals + session-start banner on invalid + tour `` quoting; D3 skill/agent prose: drop the "until run D" caveats, stale COMMIT + PUSH headings, release-executor version regex, + doc-sync) — fail-CLOSED on an unparseable `gitflow.autopush` in every reader at once (lib `_gitflow_push_off`, the two emitted push hooks + githooks regen, unpushed-guard) so the "invalid → lib/hooks still push" caveat in CHANGELOG/SETTINGS/skills can be removed; push-guard residuals (inner-quote/backslash tokens, lone-surrogate payload, `*) deny` default, up-front tool check, T42 base, literal `true` test); verb stderr: `LC_ALL=C` done, truncation marker + sanitizer test; client-handover: stale "COMMIT + PUSH" headings, `` quoting in tour hints; release-executor own version regex ## test hermeticity (2026-10-06, found during manual-push-mode run A) From b73d1b127e3adbec21d158557681177627e7a05a Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 15:25:11 +0200 Subject: [PATCH 023/547] =?UTF-8?q?chore(memory):=20model-router=20wave=20?= =?UTF-8?q?0=20=E2=80=94=20plan,=20LRN-203/204,=20BLK-029,=20journal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/blockers.md | 9 + .claude/memory/journal.md | 2 + .claude/memory/learnings.md | 9 + .claude/tasks/TODO.md | 9 + .../plans/2026-10-08-model-router-mod.md | 159 ++++++++++++++++++ 5 files changed, 188 insertions(+) create mode 100644 .claude/tasks/plans/2026-10-08-model-router-mod.md diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index cfe9f7f..cbf3a64 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -48,6 +48,7 @@ rules: | BLK-026 | 2026-10-06 | `make test` red on macOS: 13 suites, GNU-only idioms in suite + 7 libs (SIGPIPE under pipefail, `sed -i`, `wc` padding, `stat -c`, `realpath -m`, bare `timeout`, `grep -oP`) | resolved | | BLK-027 | 2026-10-06 | this machine never ran `make link`/`make plugin`: no global `core.hooksPath` → post-commit push never fired, branches landed ahead of upstream; 11 vendored skills + `~/.claude/.env` missing | resolved (link) / open (plugin) | | BLK-028 | 2026-10-06 | notify-attention on a VS Code client: bell + toast silent-degradation faults (merge of BLK-019 + BLK-020): terminalBell sound default off, ext hooks only terminals born after activation, Code muted in Windows mixer | resolved | +| BLK-029 | 2026-10-08 | Claude Code mods (2.1.294): alias → id resolution for a model set by a hook lags the Agent tool's (`sonnet` → `claude-sonnet-5`, 404); Agent tool schema refuses full ids | upstream | --- @@ -305,3 +306,11 @@ rules: - **Probe order (do FIRST, before server archaeology)**: fresh VS Code terminal, `printf '\a\a\033]777;notify;Test;hello\033\\'` → splits terminal path from client renderer; palette `Help: List Signal Sounds` → Terminal Bell preview bypasses terminal/BEL/hook/dtach/ext, isolates renderer audio in one step. - **Status**: resolved (BLK-019 2026-09-01, BLK-020 A+B 2026-09-02/03). Sources superseded by this entry; bodies kept for history. - **Reference**: `~/.claude/hooks/notify-attention.sh` header documents the setting; [[LRN-145]] terminalSequence-not-/dev/tty; silent-degradation class [[LRN-047]]; sources [[BLK-019]], [[BLK-020]]. + +## BLK-029 — Mods: model alias set by a hook resolves to a stale id (`sonnet` → `claude-sonnet-5`, 404) — 2026-10-08 +- **Friction**: model-router spike. Sub-agent routed by `agent.spawn` or `tool.call Agent` rewrite with alias `sonnet`/`haiku` → "model_not_found HTTP 404, model sent to the API: claude-sonnet-5". Same alias typed by the model in the Agent tool param → `claude-sonnet-5-5`, OK. +- **Real cause**: two alias tables in the CLI (2.1.294): the Agent tool's is current, the function-hooks path's is stale. Not an access issue (`/model` lists all four tiers; explicit haiku/sonnet dispatches answered). +- **Solution**: hooks write full ids (`claude-sonnet-5-5`, `claude-haiku-4-5-20251001`, `claude-opus-5-5`, `claude-fable-5-1`) from the mod's own table; Agent tool param rewrite stays alias-only (schema enum) → the mod sets the model at `agent.spawn`, not at the param. +- **Status**: upstream (report to anthropics/claude-code with the request id `req_011Cfppp7VFt8z2Pd3zJrpUi`); workaround in model-router. +- **Reference**: [[LRN-203]], plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`. + diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index d59a38e..739c1be 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -577,3 +577,5 @@ rules: - Merge (user go "tu peux merge dans develop"): final full suite green (46 suites minus the declared env red) + Health Stack shellcheck clean on the branch tip → `gitflow finish feature manual-push-mode` → develop 669db06, pushed, branch removed local + origin. 19 commits (runs A, B, C1/C2, D1/D2/D3 + docs + memory). User answered: only pushes change; commits/branches/local merges untouched; invalid value now fail-closed everywhere. User plan: dotfiles installer prompts for `gitflow.autopush` (default false) — told them the gitconfig template also needs `core.hooksPath` (the install wiped it). Open: user probe `! git push --dry-run` under autopush=false; AC6 env red (design-tool-gate); post-run-D residuals in TODO. - User tested manual-push mode on their machine: works (no auto push under `false`, bang-prefixed dry-run passes). Prompt handed over for the dotfiles repo: gitconfig template gets `core.hooksPath = ~/.claude/githooks` + `[gitflow] autopush = @AUTOPUSH@` rendered from an install question (default false, true/false only, unrendered placeholder = render failure). BDR-112 amended. +## 2026-10-08 +- model-router mod, wave 0 spike (user ask: one mod routes model + effort per request, replaces effort-* shifters + pins). Plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`, 4 decisions by AskUserQuestion (spike-first main-loop switch, `CLAUDE_CODE_PLUGIN_DIRS` load, migration wave 2, names model-router / route / /route), rule "pin = entry default, sub-tasks route finer". Spike in dev-mods, hot reload on: `turn.step` effort rewrite proven (transcript `effort` field is the oracle, not `CLAUDE_EFFORT`); sub-agent model at `agent.spawn` + effort per step by agentId proven; main-loop fable → sonnet-5-5/low for 3 steps then back: works, one cold-cache step per switch INTO a model, return free. Found: hook-side alias resolver stale (`sonnet` → `claude-sonnet-5`, 404; Agent tool enum resolves the same alias to 5-5) → mod writes full ids only. feature/model-router-mod open, nothing committed yet (plan + TODO + journal pending). diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index c3b2bb9..c46d9a0 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1748,3 +1748,12 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s ## LRN-202 — Reading a stderr-then-stdout verb from a hook: `out=$(cmd 2>&1)`, last line = word, prefix line = reason; no temp file; lib path absolute before any cd - **Context**: unpushed-guard plan used `2>"${TMPDIR:-/tmp}/x.$$"` + cat + rm: fail-OPEN when TMPDIR is full (`|| mode=auto`), predictable path, symlink-followable on shared /tmp, leaked on kill; `mode=$(cmd 2>&1 >/dev/null)` captures ONLY stderr. push-guard's `mktemp` variant added `set -u` trap hazards. The verb writes its stderr line BEFORE its stdout word in one process, so `${out##*$'\n'}` is the word and the `gitflow.sh push-mode:` line is the reason (select by prefix, not `head -1`: a bash startup warning could precede it). Resolve the lib path to an absolute one BEFORE the hook's `cd "$cwd"` (a relative invocation otherwise resolves into the target repo). - **Apply**: hooks never touch temp files for a one-line capture; anything but the expected word is treated as the fail-closed state, never as the default. Links [[BDR-114]], [[LRN-196]], [[LRN-199]]. + +## LRN-203 — Mod hooks: model ALIAS set by a hook resolves through stale table (`sonnet` → `claude-sonnet-5`, 404); write full ids; oracle = transcript fields, not `CLAUDE_EFFORT` +- **Context**: model-router spike 2026-10-08, CLI 2.1.294. `agent.spawn` or `tool.call Agent` param rewrite with alias `sonnet` → API got `claude-sonnet-5`, HTTP 404 model_not_found. Same alias passed by the model in the Agent tool param → `claude-sonnet-5-5`, fine. Full id `claude-sonnet-5-5` from hook → fine, every step answered by 5-5. Agent tool schema enum refuses full ids, so full ids reach API only via hooks. Effort rewrite at `turn.step` proven by transcript record field `effort` (high → medium); `CLAUDE_EFFORT` env + `perTurnEffort` stay at turn setting, blind to per-request rewrite. +- **Apply**: any mod that sets a model carries its own alias → full-id table (one place to bump per tier release). Verify routing with transcript `message.model` + record `effort`, never env vars. Links [[BDR-108]] (aliases as pins: still right at the Agent-tool call site, wrong inside hooks), [[BLK-029]]. + +## LRN-204 — Main-loop model switch mid-turn works, costs one cold-cache step on the full context per switch INTO a model; return free (per-model cache, 1 h TTL) +- **Context**: spike 2026-10-08, fable → `claude-sonnet-5-5`/low for 3 steps on ~260k context, then back. Conversation intact (tools, results, thinking blocks from another model in history: no error). First sonnet step cache_read 0 (full 260k billed), next steps 237k cached; return to fable step read 263k cached. +- **Apply**: switch the main loop only for spans long enough to amortize one uncached read of the whole context (many mechanical steps), never per tool call; short mechanical work → small-context haiku sub-agent. Haiku 4.5 window 200k: a long main loop cannot go to haiku at all. Flag off by default in model-router. Links [[LRN-203]], [[BDR-107]]. + diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index c624d12..6eb8418 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -1,5 +1,14 @@ # TODO +## 2026-10-08 — model-router mod: one mod routes model + effort per request (feature/model-router-mod) +Plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`. Decisions 2026-10-08: main-loop +model switch spike-first then flag off; load via `CLAUDE_CODE_PLUGIN_DIRS` + link.sh; +migration of shifters/pins/model-gate in wave 2 after proof; names model-router / route / /route. +- [x] W0 spike in dev-mods (hot reload): facts a-d established 2026-10-08 (plan file § Spike facts); e moved to W1.10 +- [ ] W1 core mod in `mods/model-router/` (config, route tool, /route, agents, skills, prompt rules, visibility, tests, install) +- [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs +- [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B + ## 2026-09-30 — Higgsfield pack: CLI + skills in the install process, off by default (feature/higgsfield-pack) Contract `.claude/tasks/contracts/2026-09-30-higgsfield-pack-1412.md`, spec + plan under `docs/superpowers/` (transient). Approved 2026-09-30: toggle pack off by default, two toggles, diff --git a/.claude/tasks/plans/2026-10-08-model-router-mod.md b/.claude/tasks/plans/2026-10-08-model-router-mod.md new file mode 100644 index 0000000..20f3832 --- /dev/null +++ b/.claude/tasks/plans/2026-10-08-model-router-mod.md @@ -0,0 +1,159 @@ +# PLAN — model-router mod (feature/model-router-mod) + +User ask 2026-10-08: one Claude Code mod that routes every request to the +model and effort its task deserves, main loop and sub-agents alike, declared +or automatic, configurable, loaded in every session (user scope). Replaces +the five `effort-*` shifter skills, the `effort:` / `model:` frontmatter +pins, `lib/effort-pins.txt` + `.sh` and `lib/model-gate.md` once proven. + +Decisions taken 2026-10-08 (user, AskUserQuestion): +- Main-loop MODEL switch: spike first, then behind a userConfig flag, off by + default, applied only on explicit declaration. Main-loop EFFORT always routed. +- Loading: `CLAUDE_CODE_PLUGIN_DIRS` in settings.json `env`, mod lives in the + repo under `mods/model-router/`, symlinked by link.sh. No marketplace. +- Migration: wave 2, after wave 1 is proven. Mod = single source of truth. +- Names: mod `model-router`, tool `route` (model sees `mcp__model-router__route`), + command `/route`, config `~/.claude/model-router.json`. + +## Routing rule (user, 2026-10-08): pin = entry default, sub-tasks route finer +The existing pins and `effort-*` shifters were built for this same goal with +the tools of their time; the mod replaces them (or nearly). A pin is not to +be contested one by one, but some were forced: a skill pinned to one level +does many different things inside one run. So: +- the entry pin of a skill or agent (today frontmatter / effort-pins.txt, + tomorrow the config table) = the DEFAULT route of the run, never a ceiling + or a floor; +- inside the run every sub-task routes to its own phase: declared by the + skill through the `route` tool (replaces `Skill(effort-*)` + pairing rule), + or derived by the mod (Agent dispatch → orchestrate, Skill load → its + entry phase, Read/Grep result → comprehension level, bookkeeping tail → + mechanical); +- an explicit per-call choice (Agent `model`/`effort` param, `/route`, + `ultrathink`) beats the derived phase for that span; +- wave 1 keeps the frontmatter pins as the entry defaults (the mod reads the + same values), wave 2 moves them into the config table and deletes the + frontmatter + shifters. Skills get their intra-run `route` calls in wave 2 + (the 15 `Skill(effort-*)` citers first). + +## Spike facts so far (2026-10-08) +- (a) main-loop effort rewrite at `turn.step` reaches the API: transcript + records flip `effort: high` → `medium` after a `route` call. `CLAUDE_EFFORT` + is NOT an oracle (turn-level setting); the transcript `effort` field is. +- (c) sub-agent steps are visible by `agentId`; an explicit Agent `model` + param resolves fine (sonnet → claude-sonnet-5-5, haiku → claude-haiku-4-5-20251001; + haiku steps carry `effort: undefined`, no effort on that model). +- ROOT CAUSE of the 404 (T1-T3, 2026-10-08): a model set by a hook as an + ALIAS is resolved by a stale table (`sonnet` -> `claude-sonnet-5`, 404); + the Agent tool's own enum resolves the same alias to `claude-sonnet-5-5`. + T1 param rewrite + alias: 404. T2 spawn rewrite + alias: 404. T3b spawn + rewrite + full id `claude-sonnet-5-5`: OK, every step answered by + claude-sonnet-5-5 at effort medium (turn.step by agentId also OK). + Rule for the mod: ALWAYS write full model ids from its own alias -> id + table in the config (one place to bump when a tier ships). The Agent tool + schema accepts only aliases, so full ids can only come from the hooks. + To report upstream: hook-side alias resolution lags the tool's. +- T4 main-loop model switch (fable -> claude-sonnet-5-5/low, switch on): WORKS. + Steps 11 and 12 answered by claude-sonnet-5-5 at effort low, transcript + records agree, thinking still produced (4.6 s), conversation intact (897 + messages, tools and results carried across). COST: the first step after a + switch read 0 cached tokens on a ~260k context (cache is per model), the + next step read 237k. Switching BACK to fable at step 14 read 263k cached + tokens: the fable cache survived three sonnet steps (per-model caches, + 1 h TTL), so the return is free. Every switch INTO another model pays one + cold-cache step on the full context. Consequence for the design: main-loop + model switches only for spans long enough to amortize (many mechanical + steps), never per tool call; short mechanical work goes to a haiku + sub-agent whose context is small. Flag stays off by default. +- Open: T3a (param rewrite + full id), fable/opus ids for the table, + switching back mid-turn, behavior with thinking blocks from another model + in history (no error seen), headless `-p` run. + +## Harness facts (types 2.1.292, CLI 2.1.294) +- `turn.step` (async generator) rewrites `model` and `effort` per request; + `e.agentId` set inside a sub-agent loop. Pinned: turn, index, messageCount. +- `agent.spawn` rewrites `model` (not effort); result carries `agentId`. +- `tool.call {tool:'Agent'}` sees and rewrites the call's `model` / `effort` + params; `tool.call {tool:'Skill'}` names the skill loading. +- `$.tool.register` / `$.command.register` (`immediate: true` runs mid-turn). +- `$.model.classify(text, labels)`, `$.session.usage().rateLimits`. +- Hooks run under `claude -p` too (closes the BDR-107 headless gap). +- Hook budget 10 s own code; `$` calls do not count. +- Honest limit: a hook cannot know what the NEXT request will decide to do. + Routing = declared phase (skill table, `route` tool, `/route`, prompt + rules) + conservative after-the-fact heuristics on the following step. + +## Phase table (proposal, config-driven) +| phase | model | effort | when | +|---|---|---|---| +| plan | session | xhigh | brainstorm, plan, architecture, challenge synthesis, audit verdict | +| reflect | session | high | diagnosis, reading to understand, contract, review | +| orchestrate | session | medium | between dispatches, reading a report | +| escalate | session | max | `ultrathink`, stuck loop, STOP relaunch | +| judge | opus | xhigh | dispatched challengers, analyzers, audits (BDR-076) | +| implement | sonnet | medium | code from a closed plan (feater, bugfixer, …) | +| write | sonnet | medium | docs, prose from decided content | +| verify | sonnet | xhigh | verifier, security-auditor | +| mechanical | haiku | low | cp/mv, git bookkeeping, status collection, listing | + +## Wave 0 — spike (dev-mods folder, hot reload, this session) +- [x] W0.1 minimal mod: `/route` command, `route` tool, `turn.step` logging + + rewrite, `agent.spawn` rewrite, `ultrathink` → max, spinner suffix +- [x] W0.2 `claude plugin validate` clean; type-check with the header tsconfig +- [x] W0.3 facts to establish, each with its evidence (usage.model, CLAUDE_EFFORT, + debug log): (a) effort rewrite on main loop takes effect; (b) model rewrite + on main loop mid-turn: works / breaks (thinking signatures, cache, tools); + (c) sub-agent model via spawn + effort via step by agentId; (d) `/route` + immediate mid-turn; (e) load via `CLAUDE_CODE_PLUGIN_DIRS` from settings env → moved to W1.10 +- [x] W0.4 record facts → journal + BDR draft; freeze wave 1 scope (facts in this file; registries pending user go) + +## Wave 1 — core (repo `mods/model-router/`) +- [ ] W1.1 config loader: `~/.claude/model-router.json` (phases, agents, + skills, prompt rules, defaults); schema check; `/route reload` +- [ ] W1.2 state: per-loop phase (main + agentId map), reset at `turn.start` + to the prompt-derived phase; explicit > table > heuristic +- [ ] W1.3 `route` tool + `/route [phase|show|reload|clear]` (immediate) +- [ ] W1.4 agents: `tool.call Agent` param rewrite + `agent.spawn` model + + `turn.step` effort by agentId; covers built-ins (Explore, Plan, general-purpose) +- [ ] W1.5 skills: `tool.call Skill` → phase from the skills table; any + skill load RESETS the main route to that skill's entry phase (table, + else the frontmatter `effort:` the harness just applied), so no route + declared earlier in the turn survives a skill change silently +- [ ] W1.5b single-writer bridge for the legacy shifters (user, 2026-10-08: + doublon + silent one-way conflict): `tool.call {tool:'Skill', skill: + /^effort-/}` answers WITHOUT `next` (skill text never loaded, no pairing + rule) and translates the level into a route on the calling loop; + `skill.prompt {skill:/^effort-/}` does the same for a user-typed + `/effort-max` and returns a one-line text. The 15 citers keep working + untouched until wave 2 rewrites them to `route`. Rule: every effort + change goes through the mod's state; frontmatter values are inputs. +- [ ] W1.6 prompt rules: `ultrathink` → escalate; keyword → phase (effort up + only; never a main-loop model change without declaration) +- [ ] W1.7 visibility: Spinner suffix `· /`, `$.ui.status`, + `$.ui.log` when verbose, `/route show` +- [ ] W1.8 userConfig: `mainLoopModelSwitch` (false), `verbose` (false), + `classifier` (false) +- [ ] W1.9 tests `*.test.ts` under `claude plugin test`; `claude plugin validate` +- [ ] W1.10 install: `mods/` symlink + `CLAUDE_CODE_PLUGIN_DIRS` in settings.json + env via link.sh; doctor line; README/USAGE/CHANGELOG +- [ ] W1.11 contract + GATE 0 + fresh verifier + security gate; `make test` + +## Wave 2 — migration (after wave 1 proven) +- [ ] W2.1 15 skills `Skill(effort-*)` → `route` tool calls (lib/effort-shift.md rewritten) +- [ ] W2.2 remove `skills/effort-*`, `lib/effort-pins.txt`, `lib/effort-pins.sh`, + install/update steps, `effort:` frontmatter on skills and agents +- [ ] W2.3 `lib/model-gate.md` + `lib/model-check.sh` → mod rule (reflect on a + small model → raise); census tests repointed to the config table +- [ ] W2.4 docs + CHANGELOG + registries (BDR, LRN, EVAL via effort-audit.py) + +## Wave 3 — optional +- [ ] W3.1 per-step heuristics (Read/Grep → +1 level next step; Agent return → orchestrate) +- [ ] W3.2 haiku classifier on `prompt.submit` (`$.model.classify`) +- [ ] W3.3 quota-aware downgrade from `$.session.usage().rateLimits` +- [ ] W3.4 A/B via `lib/effort-audit.py` + +## Risks +- Main-loop model switch mid-turn unproven (W0.3b decides). +- A mod bug cuts all routing at once: fail-open (`.catch` → `next(e)`), never deny. +- Two sources of truth during wave 1 (pins + mod): mod must agree with the + pins until wave 2 removes them. +- API early access: types change between releases; pin the CLI version in the README. From b721c94dcbae8167d3fc1ce36ccf2b506f2ff9e9 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 16:26:57 +0200 Subject: [PATCH 024/547] =?UTF-8?q?feat(mods):=20model-router=20mod,=20wav?= =?UTF-8?q?e=201-A=20=E2=80=94=20per-request=20model/effort=20routing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Function-hooks plugin under mods/model-router: routes effort (and, behind a flag, the model) of every main-loop request, sets built-in sub-agents' model at spawn with full ids, answers Skill(effort-*) itself (single writer, no pairing rule), exposes the route tool and /route, validates the optional ~/.claude/model-router.json. 11 plugin tests, validate + tsc clean. Contract .claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md. --- mods/model-router/.claude-plugin/plugin.json | 8 + mods/model-router/hooks/hooks.json | 1 + mods/model-router/hooks/register.test.ts | 202 +++++ mods/model-router/hooks/register.ts | 834 +++++++++++++++++++ 4 files changed, 1045 insertions(+) create mode 100644 mods/model-router/.claude-plugin/plugin.json create mode 100644 mods/model-router/hooks/hooks.json create mode 100644 mods/model-router/hooks/register.test.ts create mode 100644 mods/model-router/hooks/register.ts diff --git a/mods/model-router/.claude-plugin/plugin.json b/mods/model-router/.claude-plugin/plugin.json new file mode 100644 index 0000000..548269f --- /dev/null +++ b/mods/model-router/.claude-plugin/plugin.json @@ -0,0 +1,8 @@ +{ + "name": "model-router", + "version": "0.1.0", + "description": "Routes every model request (main loop and sub-agents) to the model and effort its phase deserves, from a user config, a route tool, /route and skill or prompt rules.", + "author": { + "name": "bchanot" + } +} diff --git a/mods/model-router/hooks/hooks.json b/mods/model-router/hooks/hooks.json new file mode 100644 index 0000000..5fcba7c --- /dev/null +++ b/mods/model-router/hooks/hooks.json @@ -0,0 +1 @@ +{ "modules": ["./register.ts"] } diff --git a/mods/model-router/hooks/register.test.ts b/mods/model-router/hooks/register.test.ts new file mode 100644 index 0000000..5c0c634 --- /dev/null +++ b/mods/model-router/hooks/register.test.ts @@ -0,0 +1,202 @@ +import { test, expect } from 'claude-code/testing' +import type { Engine } from 'claude-code/testing' +import type { On } from 'claude-code' + +/** Fires session.start so the mod loads its config and registers /route. */ +async function boot($: Engine, on: On): Promise { + on('session.start', ($, e) => ({ cwd: e.cwd })) + await $.session.start({ cwd: '/tmp', surface: null, isInteractive: false }) +} + +/** Runs `/route ` as the user would type it. */ +async function route($: Engine, args: string): Promise { + const out = await $.command.run({ + command: 'route', + args, + origin: { kind: 'composer' }, + presentation: { isFullscreen: false, columns: 80 }, + }) + return out.text ?? '' +} + +/** The `main:` line of `show`: the phases listing holds every id and level. */ +function mainLine(text: string): string { + return text.split('\n').find(l => l.startsWith('main:')) ?? '' +} + +const spawnInput = (model?: string) => ({ + tool_use_id: 't1', + prompt: 'x', + description: 'd', + subagentType: 'Explore', + provider: { plugin: 'engine', tier: 'core' as const }, + parentModel: 'claude-fable-5-1', + background: false, + fork: false, + ...(model === undefined ? {} : { model }), +}) + +test('Skill(effort-low) is answered without next, route shows low', async ( + $, on) => { + let reached = false + on('tool.call', { tool: 'Skill' }, () => { + reached = true + return { result: { success: true, commandName: 'bottom' } } + }) + await boot($, on) + const out = await $.tool.call({ tool: 'Skill', skill: 'effort-low' }) + expect(out).toMatchObject({ + result: { success: true, commandName: 'effort-low' }, + }) + expect(reached).toBe(false) + const line = mainLine(await route($, 'show')) + expect(line).toContain('skill effort-low') + expect(line).toContain('effort low') +}) + +test('route tool with phase orchestrate sets medium on main', async ( + $, on) => { + await boot($, on) + const out = await $.tool.call({ + tool: 'mcp__model-router__route', + phase: 'orchestrate', + }) + expect(out).toHaveProperty('result') + const line = mainLine(await route($, 'show')) + expect(line).toContain('model orchestrate') + expect(line).toContain('effort medium') +}) + +test('/route clear drops the route', async ($, on) => { + await boot($, on) + await $.tool.call({ tool: 'mcp__model-router__route', phase: 'plan' }) + expect(mainLine(await route($, 'show'))).toContain('model plan') + await route($, 'clear') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('/route bogus names the phases', async ($, on) => { + await boot($, on) + const text = await route($, 'bogus') + expect(text).toContain('unknown') + for (const phase of ['plan', 'judge', 'explore', 'mechanical']) { + expect(text).toContain(phase) + } +}) + +test('ultrathink in a prompt sets escalate on main', async ($, on) => { + on('prompt.submit', ($, e) => ({ text: e.text })) + await boot($, on) + await $.prompt.submit({ + text: 'ultrathink please', + wait: false, + origin: { kind: 'composer' }, + }) + expect(mainLine(await route($, 'show'))).toContain('prompt escalate') +}) + +test('/route model: alias resolved, id passed, typo refused', async ( + $, on) => { + await boot($, on) + const alias = await route($, 'model=sonnet') + expect(mainLine(alias)).toContain('claude-sonnet-5-5') + const id = await route($, 'model=claude-x-9') + expect(mainLine(id)).toContain('claude-x-9') + expect(await route($, 'model=sonet')).toContain('unknown') +}) + +test('Explore spawn gets the sonnet id; an explicit model wins', async ( + $, on) => { + const seen: (string | undefined)[] = [] + on('agent.spawn', ($, e) => { + seen.push(e.model) + return { model: e.model ?? e.parentModel, agentId: 'a1' } + }) + await boot($, on) + await $.agent.spawn(spawnInput()) + await $.agent.spawn(spawnInput('opus')) + expect(seen).toEqual(['claude-sonnet-5-5', 'opus']) +}) + +test('a sticky /route wins over a model-declared route', async ($, on) => { + await boot($, on) + await route($, 'judge') + const out = await $.tool.call({ + tool: 'mcp__model-router__route', + phase: 'mechanical', + }) + expect(JSON.stringify(out)).toContain('sticky') + expect(mainLine(await route($, 'show'))).toContain('user judge') +}) + +test('/route off makes the route tool a no-op', async ($, on) => { + await boot($, on) + await route($, 'off') + const out = await $.tool.call({ + tool: 'mcp__model-router__route', + phase: 'plan', + }) + expect(JSON.stringify(out)).toContain('off') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +type Seen = { model: string; effort: unknown } + +/** A bottom turn.step hook that records what reaches the model. */ +function recordSteps(on: On, seen: Seen[]): void { + on('turn.step', async function* ($, e) { + seen.push({ model: e.model, effort: e.effort }) + return { + turnId: e.turnId, + index: e.index, + answer: '', + toolUses: [], + stopReason: 'end_turn' as const, + usage: null, + } + }) +} + +const stepInput = (agentId?: string) => ({ + turnId: 'u1', + index: 0, + model: 'claude-fable-5-1', + effort: 'low' as const, + messageCount: 1, + ...(agentId === undefined ? {} : { agentId }), +}) + +/** Streams one turn.step to its end; the hooks run as the chunks flow. */ +async function runStep( + $: Engine, + input: ReturnType, +): Promise { + const stream = $.turn.step(input) + for await (const _chunk of stream) { + // chunks are not under test + } + await stream.result +} + +test('the main step carries the routed effort, model untouched', async ( + $, on) => { + const seen: Seen[] = [] + recordSteps(on, seen) + await boot($, on) + await $.tool.call({ tool: 'mcp__model-router__route', phase: 'plan' }) + await runStep($, stepInput()) + expect(seen).toEqual([{ model: 'claude-fable-5-1', effort: 'xhigh' }]) +}) + +test('a tabled agent steps at its table effort', async ($, on) => { + const seen: Seen[] = [] + recordSteps(on, seen) + on('agent.spawn', ($, e) => ({ + model: e.model ?? e.parentModel, + agentId: 'a1', + })) + await boot($, on) + await $.agent.spawn(spawnInput()) + await runStep($, stepInput('a1')) + expect(seen).toEqual([{ model: 'claude-fable-5-1', effort: 'medium' }]) +}) diff --git a/mods/model-router/hooks/register.ts b/mods/model-router/hooks/register.ts new file mode 100644 index 0000000..9bf4ae4 --- /dev/null +++ b/mods/model-router/hooks/register.ts @@ -0,0 +1,834 @@ +// model-router: routes each model request (main loop and sub-agents) to the +// model and effort its phase deserves. Phases, agents, skills and prompt +// rules come from DEFAULT_CONFIG, overridable by ~/.claude/model-router.json. +// 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' + +type Api = EngineInterface +type Level = 'low' | 'medium' | 'high' | 'xhigh' | 'max' +type Route = { model?: string; effort?: Level } // model: alias or full id +type PromptRule = { pattern: string; phase: string } +type Config = { + models: Record // alias -> full id + windows: Record // full id -> context window (tokens) + phases: Record + agents: Record // built-in subagentType -> phase + skills: Record // skill name -> phase + prompt: PromptRule[] + mainModelSwitch: boolean + verbose: boolean + spinner: boolean +} +type Rule = { re: RegExp; phase: string } +type Source = 'user' | 'model' | 'skill' | 'prompt' | 'slash' +type Routed = { phase: string; route: Route; source: Source } +type Loop = { + effort?: Level + model?: string // routed by the table or an in-agent call + spawnModel: string // the engine's model at spawn + frozen: boolean // fork or workflow agent: never re-modelled + explicitModel: boolean // Agent call gave a model: axis frozen + explicitEffort: boolean // Agent call gave an effort: axis frozen +} +type State = { + cfg: Config + rules: Rule[] + source: string // 'defaults' or the override path + userMain: Routed | null // /route by the user, sticky until /route clear + turnMain: Routed | null // tool, skill, slash, prompt; dropped at turn end + pendingPrompt: Routed | null // typed mid-turn, promoted next turn + loops: Map // agentId -> that loop's routing + explicitEffort: Map // Agent tool_use_id -> effort param + skillCalls: number // Skill tool calls in flight + off: boolean // /route off: every hook passes through + lastMain: string // "model/effort" of the last main step (spinner) + windowWarned: boolean // context-window warning already logged this turn +} +type Log = (text: string) => void +type StepIn = Readonly +type Plan = { model: string; effort: StepIn['effort'] } +type RouteInput = { + phase?: unknown + effort?: unknown + clear?: unknown + agentId?: string +} +type Picked = { phase: string; route: Route } + +const LEVELS: readonly Level[] = ['low', 'medium', 'high', 'xhigh', 'max'] +const MODEL_ID = /^claude-[a-z0-9.-]+$/ +const TOOL = 'mcp__model-router__route' +const EFFORT_SKILL = /^effort-(low|medium|high|xhigh|max)$/ +const OVERRIDE = '.claude/model-router.json' +const HAIKU = 'claude-haiku' + +const DEFAULT_CONFIG: Config = { + models: { + haiku: 'claude-haiku-4-5-20251001', + sonnet: 'claude-sonnet-5-5', + opus: 'claude-opus-5-5', + fable: 'claude-fable-5-1', + }, + windows: { 'claude-haiku-4-5-20251001': 200000 }, + phases: { + plan: { effort: 'xhigh' }, + reflect: { effort: 'high' }, + orchestrate: { effort: 'medium' }, + escalate: { effort: 'max' }, + judge: { model: 'opus', effort: 'xhigh' }, + implement: { model: 'sonnet', effort: 'medium' }, + write: { model: 'sonnet', effort: 'medium' }, + verify: { model: 'sonnet', effort: 'xhigh' }, + explore: { model: 'sonnet', effort: 'medium' }, + mechanical: { model: 'haiku', effort: 'low' }, + }, + // Built-ins only: repo agents keep their frontmatter pin (wave 2). + agents: { Explore: 'explore', Plan: 'judge' }, + skills: {}, + prompt: [{ pattern: '\\bultrathink\\b', phase: 'escalate' }], + mainModelSwitch: false, + verbose: false, + spinner: true, +} + +// ---- config ---------------------------------------------------------- + +const isRecord = (v: unknown): v is Record => + typeof v === 'object' && v !== null && !Array.isArray(v) +const isLevel = (v: unknown): v is Level => LEVELS.some(l => l === v) +const isFullId = (v: unknown): v is string => + typeof v === 'string' && MODEL_ID.test(v) +const hasKey = (table: object, key: string): boolean => + Object.hasOwn(table, key) + +function isModelName(models: Record, v: unknown): v is string { + return typeof v === 'string' && (hasKey(models, v) || isFullId(v)) +} + +function resolveModel(cfg: Config, name: string): string { + return hasKey(cfg.models, name) ? (cfg.models[name] ?? name) : name +} + +function phaseRoute(cfg: Config, phase: string): Route | undefined { + return hasKey(cfg.phases, phase) ? cfg.phases[phase] : undefined +} + +/** Merges a user table over a default one, dropping invalid entries. */ +function mergeTable( + base: Record, + user: unknown, + name: string, + accept: (key: string, value: unknown) => T | undefined, + log: Log, +): Record { + const out = { ...base } + if (!isRecord(user)) return out + for (const [key, value] of Object.entries(user)) { + const ok = key === '__proto__' ? undefined : accept(key, value) + if (ok === undefined) log(`model-router: config ${name}.${key} ignored`) + else out[key] = ok + } + return out +} + +const acceptModel = (_key: string, v: unknown): string | undefined => + isFullId(v) ? v : undefined + +const acceptWindow = (key: string, v: unknown): number | undefined => + isFullId(key) && typeof v === 'number' && Number.isInteger(v) && v > 0 + ? v + : undefined + +function acceptPhase(models: Record) { + return (_key: string, v: unknown): Route | undefined => { + if (!isRecord(v)) return undefined + const route: Route = {} + if (v.effort !== undefined) { + if (!isLevel(v.effort)) return undefined + route.effort = v.effort + } + if (v.model !== undefined) { + if (!isModelName(models, v.model)) return undefined + route.model = v.model + } + return route.effort || route.model ? route : undefined + } +} + +function acceptPhaseRef(phases: Record) { + return (_key: string, v: unknown): string | undefined => + typeof v === 'string' && hasKey(phases, v) ? v : undefined +} + +function compiles(pattern: string): boolean { + try { + new RegExp(pattern, 'i') + return true + } catch { + return false + } +} + +function acceptRule(phases: Record, v: unknown) { + if (!isRecord(v)) return undefined + const { pattern, phase } = v + if (typeof pattern !== 'string' || typeof phase !== 'string') return undefined + return hasKey(phases, phase) && compiles(pattern) + ? { pattern, phase } + : undefined +} + +/** A user prompt array replaces the default rules; bad rules are dropped. */ +function mergePrompt( + base: PromptRule[], + user: unknown, + phases: Record, + log: Log, +): PromptRule[] { + if (!Array.isArray(user)) return base + const rules: PromptRule[] = [] + for (const item of user as unknown[]) { + const rule = acceptRule(phases, item) + if (rule) rules.push(rule) + else log('model-router: config prompt rule ignored') + } + return rules +} + +const pickBool = (v: unknown, fallback: boolean): boolean => + typeof v === 'boolean' ? v : fallback + +/** Defaults overlaid with the user's entries, each validated first. */ +function mergeConfig(user: unknown, log: Log): Config { + const base = structuredClone(DEFAULT_CONFIG) + if (!isRecord(user)) return base + const models = mergeTable( + base.models, user.models, 'models', acceptModel, log) + const phases = mergeTable( + base.phases, user.phases, 'phases', acceptPhase(models), log) + const ref = acceptPhaseRef(phases) + return { + models, + windows: mergeTable( + base.windows, user.windows, 'windows', acceptWindow, log), + phases, + agents: mergeTable(base.agents, user.agents, 'agents', ref, log), + skills: mergeTable(base.skills, user.skills, 'skills', ref, log), + prompt: mergePrompt(base.prompt, user.prompt, phases, log), + mainModelSwitch: pickBool(user.mainModelSwitch, base.mainModelSwitch), + verbose: pickBool(user.verbose, base.verbose), + spinner: pickBool(user.spinner, base.spinner), + } +} + +async function readOverride( + $: Api, + log: Log, +): Promise<{ path: string; data: unknown } | undefined> { + try { + const home = await $.env.get('HOME') + if (!home) return undefined + const path = `${home}/${OVERRIDE}` + if (!(await $.fs.exists(path))) return undefined + return { path, data: JSON.parse(await $.fs.read(path)) } + } catch (err) { + log(`model-router: ${OVERRIDE} unreadable (${String(err)}); defaults`) + return undefined + } +} + +/** Never throws; a failed read or parse leaves the defaults. */ +async function loadConfig( + $: Api, + log: Log, +): Promise<{ cfg: Config; source: string }> { + const found = await readOverride($, log) + if (!found) return { cfg: mergeConfig(undefined, log), source: 'defaults' } + return { cfg: mergeConfig(found.data, log), source: found.path } +} + +function compileRules(cfg: Config): Rule[] { + return cfg.prompt.map(r => ({ + re: new RegExp(r.pattern, 'i'), + phase: r.phase, + })) +} + +// ---- state ----------------------------------------------------------- + +function newState(cfg: Config, source: string): State { + return { + cfg, + rules: compileRules(cfg), + source, + userMain: null, + turnMain: null, + pendingPrompt: null, + loops: new Map(), + explicitEffort: new Map(), + skillCalls: 0, + off: false, + lastMain: '', + windowWarned: false, + } +} + +/** The main loop's effective route: user /route > latest turn route. */ +const mainRoute = (st: State): Routed | null => st.userMain ?? st.turnMain + +function loopOf(st: State, agentId: string): Loop { + const known = st.loops.get(agentId) + if (known) return known + const fresh: Loop = { + spawnModel: '', + frozen: false, + explicitModel: false, + explicitEffort: false, + } + st.loops.set(agentId, fresh) + return fresh +} + +/** Writes a route on an agent loop, never on an axis given explicitly. */ +function writeLoop(loop: Loop, route: Route): void { + if (!loop.explicitEffort) loop.effort = route.effort + if (!loop.explicitModel) loop.model = route.model +} + +function clearRoutes(st: State): void { + st.userMain = null + st.turnMain = null + st.pendingPrompt = null +} + +// ---- text ------------------------------------------------------------ + +const modelText = (cfg: Config, model: string | undefined): string => + model === undefined ? '-' : resolveModel(cfg, model) + +function mainText(st: State): string { + const r = mainRoute(st) + if (!r) return 'main: session defaults' + const model = modelText(st.cfg, r.route.model) + return `main: ${r.source} ${r.phase} · model ${model} · effort ${ + r.route.effort ?? '-'}` +} + +function phasesText(cfg: Config): string { + const entries = Object.entries(cfg.phases).map(([name, r]) => + `${name}=${r.model ? resolveModel(cfg, r.model) : 'session'}/${ + r.effort ?? 'session'}`) + return `phases: ${entries.join(' ')}` +} + +function show(st: State): string { + const c = st.cfg + const flag = (b: boolean) => (b ? 'on' : 'off') + return [ + mainText(st), + `router: ${st.off ? 'off' : 'on'} · switch: ${flag(c.mainModelSwitch)} · ` + + `verbose: ${flag(c.verbose)} · spinner: ${flag(c.spinner)}`, + `live loops: ${st.loops.size}`, + phasesText(c), + `config: ${st.source}`, + ].join('\n') +} + +function statusLine(st: State): string { + const r = mainRoute(st) + const now = st.off ? 'off' : r ? `${r.source} ${r.phase}` : 'session defaults' + return `route: ${now}${st.cfg.mainModelSwitch ? ' · switch on' : ''}` +} + +const refresh = ($: Api, st: State): void => $.ui.status(statusLine(st)) + +function vlog($: Api, st: State, text: string): void { + if (st.cfg.verbose) $.ui.log(text) +} + +const unknownText = (cfg: Config, token: string): string => + `unknown token "${token}"; phases: ${Object.keys(cfg.phases).join(' ')}; ` + + `levels: ${LEVELS.join(' ')}; models: ${Object.keys(cfg.models).join(' ')} ` + + 'or a full claude-* id' + +// ---- /route command -------------------------------------------------- + +/** One token: `model=x`, `effort=y`, a bare alias, id or level. */ +function applyToken(cfg: Config, route: Route, token: string): boolean { + const eq = token.indexOf('=') + const key = eq < 0 ? '' : token.slice(0, eq) + const value = eq < 0 ? token : token.slice(eq + 1) + if (key !== '' && key !== 'model' && key !== 'effort') return false + if (key !== 'model' && isLevel(value)) route.effort = value + else if (key !== 'effort' && isModelName(cfg.models, value)) { + route.model = value + } else return false + return true +} + +function parseRoute(cfg: Config, args: string): Routed | string { + const words = args.trim().split(/\s+/) + const only = words.length === 1 ? words[0] : undefined + const named = only === undefined ? undefined : phaseRoute(cfg, only) + if (only !== undefined && named) { + return { phase: only, route: { ...named }, source: 'user' } + } + const route: Route = {} + for (const word of words) { + if (!applyToken(cfg, route, word)) return unknownText(cfg, word) + } + return { phase: 'custom', route, source: 'user' } +} + +function toggle(st: State, what: string, arg: string | undefined): string { + if (arg !== 'on' && arg !== 'off') return `usage: /route ${what} on|off` + if (what === 'switch') st.cfg.mainModelSwitch = arg === 'on' + else st.cfg.verbose = arg === 'on' + return show(st) +} + +function setUserRoute($: Api, st: State, args: string): string { + const parsed = parseRoute(st.cfg, args) + if (typeof parsed === 'string') return parsed + st.userMain = parsed + refresh($, st) + return show(st) +} + +/** (Re)loads the config into the state and re-registers the route tool. */ +async function reloadConfig($: Api, st: State): Promise { + const loaded = await loadConfig($, text => $.ui.log(text)) + st.cfg = loaded.cfg + st.rules = compileRules(loaded.cfg) + st.source = loaded.source + await registerTool($, st) +} + +async function handleCommand($: Api, st: State, args: string): Promise { + const [head = '', ...rest] = args.trim().split(/\s+/) + switch (head) { + case '': + case 'show': + return show(st) + case 'clear': + clearRoutes(st) + refresh($, st) + return 'route cleared\n' + show(st) + case 'on': + case 'off': + st.off = head === 'off' + refresh($, st) + return show(st) + case 'reload': + await reloadConfig($, st) + refresh($, st) + return 'config reloaded\n' + show(st) + case 'switch': + case 'verbose': + return toggle(st, head, rest[0]) + default: + return setUserRoute($, st, args) + } +} + +// ---- route tool ------------------------------------------------------ + +async function registerTool($: Api, st: State): Promise { + try { + await $.tool.register({ + name: 'route', + description: + 'Declare the phase of the work ahead so the next model requests ' + + 'run at the effort (and model) it deserves. Call it before a span ' + + 'of work changes nature (planning, orchestrating, mechanical ' + + 'work). It acts on the calling loop only; no model choice here. ' + + `Phases: ${Object.keys(st.cfg.phases).join(', ')}.`, + inputSchema: { + type: 'object', + properties: { + phase: { type: 'string', enum: Object.keys(st.cfg.phases) }, + effort: { type: 'string', enum: [...LEVELS] }, + clear: { type: 'boolean', description: 'drop this loop\'s route' }, + }, + }, + }) + } catch (err) { + $.ui.log(`model-router: route tool not registered: ${String(err)}`) + } +} + +async function registerCommand($: Api): Promise { + try { + await $.command.register({ + name: 'route', + description: 'model-router: show or set the model and effort route', + argumentHint: + '[show|clear|off|on|reload||model= effort=' + + '|switch on|off|verbose on|off]', + immediate: true, + }) + } catch (err) { + $.ui.log(`model-router: /route not registered: ${String(err)}`) + } +} + +function pickRoute(cfg: Config, phase: unknown, effort: unknown) { + const phases = Object.keys(cfg.phases).join(', ') + const named = typeof phase === 'string' ? phaseRoute(cfg, phase) : undefined + if (phase !== undefined && !named) { + return `unknown phase "${String(phase)}"; phases: ${phases}` + } + if (effort !== undefined && !isLevel(effort)) { + return `unknown effort "${String(effort)}"; levels: ${LEVELS.join(', ')}` + } + if (phase === undefined && effort === undefined) { + return `give a phase (${phases}), an effort, or clear` + } + const route: Route = { ...named, ...(isLevel(effort) ? { effort } : {}) } + const name = typeof phase === 'string' ? phase : `effort-${String(effort)}` + return { phase: name, route } +} + +function applyRoute(st: State, agentId: string | undefined, p: Picked): void { + if (agentId === undefined) { + st.turnMain = { phase: p.phase, route: p.route, source: 'model' } + } else { + writeLoop(loopOf(st, agentId), p.route) + } +} + +function clearLoop(st: State, agentId: string | undefined): string { + if (agentId === undefined) { + st.turnMain = null + return 'route cleared for main' + } + const loop = st.loops.get(agentId) + if (loop) writeLoop(loop, {}) + return 'route cleared for this agent' +} + +/** Truthful answer: states what the calling loop will actually do. */ +function routedText(st: State, agentId: string | undefined, p: Picked): string { + if (agentId === undefined && st.userMain) { + return `recorded ${p.phase} for this turn, but a sticky /route ` + + `${st.userMain.phase} is in force; it wins until /route clear` + } + const loop = agentId === undefined ? undefined : st.loops.get(agentId) + const effort = loop?.explicitEffort ? undefined : p.route.effort + const model = agentId === undefined && !st.cfg.mainModelSwitch + ? undefined + : loop?.explicitModel ? undefined : p.route.model + const modelNote = p.route.model && model === undefined ? ' (switch off)' : '' + return `routed ${agentId === undefined ? 'main' : 'this agent'} to ` + + `${p.phase}: effort ${effort ?? 'unchanged'}, model ` + + `${model === undefined ? 'unchanged' : resolveModel(st.cfg, model)}` + + modelNote +} + +function handleRouteTool(st: State, e: RouteInput) { + if (st.off) { + return { + result: 'model-router is off (/route on to resume); nothing routed', + } + } + if (e.clear === true) return { result: clearLoop(st, e.agentId) } + const picked = pickRoute(st.cfg, e.phase, e.effort) + if (typeof picked === 'string') return { deny: picked } + applyRoute(st, e.agentId, picked) + return { result: routedText(st, e.agentId, picked) } +} + +// ---- skills ---------------------------------------------------------- + +const skillResult = (skill: string, line: string) => ({ + result: { success: true, commandName: skill, status: 'inline' as const }, + context: [line], +}) + +/** Answers Skill(effort-) in place: one writer, the skill never loads. */ +function effortBridge(st: State, agentId: string | undefined, skill: string, + level: Level) { + if (agentId === undefined) { + const route = { ...st.turnMain?.route, effort: level } + st.turnMain = { phase: skill, route, source: 'skill' } + return skillResult(skill, st.userMain + ? `model-router: ${skill} recorded, but a sticky /route ` + + `${st.userMain.phase} is in force and wins until /route clear.` + : `model-router: effort → ${level} for this loop from the next ` + + `request on; the ${skill} skill text was not loaded.`) + } + const loop = loopOf(st, agentId) + if (loop.explicitEffort) { + return skillResult(skill, 'model-router: this agent was dispatched with ' + + 'an explicit effort; the shift does not apply.') + } + loop.effort = level + return skillResult(skill, `model-router: effort → ${level} for this ` + + `loop from the next request on; the ${skill} skill text was not loaded.`) +} + +/** A non-effort skill load: resets the loop's route, applies its table row. */ +function onSkillLoad(st: State, skill: string, agentId: string | undefined) { + const table = hasKey(st.cfg.skills, skill) ? st.cfg.skills[skill] : undefined + const route = table === undefined ? undefined : phaseRoute(st.cfg, table) + if (agentId === undefined) { + if (st.turnMain && st.turnMain.source !== 'prompt') st.turnMain = null + if (table !== undefined && route) { + st.turnMain = { phase: table, route, source: 'skill' } + } + return + } + const loop = route ? loopOf(st, agentId) : st.loops.get(agentId) + if (loop) writeLoop(loop, { effort: route?.effort }) +} + +/** A user-typed /effort-: prepends one line, args ride in the text. */ +function slashEffort(st: State, skill: string, text: string) { + const level = EFFORT_SKILL.exec(skill)?.[1] + if (!isLevel(level)) return undefined + st.turnMain = { phase: skill, route: { effort: level }, source: 'slash' } + const line = st.userMain + ? `Effort ${level} recorded; the sticky /route ${st.userMain.phase} ` + + 'wins until /route clear.' + : `Effort shifted to ${level} by model-router for this turn.` + return { text: line + '\n' + text } +} + +// ---- agents ---------------------------------------------------------- + +type SpawnIn = { + tool_use_id: string + subagentType: string + provider: { plugin: string } + model?: string + fork: boolean + workflow?: unknown +} + +/** + * The table row of a built-in agent. Known limit: provider.plugin === + * 'engine' is the best built-in test at spawn; a user agent named Explore + * in a foreign project also matches (wave 1: sonnet/medium on it). + */ +function spawnRoute(cfg: Config, e: SpawnIn, frozen: boolean) { + if (frozen || e.provider.plugin !== 'engine') return undefined + if (!hasKey(cfg.agents, e.subagentType)) return undefined + const phase = cfg.agents[e.subagentType] + return phase === undefined ? undefined : phaseRoute(cfg, phase) +} + +function trackLoop(st: State, e: SpawnIn, started: { + model: string + agentId?: string +}, route: Route | undefined, frozen: boolean): void { + const given = st.explicitEffort.get(e.tool_use_id) + st.explicitEffort.delete(e.tool_use_id) + if (started.agentId === undefined) return + st.loops.set(started.agentId, { + spawnModel: started.model, + frozen, + explicitModel: e.model !== undefined, + explicitEffort: given !== undefined, + effort: given ? undefined : route?.effort, + }) +} + +// ---- turn steps ------------------------------------------------------ + +function agentPlan(st: State, e: StepIn): Plan { + const loop = e.agentId === undefined ? undefined : st.loops.get(e.agentId) + const wanted = loop?.model + const reroute = loop && wanted !== undefined && !loop.frozen && + e.model === loop.spawnModel + return { + model: reroute ? resolveModel(st.cfg, wanted) : e.model, + effort: loop?.effort ?? e.effort, + } +} + +/** True when the context still fits the target model's known window. */ +async function windowOk($: Api, st: State, id: string): Promise { + const limit = hasKey(st.cfg.windows, id) ? st.cfg.windows[id] : undefined + if (limit === undefined) return true + let tokens: number | undefined + try { + tokens = (await $.session.usage()).context.tokens + } catch { + tokens = undefined + } + if (typeof tokens === 'number' && tokens < limit) return true + if (!st.windowWarned) { + st.windowWarned = true + $.ui.log(`model-router: no switch to ${id}: context not known to fit`) + } + return false +} + +async function mainPlan($: Api, st: State, e: StepIn): Promise { + const set = mainRoute(st) + const effort = set?.route.effort ?? e.effort + const wanted = set?.route.model + if (wanted === undefined || !st.cfg.mainModelSwitch) { + return { model: e.model, effort } + } + const id = resolveModel(st.cfg, wanted) + return { model: (await windowOk($, st, id)) ? id : e.model, effort } +} + +async function planStep($: Api, st: State, e: StepIn): Promise { + const plan = e.agentId === undefined + ? await mainPlan($, st, e) + : agentPlan(st, e) + // Haiku takes no effort: omit it rather than send a hook-set value. + return plan.model.startsWith(HAIKU) ? { ...plan, effort: undefined } : plan +} + +function withPlan(e: StepIn, plan: Plan): StepIn { + const { effort: _replaced, ...rest } = e + const base = { ...rest, model: plan.model } + return plan.effort === undefined ? base : { ...base, effort: plan.effort } +} + +function stepLog(e: StepIn, plan: Plan): string { + const id = e.agentId + const loop = id === undefined ? 'main' : `agent ${id.slice(0, 8)}` + return `step ${e.index} ${loop}: ${e.model}/${String(e.effort)} → ` + + `${plan.model}/${String(plan.effort)}` +} + +function noteMain($: Api, st: State, plan: Plan): void { + st.lastMain = `${plan.model.replace(/^claude-/, '')}/${plan.effort ?? '-'}` + refresh($, st) +} + +function endMainTurn($: Api, st: State): void { + st.turnMain = st.pendingPrompt + st.pendingPrompt = null + st.explicitEffort.clear() + st.lastMain = '' + st.windowWarned = false + refresh($, st) +} + +// ---- registration ---------------------------------------------------- + +function registerSession(on: On, st: State): void { + on('session.start', async ($, e, next) => { + await reloadConfig($, st) + await registerCommand($) + refresh($, st) + return next(e) + }).catch(($, e, next) => next(e)) + on('session.end', async ($, e, next) => { + Object.assign(st, newState(st.cfg, st.source)) + return next(e) + }).catch(($, e, next) => next(e)) + on('command.run', { command: 'route' }, async ($, e) => ({ + text: await handleCommand($, st, e.args), + })).catch(($, e, next) => ({ text: `route failed (${next.error.kind})` })) +} + +function registerRouteTool(on: On, st: State): void { + on('tool.call', { tool: TOOL }, async ($, e) => { + const out = handleRouteTool(st, e) + refresh($, st) + vlog($, st, `route ${e.agentId ?? 'main'}: ${JSON.stringify(out)}`) + return out + }).catch(($, e, next) => ({ + result: `route failed (${next.error.kind}); nothing routed`, + })) +} + +function registerSkills(on: On, st: State): void { + on('tool.call', { tool: 'Skill' }, async ($, e, next) => { + if (st.off) return next(e) + const level = EFFORT_SKILL.exec(e.skill)?.[1] + if (isLevel(level)) return effortBridge(st, e.agentId, e.skill, level) + st.skillCalls += 1 + try { + onSkillLoad(st, e.skill, e.agentId) + return await next(e) + } finally { + st.skillCalls -= 1 + } + }).catch(($, e, next) => next(e)) + on('skill.prompt', async ($, e, next) => { + if (st.off || st.skillCalls > 0) return next(e) + return slashEffort(st, e.skill, e.text) ?? next(e) + }).catch(($, e, next) => next(e)) +} + +function registerAgents(on: On, st: State): void { + on('tool.call', { tool: 'Agent' }, async ($, e, next) => { + if (!st.off && isLevel(e.effort) && typeof e.tool_use_id === 'string') { + st.explicitEffort.set(e.tool_use_id, e.effort) + } + return next(e) + }).catch(($, e, next) => next(e)) + on('agent.spawn', async ($, e, next) => { + if (st.off) return next(e) + const frozen = e.fork || e.workflow !== undefined + const route = spawnRoute(st.cfg, e, frozen) + // An explicit model param on the Agent call always wins. + const wanted = e.model === undefined ? route?.model : undefined + const started = await next(wanted === undefined + ? e + : { ...e, model: resolveModel(st.cfg, wanted) }) + if (started.deny !== undefined) return started + trackLoop(st, e, started, route, frozen) + vlog($, st, `spawn ${e.subagentType}: ${e.model ?? '-'} → ${started.model}`) + return started + }).catch(($, e, next) => next(e)) +} + +function registerTurns(on: On, st: State): void { + on('turn.step', async function* ($, e, next) { + if (st.off) return yield* next(e) + const plan = await planStep($, st, e) + const changed = plan.model !== e.model || plan.effort !== e.effort + if (e.agentId === undefined) noteMain($, st, plan) + vlog($, st, stepLog(e, plan)) + const result = yield* next(changed ? withPlan(e, plan) : e) + vlog($, st, `step ${e.index} answered by ${result.usage?.model ?? '?'}`) + return result + }).catch(async function* ($, e, next) { + return yield* next(e) + }) + on('turn.complete', async ($, e, next) => { + if (e.agentId !== undefined) st.loops.delete(e.agentId) + else endMainTurn($, st) + return next(e) + }).catch(($, e, next) => next(e)) +} + +function registerPrompt(on: On, st: State): void { + on('prompt.submit', async ($, e, next) => { + if (st.off || e.origin.kind !== 'composer') return next(e) + const rule = st.rules.find(r => r.re.test(e.text)) + const route = rule ? phaseRoute(st.cfg, rule.phase) : undefined + if (rule && route) { + const routed: Routed = { phase: rule.phase, route, source: 'prompt' } + // Typed mid-turn and asked to wait: it belongs to the NEXT turn. + if (e.turnId !== undefined && e.wait) st.pendingPrompt = routed + else st.turnMain = routed + refresh($, st) + } + return next(e) + }).catch(($, e, next) => next(e)) + on('ui.render', { component: 'Spinner' }, async ($, e, next) => { + if (st.off || !st.cfg.spinner || !st.lastMain) return next(e) + const suffix = ` · ${st.lastMain}…` + return next({ ...e, props: { ...e.props, suffix } }) + }).catch(($, e, next) => next(e)) +} + +export const register: Register = on => { + const st = newState(mergeConfig(undefined, () => undefined), 'defaults') + registerSession(on, st) + registerRouteTool(on, st) + registerSkills(on, st) + registerAgents(on, st) + registerTurns(on, st) + registerPrompt(on, st) +} From e8ca713d9e16ea9cb183a0fe2cc0c956a9bee9e5 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 16:26:57 +0200 Subject: [PATCH 025/547] chore(tasks): model-router w1a contract + plan r3 --- .../2026-10-08-model-router-w1a-1533.md | 47 +++ .../plans/2026-10-08-model-router-w1a-1533.md | 347 ++++++++++++++++++ 2 files changed, 394 insertions(+) create mode 100644 .claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md create mode 100644 .claude/tasks/plans/2026-10-08-model-router-w1a-1533.md diff --git a/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md b/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md new file mode 100644 index 0000000..9c07039 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md @@ -0,0 +1,47 @@ +# CONTRACT — model-router-w1a (wave 1-A: the mod itself) +- date: 2026-10-08 | flow: feat | branch: feature/model-router-mod +- status: active + +## REQUEST (verbatim — IMMUTABLE) +Skill args: "model-router mod, wave 1-A: the mod itself under mods/model-router/ (plugin.json, hooks.json, register.ts, config.json alias→id + phases/agents/skills/prompt tables, register.test.ts); spike code in ~/.claude/dev-mods/385f7190-70f5-4bdd-b0d8-e4566cd412fd/model-router/ is the base; plan .claude/tasks/plans/2026-10-08-model-router-mod.md W1.1-W1.9" +User (fr, same session): "go pour le registre et go sur la vague 1". Earlier framing (verbatim excerpts): "repartir correctement chaque tache au model qui lui correspond […] Il faut que l'effort aussi soit en consequence […] plus propre, plus unifier et plus automatique (meme dans la discussion courante ou d'un agent on puisse switch d'un model / effort a un autre. Et le mieux que ca soit configurable et qu'on puisse l'installer et qu'il soit actif sur toutes les session en userscope"; "Il faut un pin pour le global, mais toutes les sous taches fait pas le routage donne au model correspondant"; "si la route modifie deja les efforts, alors les skills pour changer les efforts devienne inutile mais vont quand meme etre trigger. Ca fait doublon, des token pour rien used, et peut etre meme des conflits non ?" + +## CLARIFICATIONS +Q: config.json as a 5th file? / A: no — defaults live in register.ts (`DEFAULT_CONFIG`), the optional user override is `~/.claude/model-router.json` (deep-merged); `claude plugin test` runs without fs, so the mod must work with no file at all. 4 files. [orchestrator — internal, derived from the test sandbox] +Q: userConfig (W1.8) / A: dropped for 1-A — `mainModelSwitch`, `verbose`, `spinner` are keys of the same config (one source), toggled live by `/route`. [orchestrator — internal] +Q: model ids / A: hooks always write FULL ids from `config.models` (alias → id); the Agent tool param is never rewritten (its schema accepts aliases only, and the hook-side alias resolver is stale, LRN-203 / BLK-029). [orchestrator — in-force learning] +Q: precedence / A: user `/route` (sticky until `/route clear`) > the latest turn-scoped route on main (model `route` tool, a skill load's table phase or a `Skill(effort-*)` shift, a typed `/effort-*`, a prompt rule: one slot, last writer wins; a non-effort skill load resets the slot except a prompt rule) > session settings. Explicit Agent-call `model`/`effort` params always win for that agent, for its whole run: an in-agent `route` call or `Skill(effort-*)` never touches an axis given explicitly. [orchestrator — derived from the user's "pin = entry default, sub-tasks route finer"; r3 after the confirmation challenge] +Q: verbose default / A: `verbose: false` in DEFAULT_CONFIG; for now the user wants it ON to watch the routing → after the build the orchestrator writes `~/.claude/model-router.json` with `{"verbose": true}` (user-home file, outside FILE SCOPE). [gated 2026-10-08] +Q: spinner suffix default / A: on (`spinner: true`). [gated 2026-10-08] +Q: `/route` typed by the user / A: sticky until `/route clear`, wins over model-declared routes. [gated 2026-10-08] +Q: Explore built-in / A: `explore` phase = sonnet / medium (supersedes the BDR-066 wave-3 inherit for Explore). [gated 2026-10-08] +Q: legacy `Skill(effort-*)` / A: answered by the mod without loading the skill (single writer, no pairing rule); `/effort-*` typed by the user → `skill.prompt` sets the same route and returns a one-line text. [user 2026-10-08: "doublon … conflits"] + +## ACCEPTANCE CRITERIA +1. `mods/model-router/` holds exactly `.claude-plugin/plugin.json`, `hooks/hooks.json`, `hooks/register.ts`, `hooks/register.test.ts` (the engine-laid `.claude-plugin/types/` folder and `./tsconfig.json` are ignored, never committed); `claude plugin validate` passes with no warning. + CHECK: cd mods/model-router && [ "$(find . -type f | grep -v '/.claude-plugin/types/' | grep -v '^./tsconfig.json$' | sort | tr '\n' ' ')" = "./.claude-plugin/plugin.json ./hooks/hooks.json ./hooks/register.test.ts ./hooks/register.ts " ] && out=$(claude plugin validate . 2>&1) && echo "$out" | grep -q 'Validation passed' && ! echo "$out" | grep -qi 'warning' && echo FILES-VALIDATE-OK + EXPECT: FILES-VALIDATE-OK + EVIDENCE: MET exit=0 marker-found :: FILES-VALIDATE-OK +2. Type-check clean against this build's declarations (the engine-laid copy beside the spike mod). + CHECK: T=/Users/b.chanot/.claude/dev-mods/385f7190-70f5-4bdd-b0d8-e4566cd412fd/model-router/.claude-plugin/types; W=$(mktemp -d) && printf '{"compilerOptions":{"target":"es2023","lib":["es2023"],"types":[],"module":"esnext","moduleResolution":"bundler","strict":true,"noUncheckedIndexedAccess":true,"noEmit":true,"skipLibCheck":true,"jsx":"react","jsxFactory":"h","jsxFragmentFactory":"Fragment"},"include":["%s/claude-code/index.d.ts","%s/claude-code-tools/index.d.ts","%s/hooks"]}' "$T" "$T" "$PWD/mods/model-router" > "$W/tsconfig.json" && (cd "$W" && npx --yes -p typescript@5 tsc -p tsconfig.json) && echo TSC-OK + EXPECT: TSC-OK + EVIDENCE: MET exit=0 marker-found :: TSC-OK +3. `claude plugin test mods/model-router` passes; the suite covers: (a) `Skill(effort-low)` via `$.tool.call` is answered without `next` in the Skill tool's output shape (`success`, `commandName`) and the route shows `low` on main; (b) the `route` tool with `phase: "orchestrate"` sets `medium` on main and `/route show` prints it; (c) `/route clear` drops it; (d) `/route bogus` returns an error text naming the phases; (e) a `prompt.submit` text holding `ultrathink` sets `escalate` on main; (f) `/route model=sonnet` shows `claude-sonnet-5-5`, a full id passes through, a misspelt alias is refused; (g) `agent.spawn` of `Explore` without a model param reaches the bottom with `model === 'claude-sonnet-5-5'`, and with `model: 'opus'` given the param is untouched. + CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 5; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 7 ] && echo PLUGIN-TEST-OK + EXPECT: PLUGIN-TEST-OK + EVIDENCE: MET exit=0 marker-found :: (pass) a tabled agent steps at its table effort [19.75ms] 11 pass 0 fail Ran 11 tests across 1 file. [0.47s] PLUGIN-TEST-OK +4. Hooks present, as `claude plugin validate` lists them: `session.start`, `command.run{command=route}`, `tool.call{tool=mcp__model-router__route}`, `tool.call{tool=Skill}`, `tool.call{tool=Agent}`, `skill.prompt`, `agent.spawn`, `turn.step`, `prompt.submit`, `turn.complete`, `ui.render{component=Spinner}`; every gating hook carries a fail-open `.catch` (validate prints no "gating hook without .catch"). + CHECK: cd mods/model-router && out=$(claude plugin validate . 2>&1) && for h in session.start 'command.run{command=route}' 'tool.call{tool=mcp__model-router__route}' 'tool.call{tool=Skill}' 'tool.call{tool=Agent}' skill.prompt agent.spawn turn.step prompt.submit turn.complete 'ui.render{component=Spinner}'; do echo "$out" | grep -qF -- "$h" || { echo "missing $h"; exit 1; }; done && ! echo "$out" | grep -q 'without .catch' && echo HOOKS-OK + EXPECT: HOOKS-OK + EVIDENCE: MET exit=0 marker-found :: HOOKS-OK +5. Code style: no line over 80 chars, no `any` type, no `import()`; `register.ts` imports only from `claude-code` and its own plugin files. + CHECK: cd mods/model-router/hooks && ! grep -nE '.{81,}' register.ts register.test.ts && ! grep -nE ':\s*any\b||as any\b' register.ts && ! grep -q 'import(' register.ts && [ "$(grep -cE "^import .* from '(claude-code|\./)" register.ts)" -eq "$(grep -c '^import ' register.ts)" ] && echo STYLE-OK + EXPECT: STYLE-OK + EVIDENCE: MET exit=0 marker-found :: STYLE-OK +6. Judged by reading: the mod never writes a model alias into a request (every `model` it sets at `agent.spawn` or `turn.step` passes through `resolveModel`); the Agent tool's `model`/`effort` params are never rewritten and an explicit `model` param is never overridden at spawn or at any step; an agent's model is written once, at spawn (a per-step model rewrite happens only after an in-agent `route` call and only while `e.model` still equals the spawn model); a fork (`e.fork`) and a workflow agent (`e.workflow`) are never re-modelled; every write from a sub-agent's Skill or `route` call lands on that agent's loop, never on main; main-loop model changes happen only when `mainModelSwitch` is true; a `.catch` on every gating hook fails open (pass-through or an in-place answer) so a mod failure never blocks a call; all state lives in the `register` closure and the defaults constant is never mutated; no function over 25 logic lines; the spike's `via` / `stepModel` / `agentsDefault` levers and the tool's `model` / `scope` params are gone. +Q (r2): `scope: agents` / `/route agents` / A: dropped (challenge r1, no requirement behind it; per-call Agent params and the table cover it). The route tool takes `phase`, `effort`, `clear` only. [orchestrator — simplicity] +Q (r2): agents table in wave 1 / A: built-ins only (Explore, Plan), matched for the engine provider; repo agents keep their frontmatter as the single writer until wave 2. [orchestrator — single source of truth] +Q (r2): `/route off` / A: added as the session kill switch (every hook passes through). [orchestrator — robustness] + +## FILE SCOPE +mods/model-router/.claude-plugin/plugin.json · mods/model-router/hooks/hooks.json · mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts diff --git a/.claude/tasks/plans/2026-10-08-model-router-w1a-1533.md b/.claude/tasks/plans/2026-10-08-model-router-w1a-1533.md new file mode 100644 index 0000000..dd88350 --- /dev/null +++ b/.claude/tasks/plans/2026-10-08-model-router-w1a-1533.md @@ -0,0 +1,347 @@ +# PLAN — model-router wave 1-A: the mod (dispatch-ready) — REVISED r3 + +r3 changes (confirmation pass, 4 MAJOR + minors): explicit Agent params are +frozen on the Loop and never overridden by in-agent `route`/`Skill(effort-*)`; +`pendingPrompt` honours `e.wait`; tests assert on the `main:` line of `show` +only, with full typed inputs; haiku gets `effort: undefined`; `userMain` +beats every turn route including a typed `/effort-` (the text says so); +`skill.prompt` acts only when no Skill call is in flight; route tool handles +`clear` first and answers "off" in place; `turn.step` catch is a generator; +windows keyed by resolved id; validate user entries BEFORE merging; truthful +answers; unpinned-skill reset accepted and documented. +Contract: .claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md +Wave plan + harness facts: .claude/tasks/plans/2026-10-08-model-router-mod.md +Base: the spike `~/.claude/dev-mods/385f7190-70f5-4bdd-b0d8-e4566cd412fd/model-router/hooks/register.ts` +(read it first; keep its proven hook shapes; drop its spike levers `via`, +`stepModel`, `agentsDefault`, the tool's `model`/`scope`/`mainModelSwitch` +params and the hardcoded PHASES). +API reference: `/.claude-plugin/types/claude-code/index.d.ts` (grep the +event or noun; `declare module 'claude-code/testing'` for the test kit) and +`/.claude-plugin/types/claude-code-tools/index.d.ts` (`Skill: {`, +`Agent: {`, and the Skill RESULT schema near line 5139). + +r2 changes (challenge round, 3 lenses): agents table = built-ins only; one +writer per agent model (spawn), no per-step model rewrite unless an in-agent +`route` call changed it and the engine did not fall back; every write goes +to the CALLING loop; `agentsNext` / `scope` / `/route agents` / tool `model` +dropped; Skill bridge answers in the tool's output shape; unconditional +skill-load reset (prompt route kept); config validated at load, refs +resolved once; state in the `register` closure, cloned defaults; `/route off` +kill switch; queued `ultrathink` promoted to its own turn; AC1/AC5 amended. + +## Files +- [ ] mods/model-router/.claude-plugin/plugin.json — `{ "name": "model-router", "version": "0.1.0", "description": "", "author": { "name": "bchanot" } }` +- [ ] mods/model-router/hooks/hooks.json — `{ "modules": ["./register.ts"] }` +- [ ] mods/model-router/hooks/register.ts — the hooks module (below) +- [ ] mods/model-router/hooks/register.test.ts — `claude plugin test` suite (below) +The engine lays `./tsconfig.json` and `.claude-plugin/types/` beside a loaded +mod; both are ignored by AC1 and gitignored in wave 1-B. Never commit them. + +## Config (one shape, defaults in code, optional override on disk) +```ts +type Level = 'low' | 'medium' | 'high' | 'xhigh' | 'max' +type Route = { model?: string; effort?: Level } // model = alias OR full id +type Config = { + models: Record // alias → full id + windows: Record // alias → context window (tokens) + phases: Record + agents: Record // built-in subagentType → phase name + skills: Record // skill name → phase name + prompt: { pattern: string; phase: string }[] // regex source, flag i + mainModelSwitch: boolean; verbose: boolean; spinner: boolean +} +``` +DEFAULT_CONFIG values: +- models: haiku→`claude-haiku-4-5-20251001`, sonnet→`claude-sonnet-5-5`, + opus→`claude-opus-5-5`, fable→`claude-fable-5-1`. +- windows: `claude-haiku-4-5-20251001`→200000 (keyed by FULL id; others + unknown: absent = no check). +- phases: plan {effort xhigh}, reflect {effort high}, orchestrate {effort medium}, + escalate {effort max}, judge {opus, xhigh}, implement {sonnet, medium}, + write {sonnet, medium}, verify {sonnet, xhigh}, explore {sonnet, medium}, + mechanical {haiku, low}. A phase without `model` keeps the loop's model. +- agents: Explore→explore, Plan→judge. NOTHING else in wave 1: every repo + agent keeps its frontmatter pin (the engine applies it); the pins move into + this table in wave 2, in the same change that deletes the frontmatter. +- skills: {} (wave 2 fills it). +- prompt: [{ pattern: '\\bultrathink\\b', phase: 'escalate' }]. +- mainModelSwitch false, verbose false, spinner true. (Pass B, user + 2026-10-08: verbose default off but ON for now through the override file, + spinner on, user `/route` sticky, Explore → sonnet/medium.) + +`loadConfig($, log)` → `Config` (never throws): +1. `home = await $.env.get('HOME')`; path `${home}/.claude/model-router.json`; + `$.fs.exists` then `$.fs.read`; `JSON.parse`. Any failure → the defaults. +2. `mergeConfig(D, u, log)`: FIXED merge, no recursion, VALIDATE EACH USER + ENTRY BEFORE IT REPLACES A DEFAULT (an invalid user `models.sonnet` is + dropped and the default kept, so the phases on `sonnet` stay valid): + for each table (`models`, `windows`, `phases`, `agents`, `skills`) take + `u.` only when it is a plain object, then per key: valid → over + the default, invalid → `log(...)` and keep the default. Scalars + (`mainModelSwitch`, `verbose`, `spinner`) taken only when boolean. + `prompt` taken only when an array; each rule validated or dropped. + Type guards on `unknown`, no `any`. +3. Validity rules (`log(...)` ALWAYS, not only verbose: a config error must + be seen once): + - models value: string matching `/^claude-[a-z0-9.-]+$/`; + - windows: key a full id (same regex), value a positive integer; + - phase: plain object; `effort` absent or in LEVELS; `model` absent, a + `models` key or a full id; at least one of the two; + - agents / skills value: a phase name (checked after phases merged); + - prompt rule: `{ pattern: string, phase: }` whose pattern + compiles (`new RegExp(p, 'i')` in try/catch). + Lookups use `Object.hasOwn`, never bare indexing on user keys. +4. Returns `structuredClone`d data: the defaults constant is never handed + out by reference. +`compileRules(cfg)` → `{ re: RegExp; phase: string }[]` once per load. +`resolveModel(cfg, name)`: `Object.hasOwn(cfg.models, name) ? cfg.models[name] : name`. +`isModelName(cfg, v)`: a `models` key or the full-id regex. `isLevel(v)`. + +## State — ONE object built inside `register`, passed to every helper +```ts +type Source = 'user' | 'model' | 'skill' | 'prompt' | 'slash' +type Routed = { phase: string; route: Route; source: Source } +type Loop = { + effort?: Level; model?: string // routed by the table or an in-agent call + spawnModel: string; frozen: boolean // engine's model at spawn; fork/workflow + explicitModel: boolean; explicitEffort: boolean // Agent params given → axis frozen +} +type State = { + cfg: Config; rules: Rule[] + userMain: Routed | null // /route by the user; sticky until /route clear + turnMain: Routed | null // tool / skill / prompt / slash; dropped at turn end + pendingPrompt: Routed | null // prompt rule typed mid-turn, promoted next turn + loops: Map // agentId → that loop's routing + explicitEffort: Map // Agent tool_use_id → explicit effort param + skillCalls: number // Skill tool calls in flight (hook 4 ± around next) + off: boolean // /route off: every hook passes through + lastMain: string // "model/effort" of the last main step (spinner) +} +``` +`newState(cfg)` builds it; `register` calls it once; `session.start` reloads +`cfg` + `rules` into it; `session.end` rebuilds it (`/clear` fires no +`session.start`, so sticky routes must not survive a clear). +Effective main route `mainRoute(st)`: `st.userMain ?? st.turnMain`. ONE +order, transitive: user `/route` (sticky) > the latest turn route (tool, +skill, slash, prompt all share `turnMain`; last writer wins) > session. A +typed `/effort-` while a sticky route is in force does not apply; its +text says so (hook 5). +Loop lookups: `loopOf(st, e.agentId)`; a missing entry is created on first +write as `{ spawnModel: '', frozen: false, explicitModel: false, +explicitEffort: false }`. In-agent writes (hooks 3 and 4) never set an axis +whose `explicit*` flag is true: an explicit Agent param wins for the whole +run. + +## Hooks +Rule for failures: hooks that only observe or rewrite carry +`.catch(($, e, next) => next(e))`; `turn.step` streams, so its catch is the +generator form `async function* ($, e, next) { return yield* next(e) }` (a +plain function there is a type error). The four hooks that ANSWER without `next` +(command.run, the route tool, the Skill `effort-*` bridge, `skill.prompt`) +carry a `.catch` that answers in place: `{ text: 'route failed ()' }`, +`{ result: 'route failed (); nothing routed' }`, and for the two skill +hooks `next(e)` (the skill then loads normally — a safe fallback). State is +mutated only AFTER the input validated. +1. `session.start`: `st.cfg = await loadConfig(...)`, `st.rules = compileRules`; + `registerTool($, st)` (`$.tool.register({ name: 'route', description, + inputSchema })`: properties `phase` (enum = Object.keys(st.cfg.phases)), + `effort` (enum LEVELS), `clear` (boolean); no `required`). The description + tells the model: declare the phase before a span changes nature; acts on + the calling loop only; no model choice here. `$.command.register({ name: + 'route', description, argumentHint: '[show|clear|off|on|reload|| + model= effort=|switch on|off|verbose on|off]', immediate: + true })` in try/catch (log on failure, keep going). `$.ui.status(statusLine(st))`. +2. `command.run {command:'route'}` → `{ text: handleCommand($, st, e.args) }`: + `show`/empty → `show(st)`; `clear` → userMain = turnMain = pendingPrompt = + null; `off` / `on` → st.off; `reload` → loadConfig + compileRules + + `registerTool` again (the phase enum follows the config) + 'config + reloaded' + show; `switch on|off` → cfg.mainModelSwitch; `verbose on|off`; + otherwise `parseRoute(st.cfg, args)`: a phase name, or tokens `model=` + / `effort=` / bare alias / bare level, each validated by `isModelName` + / `isLevel` → `st.userMain = { phase, route, source: 'user' }`; any + unknown token → error text listing the phases and the levels. Never + calls `next`. +3. `tool.call {tool:'mcp__model-router__route'}` → `handleRouteTool`, in + this order: (i) `st.off` → `{ result: 'model-router is off (/route on to + resume); nothing routed' }`; (ii) `clear` → main: `turnMain = null`; agent: + unset the loop's `effort`/`model` → `{ result: 'route cleared for ' }`; + (iii) validate: `phase` given and not a `phases` key → `{ deny: 'unknown + phase "

"; phases: …' }` (even with a valid `effort`); `effort` given and + not a level → deny naming the levels; neither given → deny. (iv) route = + `{ ...phases[phase], ...(effort ? { effort } : {}) }` (an explicit effort + overrides the phase's). Target = the CALLING loop: main → `turnMain = { + phase: phase ?? 'effort-' + effort, route, source: 'model' }`; agent → + `loop.effort = route.effort` unless `loop.explicitEffort`; `loop.model = + route.model` unless `loop.explicitModel` (applied at step only under the + fallback guard, never on a frozen loop). (v) Answer on the EFFECTIVE + outcome: main with a sticky `userMain` → `'recorded for this turn, + but a sticky /route is in force; it wins until /route + clear'`; otherwise `'routed to : effort , model '`, and when a model is part of + the route on main while `mainModelSwitch` is off, say `model unchanged + (switch off)`. Verbose → log. +4. `tool.call {tool:'Skill'}`: + a. `e.skill` matches `/^effort-(low|medium|high|xhigh|max)$/` → the + CALLING loop: main → `turnMain = { phase: e.skill, route: { ...st.turnMain?.route, effort }, source: 'skill' }` + (effort merged over the current turn route, last loaded wins); agent → + `loopOf(...).effort = level` unless `loop.explicitEffort` (entry created + if missing: an untabled agent's shift must still land). Answer WITHOUT + `next`, in the Skill tool's output shape (claude-code-tools ~5139; a + string result is refused and the skill would load): + `{ result: { success: true, commandName: e.skill, status: 'inline' }, + context: [] }` where `` states the effective outcome: + `'model-router: effort → for this loop from the next request on; the + effort- skill text was not loaded.'`, or when main has a sticky + `userMain`: `'model-router: effort- recorded, but a sticky /route + is in force and wins until /route clear.'`, or when the agent + axis is explicit: `'model-router: this agent was dispatched with an + explicit effort; the shift does not apply.'` + b. Any other skill: `st.skillCalls += 1` before `next(e)`, `-= 1` after + (try/finally). Main → `turnMain = null` when its source is 'model', + 'skill' or 'slash' (a 'prompt' route such as `ultrathink` stays unless + the skill has a table entry); `Object.hasOwn(cfg.skills, e.skill)` → + `turnMain = { phase, route, source: 'skill' }`. Agent → unset the loop's + non-explicit `effort`/`model`; table entry → `loop.effort = route.effort` + unless explicit (never model). Accepted change vs the legacy shifters: + loading an UNPINNED skill after a shift returns main to the harness + level (orchestrators already re-assert after a nested skill, + lib/effort-shift.md § Re-assert). Then `return next(e)`. +5. `skill.prompt {skill: /^effort-/}`: `st.skillCalls > 0` (reached through + the bridge's fallback or a Skill call) → `next(e)`. Otherwise it is a + user-typed `/effort-` (or a preload, unsupported: treated the same): + level parse; `turnMain = { phase: e.skill, route: { effort }, source: + 'slash' }`; return `{ text: + '\n' + e.text }` (prepend, never + replace: args ride in the text) where `` is `'Effort shifted to + by model-router for this turn.'` or, with a sticky `userMain`, `'Effort + recorded; the sticky /route wins until /route clear.'`. + Unknown suffix → `next(e)`. +6. `tool.call {tool:'Agent'}`: `isLevel(e.effort) && typeof e.tool_use_id === + 'string'` → `st.explicitEffort.set(e.tool_use_id, e.effort)`; always + `return next(e)` unchanged (params are never rewritten). +7. `agent.spawn`: `frozen = e.fork || e.workflow !== undefined`. Route: + `!frozen && e.provider.plugin === 'engine' && Object.hasOwn(cfg.agents, e.subagentType)` + → `cfg.phases[cfg.agents[e.subagentType]]`, else none. Model rewrite ONLY + when route?.model is set AND `e.model === undefined` (an explicit param + wins): `next({ ...e, model: resolveModel(cfg, route.model) })`, else + `next(e)`. On a non-deny result with `agentId`: `loops.set(agentId, { + spawnModel: result.model, frozen, explicitModel: e.model !== undefined, + explicitEffort: given !== undefined, effort: given ? undefined : route?.effort })` + where `given = explicitEffort.get(e.tool_use_id)` (then deleted). `model` + is NOT stored at spawn: the engine already runs the agent on it. Verbose + log `spawn : → `. Known limit, + documented in a comment: `provider.plugin === 'engine'` is the best + available test for a built-in at spawn; a user agent named `Explore` in a + foreign project would also match (wave 1 impact: sonnet/medium on it). +8. `turn.step` (async generator). `st.off` → log when verbose, `yield* next(e)`. + Agent loop (`e.agentId`): `loop = loops.get(...)`; `effort = loop?.effort ?? + e.effort`; `model = loop?.model && !loop.frozen && e.model === loop.spawnModel + ? resolveModel(cfg, loop.model) : e.model` (an engine fallback — `e.model` + differs from the spawn model — is never fought). Main: `set = mainRoute(st)`; + `effort = set?.route.effort ?? e.effort`; `model = set?.route.model && + cfg.mainModelSwitch && windowOk ? resolved : e.model`, where `resolved = + resolveModel(cfg, set.route.model)` and `windowOk` = no + `cfg.windows[resolved]` entry (windows are keyed by FULL id; the defaults + key haiku's full id) or `(await $.session.usage()).context.tokens` is a + number below it; an absent `tokens` or a failed `usage()` → no switch, + logged once per turn. If the model actually sent starts with + `claude-haiku`, send `effort: undefined` (omit it entirely; haiku takes + none and a hook-set effort on it is unproven). Main → `lastMain = + '/'`, `$.ui.status(statusLine(st))`. Verbose → + log before (`step : → `) and after (`answered by + `). `const r = yield* next(changed ? { ...e, model, effort } : e); return r`. +9. `prompt.submit`: `e.origin.kind !== 'composer'` → `next(e)`. First rule in + `st.rules` whose `re.test(e.text)` → `routed = { phase, route, source: 'prompt' }`; + `e.turnId !== undefined && e.wait` (typed mid-turn and asked to wait: it + belongs to the NEXT turn) → `st.pendingPrompt = routed`; otherwise + (idle, or delivered INTO the running turn) → `st.turnMain = routed`. + `return next(e)`. +10. `turn.complete`: `e.agentId` → `loops.delete(e.agentId)`. Main → + `turnMain = pendingPrompt; pendingPrompt = null; explicitEffort.clear(); + lastMain = ''`; `$.ui.status(statusLine(st))`. `return next(e)`. +11. `ui.render {component:'Spinner'}`: `cfg.spinner && lastMain` → + `next({ ...e, props: { ...e.props, suffix: ' · ' + lastMain + '…' } })` else `next(e)`. +12. `session.end`: `Object.assign(st, newState(st.cfg))` (keeps the loaded + config, drops every route and map). `return next(e)`. +`statusLine(st)`: `'route: ' + (st.off ? 'off' : describe(mainRoute(st)) )` +where `describe` = `' '` or `'session defaults'`, plus +`' · switch on'` when `cfg.mainModelSwitch`. +`show(st)`: main (effective, with its source), off/on, switch, verbose, +spinner, live loops count, phases as `name=/` +(resolved ids printed, so a wrong `models` entry is visible), config source +line (`defaults` or the override path). + +## Tests (register.test.ts, `import { test, expect } from 'claude-code/testing'`) +Read the kit's declarations first (`declare module 'claude-code/testing'`): +`test(name, async ($, on) => …)`; events are fired as calls on `$` with the +event's FULL input (the kit's `$` is `EngineCall = (e: Args)`, and +AC2 type-checks the test file): `$.command.run({ command: 'route', args: +'show', origin: { kind: 'composer' }, presentation: })`, `$.prompt.submit({ text: 'ultrathink please', wait: false, +origin: { kind: 'composer' } })`, `$.agent.spawn({ tool_use_id: 't1', +prompt: 'x', description: 'd', subagentType: 'Explore', provider: { plugin: +'engine', tier: 'core' }, parentModel: 'claude-fable-5-1', background: false, +fork: false })`, `$.tool.call({ tool: 'Skill', skill: 'effort-low' })`. Read +each input type and fill every required field; never relax a test to dodge +a type. Establish from the kit whether `session.start` fires at load; if +not, fire `$.session.start(...)` first in every test. An event whose hook +calls `next` needs a BOTTOM hook registered by the test through its `on` +(the kit's bottom throws otherwise), e.g. `on('prompt.submit', ($, e) => ({ +text: e.text }))`, `on('agent.spawn', ($, e) => ({ model: e.model, agentId: +'a1' }))`. A helper `mainLine(text)` returns the `main:` line of `show`; +EVERY assertion on a route reads that line only (the phases listing always +contains every id and level, so matching the whole text proves nothing). +Tests (one per contract item 3a-3g): +- 3a `Skill(effort-low)` via `$.tool.call`: resolves with `result.success === + true` and `result.commandName === 'effort-low'`; a bottom `on('tool.call', + { tool: 'Skill' })` registered by the test is NOT reached (flag); `mainLine` + contains `skill effort-low` and `low`. +- 3b route tool `{ phase: 'orchestrate' }` → `mainLine` contains `model + orchestrate` and `medium`. +- 3c `/route clear` → `mainLine` contains `session defaults`. +- 3d `/route bogus` → text contains `unknown` and every phase name. +- 3e `$.prompt.submit` with `ultrathink`, `wait: false`, no `turnId` → + `mainLine` contains `prompt escalate`. +- 3f `/route model=sonnet` → `mainLine` contains `claude-sonnet-5-5`; `/route + model=claude-x-9` → `mainLine` contains `claude-x-9`; `/route model=sonet` → + text contains `unknown`. +- 3g spawn path: `$.agent.spawn(...)` for `Explore` without `model`, bottom + hook captures `e.model === 'claude-sonnet-5-5'`; with `model: 'opus'` given + → captured `e.model === 'opus'`. +No fs, network or process in tests: the defaults path is the one exercised. + +## Edge cases +- `$.command.register` throws when `/route` is taken → log, keep the tool. +- `loadConfig` never throws out of `session.start`; invalid entries dropped with a log. +- `/clear` → `session.end` rebuilds the state; `/route reload` re-registers the tool. +- Remote agents raise no `turn.complete`; denied Agent calls never spawn: both + maps are bounded by `explicitEffort.clear()` at main turn end and `loops` + entries only for started agents (a leak of a few entries per turn is accepted). +- `loops.delete` at an agent's `turn.complete`: a resumed agent (SendMessage, + woken teammate) runs its later turns at the engine's effort. Accepted in + wave 1 (built-ins only); revisit with the pins in wave 2. +- Spawn-vs-first-step race: the loop entry is set after `next(e)` resolves, + so step 0 of a tabled built-in may run at the engine's effort. Accepted in + wave 1 (Explore/Plan only); wave 2 verifies the ordering before pins move. +- Unpinned agents (general-purpose, interviewer, client-handover-writer) no + longer inherit a shifted level: the bridge does not move the harness + level. Accepted: BDR-077 already requires explicit call-site params for + built-ins; the two inline-load agents run on main's own route. +- The word `any` must not appear as a TypeScript type in register.ts + (AC5 greps `: any`, ``, `as any`). + +## Disposition (STEP 0.6) +- honors BDR-066/076/077 (tiers): wave 1 touches only the two built-ins that + carry no pin (Explore sonnet/medium, Plan opus/xhigh); every repo agent + keeps its frontmatter as the single writer; explicit call-site params win. +- honors BDR-107/108: levels and aliases unchanged; aliases stay the config's + vocabulary, full ids are resolved by the mod (LRN-203, BLK-029). +- LRN-180/181 made moot: the bridge answers `Skill(effort-*)` itself, no + pairing rule. "Last loaded wins" holds among pinned skills and shifts; the + one behaviour change, accepted: loading an UNPINNED skill after a shift + returns main to the harness level (orchestrators re-assert after nested + skills already, lib/effort-shift.md § Re-assert). +- LRN-204: main-loop model switch behind `mainModelSwitch` (default false) and + a context-window guard. +- BDR-044 not contradicted: the mod routes model/effort, never skills. +- Deferred (minor, challenge r1): a ceiling on model-declared efforts; the + spawn-vs-step race. From 6dc2d748fccffa667c612dca63633958c02a233d Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 16:27:43 +0200 Subject: [PATCH 026/547] =?UTF-8?q?chore(memory):=20journal=20+=20TODO=20?= =?UTF-8?q?=E2=80=94=20model-router=20wave=201-A=20done,=20hardening=20+?= =?UTF-8?q?=201-B=20queued?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 739c1be..5e77116 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -579,3 +579,4 @@ rules: ## 2026-10-08 - model-router mod, wave 0 spike (user ask: one mod routes model + effort per request, replaces effort-* shifters + pins). Plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`, 4 decisions by AskUserQuestion (spike-first main-loop switch, `CLAUDE_CODE_PLUGIN_DIRS` load, migration wave 2, names model-router / route / /route), rule "pin = entry default, sub-tasks route finer". Spike in dev-mods, hot reload on: `turn.step` effort rewrite proven (transcript `effort` field is the oracle, not `CLAUDE_EFFORT`); sub-agent model at `agent.spawn` + effort per step by agentId proven; main-loop fable → sonnet-5-5/low for 3 steps then back: works, one cold-cache step per switch INTO a model, return free. Found: hook-side alias resolver stale (`sonnet` → `claude-sonnet-5`, 404; Agent tool enum resolves the same alias to 5-5) → mod writes full ids only. feature/model-router-mod open, nothing committed yet (plan + TODO + journal pending). +- model-router wave 1-A (/feat, user go): mod built in `mods/model-router/` (4 files, 834 + 202 lines, 11 plugin tests). Plan r1 → r3: 3 challengers (simplicity CONCERNS, robustness CONCERNS(6), correctness FATAL(8)) + 1 confirmation CONCERNS(4); converged on: agents table = built-ins only in wave 1 (frontmatter stays single writer), agent model written once at spawn, explicit Agent params frozen per loop, every sub-agent write on its own loop, Skill bridge answers in the Skill tool's OUTPUT schema (string result refused → skill would load), config validated before merge, state in closure, `/route off`. feater DONE first pass; GATE 0 MET; verifier CONFORME 6/6; security PASS (4 MEDIUM + 5 LOW parked in TODO for user go). Commits b721c94 (mod) + e8ca713 (contract/plan). Override `~/.claude/model-router.json` {verbose:true} written (pass B). Doc-sync deferred to 1-B. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 6eb8418..3050a16 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -5,7 +5,9 @@ Plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`. Decisions 2026-10-08: model switch spike-first then flag off; load via `CLAUDE_CODE_PLUGIN_DIRS` + link.sh; migration of shifters/pins/model-gate in wave 2 after proof; names model-router / route / /route. - [x] W0 spike in dev-mods (hot reload): facts a-d established 2026-10-08 (plan file § Spike facts); e moved to W1.10 -- [ ] W1 core mod in `mods/model-router/` (config, route tool, /route, agents, skills, prompt rules, visibility, tests, install) +- [x] W1-A the mod in `mods/model-router/` (b721c94, contract `2026-10-08-model-router-w1a-1533`, plan r3): challenge 3 lenses + 1 confirmation (2 BLOCKER + 10 MAJOR closed by named changes), feater DONE first pass, GATE 0 MET 5/5, verifier CONFORME 6/6, security PASS (4 MEDIUM + 5 LOW reported, below) +- [ ] W1-A hardening (security report, user decision): `/route` command origin check (`composer` only); in-agent `route` must not re-model the agent (strip `route.model` for agent loops, drop the dead per-step model path, align the tool description); ReDoS caps on config patterns (length ≤ 200, test ≤ 4 KB); one log per session in every `.catch` + log the silent config drops; phase key charset `^[a-z][a-z0-9_-]{0,31}$`; `additionalProperties: false` on the tool schema + `typeof e.skill`; post-`next` bookkeeping in try/catch; config file size cap 64 KB. Deferred by design: effort ceiling for model-declared routes; window check beyond haiku. +- [ ] W1-B install + docs: `mods/` symlink + `CLAUDE_CODE_PLUGIN_DIRS` in settings.json env via link.sh, root `.gitignore` for the engine-laid `mods/*/tsconfig.json` + `.claude-plugin/types/`, doctor line, README/USAGE/CHANGELOG (doc-sync deferred here from the 1-A /feat run: nothing to document before the install exists), live test in session (swap the spike for the real mod) - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B From 64702d50eaf46156f10f9ef30011e99e0254c459 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 16:38:08 +0200 Subject: [PATCH 027/547] =?UTF-8?q?chore(memory):=20BDR-115=20+=20LRN-205/?= =?UTF-8?q?206=20+=20EVAL-040=20=E2=80=94=20model-router=20architecture,?= =?UTF-8?q?=20tool=20output=20schema,=20plugin=20test=20kit,=20challenge?= =?UTF-8?q?=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 9 +++++++++ .claude/memory/evals.md | 9 +++++++++ .claude/memory/learnings.md | 8 ++++++++ .../2026-10-08-model-router-w1a-1533.md | 19 +++++++++++++++++++ 4 files changed, 45 insertions(+) diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 4082f09..1dc23fb 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -132,6 +132,7 @@ rules: | BDR-108 | 2026-09-29 | Effort round: level on every skill next to its model pin (3 repo + 25 vendored via `lib/effort-pins.txt` re-applied after the LAST vendoring step of install + resync), design stack ONE level (high), model pins stay tier aliases: quality/price trade-off = tier × effort, never version | accepted | | BDR-109 | 2026-09-30 | Higgsfield pack: npm CLI `latest` + 8 upstream skills git-cloned into gitignored `skills-external/higgsfield-*`, OFF by default, in no profile; two toggles (`higgsfield` = allowlist of 7 media skills, `higgsfield-websites` = landing-page aid, never website create/deploy/publish); CLI presence by probe; routing on explicit ask | accepted | | BDR-110 | 2026-10-06 | Shell portability doctrine: native userland on macOS AND Linux, no Homebrew GNU tools on PATH; `lib/tests/portability-census.test.sh` locks deterministic GNU-only idioms | accepted | +| BDR-115 | 2026-10-08 | model-router mod: pin = entry default, sub-tasks route finer; one writer per axis; full ids from the mod table; built-ins-only agents table until frontmatter pins go; state in closure | accepted | --- @@ -1393,3 +1394,11 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: regen via `install-hook` (writes a LOCAL hooks-path entry) or `global-hooks` (writes the GLOBAL config when the value is missing — it was, [[LRN-200]]) → `emit-hook > file` only; temp file for the verb's stderr in a hook (fail-open on a full TMPDIR, predictable path) → `2>&1` capture ([[LRN-202]]); classification before the token cap (13 s flood) → cap first ([[LRN-201]]); shell check of the release version string (interpolation sink) → by reading. - **Gates**: D1 3 lenses + confirm FATAL(1) (global-config write) → emit-hook; feater; GATE 0 MET; verifier CONFORME; security PASS. D2 3 lenses + confirm FATAL(3) (escape alternative, same-quote-inside, `bare=$one` when unparsed); feater; GATE 0 MET; verifier CONFORME; security BLOCK(1) cap-after-fork → fixed (20k tokens 0.13 s) → CONFORME + PASS. D3 3 lenses + confirm CONCERNS(3); feater; CONFORME + PASS. - **Refs**: contracts/plans `2026-10-07-manual-push-failclosed-d1-1522`, `…-guard-residuals-d2-1526`, `…-prose-d3-1530`; commits 472cccb, 3c59333, 64ca0f8 (feature/manual-push-mode, UNMERGED). Supersedes the "fail-open on invalid value" line of [[BDR-111]]. Links [[BDR-112]], [[BDR-113]], [[LRN-114]], [[LRN-196]]. Residuals: TODO "post-run-D residuals" (soft_deny names only `false`; stale `.githooks/` in onboarded repos until reconcile). + +## BDR-115 — model-router mod: pin = entry default, sub-tasks route finer; one writer per axis; full ids; built-ins-only table until pins go [accepted] (2026-10-08) +- **Decision**: one function-hooks mod (`mods/model-router/`) routes model + effort per request. Rules: (1) a skill/agent pin = DEFAULT route of the run, never ceiling/floor; inside the run every sub-task routes to its phase, declared (`route` tool, `/route`, `ultrathink`) or derived (skill load, agent dispatch). (2) ONE writer per axis: `Skill(effort-*)` answered by the mod WITHOUT loading the skill (no pairing rule, no doublon); every write lands on the CALLING loop; explicit Agent params frozen per loop for the whole run; agent model written once at spawn. (3) hooks write FULL ids from `config.models` ([[LRN-203]]). (4) wave 1 agents table = built-ins only (Explore sonnet/medium, Plan opus/xhigh); repo agents keep frontmatter as single writer until wave 2 moves pins into the table and deletes frontmatter + shifters + effort-pins + model-gate. (5) precedence: user `/route` sticky > latest turn route (one slot, last writer wins; non-effort skill load resets it except a prompt rule) > session. (6) main-loop model switch behind `mainModelSwitch` (default off) + context-window guard ([[LRN-204]]). (7) state in `register` closure, defaults cloned, `/route off` kill switch, config validated before merge. Load: `CLAUDE_CODE_PLUGIN_DIRS` in settings env via link.sh (wave 1-B). +- **Why**: user 2026-10-08: existing pins + `effort-*` shifters built for this goal with older tools; some pins forced (one level for a skill doing many things). Mods expose `turn.step` model/effort rewrite + `agent.spawn` + `tool.call` answers = cleaner, unified, automatic, works headless too (BDR-107 gap). +- **Alternatives rejected**: agents table copying the 21 frontmatter pins in wave 1 (third source of truth, silent override of a frontmatter edit); `scope: agents` / `/route agents` bulk lever (no requirement, sixth precedence tier); `model` param on the model-facing tool (typo → LRN-203 404 class); per-step agent model rewrite (fights engine fallback, beat explicit params); `userConfig` (one config file instead); marketplace install (live symlink repo model); `source`-dependent skill-load reset (kept stale shifts). +- **Gates**: plan r1 → r3 through 3 challengers + 1 confirmation (2 BLOCKER + 10 MAJOR closed, [[EVAL-040]]); feater DONE first pass; GATE 0 MET; verifier CONFORME 6/6; security PASS + hardening round (criteria 7-11). +- **Refs**: plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`, contract `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md`, [[BDR-107]], [[BDR-108]], [[BLK-029]], [[LRN-205]], [[LRN-206]]. + diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 9ece412..d0078a9 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -60,6 +60,7 @@ rules: | EVAL-037 | 2026-09-28 | correction of EVAL-035/036 counts: transcript records are per content block; deduped by message.id → main-loop thinking share 99.9%, thinking share of weighted cost 5.6%, sonnet think/msg 26→0.2, A/B requests 9→8 | conclusions hold (sharper: main-loop thinking 96.6%→99.9%, weighted-cost thinking corrected 8.4%→5.6%); effort-audit.py dedupes from a3b479e+ | | EVAL-038 | 2026-09-29 | correction of EVAL-037: 94 % of sub-agent usage records carry no `output_tokens_details` (Fable subs at xhigh read 0 thinking, impossible with always-on thinking) → sub-agent thinking UNMEASURED, not ≈0; main loop 100 % counted; weighted-cost split (61/39) still holds | `effort-audit.py` prints coverage + CAVEAT; cite the cost split only; agent effort pins stay unmeasured; a tier move on a price argument = judgment, not figure | | EVAL-039 | 2026-09-30 | ship-feature run higgsfield-pack: plan dry-run in scratch → 0 executor failure on 7 tasks; challenge found 7 MAJOR I missed; floor-guard caught 2 shellcheck suppressions of mine; final review found README/code gap | keep | +| EVAL-040 | 2026-10-08 | model-router w1a plan: 3 challengers + 1 confirmation found 2 BLOCKER + 14 MAJOR on a plan judged closed; executor then passed every gate first time | keep the round, never dispatch a mod plan without it | --- @@ -370,3 +371,11 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Method**: plan code dry-run in a scratch copy before the gate (suite per stage 0/5→5/0, 6/8→14/0, 14/1→15/0, 15/1→16/0, 4 mutation tests); 3 challengers + 1 confirmation; SDD per-task reviews; GATE 0/1/2 twice; final review on opus. - **Anomaly**: my first plan was green in dry-run and still wrong on 7 MAJOR points (shim vs binary, unbounded toggle probe, denylist membership, vacuous fixtures, askpass prompt): a dry-run proves the code does what I wrote, not that I wrote the right thing. Floor-guard flagged 2 `shellcheck disable=SC2016` I added to keep "shellcheck clean" green. Final review found the README promised drift reporting that the enabled state never reached. doc-syncer patch hit a shape escalation because I filed a script-comment edit under MINOR doc. One oracle of mine was shape-bound ([[LRN-188]]). - **Action**: keep the pre-gate dry-run (0 executor failure, 1 fix round in 7 tasks) AND the challenge (orthogonal finds); never silence a linter to satisfy a criterion, rewrite the line; doc patch plans carry public-doc paths only, script comments go as code commits. + +## EVAL-040 — model-router w1a: the challenge round caught what the author could not see +- **Date**: 2026-10-08 +- **Output checked**: plan `.claude/tasks/plans/2026-10-08-model-router-w1a-1533.md` r1, written after a successful spike with every harness fact in hand. +- **Method**: 3 blind opus challengers (simplicity CONCERNS(3), robustness CONCERNS(6), correctness FATAL(8)) + 1 confirmation (CONCERNS(4)); every BLOCKER/MAJOR closed by a named plan change (r2, r3); then feater, GATE 0, verifier, security. +- **Anomaly**: r1 carried 2 BLOCKER (explicit Agent `model` overridden at every step; Skill bridge answer shape refused by the output schema → doublon kept) + 10 MAJOR, all invisible to me: spike levers carried over as design (`agentsNext`, per-step model rewrite), a table copying 21 pins = third source of truth, writes on main from sub-agent loops. Confirmation found 4 more MAJOR (explicit params vs in-agent writes, `e.wait`, vacuous test assertions, haiku effort). Executor then DONE first pass, verifier CONFORME 6/6, security PASS: the plan was the whole risk. +- **Action**: a mod plan always goes through the full round + confirmation; test assertions must read the one line that carries the value; spike code is a FACT source, never a design source ([[BDR-115]], [[LRN-205]], [[LRN-206]]). + diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index c46d9a0..91110c6 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1757,3 +1757,11 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s - **Context**: spike 2026-10-08, fable → `claude-sonnet-5-5`/low for 3 steps on ~260k context, then back. Conversation intact (tools, results, thinking blocks from another model in history: no error). First sonnet step cache_read 0 (full 260k billed), next steps 237k cached; return to fable step read 263k cached. - **Apply**: switch the main loop only for spans long enough to amortize one uncached read of the whole context (many mechanical steps), never per tool call; short mechanical work → small-context haiku sub-agent. Haiku 4.5 window 200k: a long main loop cannot go to haiku at all. Flag off by default in model-router. Links [[LRN-203]], [[BDR-107]]. +## LRN-205 — A hook answering `tool.call` in place of a built-in tool must return that tool's OUTPUT schema shape; a string result is refused and the tool runs anyway +- **Context**: model-router Skill bridge, plan r1: `{ result: '' }` for `Skill(effort-*)`. Challenger: Skill has output schema `{ success, commandName, status?, … }` (claude-code-tools index.d.ts ~5139); core validates a hook's answer against it (claude-code index.d.ts ~12641), wrong shape = hook skipped = skill loads = the exact doublon the bridge exists to remove. Fix: `{ result: { success: true, commandName: e.skill, status: 'inline' }, context: ['…'] }`; text for the model goes in `context`, never in `result`. +- **Apply**: before answering any `tool.call` without `next`, grep the tool's RESULT type in claude-code-tools and mirror it; put model-facing prose in `context`. Links [[BDR-115]], [[LRN-203]]. + +## LRN-206 — `claude plugin test` kit facts (2.1.294): nothing fires at load, inputs are the FULL event, a bottom hook is mandatory under every `next`, `turn.step` streams +- **Context**: model-router tests. Kit `$` is `EngineCall = (e: Args)`: `command.run` needs `origin` + `presentation`, `prompt.submit` needs `wait` + `origin`, `agent.spawn` needs `tool_use_id, description, provider, parentModel, background, fork`; the test file is type-checked with the hooks (tsc include). `session.start` does NOT fire at load → every test boots with a bottom `on('session.start')` + `$.session.start({ cwd, surface: null, isInteractive: false })`. A hook calling `next` hits the kit's bottom which throws unless the test registered one (`on('agent.spawn', ($, e) => ({ model: e.model, agentId: 'a1' }))`). `$.turn.step` returns a stream: drain with `for await` then await `.result` (awaiting `.result` alone runs no hook). No fs/network/process: defaults path only. Assert on the ONE line that carries the value (a `show()` listing every phase always contains every id and level). +- **Apply**: write the boot helper first, type every input from the declarations, never relax a test to dodge a type. Links [[BDR-115]]. + diff --git a/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md b/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md index 9c07039..3221849 100644 --- a/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md +++ b/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md @@ -43,5 +43,24 @@ Q (r2): `scope: agents` / `/route agents` / A: dropped (challenge r1, no require Q (r2): agents table in wave 1 / A: built-ins only (Explore, Plan), matched for the engine provider; repo agents keep their frontmatter as the single writer until wave 2. [orchestrator — single source of truth] Q (r2): `/route off` / A: added as the session kill switch (every hook passes through). [orchestrator — robustness] +## HARDENING ROUND (security gate 2026-10-08, user go "oui durcis") — criteria 7-11 +7. `/route` is user-only: `command.run` answers `{ text: 'route: user-only command' }` without acting when `e.origin.kind !== 'composer'`; a test proves it (origin `{ kind: 'plugin', name: 'x' }` or the kit's non-composer origin → text contains `user-only`, state unchanged). + CHECK: cd mods/model-router && grep -q "origin.kind" hooks/register.ts && grep -q "user-only" hooks/register.ts && grep -q "user-only" hooks/register.test.ts && echo ORIGIN-OK + EXPECT: ORIGIN-OK + EVIDENCE: pending +8. An in-agent `route` call or skill table entry never changes that agent's MODEL: the `Loop` type has no `model` axis and no `explicitModel` flag, `turn.step` on an agent loop rewrites `effort` only, the route tool's description says "effort only; the model of a sub-agent is fixed at spawn". A test proves it: a route tool call carrying `agentId: 'a1'` with `phase: 'judge'` followed by a `turn.step` for `a1` leaves `model` as given and sets `effort` to `xhigh`. + CHECK: cd mods/model-router && ! grep -qE "loop\.model|explicitModel|spawnModel" hooks/register.ts && grep -q "fixed at spawn" hooks/register.ts && echo NO-AGENT-MODEL-OK + EXPECT: NO-AGENT-MODEL-OK + EVIDENCE: pending +9. Config hardening: a prompt rule pattern longer than 200 chars is dropped (logged); `re.test` runs on at most the first 4096 chars of the prompt; phase keys must match `^[a-z][a-z0-9_-]{0,31}$` (others dropped, logged); the override file is refused above 65536 bytes (logged, defaults kept); the route tool schema carries `additionalProperties: false`; the Skill hook checks `typeof e.skill === 'string'`. + CHECK: cd mods/model-router && grep -q "additionalProperties: false" hooks/register.ts && grep -qE "\[a-z\]\[a-z0-9_-\]\{0,31\}" hooks/register.ts && grep -qE "4096|4_096" hooks/register.ts && grep -qE "65536|65_536|64 \* 1024" hooks/register.ts && grep -qE "200" hooks/register.ts && grep -q "typeof e.skill === 'string'" hooks/register.ts && echo CONFIG-HARDEN-OK + EXPECT: CONFIG-HARDEN-OK + EVIDENCE: pending +10. Visible fail-open: every `.catch` logs once per session per hook (`$.ui.log('model-router: failed (): routing skipped for this event')`, a `warned: Set` in the state) before passing through or answering; the three silent config drops (non-object top level, wrong-typed table, non-array `prompt`) log a line. + CHECK: cd mods/model-router && [ "$(grep -c '\.catch(' hooks/register.ts)" -ge 12 ] && grep -q "warned" hooks/register.ts && grep -q "routing skipped" hooks/register.ts && echo CATCH-LOG-OK + EXPECT: CATCH-LOG-OK + EVIDENCE: pending +11. Post-`next` bookkeeping (loop tracking and logs after `await next(...)` in `agent.spawn` and the Skill hook) runs inside its own try/catch so a logging failure can never make the `.catch` re-run `next`. Judged by reading, with criteria 1-6 still MET (validate, tsc, tests ≥ 13, style, AC6 minus the removed model axis). + ## FILE SCOPE mods/model-router/.claude-plugin/plugin.json · mods/model-router/hooks/hooks.json · mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts From 346d6aeab2894495c40e9d4d90afbbdd0bb56a6b Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 16:53:43 +0200 Subject: [PATCH 028/547] =?UTF-8?q?feat(mods):=20model-router=20hardening?= =?UTF-8?q?=20=E2=80=94=20user-only=20/route,=20effort-only=20agent=20rout?= =?UTF-8?q?es,=20config=20caps,=20visible=20fail-open?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Security-gate round on the wave 1-A mod: /route answers only a composer origin; an in-agent route call can no longer change the agent's model (effort only, model fixed at spawn); config patterns capped (200 chars, 4096-char scan), phase keys restricted, override file refused above 64 KB, additionalProperties false on the tool schema; every .catch logs once per session; post-next bookkeeping isolated. 14 plugin tests, verifier 11/11. --- mods/model-router/hooks/register.test.ts | 38 ++++ mods/model-router/hooks/register.ts | 218 ++++++++++++++++------- 2 files changed, 196 insertions(+), 60 deletions(-) diff --git a/mods/model-router/hooks/register.test.ts b/mods/model-router/hooks/register.test.ts index 5c0c634..030970b 100644 --- a/mods/model-router/hooks/register.test.ts +++ b/mods/model-router/hooks/register.test.ts @@ -200,3 +200,41 @@ test('a tabled agent steps at its table effort', async ($, on) => { await runStep($, stepInput('a1')) expect(seen).toEqual([{ model: 'claude-fable-5-1', effort: 'medium' }]) }) + +test('/route from a non-composer origin is refused, state kept', async ( + $, on) => { + await boot($, on) + await route($, 'judge') + const out = await $.command.run({ + command: 'route', + args: 'mechanical', + origin: { kind: 'plugin', name: 'x' }, + presentation: { isFullscreen: false, columns: 80 }, + }) + expect(out.text).toContain('user-only') + expect(mainLine(await route($, 'show'))).toContain('user judge') +}) + +test('an in-agent route sets effort only, the model stays', async ($, on) => { + const seen: Seen[] = [] + recordSteps(on, seen) + await boot($, on) + await $.tool.call({ + tool: 'mcp__model-router__route', + phase: 'judge', + agentId: 'a1', + }) + await runStep($, { ...stepInput('a1'), model: 'claude-sonnet-5-5' }) + expect(seen).toEqual([{ model: 'claude-sonnet-5-5', effort: 'xhigh' }]) +}) + +test('a rule only scans the first 4096 chars of a prompt', async ($, on) => { + on('prompt.submit', ($, e) => ({ text: e.text })) + await boot($, on) + await $.prompt.submit({ + text: 'x'.repeat(5000) + ' ultrathink', + wait: false, + origin: { kind: 'composer' }, + }) + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) diff --git a/mods/model-router/hooks/register.ts b/mods/model-router/hooks/register.ts index 9bf4ae4..fa00a06 100644 --- a/mods/model-router/hooks/register.ts +++ b/mods/model-router/hooks/register.ts @@ -24,11 +24,7 @@ type Rule = { re: RegExp; phase: string } type Source = 'user' | 'model' | 'skill' | 'prompt' | 'slash' type Routed = { phase: string; route: Route; source: Source } type Loop = { - effort?: Level - model?: string // routed by the table or an in-agent call - spawnModel: string // the engine's model at spawn - frozen: boolean // fork or workflow agent: never re-modelled - explicitModel: boolean // Agent call gave a model: axis frozen + effort?: Level // an agent's model is fixed at spawn: effort is its only axis explicitEffort: boolean // Agent call gave an effort: axis frozen } type State = { @@ -44,6 +40,7 @@ type State = { off: boolean // /route off: every hook passes through lastMain: string // "model/effort" of the last main step (spinner) windowWarned: boolean // context-window warning already logged this turn + warned: Set // hooks whose fail-open was already logged } type Log = (text: string) => void type StepIn = Readonly @@ -62,6 +59,10 @@ const TOOL = 'mcp__model-router__route' const EFFORT_SKILL = /^effort-(low|medium|high|xhigh|max)$/ const OVERRIDE = '.claude/model-router.json' const HAIKU = 'claude-haiku' +const MAX_PATTERN = 200 // chars of a prompt-rule pattern +const MAX_PROMPT_SCAN = 4096 // chars of a prompt a rule is run against +const MAX_CONFIG_BYTES = 65536 // override file size +const PHASE_KEY = /^[a-z][a-z0-9_-]{0,31}$/ const DEFAULT_CONFIG: Config = { models: { @@ -123,7 +124,12 @@ function mergeTable( log: Log, ): Record { const out = { ...base } - if (!isRecord(user)) return out + if (!isRecord(user)) { + if (user !== undefined) { + log(`model-router: config ${name} ignored: not an object`) + } + return out + } for (const [key, value] of Object.entries(user)) { const ok = key === '__proto__' ? undefined : accept(key, value) if (ok === undefined) log(`model-router: config ${name}.${key} ignored`) @@ -141,8 +147,8 @@ const acceptWindow = (key: string, v: unknown): number | undefined => : undefined function acceptPhase(models: Record) { - return (_key: string, v: unknown): Route | undefined => { - if (!isRecord(v)) return undefined + return (key: string, v: unknown): Route | undefined => { + if (!PHASE_KEY.test(key) || !isRecord(v)) return undefined const route: Route = {} if (v.effort !== undefined) { if (!isLevel(v.effort)) return undefined @@ -158,7 +164,9 @@ function acceptPhase(models: Record) { function acceptPhaseRef(phases: Record) { return (_key: string, v: unknown): string | undefined => - typeof v === 'string' && hasKey(phases, v) ? v : undefined + typeof v === 'string' && PHASE_KEY.test(v) && hasKey(phases, v) + ? v + : undefined } function compiles(pattern: string): boolean { @@ -174,6 +182,7 @@ function acceptRule(phases: Record, v: unknown) { if (!isRecord(v)) return undefined const { pattern, phase } = v if (typeof pattern !== 'string' || typeof phase !== 'string') return undefined + if (pattern.length > MAX_PATTERN) return undefined return hasKey(phases, phase) && compiles(pattern) ? { pattern, phase } : undefined @@ -186,7 +195,12 @@ function mergePrompt( phases: Record, log: Log, ): PromptRule[] { - if (!Array.isArray(user)) return base + if (!Array.isArray(user)) { + if (user !== undefined) { + log('model-router: config prompt ignored: not a list') + } + return base + } const rules: PromptRule[] = [] for (const item of user as unknown[]) { const rule = acceptRule(phases, item) @@ -202,7 +216,10 @@ const pickBool = (v: unknown, fallback: boolean): boolean => /** Defaults overlaid with the user's entries, each validated first. */ function mergeConfig(user: unknown, log: Log): Config { const base = structuredClone(DEFAULT_CONFIG) - if (!isRecord(user)) return base + if (!isRecord(user)) { + if (user !== undefined) log('model-router: config ignored: not an object') + return base + } const models = mergeTable( base.models, user.models, 'models', acceptModel, log) const phases = mergeTable( @@ -222,6 +239,24 @@ function mergeConfig(user: unknown, log: Log): Config { } } +/** The file's text, or undefined (logged) when it exceeds the cap. */ +async function readCapped( + $: Api, + path: string, + log: Log, +): Promise { + const tooBig = + `model-router: ${OVERRIDE} over ${MAX_CONFIG_BYTES} bytes; defaults` + if ((await $.fs.stat(path)).size > MAX_CONFIG_BYTES) { + log(tooBig) + return undefined + } + const text = await $.fs.read(path) + if (text.length <= MAX_CONFIG_BYTES) return text + log(tooBig) + return undefined +} + async function readOverride( $: Api, log: Log, @@ -231,7 +266,8 @@ async function readOverride( if (!home) return undefined const path = `${home}/${OVERRIDE}` if (!(await $.fs.exists(path))) return undefined - return { path, data: JSON.parse(await $.fs.read(path)) } + const text = await readCapped($, path, log) + return text === undefined ? undefined : { path, data: JSON.parse(text) } } catch (err) { log(`model-router: ${OVERRIDE} unreadable (${String(err)}); defaults`) return undefined @@ -271,6 +307,28 @@ function newState(cfg: Config, source: string): State { off: false, lastMain: '', windowWarned: false, + warned: new Set(), + } +} + +/** Logs a hook's fail-open once per session; never throws itself. */ +function warnOnce(st: State, $: Api, hook: string, kind: string): void { + if (st.warned.has(hook)) return + st.warned.add(hook) + try { + $.ui.log(`model-router: ${hook} failed (${kind}): ` + + 'routing skipped for this event') + } catch { + // a failing log must not break the fail-open itself + } +} + +/** Runs post-`next` bookkeeping so its failure can never re-run `next`. */ +function safely(st: State, $: Api, hook: string, work: () => void): void { + try { + work() + } catch { + warnOnce(st, $, hook, 'bookkeeping') } } @@ -281,9 +339,6 @@ function loopOf(st: State, agentId: string): Loop { const known = st.loops.get(agentId) if (known) return known const fresh: Loop = { - spawnModel: '', - frozen: false, - explicitModel: false, explicitEffort: false, } st.loops.set(agentId, fresh) @@ -293,7 +348,6 @@ function loopOf(st: State, agentId: string): Loop { /** Writes a route on an agent loop, never on an axis given explicitly. */ function writeLoop(loop: Loop, route: Route): void { if (!loop.explicitEffort) loop.effort = route.effort - if (!loop.explicitModel) loop.model = route.model } function clearRoutes(st: State): void { @@ -439,10 +493,11 @@ async function registerTool($: Api, st: State): Promise { await $.tool.register({ name: 'route', description: - 'Declare the phase of the work ahead so the next model requests ' + - 'run at the effort (and model) it deserves. Call it before a span ' + - 'of work changes nature (planning, orchestrating, mechanical ' + - 'work). It acts on the calling loop only; no model choice here. ' + + 'Declare the phase of the work ahead so the next requests of THIS ' + + 'loop run at the right effort (and, on the main loop, the model ' + + 'when the switch is on). Call it before a span of work changes ' + + 'nature (planning, orchestrating, mechanical work). Effort only ' + + 'for a sub-agent; the model of a sub-agent is fixed at spawn. ' + `Phases: ${Object.keys(st.cfg.phases).join(', ')}.`, inputSchema: { type: 'object', @@ -451,6 +506,7 @@ async function registerTool($: Api, st: State): Promise { effort: { type: 'string', enum: [...LEVELS] }, clear: { type: 'boolean', description: 'drop this loop\'s route' }, }, + additionalProperties: false, }, }) } catch (err) { @@ -516,10 +572,12 @@ function routedText(st: State, agentId: string | undefined, p: Picked): string { } const loop = agentId === undefined ? undefined : st.loops.get(agentId) const effort = loop?.explicitEffort ? undefined : p.route.effort - const model = agentId === undefined && !st.cfg.mainModelSwitch - ? undefined - : loop?.explicitModel ? undefined : p.route.model - const modelNote = p.route.model && model === undefined ? ' (switch off)' : '' + const model = agentId === undefined && st.cfg.mainModelSwitch + ? p.route.model + : undefined + const modelNote = !p.route.model || model !== undefined + ? '' + : agentId === undefined ? ' (switch off)' : ' (fixed at spawn)' return `routed ${agentId === undefined ? 'main' : 'this agent'} to ` + `${p.phase}: effort ${effort ?? 'unchanged'}, model ` + `${model === undefined ? 'unchanged' : resolveModel(st.cfg, model)}` + @@ -619,16 +677,12 @@ function spawnRoute(cfg: Config, e: SpawnIn, frozen: boolean) { } function trackLoop(st: State, e: SpawnIn, started: { - model: string agentId?: string -}, route: Route | undefined, frozen: boolean): void { +}, route: Route | undefined): void { const given = st.explicitEffort.get(e.tool_use_id) st.explicitEffort.delete(e.tool_use_id) if (started.agentId === undefined) return st.loops.set(started.agentId, { - spawnModel: started.model, - frozen, - explicitModel: e.model !== undefined, explicitEffort: given !== undefined, effort: given ? undefined : route?.effort, }) @@ -638,13 +692,7 @@ function trackLoop(st: State, e: SpawnIn, started: { function agentPlan(st: State, e: StepIn): Plan { const loop = e.agentId === undefined ? undefined : st.loops.get(e.agentId) - const wanted = loop?.model - const reroute = loop && wanted !== undefined && !loop.frozen && - e.model === loop.spawnModel - return { - model: reroute ? resolveModel(st.cfg, wanted) : e.model, - effort: loop?.effort ?? e.effort, - } + return { model: e.model, effort: loop?.effort ?? e.effort } } /** True when the context still fits the target model's known window. */ @@ -719,14 +767,29 @@ function registerSession(on: On, st: State): void { await registerCommand($) refresh($, st) return next(e) - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'session.start', next.error.kind) + return next(e) + }) on('session.end', async ($, e, next) => { Object.assign(st, newState(st.cfg, st.source)) return next(e) - }).catch(($, e, next) => next(e)) - on('command.run', { command: 'route' }, async ($, e) => ({ - text: await handleCommand($, st, e.args), - })).catch(($, e, next) => ({ text: `route failed (${next.error.kind})` })) + }).catch(($, e, next) => { + warnOnce(st, $, 'session.end', next.error.kind) + return next(e) + }) +} + +function registerCommandHook(on: On, st: State): void { + on('command.run', { command: 'route' }, async ($, e) => { + if (e.origin.kind !== 'composer') { + return { text: 'route: user-only command' } + } + return { text: await handleCommand($, st, e.args) } + }).catch(($, e, next) => { + warnOnce(st, $, 'command.run', next.error.kind) + return { text: `route failed (${next.error.kind})` } + }) } function registerRouteTool(on: On, st: State): void { @@ -735,28 +798,36 @@ function registerRouteTool(on: On, st: State): void { refresh($, st) vlog($, st, `route ${e.agentId ?? 'main'}: ${JSON.stringify(out)}`) return out - }).catch(($, e, next) => ({ - result: `route failed (${next.error.kind}); nothing routed`, - })) + }).catch(($, e, next) => { + warnOnce(st, $, 'route tool', next.error.kind) + return { result: `route failed (${next.error.kind}); nothing routed` } + }) } function registerSkills(on: On, st: State): void { on('tool.call', { tool: 'Skill' }, async ($, e, next) => { - if (st.off) return next(e) - const level = EFFORT_SKILL.exec(e.skill)?.[1] - if (isLevel(level)) return effortBridge(st, e.agentId, e.skill, level) + const skill = typeof e.skill === 'string' ? e.skill : undefined + if (st.off || skill === undefined) return next(e) + const level = EFFORT_SKILL.exec(skill)?.[1] + if (isLevel(level)) return effortBridge(st, e.agentId, skill, level) st.skillCalls += 1 try { - onSkillLoad(st, e.skill, e.agentId) + safely(st, $, 'Skill', () => onSkillLoad(st, skill, e.agentId)) return await next(e) } finally { st.skillCalls -= 1 } - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'Skill', next.error.kind) + return next(e) + }) on('skill.prompt', async ($, e, next) => { if (st.off || st.skillCalls > 0) return next(e) return slashEffort(st, e.skill, e.text) ?? next(e) - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'skill.prompt', next.error.kind) + return next(e) + }) } function registerAgents(on: On, st: State): void { @@ -765,7 +836,13 @@ function registerAgents(on: On, st: State): void { st.explicitEffort.set(e.tool_use_id, e.effort) } return next(e) - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'Agent', next.error.kind) + return next(e) + }) +} + +function registerSpawn(on: On, st: State): void { on('agent.spawn', async ($, e, next) => { if (st.off) return next(e) const frozen = e.fork || e.workflow !== undefined @@ -775,11 +852,18 @@ function registerAgents(on: On, st: State): void { const started = await next(wanted === undefined ? e : { ...e, model: resolveModel(st.cfg, wanted) }) - if (started.deny !== undefined) return started - trackLoop(st, e, started, route, frozen) - vlog($, st, `spawn ${e.subagentType}: ${e.model ?? '-'} → ${started.model}`) + if (typeof started.agentId === 'string') { + safely(st, $, 'agent.spawn', () => { + trackLoop(st, e, started, route) + vlog($, st, + `spawn ${e.subagentType}: ${e.model ?? '-'} → ${started.model}`) + }) + } return started - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'agent.spawn', next.error.kind) + return next(e) + }) } function registerTurns(on: On, st: State): void { @@ -790,22 +874,28 @@ function registerTurns(on: On, st: State): void { if (e.agentId === undefined) noteMain($, st, plan) vlog($, st, stepLog(e, plan)) const result = yield* next(changed ? withPlan(e, plan) : e) - vlog($, st, `step ${e.index} answered by ${result.usage?.model ?? '?'}`) + safely(st, $, 'turn.step', () => vlog($, st, + `step ${e.index} answered by ${result.usage?.model ?? '?'}`)) return result }).catch(async function* ($, e, next) { + warnOnce(st, $, 'turn.step', next.error.kind) return yield* next(e) }) on('turn.complete', async ($, e, next) => { if (e.agentId !== undefined) st.loops.delete(e.agentId) else endMainTurn($, st) return next(e) - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'turn.complete', next.error.kind) + return next(e) + }) } function registerPrompt(on: On, st: State): void { on('prompt.submit', async ($, e, next) => { if (st.off || e.origin.kind !== 'composer') return next(e) - const rule = st.rules.find(r => r.re.test(e.text)) + const scanned = e.text.slice(0, MAX_PROMPT_SCAN) + const rule = st.rules.find(r => r.re.test(scanned)) const route = rule ? phaseRoute(st.cfg, rule.phase) : undefined if (rule && route) { const routed: Routed = { phase: rule.phase, route, source: 'prompt' } @@ -815,20 +905,28 @@ function registerPrompt(on: On, st: State): void { refresh($, st) } return next(e) - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'prompt.submit', next.error.kind) + return next(e) + }) on('ui.render', { component: 'Spinner' }, async ($, e, next) => { if (st.off || !st.cfg.spinner || !st.lastMain) return next(e) const suffix = ` · ${st.lastMain}…` return next({ ...e, props: { ...e.props, suffix } }) - }).catch(($, e, next) => next(e)) + }).catch(($, e, next) => { + warnOnce(st, $, 'ui.render', next.error.kind) + return next(e) + }) } export const register: Register = on => { const st = newState(mergeConfig(undefined, () => undefined), 'defaults') registerSession(on, st) + registerCommandHook(on, st) registerRouteTool(on, st) registerSkills(on, st) registerAgents(on, st) + registerSpawn(on, st) registerTurns(on, st) registerPrompt(on, st) } From ae0179f4912d28a1e16bc8ad3622b01f17a53113 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 16:53:43 +0200 Subject: [PATCH 029/547] chore(tasks): model-router contract criteria 7-11, TODO hardening done + residuals, journal --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 3 ++- .../contracts/2026-10-08-model-router-w1a-1533.md | 12 ++++++------ 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 5e77116..adc0290 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -580,3 +580,4 @@ rules: ## 2026-10-08 - model-router mod, wave 0 spike (user ask: one mod routes model + effort per request, replaces effort-* shifters + pins). Plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`, 4 decisions by AskUserQuestion (spike-first main-loop switch, `CLAUDE_CODE_PLUGIN_DIRS` load, migration wave 2, names model-router / route / /route), rule "pin = entry default, sub-tasks route finer". Spike in dev-mods, hot reload on: `turn.step` effort rewrite proven (transcript `effort` field is the oracle, not `CLAUDE_EFFORT`); sub-agent model at `agent.spawn` + effort per step by agentId proven; main-loop fable → sonnet-5-5/low for 3 steps then back: works, one cold-cache step per switch INTO a model, return free. Found: hook-side alias resolver stale (`sonnet` → `claude-sonnet-5`, 404; Agent tool enum resolves the same alias to 5-5) → mod writes full ids only. feature/model-router-mod open, nothing committed yet (plan + TODO + journal pending). - model-router wave 1-A (/feat, user go): mod built in `mods/model-router/` (4 files, 834 + 202 lines, 11 plugin tests). Plan r1 → r3: 3 challengers (simplicity CONCERNS, robustness CONCERNS(6), correctness FATAL(8)) + 1 confirmation CONCERNS(4); converged on: agents table = built-ins only in wave 1 (frontmatter stays single writer), agent model written once at spawn, explicit Agent params frozen per loop, every sub-agent write on its own loop, Skill bridge answers in the Skill tool's OUTPUT schema (string result refused → skill would load), config validated before merge, state in closure, `/route off`. feater DONE first pass; GATE 0 MET; verifier CONFORME 6/6; security PASS (4 MEDIUM + 5 LOW parked in TODO for user go). Commits b721c94 (mod) + e8ca713 (contract/plan). Override `~/.claude/model-router.json` {verbose:true} written (pass B). Doc-sync deferred to 1-B. +- model-router W1-A hardening (user go): fresh feater on contract criteria 7-11 → gap round (dead `Loop.frozen`, spawn returns `started` verbatim, tool description) → verifier CONFORME 11/11 → security PASS (1 MEDIUM residual: ReDoS size-bounded only, self-inflicted config; 5 LOW parked). Registries BDR-115, LRN-205, LRN-206, EVAL-040 written on user go (64702d5). Next: live swap of the real mod into the hot-reload folder, then W1-B install + docs. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 3050a16..b391e2e 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -6,7 +6,8 @@ model switch spike-first then flag off; load via `CLAUDE_CODE_PLUGIN_DIRS` + lin migration of shifters/pins/model-gate in wave 2 after proof; names model-router / route / /route. - [x] W0 spike in dev-mods (hot reload): facts a-d established 2026-10-08 (plan file § Spike facts); e moved to W1.10 - [x] W1-A the mod in `mods/model-router/` (b721c94, contract `2026-10-08-model-router-w1a-1533`, plan r3): challenge 3 lenses + 1 confirmation (2 BLOCKER + 10 MAJOR closed by named changes), feater DONE first pass, GATE 0 MET 5/5, verifier CONFORME 6/6, security PASS (4 MEDIUM + 5 LOW reported, below) -- [ ] W1-A hardening (security report, user decision): `/route` command origin check (`composer` only); in-agent `route` must not re-model the agent (strip `route.model` for agent loops, drop the dead per-step model path, align the tool description); ReDoS caps on config patterns (length ≤ 200, test ≤ 4 KB); one log per session in every `.catch` + log the silent config drops; phase key charset `^[a-z][a-z0-9_-]{0,31}$`; `additionalProperties: false` on the tool schema + `typeof e.skill`; post-`next` bookkeeping in try/catch; config file size cap 64 KB. Deferred by design: effort ceiling for model-declared routes; window check beyond haiku. +- [x] W1-A hardening (user go "oui durcis", contract criteria 7-11): `/route` composer-only; no agent model axis (effort only after spawn); pattern ≤ 200 / scan ≤ 4096 / phase keys `^[a-z][a-z0-9_-]{0,31}$` / config ≤ 64 KB / `additionalProperties: false` / `typeof e.skill`; `warnOnce` in all 14 catches + config-drop logs; `safely` around post-`next` bookkeeping. feater DONE, gap round (dead `Loop.frozen`, spawn returns `started` verbatim, tool description), GATE 0 MET 9/9, verifier CONFORME 11/11, security PASS. +- [ ] W1-A residuals (security, accepted, none exploitable from outside the user's own files): ReDoS is size-bounded only (`(a+)+$` in `~/.claude/model-router.json` + a 4 KB paste hangs the hook; fix = nested-quantifier rejection or a far lower scan cap); `stat().size` trusted (FIFO/device path in ~/.claude); unrestricted `models`/`agents`/`skills` KEYS echoed raw in logs (log flood); `agentId` read from the flat tool event (engine strip unverified); 5 closures without a kit test (no fs in the kit, LRN-206); "nothing routed" catch text after a state write. - [ ] W1-B install + docs: `mods/` symlink + `CLAUDE_CODE_PLUGIN_DIRS` in settings.json env via link.sh, root `.gitignore` for the engine-laid `mods/*/tsconfig.json` + `.claude-plugin/types/`, doctor line, README/USAGE/CHANGELOG (doc-sync deferred here from the 1-A /feat run: nothing to document before the install exists), live test in session (swap the spike for the real mod) - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B diff --git a/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md b/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md index 3221849..e938038 100644 --- a/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md +++ b/.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md @@ -29,7 +29,7 @@ Q: legacy `Skill(effort-*)` / A: answered by the mod without loading the skill ( 3. `claude plugin test mods/model-router` passes; the suite covers: (a) `Skill(effort-low)` via `$.tool.call` is answered without `next` in the Skill tool's output shape (`success`, `commandName`) and the route shows `low` on main; (b) the `route` tool with `phase: "orchestrate"` sets `medium` on main and `/route show` prints it; (c) `/route clear` drops it; (d) `/route bogus` returns an error text naming the phases; (e) a `prompt.submit` text holding `ultrathink` sets `escalate` on main; (f) `/route model=sonnet` shows `claude-sonnet-5-5`, a full id passes through, a misspelt alias is refused; (g) `agent.spawn` of `Explore` without a model param reaches the bottom with `model === 'claude-sonnet-5-5'`, and with `model: 'opus'` given the param is untouched. CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 5; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 7 ] && echo PLUGIN-TEST-OK EXPECT: PLUGIN-TEST-OK - EVIDENCE: MET exit=0 marker-found :: (pass) a tabled agent steps at its table effort [19.75ms] 11 pass 0 fail Ran 11 tests across 1 file. [0.47s] PLUGIN-TEST-OK + EVIDENCE: MET exit=0 marker-found :: (pass) a rule only scans the first 4096 chars of a prompt [27.16ms] 14 pass 0 fail Ran 14 tests across 1 file. [0.60s] PLUGIN-TEST-OK 4. Hooks present, as `claude plugin validate` lists them: `session.start`, `command.run{command=route}`, `tool.call{tool=mcp__model-router__route}`, `tool.call{tool=Skill}`, `tool.call{tool=Agent}`, `skill.prompt`, `agent.spawn`, `turn.step`, `prompt.submit`, `turn.complete`, `ui.render{component=Spinner}`; every gating hook carries a fail-open `.catch` (validate prints no "gating hook without .catch"). CHECK: cd mods/model-router && out=$(claude plugin validate . 2>&1) && for h in session.start 'command.run{command=route}' 'tool.call{tool=mcp__model-router__route}' 'tool.call{tool=Skill}' 'tool.call{tool=Agent}' skill.prompt agent.spawn turn.step prompt.submit turn.complete 'ui.render{component=Spinner}'; do echo "$out" | grep -qF -- "$h" || { echo "missing $h"; exit 1; }; done && ! echo "$out" | grep -q 'without .catch' && echo HOOKS-OK EXPECT: HOOKS-OK @@ -43,23 +43,23 @@ Q (r2): `scope: agents` / `/route agents` / A: dropped (challenge r1, no require Q (r2): agents table in wave 1 / A: built-ins only (Explore, Plan), matched for the engine provider; repo agents keep their frontmatter as the single writer until wave 2. [orchestrator — single source of truth] Q (r2): `/route off` / A: added as the session kill switch (every hook passes through). [orchestrator — robustness] -## HARDENING ROUND (security gate 2026-10-08, user go "oui durcis") — criteria 7-11 +Hardening round (security gate 2026-10-08, user go "oui durcis") — criteria 7-11, same ledger: 7. `/route` is user-only: `command.run` answers `{ text: 'route: user-only command' }` without acting when `e.origin.kind !== 'composer'`; a test proves it (origin `{ kind: 'plugin', name: 'x' }` or the kit's non-composer origin → text contains `user-only`, state unchanged). CHECK: cd mods/model-router && grep -q "origin.kind" hooks/register.ts && grep -q "user-only" hooks/register.ts && grep -q "user-only" hooks/register.test.ts && echo ORIGIN-OK EXPECT: ORIGIN-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: ORIGIN-OK 8. An in-agent `route` call or skill table entry never changes that agent's MODEL: the `Loop` type has no `model` axis and no `explicitModel` flag, `turn.step` on an agent loop rewrites `effort` only, the route tool's description says "effort only; the model of a sub-agent is fixed at spawn". A test proves it: a route tool call carrying `agentId: 'a1'` with `phase: 'judge'` followed by a `turn.step` for `a1` leaves `model` as given and sets `effort` to `xhigh`. CHECK: cd mods/model-router && ! grep -qE "loop\.model|explicitModel|spawnModel" hooks/register.ts && grep -q "fixed at spawn" hooks/register.ts && echo NO-AGENT-MODEL-OK EXPECT: NO-AGENT-MODEL-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: NO-AGENT-MODEL-OK 9. Config hardening: a prompt rule pattern longer than 200 chars is dropped (logged); `re.test` runs on at most the first 4096 chars of the prompt; phase keys must match `^[a-z][a-z0-9_-]{0,31}$` (others dropped, logged); the override file is refused above 65536 bytes (logged, defaults kept); the route tool schema carries `additionalProperties: false`; the Skill hook checks `typeof e.skill === 'string'`. CHECK: cd mods/model-router && grep -q "additionalProperties: false" hooks/register.ts && grep -qE "\[a-z\]\[a-z0-9_-\]\{0,31\}" hooks/register.ts && grep -qE "4096|4_096" hooks/register.ts && grep -qE "65536|65_536|64 \* 1024" hooks/register.ts && grep -qE "200" hooks/register.ts && grep -q "typeof e.skill === 'string'" hooks/register.ts && echo CONFIG-HARDEN-OK EXPECT: CONFIG-HARDEN-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: CONFIG-HARDEN-OK 10. Visible fail-open: every `.catch` logs once per session per hook (`$.ui.log('model-router: failed (): routing skipped for this event')`, a `warned: Set` in the state) before passing through or answering; the three silent config drops (non-object top level, wrong-typed table, non-array `prompt`) log a line. CHECK: cd mods/model-router && [ "$(grep -c '\.catch(' hooks/register.ts)" -ge 12 ] && grep -q "warned" hooks/register.ts && grep -q "routing skipped" hooks/register.ts && echo CATCH-LOG-OK EXPECT: CATCH-LOG-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: CATCH-LOG-OK 11. Post-`next` bookkeeping (loop tracking and logs after `await next(...)` in `agent.spawn` and the Skill hook) runs inside its own try/catch so a logging failure can never make the `.catch` re-run `next`. Judged by reading, with criteria 1-6 still MET (validate, tsc, tests ≥ 13, style, AC6 minus the removed model axis). ## FILE SCOPE From 77ad7cf494f53cfc1915b18058c723afe42ad6a6 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 18:37:32 +0200 Subject: [PATCH 030/547] =?UTF-8?q?chore(tasks):=20model-router=20W1-B=20s?= =?UTF-8?q?plit=20=E2=80=94=20floor=20+=20wiring=20contracts/plans,=20skil?= =?UTF-8?q?ls-dir=20loading=20decision,=20journal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 3 +- .../2026-10-08-model-router-floor-1835.md | 33 ++++++ .../2026-10-08-model-router-wiring-1835.md | 45 ++++++++ .../2026-10-08-model-router-floor-1835.md | 108 ++++++++++++++++++ .../plans/2026-10-08-model-router-mod.md | 21 ++++ .../2026-10-08-model-router-wiring-1835.md | 106 +++++++++++++++++ 7 files changed, 316 insertions(+), 1 deletion(-) create mode 100644 .claude/tasks/contracts/2026-10-08-model-router-floor-1835.md create mode 100644 .claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md create mode 100644 .claude/tasks/plans/2026-10-08-model-router-floor-1835.md create mode 100644 .claude/tasks/plans/2026-10-08-model-router-wiring-1835.md diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index adc0290..0af5f38 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -581,3 +581,4 @@ rules: - model-router mod, wave 0 spike (user ask: one mod routes model + effort per request, replaces effort-* shifters + pins). Plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`, 4 decisions by AskUserQuestion (spike-first main-loop switch, `CLAUDE_CODE_PLUGIN_DIRS` load, migration wave 2, names model-router / route / /route), rule "pin = entry default, sub-tasks route finer". Spike in dev-mods, hot reload on: `turn.step` effort rewrite proven (transcript `effort` field is the oracle, not `CLAUDE_EFFORT`); sub-agent model at `agent.spawn` + effort per step by agentId proven; main-loop fable → sonnet-5-5/low for 3 steps then back: works, one cold-cache step per switch INTO a model, return free. Found: hook-side alias resolver stale (`sonnet` → `claude-sonnet-5`, 404; Agent tool enum resolves the same alias to 5-5) → mod writes full ids only. feature/model-router-mod open, nothing committed yet (plan + TODO + journal pending). - model-router wave 1-A (/feat, user go): mod built in `mods/model-router/` (4 files, 834 + 202 lines, 11 plugin tests). Plan r1 → r3: 3 challengers (simplicity CONCERNS, robustness CONCERNS(6), correctness FATAL(8)) + 1 confirmation CONCERNS(4); converged on: agents table = built-ins only in wave 1 (frontmatter stays single writer), agent model written once at spawn, explicit Agent params frozen per loop, every sub-agent write on its own loop, Skill bridge answers in the Skill tool's OUTPUT schema (string result refused → skill would load), config validated before merge, state in closure, `/route off`. feater DONE first pass; GATE 0 MET; verifier CONFORME 6/6; security PASS (4 MEDIUM + 5 LOW parked in TODO for user go). Commits b721c94 (mod) + e8ca713 (contract/plan). Override `~/.claude/model-router.json` {verbose:true} written (pass B). Doc-sync deferred to 1-B. - model-router W1-A hardening (user go): fresh feater on contract criteria 7-11 → gap round (dead `Loop.frozen`, spawn returns `started` verbatim, tool description) → verifier CONFORME 11/11 → security PASS (1 MEDIUM residual: ReDoS size-bounded only, self-inflicted config; 5 LOW parked). Registries BDR-115, LRN-205, LRN-206, EVAL-040 written on user go (64702d5). Next: live swap of the real mod into the hot-reload folder, then W1-B install + docs. +- model-router live checks on Opus 5.5 (user /model, uncommitted settings.json change left to the user): Skill(effort-low) bridge answered in place → next request low; ultrathink turn ran max (engine base medium); Explore without params → claude-sonnet-5-5, 3 steps medium. Loading switched to tracked symlink skills/model-router → @skills-dir (PLUGIN_DIRS non-portable: absolute path, no $HOME expansion, tracked settings); isolated-HOME probe listed/enabled/loaded. User chose floor semantics for ultrathink + typed /effort-. W1-B split: B1 floor (register.ts) + B2 wiring (symlink, gitignore, mods suite, doctor, CLAUDE.md); 6 challengers in flight. Effort shifters skipped this turn: the bridge would overwrite the user's ultrathink until B1 lands. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index b391e2e..d1b2620 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -8,7 +8,8 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [x] W1-A the mod in `mods/model-router/` (b721c94, contract `2026-10-08-model-router-w1a-1533`, plan r3): challenge 3 lenses + 1 confirmation (2 BLOCKER + 10 MAJOR closed by named changes), feater DONE first pass, GATE 0 MET 5/5, verifier CONFORME 6/6, security PASS (4 MEDIUM + 5 LOW reported, below) - [x] W1-A hardening (user go "oui durcis", contract criteria 7-11): `/route` composer-only; no agent model axis (effort only after spawn); pattern ≤ 200 / scan ≤ 4096 / phase keys `^[a-z][a-z0-9_-]{0,31}$` / config ≤ 64 KB / `additionalProperties: false` / `typeof e.skill`; `warnOnce` in all 14 catches + config-drop logs; `safely` around post-`next` bookkeeping. feater DONE, gap round (dead `Loop.frozen`, spawn returns `started` verbatim, tool description), GATE 0 MET 9/9, verifier CONFORME 11/11, security PASS. - [ ] W1-A residuals (security, accepted, none exploitable from outside the user's own files): ReDoS is size-bounded only (`(a+)+$` in `~/.claude/model-router.json` + a 4 KB paste hangs the hook; fix = nested-quantifier rejection or a far lower scan cap); `stat().size` trusted (FIFO/device path in ~/.claude); unrestricted `models`/`agents`/`skills` KEYS echoed raw in logs (log flood); `agentId` read from the flat tool event (engine strip unverified); 5 closures without a kit test (no fs in the kit, LRN-206); "nothing routed" catch text after a state write. -- [ ] W1-B install + docs: `mods/` symlink + `CLAUDE_CODE_PLUGIN_DIRS` in settings.json env via link.sh, root `.gitignore` for the engine-laid `mods/*/tsconfig.json` + `.claude-plugin/types/`, doctor line, README/USAGE/CHANGELOG (doc-sync deferred here from the 1-A /feat run: nothing to document before the install exists), live test in session (swap the spike for the real mod) +- [ ] W1-B1 floor precedence (contract `2026-10-08-model-router-floor-1835`): `ultrathink` + typed `/effort-` = floor for the main turn (user choice 2026-10-08) +- [ ] W1-B2 wiring (contract `2026-10-08-model-router-wiring-1835`): tracked symlink `skills/model-router` → `../mods/model-router` (loads as `@skills-dir`; PLUGIN_DIRS dropped: absolute paths in tracked settings), `.gitignore` engine-laid files, `lib/tests/mods.test.sh`, doctor `── Mods ──`, CLAUDE.md `## mods/`; then doc-sync (README/USAGE/CHANGELOG), live swap (remove the hot-reload link, `/reload-plugins`), BDR-115 amendment - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B diff --git a/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md b/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md new file mode 100644 index 0000000..53daccc --- /dev/null +++ b/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md @@ -0,0 +1,33 @@ +# CONTRACT — model-router-floor (wave 1-B1: user effort floor for the turn) +- date: 2026-10-08 | flow: feat | branch: feature/model-router-mod +- status: active + +## REQUEST (verbatim — IMMUTABLE) +AskUserQuestion 2026-10-08, question: "Aujourd'hui, `ultrathink` met le tour en max, mais si je déclare une phase (ex. orchestrate) puis charge un skill, ton max est perdu pour la suite du tour. Ça contredit notre règle « un choix explicite bat la phase déduite ». Quel sens donner à `ultrathink` et à un `/effort-x` tapé par toi ?" +User's answer: "Plancher pour le tour (Recommended)" — option text: "Ton niveau est un minimum pour tout le tour. Les routes du modèle et des skills peuvent monter au-dessus (escalade à max), jamais descendre en dessous. Il passe aussi par-dessus un /route sticky plus bas." +Session rule this fixes (wave plan, user-approved 2026-10-08): "an explicit per-call choice (Agent `model`/`effort` param, `/route`, `ultrathink`) beats the derived phase for that span". +User, same turn: "continu avec Opus en /ultrathink". + +## CLARIFICATIONS +Q: which loops does the floor cover? / A: the MAIN loop only ("le tour" = the user's turn); sub-agents keep their own routes and pins. [orchestrator — derived, stated to the user] +Q: model axis / A: the floor constrains effort only. A floor route's model (none by default: ultrathink → escalate carries none) applies on main only when neither the sticky nor the turn route names a model, and only with the switch on. [orchestrator — internal] +Q: numeric or absent engine effort / A: the floor level replaces it (the user's explicit level wins over an unknown budget); the haiku effort omission still applies after flooring. [orchestrator — internal] +Q: who clears the floor / A: main turn end (a queued prompt's floor is then promoted), `/route clear`, `/route off` (pass-through). A model `route({clear})`, a `Skill(effort-*)` or any skill load never touches it. [orchestrator — derived from "jamais descendre en dessous"] + +## ACCEPTANCE CRITERIA +1. Suite green with the new tests: `claude plugin test` passes with at least 19 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. + CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 19 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo FLOOR-SUITE-OK + EXPECT: FLOOR-SUITE-OK + EVIDENCE: pending +2. Type-check clean against this build's declarations. + CHECK: T=/Users/b.chanot/.claude/dev-mods/385f7190-70f5-4bdd-b0d8-e4566cd412fd/model-router/.claude-plugin/types; [ -d "$T" ] || T=/Users/b.chanot/Documents/claude/mods/model-router/.claude-plugin/types; W=$(mktemp -d) && printf '{"compilerOptions":{"target":"es2023","lib":["es2023"],"types":[],"module":"esnext","moduleResolution":"bundler","strict":true,"noUncheckedIndexedAccess":true,"noEmit":true,"skipLibCheck":true,"jsx":"react","jsxFactory":"h","jsxFragmentFactory":"Fragment"},"include":["%s/claude-code/index.d.ts","%s/claude-code-tools/index.d.ts","%s/hooks"]}' "$T" "$T" "$PWD/mods/model-router" > "$W/tsconfig.json" && (cd "$W" && npx --yes -p typescript@5 tsc -p tsconfig.json) && echo TSC-OK + EXPECT: TSC-OK + EVIDENCE: pending +3. The floor is its own slot: `turnFloor` is declared in `State`, initialised in `newState`, written by the prompt rule and by a typed `/effort-`, cleared by `/route clear` and at main turn end; the suite carries at least 6 tests whose name contains `floor`. + CHECK: cd mods/model-router/hooks && [ "$(grep -c 'turnFloor' register.ts)" -ge 6 ] && [ "$(grep -cE "^\s*test\('[^']*floor" register.test.ts)" -ge 6 ] && echo FLOOR-SLOT-OK + EXPECT: FLOOR-SLOT-OK + EVIDENCE: pending +4. Judged by reading: effective main effort = the higher (LEVELS order) of the floor and `(userMain ?? turnMain)?.route.effort ?? e.effort`, the floor replacing a numeric or absent engine effort; the floor never applies to a sub-agent step; `turnMain` only ever holds 'model' or 'skill' sources; the prompt rule writes `turnFloor` (or `pendingPrompt` when typed mid-turn with `wait`), promoted into `turnFloor` at main turn end; a non-effort skill load resets `turnMain` only; a model `route({clear})` clears `turnMain` only; every answer that the floor overrides says so truthfully (Skill bridge context, route tool text, `/effort-` text); `/route show` and the status line display the floor; every criterion of `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md` still holds; no function over 25 logic lines. + +## FILE SCOPE +mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts diff --git a/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md b/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md new file mode 100644 index 0000000..fac021b --- /dev/null +++ b/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md @@ -0,0 +1,45 @@ +# CONTRACT — model-router-wiring (wave 1-B2: active in every session, tests, doctor) +- date: 2026-10-08 | flow: feat | branch: feature/model-router-mod +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr, first message of the session): "Et le mieux que ca soit configurable et qu'on puisse l'installer et qu'il soit actif sur toutes les session en userscope". +AskUserQuestion 2026-10-08, question on the loading mechanism (CLAUDE_CODE_PLUGIN_DIRS needs an absolute path, no $HOME expansion in settings `env`, settings.json is tracked and shared): answer "1 . Mais ce n'est pas un skill on est d'accord ? C'est un mod. don cplus u plugin. ET du coup pourquoi pqs link directement ule dossier mod vers le .claude/mods directement via le link.sh ? Pourquoi passer par skills ?" (option 1 = "Lien sous skills/ (Recommended)"). +Explanation given to the user the same turn: a mod is a plugin, not a skill; Claude Code loads a plugin only from a marketplace, an absolute `CLAUDE_CODE_PLUGIN_DIRS` path, a claude.ai sync, or a plugin folder (`.claude-plugin/plugin.json`) under `~/.claude/skills/` (origin `@skills-dir`, loaded in place); a `~/.claude/mods` link alone loads nothing. +Same question batch, settings answer: "Je gère moi-même" (the user's uncommitted `/model` change to settings.json). + +## CLARIFICATIONS +Q: loading mechanism / A: `skills/` = relative symlink `../mods/`, tracked in git; loads as `@skills-dir`, in place, on every machine where link.sh links `~/.claude/skills`. No settings.json change, no link.sh change. Probe 2026-10-08 in an isolated HOME: listed, enabled, "Status: ✔ loaded". [gated 2026-10-08] +Q: settings.json / A: the working-tree change (model → opus, env block moved) stays untouched and out of every commit. [gated 2026-10-08] +Q: override convention / A: a mod's optional user config lives at `~/.claude/.json` (model-router already reads `~/.claude/model-router.json`). [orchestrator] +Q: doctor scope / A: per mod: the loading link resolves into the repo mod dir; `claude plugin list --json` lists `@skills-dir` enabled (warn, not fail, when absent, disabled, or `claude` missing); the override file parses as JSON when present. [orchestrator] + +## ACCEPTANCE CRITERIA +1. `skills/model-router` is a symlink whose target is exactly `../mods/model-router`, and git does not ignore it. + CHECK: [ -L skills/model-router ] && [ "$(readlink skills/model-router)" = "../mods/model-router" ] && ! git check-ignore -q skills/model-router && echo LINK-OK + EXPECT: LINK-OK + EVIDENCE: pending +2. Engine-laid files are ignored: a mod's root `tsconfig.json` and anything under its `.claude-plugin/types/`; the tracked mod files are not ignored. + CHECK: git check-ignore -q mods/model-router/tsconfig.json && git check-ignore -q mods/model-router/.claude-plugin/types/claude-code/index.d.ts && ! git check-ignore -q mods/model-router/hooks/register.ts && ! git check-ignore -q mods/model-router/.claude-plugin/plugin.json && echo IGNORE-OK + EXPECT: IGNORE-OK + EVIDENCE: pending +3. `lib/tests/mods.test.sh` passes on the repo and fails on a fixture that lacks the loading link (positive control through `MODS_ROOT`). + CHECK: make test suite=lib/tests/mods.test.sh >/dev/null 2>&1 && W=$(mktemp -d) && mkdir -p "$W/mods" "$W/skills" && cp -R mods/model-router "$W/mods/" && ! MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && ln -s ../mods/model-router "$W/skills/model-router" && MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && echo MODS-SUITE-OK + EXPECT: MODS-SUITE-OK + EVIDENCE: pending +4. `doctor.sh` prints a `── Mods ──` section with a ✓ line for the model-router loading link. + CHECK: out=$(bash doctor.sh 2>&1); echo "$out" | sed -n '/── Mods ──/,/^$/p' | grep -q '✓.*model-router' && echo DOCTOR-MODS-OK + EXPECT: DOCTOR-MODS-OK + EVIDENCE: pending +5. `CLAUDE.md` has a `## mods/` section naming the `skills/` relative symlink, the `@skills-dir` origin, why not `CLAUDE_CODE_PLUGIN_DIRS`, the gitignored engine-laid files, `~/.claude/.json`, the suite command and how to turn a mod off. + CHECK: grep -q '^## mods/' CLAUDE.md && grep -q '@skills-dir' CLAUDE.md && grep -q 'CLAUDE_CODE_PLUGIN_DIRS' CLAUDE.md && grep -q 'mods.test.sh' CLAUDE.md && grep -q '.json' CLAUDE.md && grep -q '@skills-dir": false' CLAUDE.md && echo CLAUDEMD-OK + EXPECT: CLAUDEMD-OK + EVIDENCE: pending +6. Health stack on the touched shell files, doctrine census green. + CHECK: shellcheck lib/tests/mods.test.sh doctor.sh && make test suite=lib/tests/doctrine-citers.test.sh >/dev/null 2>&1 && echo HEALTH-OK + EXPECT: HEALTH-OK + EVIDENCE: pending +7. Judged by reading: no change to settings.json, link.sh or any install script; the user's settings.json working-tree diff is untouched; the suite SKIPs (explicit SKIP line, exit 0 for that part) only the `claude`-dependent checks when `claude` is absent, and fails when no mod is found at all; doctor's new section never increments the core-link counter (`_LINK_PASS`) and never fails on a missing `claude`; the CLAUDE.md section is terse English matching the file's style. + +## FILE SCOPE +skills/model-router (new symlink) · .gitignore · lib/tests/mods.test.sh (new) · doctor.sh · CLAUDE.md diff --git a/.claude/tasks/plans/2026-10-08-model-router-floor-1835.md b/.claude/tasks/plans/2026-10-08-model-router-floor-1835.md new file mode 100644 index 0000000..6058c60 --- /dev/null +++ b/.claude/tasks/plans/2026-10-08-model-router-floor-1835.md @@ -0,0 +1,108 @@ +# PLAN — model-router wave 1-B1: user effort floor for the turn (dispatch-ready) +Contract: .claude/tasks/contracts/2026-10-08-model-router-floor-1835.md +Code: mods/model-router/hooks/register.ts (read it in full first) and +register.test.ts. API truth: the engine-laid declarations under +mods/model-router/.claude-plugin/types/ (claude-code/index.d.ts, +claude-code-tools/index.d.ts). + +## Why +Today the prompt rule (`ultrathink` → escalate) and a typed `/effort-` +share ONE slot (`turnMain`) with the model's `route` calls and the +`Skill(effort-*)` bridge: last writer wins, and a later skill load resets +the slot to the session default. A user's explicit level is therefore lost +mid-turn. The user chose FLOOR semantics: their level is a minimum for the +whole main turn; derived routes may go above it, never below; it also +lifts a lower sticky `/route`. + +## Precedence after the change (main loop only) +- model axis (unchanged order, floor last): `userMain ?? turnMain ?? turnFloor` + route's `model`, applied only with `mainModelSwitch` and the window guard. +- effort axis: `base = (userMain ?? turnMain)?.route.effort ?? e.effort`; + `effort = floored(base, turnFloor?.route.effort)`. +- `floored(effort, floor)`: no floor → `effort`; `effort` is a Level whose + LEVELS index ≥ the floor's → `effort`; otherwise (lower Level, a number, + or undefined) → `floor`. +- The haiku omission (`effort: undefined` when the model sent starts with + `claude-haiku`) still runs AFTER flooring. +- Sub-agent steps (`e.agentId` set) never read `turnFloor`. + +## Changes in register.ts (names as in the current file) +1. `State`: add `turnFloor: Routed | null` with the comment `user-explicit + level for this turn (prompt rule, typed /effort-): a floor, main loop + only`; reword the `turnMain` comment to `model route tool, skill table + row, Skill(effort-*) bridge; dropped at turn end`. `newState`: + `turnFloor: null`. +2. Helpers (new, small): `const rank = (l: Level): number => LEVELS.indexOf(l)`; + `function floored(effort: StepIn['effort'], floor: Level | undefined)` + per the rule above. A helper `floorLevel(st)` returning + `st.turnFloor?.route.effort` is allowed if it keeps call sites short. +3. `mainPlan`: compute `base` and `effort = floored(base, floorLevel(st))`; + `wanted = set?.route.model ?? st.turnFloor?.route.model`; the rest + (switch, window guard) unchanged. +4. `registerPrompt` / `prompt.submit`: the non-queued branch writes + `st.turnFloor = routed` (instead of `st.turnMain`); the queued branch + (`e.turnId !== undefined && e.wait`) keeps writing `st.pendingPrompt`. +5. `slashEffort`: write `st.turnFloor = { phase: skill, route: { effort: + level }, source: 'slash' }`; returned text line becomes `Effort floor + set by model-router for this turn: nothing below it runs.` + followed by `\n` + the original text (prepend, never replace). +6. `onSkillLoad` (main branch): `st.turnMain = null` unconditionally (the + slot no longer holds prompt or slash routes), then the table row as now. + `turnFloor` is never touched there. +7. `clearRoutes` (`/route clear`): also `st.turnFloor = null`. + `clearLoop` (model `route({clear})`, main branch): `turnMain` only, as now. +8. `endMainTurn`: `st.turnFloor = st.pendingPrompt; st.pendingPrompt = + null; st.turnMain = null;` then the existing resets. +9. Truthful answers (main branch only; agent branches unchanged): + - `effortBridge`: keep the sticky sentence when `st.userMain` is set; + else when the floor ranks above `level`: `model-router: + recorded, but the user's floor for this turn keeps main at ; + the skill text was not loaded.`; else the current sentence. + - `routedText`: keep the sticky branch; else when `p.route.effort` is + set and the floor ranks above it, print the effort as ` (user + floor; asked )`. +10. Display: `mainText` appends ` · floor ()` when `turnFloor` is + set (also after `main: session defaults`); `statusLine` appends + ` · floor `. + +## Tests in register.test.ts (keep every existing test; adapt only what +the new slot changes, e.g. the `ultrathink` test now expects the floor on +the `main:` line). Add at least six tests whose names contain `floor`, +using the existing boot helper, full typed inputs and bottom hooks, and +asserting on the `main:` line or on what the bottom `turn.step` hook +receives (drain the stream with `for await`, then `.result`): +- `floor: ultrathink survives a model route` — prompt `ultrathink` + (composer, `wait: false`, no `turnId`) then route tool `orchestrate` → + a main step with engine effort `high` reaches the bottom at `max`. +- `floor: a typed /effort-medium floors a lower route and allows a higher + one` — `$.skill.prompt({ skill: 'effort-medium', text: 'x' })` (no Skill + call in flight) → route tool `mechanical` → main step at `medium`; + then route tool `escalate` → main step at `max`. +- `floor: survives a skill load` — ultrathink, route tool `orchestrate`, + then a non-effort `Skill` call (bottom `tool.call` hook registered) → + main step at `max`, and `main:` line no longer names `orchestrate`. +- `floor: lifts a lower sticky route, then ends with the turn` — `/route + effort=low` then ultrathink → main step at `max`; fire a main + `turn.complete` → next main step at `low`. +- `floor: main only` — ultrathink, spawn `Explore` (bottom `agent.spawn` + hook returning an `agentId`), then a step for that `agentId` → reaches + the bottom at `medium`, not `max`. +- `floor: /route clear removes it` — ultrathink, `/route clear` → main + step keeps the engine effort. +Optional seventh: the bridge context line names the floor when it wins. + +## Constraints +- Style: ≤ 25 logic lines per function, 80 chars per line, no `any`, no + module-level mutable state, doc comments state intent. +- Do not touch: the agent axis, the spawn table, config loading, the + hardening (caps, warnOnce, safely), the route tool schema. +- Verify (paste outputs): `claude plugin validate .`, the contract's tsc + command, `claude plugin test .`, then from the repo root + `bash ~/.claude/lib/gates.sh run .claude/tasks/contracts/2026-10-08-model-router-floor-1835.md`. + +## Disposition +- honors BDR-115 (one writer per axis, calling-loop writes, truthful + answers) and the wave plan's routing rule (explicit user choice beats the + derived phase); supersedes the 1-A contract's one-slot precedence for + prompt and slash sources. +- LRN-206 (kit facts) applies to every new test. diff --git a/.claude/tasks/plans/2026-10-08-model-router-mod.md b/.claude/tasks/plans/2026-10-08-model-router-mod.md index 20f3832..b5ff7a6 100644 --- a/.claude/tasks/plans/2026-10-08-model-router-mod.md +++ b/.claude/tasks/plans/2026-10-08-model-router-mod.md @@ -95,6 +95,27 @@ does many different things inside one run. So: | verify | sonnet | xhigh | verifier, security-auditor | | mechanical | haiku | low | cp/mv, git bookkeeping, status collection, listing | +## Decisions 2026-10-08 (evening, user via AskUserQuestion) +- LOADING (supersedes "CLAUDE_CODE_PLUGIN_DIRS via settings.json + link.sh"): + PLUGIN_DIRS needs absolute paths, settings `env` has no `$HOME` + expansion, settings.json is tracked and shared across machines; a local + marketplace `add` writes an absolute path into settings.json too. Chosen: + tracked relative symlink `skills/` → `../mods/`; Claude Code + loads it as `@skills-dir`, in place (docs plugins/loading; probe in + an isolated HOME: listed, enabled, loaded). Repo scripts walking skills/ + glob `*/SKILL.md` or fixed names: unaffected. User asked why not + `~/.claude/mods`: Claude Code scans no such folder, a link there loads + nothing. +- PRECEDENCE: `ultrathink` (prompt rule) and a typed `/effort-` become a + FLOOR for the main turn: derived routes may go above, never below; it + lifts a lower sticky `/route`. Main loop only. +- settings.json: the user's uncommitted `/model` change (model → opus) is + theirs to manage; never staged. +- Live 2026-10-08: Skill(effort-low) bridge answered in place, next request + `low`; `ultrathink` turn on Opus ran at `max` (engine base `medium`); + Explore without params spawned on `claude-sonnet-5-5`, all 3 steps + `medium` (no spawn/step race observed). + ## Wave 0 — spike (dev-mods folder, hot reload, this session) - [x] W0.1 minimal mod: `/route` command, `route` tool, `turn.step` logging + rewrite, `agent.spawn` rewrite, `ultrathink` → max, spinner suffix diff --git a/.claude/tasks/plans/2026-10-08-model-router-wiring-1835.md b/.claude/tasks/plans/2026-10-08-model-router-wiring-1835.md new file mode 100644 index 0000000..b136601 --- /dev/null +++ b/.claude/tasks/plans/2026-10-08-model-router-wiring-1835.md @@ -0,0 +1,106 @@ +# PLAN — model-router wave 1-B2: active in every session, tests, doctor (dispatch-ready) +Contract: .claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md +Repo root: /Users/b.chanot/Documents/claude (branch feature/model-router-mod). + +## Facts this plan rests on (verified 2026-10-08) +- Claude Code loads a folder holding `.claude-plugin/plugin.json` under + `~/.claude/skills/` as `@skills-dir`, in place, live at the next + session start or `/reload-plugins` (docs: plugins/loading "In-place and + copied plugins"; probe in an isolated HOME: listed, enabled, loaded). +- `~/.claude/skills` is already a symlink to the repo's `skills/` (link.sh). +- Repo scripts that walk `skills/` glob `*/SKILL.md` or fixed paths + (doctor.sh, lib/skill-routing-census.py, the census suites); + lib/profile.sh only moves entries named in a profile. An entry without + SKILL.md is never counted, moved or flagged. +- The engine lays `/tsconfig.json` (extends the types) and + `/.claude-plugin/types/` (own `.gitignore` holding `*`) when a mod + loads; today `mods/model-router/tsconfig.json` shows as untracked. +- settings.json carries the user's uncommitted `/model` change: never + stage, edit or restore it. + +## Files +- [ ] `skills/model-router` — new RELATIVE symlink: from the repo root, + `ln -s ../mods/model-router skills/model-router`. Nothing else in skills/. +- [ ] `.gitignore` — append a block: + ``` + # mods/: files the engine lays beside a loaded mod (editor types) + mods/*/tsconfig.json + mods/*/.claude-plugin/types/ + ``` + Check first that no existing pattern ignores `skills/model-router` or + the tracked mod files (contract AC1/AC2 oracles). +- [ ] `lib/tests/mods.test.sh` — new suite, style of the existing suites + (read lib/tests/effort-pins.test.sh first and mirror its header, helpers + and summary). Behaviour: + - `ROOT="${MODS_ROOT:-}"`. + - Collect `$ROOT/mods/*/.claude-plugin/plugin.json`; none → FAIL + ("no mod found") so the suite can never pass vacuously. + - Per mod dir ``: (1) the manifest `name` (python3 json, argv — + never string-spliced) equals the folder name; (2) `$ROOT/skills/` + is a symlink whose `readlink` is exactly `../mods/`; (3) when + `command -v claude` succeeds: `claude plugin validate "$ROOT/mods/"` + prints `Validation passed` and no `warning` (case-insensitive); + (4) same condition: `claude plugin test "$ROOT/mods/"` exits 0. + - `claude` absent → one `SKIP: claude CLI not found — validate/test not + run` line; checks (1)-(2) still run and decide the exit code. + - Exit 1 on any failure, 0 otherwise; one PASS/FAIL line per check and a + final count line. + - shellcheck clean. No network, no writes outside a `mktemp -d` if any + scratch is needed (none expected). +- [ ] `doctor.sh` — new section `── Mods ──`, placed right after the + "Vendored skills" section (read lines 120-160 first; mirror its + `echo ""` / heading / pass-warn-fail-info style). For each + `$REPO/mods/*/` holding `.claude-plugin/plugin.json` (`` = folder): + - link `$HOME/.claude/skills/`: `readlink -f` equal to + `$REPO/mods/` → `pass "mod : loading link ~/.claude/skills/"`; + missing → `fail "mod : ~/.claude/skills/ MISSING — git checkout skills/, then make link"`; + elsewhere → `warn`. Do NOT call `check_symlink` (it feeds the core-link + counter `_LINK_PASS` / `_EXPECTED_LINKS`). + - `command -v claude` → `claude plugin list --json` parsed with python3 + (argv/stdin, no splicing): id `@skills-dir` with `enabled: true` + → `pass "mod : loaded as @skills-dir"`; present but + disabled → `warn "... disabled (enabledPlugins \"@skills-dir\": false)"`; + absent → `warn "... not listed — new session or /reload-plugins"`. + `claude` missing → `info "claude CLI not found — load state not checked"`. + - `$HOME/.claude/.json` present → `python3 -m json.tool` (quiet) + → `pass "mod : override ~/.claude/.json parses"` or + `fail "... invalid JSON"`; absent → nothing. + - No mod at all → `info "no mods"`. +- [ ] `CLAUDE.md` (project, repo root) — new section `## mods/ — function-hooks + plugins (Claude Code mods)` placed after the graphify section, terse + English in the file's own style, at most ~14 lines, covering: what lives + in `mods//`; it loads through the tracked relative symlink + `skills/` → `../mods/` as `@skills-dir` (in place, live + at the next session or `/reload-plugins`); why not + `CLAUDE_CODE_PLUGIN_DIRS` (absolute path, settings `env` has no `$HOME` + expansion, settings.json is tracked) nor a local marketplace (its `add` + writes an absolute path into settings.json); engine-laid + `tsconfig.json` + `.claude-plugin/types/` are gitignored; optional user + config `~/.claude/.json`; tests `make test suite=lib/tests/mods.test.sh` + (validate + `claude plugin test`); turn a mod off with + `"@skills-dir": false` in `enabledPlugins`; a dev copy loaded with + `--plugin-dir` or the hot-reload folder shadows the skills-dir copy + (same name, session-only wins). + +## Verify (executor pastes outputs) +`ls -l skills/model-router`; `git check-ignore -v mods/model-router/tsconfig.json`; +`make test suite=lib/tests/mods.test.sh`; the contract AC3 positive control; +`bash doctor.sh | sed -n '/── Mods ──/,/^$/p'`; `shellcheck lib/tests/mods.test.sh doctor.sh`; +`git status --short` (settings.json still ` M`, untouched); then from the +repo root `bash ~/.claude/lib/gates.sh run .claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md`. + +## Edge cases +- The engine-laid `mods/model-router/tsconfig.json` already exists on disk: + after the `.gitignore` change it must disappear from `git status`. +- doctor runs without `claude` on PATH (Linux box): info line, no failure. +- A second mod later: the suite and doctor loop over `mods/*/` already. +- A hot-reload or `--plugin-dir` copy of the same mod shadows the + skills-dir copy in that session; doctor reads `claude plugin list` from a + fresh process, which sees only the skills-dir copy. + +## Disposition +- honors BDR-115 (mod in `mods/`, single source); amends its "Load:" line + (PLUGIN_DIRS → skills-dir link), to be recorded at capitalize. +- honors the destructive-tools rule: no recursive delete, no transfer + tool; LRN-150/LRN-171 shell hygiene (`command grep` where a shim can + interfere is not needed here: plain bash). From 868a7f05153a41ef129c61f1c3748f2b2731ce20 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 09:24:32 +0200 Subject: [PATCH 031/547] chore(tasks): model-router B1/B2 plans r2 after the 6-lens challenge round --- .../2026-10-08-model-router-floor-1835.md | 15 +++-- .../2026-10-08-model-router-wiring-1835.md | 20 ++++-- .../2026-10-08-model-router-floor-1835.md | 64 +++++++++++++++++++ .../2026-10-08-model-router-wiring-1835.md | 60 +++++++++++++++++ 4 files changed, 146 insertions(+), 13 deletions(-) diff --git a/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md b/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md index 53daccc..30943eb 100644 --- a/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md +++ b/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md @@ -10,24 +10,27 @@ User, same turn: "continu avec Opus en /ultrathink". ## CLARIFICATIONS Q: which loops does the floor cover? / A: the MAIN loop only ("le tour" = the user's turn); sub-agents keep their own routes and pins. [orchestrator — derived, stated to the user] -Q: model axis / A: the floor constrains effort only. A floor route's model (none by default: ultrathink → escalate carries none) applies on main only when neither the sticky nor the turn route names a model, and only with the switch on. [orchestrator — internal] +Q: model axis / A: one rule: `userMain?.route.model ?? turnMain?.route.model ?? turnFloor?.route.model`, applied only with the switch on (r2). [orchestrator — internal] +Q (r2): default vs minimum / A: the user's level is the turn's default when no sticky or turn route names an effort AND its minimum; a typed `/effort-low` therefore still lowers an unrouted turn. Derived from the chosen option ("Ton niveau est un minimum pour tout le tour") plus the challenge finding that a pure floor would make `/effort-low` a no-op. [orchestrator — r2] +Q (r2): mid-turn prompt / A: applied to the running turn AND kept for the next (`wait` ignored, the engine queues either way). [orchestrator — r2] +Q (r2): per-machine off switch / A: `"enabled": false` in `~/.claude/model-router.json` (untracked); an `enabledPlugins` entry would dirty the tracked settings.json on every machine. [orchestrator — r2, from the user's "configurable"] Q: numeric or absent engine effort / A: the floor level replaces it (the user's explicit level wins over an unknown budget); the haiku effort omission still applies after flooring. [orchestrator — internal] Q: who clears the floor / A: main turn end (a queued prompt's floor is then promoted), `/route clear`, `/route off` (pass-through). A model `route({clear})`, a `Skill(effort-*)` or any skill load never touches it. [orchestrator — derived from "jamais descendre en dessous"] ## ACCEPTANCE CRITERIA -1. Suite green with the new tests: `claude plugin test` passes with at least 19 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. - CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 19 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo FLOOR-SUITE-OK +1. Suite green with the new tests: `claude plugin test` passes with at least 22 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. + CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 22 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo FLOOR-SUITE-OK EXPECT: FLOOR-SUITE-OK EVIDENCE: pending 2. Type-check clean against this build's declarations. CHECK: T=/Users/b.chanot/.claude/dev-mods/385f7190-70f5-4bdd-b0d8-e4566cd412fd/model-router/.claude-plugin/types; [ -d "$T" ] || T=/Users/b.chanot/Documents/claude/mods/model-router/.claude-plugin/types; W=$(mktemp -d) && printf '{"compilerOptions":{"target":"es2023","lib":["es2023"],"types":[],"module":"esnext","moduleResolution":"bundler","strict":true,"noUncheckedIndexedAccess":true,"noEmit":true,"skipLibCheck":true,"jsx":"react","jsxFactory":"h","jsxFragmentFactory":"Fragment"},"include":["%s/claude-code/index.d.ts","%s/claude-code-tools/index.d.ts","%s/hooks"]}' "$T" "$T" "$PWD/mods/model-router" > "$W/tsconfig.json" && (cd "$W" && npx --yes -p typescript@5 tsc -p tsconfig.json) && echo TSC-OK EXPECT: TSC-OK EVIDENCE: pending -3. The floor is its own slot: `turnFloor` is declared in `State`, initialised in `newState`, written by the prompt rule and by a typed `/effort-`, cleared by `/route clear` and at main turn end; the suite carries at least 6 tests whose name contains `floor`. - CHECK: cd mods/model-router/hooks && [ "$(grep -c 'turnFloor' register.ts)" -ge 6 ] && [ "$(grep -cE "^\s*test\('[^']*floor" register.test.ts)" -ge 6 ] && echo FLOOR-SLOT-OK +3. The floor is its own slot: `turnFloor` is declared in `State`, initialised in `newState`, written by the prompt rule and by a typed `/effort-`, cleared by `/route clear` and at main turn end; the suite carries at least 8 tests whose name contains `floor`; one helper `mainEffort` decides the main effort; the config key `enabled` exists. + CHECK: cd mods/model-router/hooks && [ "$(grep -c 'turnFloor' register.ts)" -ge 6 ] && [ "$(grep -cE "^\s*test\('[^']*floor" register.test.ts)" -ge 8 ] && grep -q 'mainEffort' register.ts && grep -q 'enabled' register.ts && echo FLOOR-SLOT-OK EXPECT: FLOOR-SLOT-OK EVIDENCE: pending -4. Judged by reading: effective main effort = the higher (LEVELS order) of the floor and `(userMain ?? turnMain)?.route.effort ?? e.effort`, the floor replacing a numeric or absent engine effort; the floor never applies to a sub-agent step; `turnMain` only ever holds 'model' or 'skill' sources; the prompt rule writes `turnFloor` (or `pendingPrompt` when typed mid-turn with `wait`), promoted into `turnFloor` at main turn end; a non-effort skill load resets `turnMain` only; a model `route({clear})` clears `turnMain` only; every answer that the floor overrides says so truthfully (Skill bridge context, route tool text, `/effort-` text); `/route show` and the status line display the floor; every criterion of `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md` still holds; no function over 25 logic lines. +4. Judged by reading: effective main effort comes from ONE helper `mainEffort` used by `mainPlan` and by every answer text: base `(userMain ?? turnMain)?.route.effort ?? turnFloor?.route.effort ?? e.effort`, then floored by `turnFloor` (LEVELS order; a numeric or absent value is replaced); the floor never applies to a sub-agent step; `turnMain` only ever holds 'model' or 'skill' sources; the prompt rule writes `turnFloor` (keeping the higher of two) and, when typed mid-turn (`turnId` set, `wait` ignored), also `pendingPrompt`, promoted into `turnFloor` at main turn end; `"enabled": false` in the override file makes every hook pass through after each config load (`/route on` re-enables for the session); a non-effort skill load resets `turnMain` only; a model `route({clear})` clears `turnMain` only; every answer that the floor overrides says so truthfully (Skill bridge context, route tool text, `/effort-` text); `/route show` and the status line display the floor; every criterion of `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md` still holds; no function over 25 logic lines. ## FILE SCOPE mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts diff --git a/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md b/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md index fac021b..6f887de 100644 --- a/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md +++ b/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md @@ -19,18 +19,22 @@ Q: doctor scope / A: per mod: the loading link resolves into the repo mod dir; ` CHECK: [ -L skills/model-router ] && [ "$(readlink skills/model-router)" = "../mods/model-router" ] && ! git check-ignore -q skills/model-router && echo LINK-OK EXPECT: LINK-OK EVIDENCE: pending -2. Engine-laid files are ignored: a mod's root `tsconfig.json` and anything under its `.claude-plugin/types/`; the tracked mod files are not ignored. - CHECK: git check-ignore -q mods/model-router/tsconfig.json && git check-ignore -q mods/model-router/.claude-plugin/types/claude-code/index.d.ts && ! git check-ignore -q mods/model-router/hooks/register.ts && ! git check-ignore -q mods/model-router/.claude-plugin/plugin.json && echo IGNORE-OK +2. Engine-laid files are ignored for ANY mod: a mod's root `tsconfig.json` (root `.gitignore`; the `.claude-plugin/types/` folder ignores itself); the tracked mod files are not ignored. + CHECK: git check-ignore -q mods/model-router/tsconfig.json && git check-ignore -q mods/zz-future/tsconfig.json && ! git check-ignore -q mods/model-router/hooks/register.ts && ! git check-ignore -q mods/model-router/.claude-plugin/plugin.json && [ -z "$(git status --short mods/)" ] && echo IGNORE-OK EXPECT: IGNORE-OK EVIDENCE: pending -3. `lib/tests/mods.test.sh` passes on the repo and fails on a fixture that lacks the loading link (positive control through `MODS_ROOT`). - CHECK: make test suite=lib/tests/mods.test.sh >/dev/null 2>&1 && W=$(mktemp -d) && mkdir -p "$W/mods" "$W/skills" && cp -R mods/model-router "$W/mods/" && ! MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && ln -s ../mods/model-router "$W/skills/model-router" && MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && echo MODS-SUITE-OK +3. `lib/tests/mods.test.sh` passes on the repo, fails on a fixture that lacks the loading link, fails on an empty `mods/`, and SKIPs (exit 0) the CLI checks when `claude plugin test` is unavailable (probe by capability, PATH-shadowed `claude` in the control). + CHECK: make test suite=lib/tests/mods.test.sh >/dev/null 2>&1 && W=$(mktemp -d) && mkdir -p "$W/mods" "$W/skills" "$W/bin" && cp -R mods/model-router "$W/mods/" && ! MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && ln -s ../mods/model-router "$W/skills/model-router" && MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && printf '#!/bin/sh\nexit 1\n' > "$W/bin/claude" && chmod +x "$W/bin/claude" && PATH="$W/bin:$PATH" MODS_ROOT="$W" bash lib/tests/mods.test.sh 2>&1 | grep -q '^SKIP' && E=$(mktemp -d) && mkdir -p "$E/mods" "$E/skills" && ! MODS_ROOT="$E" bash lib/tests/mods.test.sh >/dev/null 2>&1 && echo MODS-SUITE-OK EXPECT: MODS-SUITE-OK EVIDENCE: pending -4. `doctor.sh` prints a `── Mods ──` section with a ✓ line for the model-router loading link. - CHECK: out=$(bash doctor.sh 2>&1); echo "$out" | sed -n '/── Mods ──/,/^$/p' | grep -q '✓.*model-router' && echo DOCTOR-MODS-OK +4. `doctor.sh` prints a `── Mods ──` section with a ✓ line for model-router; with the link absent (HOME pointed at a scratch `.claude` whose `skills/` lacks the link) the section prints an info line, doctor reaches its summary and exits 0 for that section's sake (no new error). + CHECK: out=$(bash doctor.sh 2>&1); echo "$out" | sed -n '/── Mods ──/,/^$/p' | grep -q '✓.*model-router' && H=$(mktemp -d) && mkdir -p "$H/.claude/skills" && o2=$(HOME="$H" bash doctor.sh 2>&1); echo "$o2" | sed -n '/── Mods ──/,/^$/p' | grep -qi 'not linked' && echo "$o2" | grep -q '═══' && echo DOCTOR-MODS-OK EXPECT: DOCTOR-MODS-OK EVIDENCE: pending +4b. The mod is enabled through the tracked link in a FRESH process: `claude plugin list --json` lists `model-router@skills-dir` with `enabled: true` (run after the dev-mods link is removed, see W6). + CHECK: claude plugin list --json 2>/dev/null | python3 -c 'import json,sys; rows=json.load(sys.stdin); ok=any(r.get("id")=="model-router@skills-dir" and r.get("enabled") is True for r in rows); sys.exit(0 if ok else 1)' && echo LOADED-OK + EXPECT: LOADED-OK + EVIDENCE: pending 5. `CLAUDE.md` has a `## mods/` section naming the `skills/` relative symlink, the `@skills-dir` origin, why not `CLAUDE_CODE_PLUGIN_DIRS`, the gitignored engine-laid files, `~/.claude/.json`, the suite command and how to turn a mod off. CHECK: grep -q '^## mods/' CLAUDE.md && grep -q '@skills-dir' CLAUDE.md && grep -q 'CLAUDE_CODE_PLUGIN_DIRS' CLAUDE.md && grep -q 'mods.test.sh' CLAUDE.md && grep -q '.json' CLAUDE.md && grep -q '@skills-dir": false' CLAUDE.md && echo CLAUDEMD-OK EXPECT: CLAUDEMD-OK @@ -39,7 +43,9 @@ Q: doctor scope / A: per mod: the loading link resolves into the repo mod dir; ` CHECK: shellcheck lib/tests/mods.test.sh doctor.sh && make test suite=lib/tests/doctrine-citers.test.sh >/dev/null 2>&1 && echo HEALTH-OK EXPECT: HEALTH-OK EVIDENCE: pending -7. Judged by reading: no change to settings.json, link.sh or any install script; the user's settings.json working-tree diff is untouched; the suite SKIPs (explicit SKIP line, exit 0 for that part) only the `claude`-dependent checks when `claude` is absent, and fails when no mod is found at all; doctor's new section never increments the core-link counter (`_LINK_PASS`) and never fails on a missing `claude`; the CLAUDE.md section is terse English matching the file's style. +7. Judged by reading: no change to settings.json, link.sh or any install script; the suite probes the CAPABILITY (`claude plugin test --help`), bounds every CLI call in time, captures `2>&1`, SKIPs with a reason, fails when no mod is found; doctor's section is fail-soft under `set -euo pipefail` (existence test before readlink, `-ef` comparison, one guarded `claude plugin list --json`, python exits 0 with `unknown` on any parse error), never increments `_LINK_PASS`, says "enabled" not "loaded", treats a missing link as info; the link step is idempotent; CLAUDE.md names the per-machine `"enabled": false` switch, the tracked-settings cost of `enabledPlugins`, and the dev-copy shadowing rule; the CLAUDE.md section is terse English matching the file's style. +Q (r2): ordering / A: this contract runs after the floor contract (`2026-10-08-model-router-floor-1835`) is committed and green. [orchestrator] +Q (r2): update-all `claude plugin update` over `@skills-dir` / A: accepted residual (one recurring warn), logged in TODO; out of FILE SCOPE. [orchestrator] ## FILE SCOPE skills/model-router (new symlink) · .gitignore · lib/tests/mods.test.sh (new) · doctor.sh · CLAUDE.md diff --git a/.claude/tasks/plans/2026-10-08-model-router-floor-1835.md b/.claude/tasks/plans/2026-10-08-model-router-floor-1835.md index 6058c60..8c3019b 100644 --- a/.claude/tasks/plans/2026-10-08-model-router-floor-1835.md +++ b/.claude/tasks/plans/2026-10-08-model-router-floor-1835.md @@ -106,3 +106,67 @@ Optional seventh: the bridge context line names the floor when it wins. derived phase); supersedes the 1-A contract's one-slot precedence for prompt and slash sources. - LRN-206 (kit facts) applies to every new test. + +## r2 — challenge round (3 lenses, 0 BLOCKER, 4 MAJOR): BINDING, overrides the sections above where they conflict +R1. ONE decision helper, used by `mainPlan` AND by every answer text: + `mainEffort(st, engine: StepIn['effort'])` → `{ effort, by }` with + `by` ∈ `'floor' | 'sticky' | 'turn' | 'engine'`. + `base = (st.userMain ?? st.turnMain)?.route.effort + ?? st.turnFloor?.route.effort ?? engine` + `effort = floored(base, st.turnFloor?.route.effort)`; `by = 'floor'` + when the floor raised or supplied the value, else the slot it came from. + The user's level is therefore BOTH the turn's default (when no sticky + or turn route names an effort) AND its minimum: a typed `/effort-low` + lowers a turn that has no route (engine `high` → `low`), and a route + can still go higher. No text function compares ranks on its own. +R2. Model axis, one rule written once (contract updated): + `st.userMain?.route.model ?? st.turnMain?.route.model ?? st.turnFloor?.route.model`, + switch and window guard unchanged. +R3. Prompt rule with `e.turnId !== undefined` (typed while a turn runs; + `wait` is IGNORED: the engine queues every mid-turn prompt either way): + write the floor NOW (higher of the existing floor and the new one) + AND set `pendingPrompt` to it, so the turn that reads the prompt has it + whichever it is. No `turnId` → write the floor (higher of two). + `endMainTurn` promotes `pendingPrompt` into `turnFloor`. Two floors in + one turn always keep the higher one (prompt rule and typed slash). +R4. Truthful texts, all phrased from `mainEffort` (main branch only): + - Skill bridge, route tool, typed `/effort-`: when `by === 'floor'` + and the result differs from what was asked, name the floor and its + source (`ultrathink rule` or `typed /effort-`) and add + `/route clear to drop it`; when `by === 'sticky'`, the sticky + sentence; the old fixed "sticky wins" sentences go. + - `/effort-` text: `Effort set by model-router for the main loop + this turn (minimum; a higher route still applies).` plus the floor + or sticky outcome when one changes it. + - main loop on a haiku model: print `effort - (haiku takes none)`. + - model `route({clear})` on main with a floor set: append `; user floor + () still holds — /route clear drops it`. +R5. Display: `mainText` / `statusLine` show ` · floor ` only when the + floor carries an effort AND the router is on; the `skill.prompt` hook + calls `refresh($, st)` after the slash write. +R6. Persistent per-machine off switch (wiring challenge, user's "configurable"): + config key `enabled: boolean` (default `true`) in + `~/.claude/model-router.json` (untracked, per machine). `false` → + `st.off = true` after every config load (session start, `/route + reload`); `/route on` re-enables for the session only; `show` and the + status line say `off (config)` vs `off`. Merged with `pickBool` like + the other scalars; `DEFAULT_CONFIG.enabled = true`. +R7. Tests (replace the list above where it differs): `runStep` takes a + full `TurnStepInput` (from 'claude-code'); every floor test steps with + engine effort `high` (or `xhigh`); every `test('…', async (` line ≤ 80 + chars with `floor` in the single-line name. At least 8 floor tests: + ultrathink survives a model route · typed /effort-medium clamps low, + lets max pass · typed /effort-low lowers an unrouted turn (engine high + → low) · survives a skill load · lifts a lower sticky then ends with + the turn · main only (agent step unaffected) · /route clear removes it + · mid-turn prompt (turnId + wait) is applied now AND promoted after the + main turn.complete · mandatory text test: sticky `/route effort=low`, + ultrathink, route tool `plan` → the answer names the floor. + `enabled: false` cannot be reached in the kit (no fs, LRN-206): cover + the off path through `/route off` and say so in a comment. +R8. Residuals accepted (logged in TODO, not built): floor expiry depends on + a main `turn.complete` reaching this mod (another plugin answering it + without `next` would keep it); `skill.prompt` cannot tell a typed + `/effort-` from a sub-agent preload (no agentId; no repo agent + preloads one); an incidental "ultrathink" in pasted text floors the + turn (mitigated by R4 naming the source and the `/route clear` hint). diff --git a/.claude/tasks/plans/2026-10-08-model-router-wiring-1835.md b/.claude/tasks/plans/2026-10-08-model-router-wiring-1835.md index b136601..9b05f82 100644 --- a/.claude/tasks/plans/2026-10-08-model-router-wiring-1835.md +++ b/.claude/tasks/plans/2026-10-08-model-router-wiring-1835.md @@ -98,6 +98,66 @@ repo root `bash ~/.claude/lib/gates.sh run .claude/tasks/contracts/2026-10-08-mo skills-dir copy in that session; doctor reads `claude plugin list` from a fresh process, which sees only the skills-dir copy. +## r2 — challenge round (3 lenses, 0 BLOCKER, 5 MAJOR): BINDING, overrides the sections above where they conflict +W1. ORDER: this plan runs AFTER the floor plan (B1) is committed and green + on the same branch: the suite and doctor test whatever register.ts is + on disk. +W2. `.gitignore`: add ONLY `mods/*/tsconfig.json` with the comment + `# mods/: the engine lays tsconfig.json beside a loaded mod; its + .claude-plugin/types/ ignores itself`. (The types folder carries its + own `.gitignore` holding `*`.) +W3. Link step idempotent: `[ -L skills/model-router ] || ln -s + ../mods/model-router skills/model-router` (a bare `ln -s` re-run would + create a nested link inside the mod). +W4. `lib/tests/mods.test.sh` fail-soft and bounded: + - capability probe, not presence: `command -v claude` AND `claude plugin + test --help >/dev/null 2>&1`; otherwise ONE `SKIP: claude plugin test + unavailable () — validate/test not run` line, checks (1)-(2) + still decide the exit code; + - `claude plugin validate` and `claude plugin test` captured with `2>&1`; + the validate verdict is the line matching `Validation passed`, with + `warning` searched only in that captured output; + - every CLI call bounded: `timeout 120` when available (coreutils / + `gtimeout`), else a background-and-wait guard; a timeout is a FAIL + naming it; + - no mod found → FAIL (never vacuous). +W5. doctor `── Mods ──` fail-soft under `set -euo pipefail`: + - `[ -L "$link" ] || [ -e "$link" ]` BEFORE any readlink; compare with + `[ "$link" -ef "$REPO/mods/" ]` (handles logical vs physical + repo paths), never string equality on `readlink -f`; + - a missing link is `info "mod : not linked (skills/ absent) + — git checkout skills/ if wanted"`, NOT `fail` (a user may + remove the link on purpose; doctor red forever would break + update-all's final doctor run); + - ONE `claude plugin list --json` call before the loop, inside + `if ! out=$(claude plugin list --json 2>/dev/null); then warn "mods: + claude plugin list failed — load state not checked"; out=""; fi`; the + python3 parse reads stdin, exits 0 always, prints `enabled|disabled| + absent|unknown` per name (any parse error → `unknown`); + - wording: `pass "mod : enabled as @skills-dir"` (not + "loaded": the list proves enablement, not a successful load); + `disabled` → warn naming `"@skills-dir": false`; `absent` → + `warn "mod : not listed as @skills-dir — run: claude plugin + validate mods/ (policy, manifest or name conflict)"` (a fresh + process rescans skills/, so a restart changes nothing); `unknown` → + warn "list output not understood"; + - `claude` missing → nothing (doctor's Prerequisites section already + fails on it); no override-file JSON check (the mod validates its own + config and logs at session start). +W6. CLAUDE.md `## mods/` also says: the only per-machine off switch is + `"enabled": false` in `~/.claude/.json` (untracked); an + `enabledPlugins` `"@skills-dir": false` entry works too but lands + in the TRACKED settings.json, so it dirties every machine's tree; and + that a hot-reload / `--plugin-dir` copy of the same name shadows the + skills-dir copy for that session (docs plugins/loading "Name + conflicts"), so the dev link in `~/.claude/dev-mods//` must + be removed before `/reload-plugins` is read as a test of the skills-dir + path. +W7. `update-all.sh` runs `claude plugin update` over every listed plugin + (lines ~606-618): a `@skills-dir` entry will produce one recurring + warn there. Accepted residual, logged in TODO (an update-all edit is + out of this contract's FILE SCOPE). + ## Disposition - honors BDR-115 (mod in `mods/`, single source); amends its "Load:" line (PLUGIN_DIRS → skills-dir link), to be recorded at capitalize. From 1ff608a68cf8509d64cbb8e50b4defb986c3ca18 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 10:12:28 +0200 Subject: [PATCH 032/547] =?UTF-8?q?feat(mods):=20model-router=20user=20eff?= =?UTF-8?q?ort=20floor=20=E2=80=94=20ultrathink=20and=20typed=20/effort-=20set=20the=20main=20turn's=20default=20and=20minimum?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One decision helper (mainEffort) feeds the plan and every answer text; per-axis precedence (sticky > turn route > floor > engine); a mid-turn prompt floors the running turn and the next; per-machine kill switch "enabled": false in ~/.claude/model-router.json, kept across /clear and across a failed reload; typed /effort- attested at prompt.submit so a sub-agent preload cannot floor the main loop. 30 plugin tests. --- mods/model-router/hooks/register.test.ts | 216 +++++++++++++++++- mods/model-router/hooks/register.ts | 276 +++++++++++++++++++---- 2 files changed, 439 insertions(+), 53 deletions(-) diff --git a/mods/model-router/hooks/register.test.ts b/mods/model-router/hooks/register.test.ts index 030970b..b1074d5 100644 --- a/mods/model-router/hooks/register.test.ts +++ b/mods/model-router/hooks/register.test.ts @@ -1,6 +1,6 @@ import { test, expect } from 'claude-code/testing' import type { Engine } from 'claude-code/testing' -import type { On } from 'claude-code' +import type { On, TurnStepInput } from 'claude-code' /** Fires session.start so the mod loads its config and registers /route. */ async function boot($: Engine, on: On): Promise { @@ -84,7 +84,7 @@ test('/route bogus names the phases', async ($, on) => { } }) -test('ultrathink in a prompt sets escalate on main', async ($, on) => { +test('ultrathink in a prompt sets a max floor on main', async ($, on) => { on('prompt.submit', ($, e) => ({ text: e.text })) await boot($, on) await $.prompt.submit({ @@ -92,7 +92,7 @@ test('ultrathink in a prompt sets escalate on main', async ($, on) => { wait: false, origin: { kind: 'composer' }, }) - expect(mainLine(await route($, 'show'))).toContain('prompt escalate') + expect(mainLine(await route($, 'show'))).toContain('floor max') }) test('/route model: alias resolved, id passed, typo refused', async ( @@ -169,7 +169,7 @@ const stepInput = (agentId?: string) => ({ /** Streams one turn.step to its end; the hooks run as the chunks flow. */ async function runStep( $: Engine, - input: ReturnType, + input: TurnStepInput, ): Promise { const stream = $.turn.step(input) for await (const _chunk of stream) { @@ -238,3 +238,211 @@ test('a rule only scans the first 4096 chars of a prompt', async ($, on) => { }) expect(mainLine(await route($, 'show'))).toContain('session defaults') }) + +// ---- user effort floor ------------------------------------------------- + +const ROUTE_TOOL = 'mcp__model-router__route' + +/** A main (or agent) step as the engine would make it: engine effort high. */ +const highStep = (agentId?: string): TurnStepInput => ({ + ...stepInput(agentId), + effort: 'high' as const, +}) + +/** Types `ultrathink` in the composer, idle or over a running turn. */ +async function ultrathink($: Engine, turnId?: string): Promise { + await $.prompt.submit({ + text: 'ultrathink please', + wait: turnId !== undefined, + origin: { kind: 'composer' }, + ...(turnId === undefined ? {} : { turnId }), + }) +} + +/** Ends a main turn: the floor's life is bounded by this event. */ +async function endTurn($: Engine): Promise { + await $.turn.complete({ + turnId: 'u1', + answer: '', + durationMs: 1, + isAborted: false, + reason: 'answer', + }) +} + +/** One main step; returns the effort that reached the bottom hook. */ +async function stepEffort($: Engine, seen: Seen[]): Promise { + await runStep($, highStep()) + return seen[seen.length - 1]?.effort +} + +/** Boots with a bottom step recorder and prompt/turn hooks in place. */ +async function bootFloor($: Engine, on: On): Promise { + const seen: Seen[] = [] + recordSteps(on, seen) + on('prompt.submit', ($, e) => ({ text: e.text })) + on('turn.complete', () => ({ text: '' })) + on('tool.call', { tool: 'Skill' }, () => ({ + result: { success: true, commandName: 'other' }, + })) + on('agent.spawn', ($, e) => ({ + model: e.model ?? e.parentModel, + agentId: 'a1', + })) + await boot($, on) + return seen +} + +test('floor: ultrathink survives a model route', async ($, on) => { + const seen = await bootFloor($, on) + await ultrathink($) + await $.tool.call({ tool: ROUTE_TOOL, phase: 'orchestrate' }) + expect(await stepEffort($, seen)).toBe('max') +}) + +test('floor: typed /effort-medium clamps low, lets max pass', async ( + $, on) => { + const seen = await bootFloor($, on) + await $.skill.prompt({ skill: 'effort-medium', text: 'x' }) + await $.tool.call({ tool: ROUTE_TOOL, phase: 'mechanical' }) + expect(await stepEffort($, seen)).toBe('medium') + await $.tool.call({ tool: ROUTE_TOOL, phase: 'escalate' }) + expect(await stepEffort($, seen)).toBe('max') +}) + +test('floor: typed /effort-low lowers an unrouted turn', async ($, on) => { + const seen = await bootFloor($, on) + const out = await $.skill.prompt({ skill: 'effort-low', text: 'x' }) + expect(out.text).toContain('minimum') + expect(await stepEffort($, seen)).toBe('low') +}) + +test('floor: survives a skill load', async ($, on) => { + const seen = await bootFloor($, on) + await ultrathink($) + await $.tool.call({ tool: ROUTE_TOOL, phase: 'orchestrate' }) + await $.tool.call({ tool: 'Skill', skill: 'other' }) + expect(await stepEffort($, seen)).toBe('max') + expect(mainLine(await route($, 'show'))).not.toContain('orchestrate') +}) + +test('floor: lifts a lower sticky, then ends with the turn', async ( + $, on) => { + const seen = await bootFloor($, on) + await route($, 'effort=low') + await ultrathink($) + expect(await stepEffort($, seen)).toBe('max') + await endTurn($) + expect(await stepEffort($, seen)).toBe('low') +}) + +test('floor: main only, an agent step is unaffected', async ($, on) => { + const seen = await bootFloor($, on) + await $.agent.spawn(spawnInput()) + await ultrathink($) + await runStep($, highStep('a1')) + expect(seen[0]?.effort).toBe('medium') +}) + +test('floor: /route clear removes it', async ($, on) => { + const seen = await bootFloor($, on) + await ultrathink($) + expect(mainLine(await route($, 'show'))).toContain('floor max') + await route($, 'clear') + expect(await stepEffort($, seen)).toBe('high') + expect(mainLine(await route($, 'show'))).not.toContain('floor') +}) + +test('floor: a mid-turn prompt applies now and is kept for the next', async ( + $, on) => { + const seen = await bootFloor($, on) + await ultrathink($, 'u1') + expect(await stepEffort($, seen)).toBe('max') + await endTurn($) + expect(await stepEffort($, seen)).toBe('max') + await endTurn($) + expect(await stepEffort($, seen)).toBe('high') +}) + +test('floor: the route answer names the floor over a sticky', async ( + $, on) => { + await bootFloor($, on) + await route($, 'effort=low') + await ultrathink($) + const out = await $.tool.call({ tool: ROUTE_TOOL, phase: 'plan' }) + const text = JSON.stringify(out) + expect(text).toContain('user floor max (prompt rule escalate)') + expect(text).toContain('/route clear') +}) + +// `enabled: false` in ~/.claude/model-router.json cannot be reached here (the +// kit has no fs); the shared off path is covered through `/route off`. +test('floor: /route off keeps the floor from routing', async ($, on) => { + const seen = await bootFloor($, on) + await ultrathink($) + await route($, 'off') + expect(await stepEffort($, seen)).toBe('high') + expect(mainLine(await route($, 'show'))).not.toContain('floor') +}) + +test('per axis: a model-only sticky keeps the turn route effort', async ( + $, on) => { + const seen = await bootFloor($, on) + await route($, 'model=sonnet') + await $.tool.call({ tool: ROUTE_TOOL, phase: 'orchestrate' }) + expect(await stepEffort($, seen)).toBe('medium') +}) + +// The config-driven `offConfig` is re-applied in the same rebuild; only the +// session-only off is reachable here (the kit has no fs). +test('session.end rebuild drops a session-only /route off', async ( + $, on) => { + on('session.end', ($, e) => ({ sessionId: e.sessionId })) + await boot($, on) + await route($, 'off') + await $.session.end({ + reason: 'clear', + sessionId: 's1', + resume: { id: 's1' }, + }) + expect(await route($, 'show')).toContain('router: on') +}) + +// The kit has no fs: the reload read fails, so the previous cfg must stay. +test('reload with an unreadable override keeps the previous config', async ( + $, on) => { + await boot($, on) + await route($, 'switch on') + const out = await route($, 'reload') + expect(out).toContain('switch: on') + expect(await route($, 'show')).toContain('switch: on') +}) + +test('typed marker: a preload in a live agent is ignored', async ($, on) => { + const seen = await bootFloor($, on) + await $.agent.spawn(spawnInput()) + const out = await $.skill.prompt({ skill: 'effort-max', text: 'x' }) + expect(out.text?.startsWith('model-router: effort-max preload')).toBe(true) + expect(mainLine(await route($, 'show'))).not.toContain('floor') + expect(await stepEffort($, seen)).not.toBe('max') +}) + +test('typed marker: /effort-max seen at submit writes the floor', async ( + $, on) => { + await bootFloor($, on) + await $.agent.spawn(spawnInput()) + await $.prompt.submit({ + text: '/effort-max go', + wait: false, + origin: { kind: 'composer' }, + }) + await $.skill.prompt({ skill: 'effort-max', text: 'x' }) + expect(mainLine(await route($, 'show'))).toContain('floor max') +}) + +test('typed slash with no agent and no marker writes the floor', async ( + $, on) => { + await bootFloor($, on) + await $.skill.prompt({ skill: 'effort-max', text: 'x' }) + expect(mainLine(await route($, 'show'))).toContain('floor max') +}) diff --git a/mods/model-router/hooks/register.ts b/mods/model-router/hooks/register.ts index fa00a06..4d757b8 100644 --- a/mods/model-router/hooks/register.ts +++ b/mods/model-router/hooks/register.ts @@ -19,6 +19,7 @@ type Config = { mainModelSwitch: boolean verbose: boolean spinner: boolean + enabled: boolean // false: every hook passes through (per machine) } type Rule = { re: RegExp; phase: string } type Source = 'user' | 'model' | 'skill' | 'prompt' | 'slash' @@ -32,12 +33,17 @@ type State = { rules: Rule[] source: string // 'defaults' or the override path userMain: Routed | null // /route by the user, sticky until /route clear - turnMain: Routed | null // tool, skill, slash, prompt; dropped at turn end - pendingPrompt: Routed | null // typed mid-turn, promoted next turn + turnMain: Routed | null // model route tool, skill table row, Skill(effort-*) + // bridge; dropped at turn end + turnFloor: Routed | null // user-explicit level for this turn (prompt rule, + // typed /effort-): a floor, main loop only + pendingPrompt: Routed | null // typed mid-turn: the next turn's floor + typedSlash: boolean // one-shot: prompt.submit saw a typed /effort- loops: Map // agentId -> that loop's routing explicitEffort: Map // Agent tool_use_id -> effort param skillCalls: number // Skill tool calls in flight - off: boolean // /route off: every hook passes through + off: boolean // /route off or config: every hook passes through + offConfig: boolean // `off` comes from the config key `enabled` lastMain: string // "model/effort" of the last main step (spinner) windowWarned: boolean // context-window warning already logged this turn warned: Set // hooks whose fail-open was already logged @@ -52,6 +58,9 @@ type RouteInput = { agentId?: string } type Picked = { phase: string; route: Route } +type Effort = StepIn['effort'] +type EffortBy = 'floor' | 'sticky' | 'turn' | 'engine' +type Decision = { effort: Effort; by: EffortBy } const LEVELS: readonly Level[] = ['low', 'medium', 'high', 'xhigh', 'max'] const MODEL_ID = /^claude-[a-z0-9.-]+$/ @@ -91,6 +100,7 @@ const DEFAULT_CONFIG: Config = { mainModelSwitch: false, verbose: false, spinner: true, + enabled: true, } // ---- config ---------------------------------------------------------- @@ -213,6 +223,14 @@ function mergePrompt( const pickBool = (v: unknown, fallback: boolean): boolean => typeof v === 'boolean' ? v : fallback +/** The kill switch: a non-boolean value is dropped, and said so. */ +function pickEnabled(v: unknown, fallback: boolean, log: Log): boolean { + if (v !== undefined && typeof v !== 'boolean') { + log('model-router: config "enabled" is not a boolean; ignored') + } + return pickBool(v, fallback) +} + /** Defaults overlaid with the user's entries, each validated first. */ function mergeConfig(user: unknown, log: Log): Config { const base = structuredClone(DEFAULT_CONFIG) @@ -236,6 +254,7 @@ function mergeConfig(user: unknown, log: Log): Config { mainModelSwitch: pickBool(user.mainModelSwitch, base.mainModelSwitch), verbose: pickBool(user.verbose, base.verbose), spinner: pickBool(user.spinner, base.spinner), + enabled: pickEnabled(user.enabled, base.enabled, log), } } @@ -246,7 +265,7 @@ async function readCapped( log: Log, ): Promise { const tooBig = - `model-router: ${OVERRIDE} over ${MAX_CONFIG_BYTES} bytes; defaults` + `model-router: ${OVERRIDE} over ${MAX_CONFIG_BYTES} bytes` if ((await $.fs.stat(path)).size > MAX_CONFIG_BYTES) { log(tooBig) return undefined @@ -257,30 +276,37 @@ async function readCapped( return undefined } -async function readOverride( - $: Api, - log: Log, -): Promise<{ path: string; data: unknown } | undefined> { +type Override = { path: string; data: unknown } | 'absent' | 'failed' + +/** 'absent': no file (defaults apply). 'failed': present but unusable. */ +async function readOverride($: Api, log: Log): Promise { try { const home = await $.env.get('HOME') - if (!home) return undefined + if (!home) return 'absent' const path = `${home}/${OVERRIDE}` - if (!(await $.fs.exists(path))) return undefined + if (!(await $.fs.exists(path))) return 'absent' const text = await readCapped($, path, log) - return text === undefined ? undefined : { path, data: JSON.parse(text) } + if (text === undefined) return 'failed' + const data: unknown = JSON.parse(text) + if (isRecord(data)) return { path, data } + log(`model-router: ${OVERRIDE} is not an object`) + return 'failed' } catch (err) { - log(`model-router: ${OVERRIDE} unreadable (${String(err)}); defaults`) - return undefined + log(`model-router: ${OVERRIDE} unreadable (${String(err)})`) + return 'failed' } } -/** Never throws; a failed read or parse leaves the defaults. */ +/** Never throws; undefined when the override exists but cannot be used. */ async function loadConfig( $: Api, log: Log, -): Promise<{ cfg: Config; source: string }> { +): Promise<{ cfg: Config; source: string } | undefined> { const found = await readOverride($, log) - if (!found) return { cfg: mergeConfig(undefined, log), source: 'defaults' } + if (found === 'failed') return undefined + if (found === 'absent') { + return { cfg: mergeConfig(undefined, log), source: 'defaults' } + } return { cfg: mergeConfig(found.data, log), source: found.path } } @@ -300,11 +326,14 @@ function newState(cfg: Config, source: string): State { source, userMain: null, turnMain: null, + turnFloor: null, pendingPrompt: null, + typedSlash: false, loops: new Map(), explicitEffort: new Map(), skillCalls: 0, off: false, + offConfig: false, lastMain: '', windowWarned: false, warned: new Set(), @@ -335,6 +364,67 @@ function safely(st: State, $: Api, hook: string, work: () => void): void { /** The main loop's effective route: user /route > latest turn route. */ const mainRoute = (st: State): Routed | null => st.userMain ?? st.turnMain +const rank = (l: Level | undefined): number => + l === undefined ? -1 : LEVELS.indexOf(l) + +/** Lifts `effort` to `floor`; a lower level, a number or none is replaced. */ +function floored(effort: Effort, floor: Level | undefined): Effort { + if (floor === undefined) return effort + return isLevel(effort) && rank(effort) >= rank(floor) ? effort : floor +} + +/** Two floors in one turn: the higher level stays (a tie takes the new). */ +function higherFloor(cur: Routed | null, next: Routed): Routed { + return cur && rank(cur.route.effort) > rank(next.route.effort) ? cur : next +} + +/** + * The one decision of the main loop's effort. The user's floor is the turn's + * default (no sticky or turn route names an effort) and its minimum. + * `by` names who set the value: the floor when it raised or supplied it. + */ +function mainEffort(st: State, engine: Effort): Decision { + const sticky = st.userMain?.route.effort + const named = sticky ?? st.turnMain?.route.effort + const floor = st.turnFloor?.route.effort + const base = named ?? floor ?? engine + const effort = floored(base, floor) + if (floor !== undefined && (named === undefined || effort !== base)) { + return { effort, by: 'floor' } + } + if (named === undefined) return { effort, by: 'engine' } + return { effort, by: sticky === undefined ? 'turn' : 'sticky' } +} + +/** Model axis: sticky, then turn route, then the floor's own model. */ +const mainModel = (st: State): string | undefined => + st.userMain?.route.model ?? + st.turnMain?.route.model ?? + st.turnFloor?.route.model + +const floorSource = (f: Routed): string => + f.source === 'prompt' ? `prompt rule ${f.phase}` : `typed /${f.phase}` + +const floorWord = (f: Routed): string => + `user floor ${f.route.effort ?? '-'} (${floorSource(f)})` + +/** + * Why main will not run at `asked`, or '' when it will. Truthful tail of + * every answer that records an effort for the main loop. + */ +function mainNote(st: State, asked: Level | undefined): string { + const d = mainEffort(st, undefined) + if (d.by === 'floor') { + if (!st.turnFloor || asked === undefined || d.effort === asked) return '' + return `${floorWord(st.turnFloor)} keeps main at ${String(d.effort)}; ` + + '/route clear to drop it' + } + return d.by === 'sticky' && st.userMain + ? `a sticky /route ${st.userMain.phase} is in force and wins until ` + + '/route clear' + : '' +} + function loopOf(st: State, agentId: string): Loop { const known = st.loops.get(agentId) if (known) return known @@ -353,20 +443,56 @@ function writeLoop(loop: Loop, route: Route): void { function clearRoutes(st: State): void { st.userMain = null st.turnMain = null + st.turnFloor = null st.pendingPrompt = null } +/** Config `enabled: false` switches the router off; true lifts only that. */ +function applyEnabled(st: State, enabled: boolean): void { + if (!enabled) { + st.off = true + st.offConfig = true + } else if (st.offConfig) { + st.off = false + st.offConfig = false + } +} + +const routerWord = (st: State): string => + st.off ? (st.offConfig ? 'off (config)' : 'off') : 'on' + // ---- text ------------------------------------------------------------ const modelText = (cfg: Config, model: string | undefined): string => model === undefined ? '-' : resolveModel(cfg, model) +/** The floor's level when it carries one and the router is on. */ +function liveFloor(st: State): { f: Routed; level: Level } | undefined { + const f = st.turnFloor + const level = f?.route.effort + return st.off || !f || level === undefined ? undefined : { f, level } +} + +/** True when the switch would put the main loop on a haiku model. */ +function mainOnHaiku(st: State): boolean { + const model = mainModel(st) + return st.cfg.mainModelSwitch && model !== undefined && + resolveModel(st.cfg, model).startsWith(HAIKU) +} + +function effortWord(st: State): string { + if (mainOnHaiku(st)) return '- (haiku takes none)' + return String(mainEffort(st, undefined).effort ?? '-') +} + function mainText(st: State): string { const r = mainRoute(st) - if (!r) return 'main: session defaults' - const model = modelText(st.cfg, r.route.model) + const live = liveFloor(st) + const floor = live ? ` · floor ${live.level} (${live.f.phase})` : '' + if (!r) return 'main: session defaults' + floor + const model = modelText(st.cfg, mainModel(st)) return `main: ${r.source} ${r.phase} · model ${model} · effort ${ - r.route.effort ?? '-'}` + effortWord(st)}${floor}` } function phasesText(cfg: Config): string { @@ -381,7 +507,7 @@ function show(st: State): string { const flag = (b: boolean) => (b ? 'on' : 'off') return [ mainText(st), - `router: ${st.off ? 'off' : 'on'} · switch: ${flag(c.mainModelSwitch)} · ` + + `router: ${routerWord(st)} · switch: ${flag(c.mainModelSwitch)} · ` + `verbose: ${flag(c.verbose)} · spinner: ${flag(c.spinner)}`, `live loops: ${st.loops.size}`, phasesText(c), @@ -391,8 +517,12 @@ function show(st: State): string { function statusLine(st: State): string { const r = mainRoute(st) - const now = st.off ? 'off' : r ? `${r.source} ${r.phase}` : 'session defaults' - return `route: ${now}${st.cfg.mainModelSwitch ? ' · switch on' : ''}` + const now = st.off + ? routerWord(st) + : r ? `${r.source} ${r.phase}` : 'session defaults' + const floor = liveFloor(st) + return `route: ${now}${floor ? ` · floor ${floor.level}` : ''}${ + st.cfg.mainModelSwitch ? ' · switch on' : ''}` } const refresh = ($: Api, st: State): void => $.ui.status(statusLine(st)) @@ -450,12 +580,21 @@ function setUserRoute($: Api, st: State, args: string): string { return show(st) } -/** (Re)loads the config into the state and re-registers the route tool. */ +/** + * (Re)loads the config into the state and re-registers the route tool. + * An unusable override keeps the previous config: the kill switch fails + * closed, never back to the defaults. + */ async function reloadConfig($: Api, st: State): Promise { const loaded = await loadConfig($, text => $.ui.log(text)) - st.cfg = loaded.cfg - st.rules = compileRules(loaded.cfg) - st.source = loaded.source + if (loaded) { + st.cfg = loaded.cfg + st.rules = compileRules(loaded.cfg) + st.source = loaded.source + applyEnabled(st, loaded.cfg.enabled) + } else { + $.ui.log('model-router: override unreadable; keeping the previous config') + } await registerTool($, st) } @@ -472,6 +611,7 @@ async function handleCommand($: Api, st: State, args: string): Promise { case 'on': case 'off': st.off = head === 'off' + st.offConfig = false refresh($, st) return show(st) case 'reload': @@ -557,7 +697,11 @@ function applyRoute(st: State, agentId: string | undefined, p: Picked): void { function clearLoop(st: State, agentId: string | undefined): string { if (agentId === undefined) { st.turnMain = null - return 'route cleared for main' + const f = st.turnFloor + const held = f && f.route.effort !== undefined + ? `; ${floorWord(f)} still holds, /route clear drops it` + : '' + return 'route cleared for main' + held } const loop = st.loops.get(agentId) if (loop) writeLoop(loop, {}) @@ -566,10 +710,8 @@ function clearLoop(st: State, agentId: string | undefined): string { /** Truthful answer: states what the calling loop will actually do. */ function routedText(st: State, agentId: string | undefined, p: Picked): string { - if (agentId === undefined && st.userMain) { - return `recorded ${p.phase} for this turn, but a sticky /route ` + - `${st.userMain.phase} is in force; it wins until /route clear` - } + const note = agentId === undefined ? mainNote(st, p.route.effort) : '' + if (note) return `recorded ${p.phase} for this turn, but ${note}` const loop = agentId === undefined ? undefined : st.loops.get(agentId) const effort = loop?.explicitEffort ? undefined : p.route.effort const model = agentId === undefined && st.cfg.mainModelSwitch @@ -610,9 +752,10 @@ function effortBridge(st: State, agentId: string | undefined, skill: string, if (agentId === undefined) { const route = { ...st.turnMain?.route, effort: level } st.turnMain = { phase: skill, route, source: 'skill' } - return skillResult(skill, st.userMain - ? `model-router: ${skill} recorded, but a sticky /route ` + - `${st.userMain.phase} is in force and wins until /route clear.` + const note = mainNote(st, level) + return skillResult(skill, note + ? `model-router: ${skill} recorded, but ${note}; the ${skill} skill ` + + 'text was not loaded.' : `model-router: effort → ${level} for this loop from the next ` + `request on; the ${skill} skill text was not loaded.`) } @@ -631,7 +774,7 @@ function onSkillLoad(st: State, skill: string, agentId: string | undefined) { const table = hasKey(st.cfg.skills, skill) ? st.cfg.skills[skill] : undefined const route = table === undefined ? undefined : phaseRoute(st.cfg, table) if (agentId === undefined) { - if (st.turnMain && st.turnMain.source !== 'prompt') st.turnMain = null + st.turnMain = null if (table !== undefined && route) { st.turnMain = { phase: table, route, source: 'skill' } } @@ -641,18 +784,38 @@ function onSkillLoad(st: State, skill: string, agentId: string | undefined) { if (loop) writeLoop(loop, { effort: route?.effort }) } -/** A user-typed /effort-: prepends one line, args ride in the text. */ +/** A user-typed /effort-: a floor for the turn, prepends one line. */ function slashEffort(st: State, skill: string, text: string) { const level = EFFORT_SKILL.exec(skill)?.[1] if (!isLevel(level)) return undefined - st.turnMain = { phase: skill, route: { effort: level }, source: 'slash' } - const line = st.userMain - ? `Effort ${level} recorded; the sticky /route ${st.userMain.phase} ` + - 'wins until /route clear.' - : `Effort shifted to ${level} by model-router for this turn.` + const route: Route = { effort: level } + const slash: Routed = { phase: skill, route, source: 'slash' } + st.turnFloor = higherFloor(st.turnFloor, slash) + const note = mainNote(st, level) + const line = `Effort ${level} set by model-router for the main loop this ` + + 'turn (minimum; a higher route still applies).' + + (note ? ` But ${note}.` : '') return { text: line + '\n' + text } } +/** + * Floor write for a skill.prompt. Only a typed slash may write it: the + * marker from prompt.submit attests the typing. Without it, a live + * sub-agent means the prompt is a preload inside that agent: ignored. + */ +function guardedSlash(st: State, skill: string, text: string) { + if (!EFFORT_SKILL.test(skill)) return undefined + if (st.typedSlash) { + st.typedSlash = false + } else if (st.loops.size > 0) { + return { + text: `model-router: ${skill} preload inside a live sub-agent is ` + + 'ignored on the main loop.\n' + text, + } + } + return slashEffort(st, skill, text) +} + // ---- agents ---------------------------------------------------------- type SpawnIn = { @@ -714,9 +877,8 @@ async function windowOk($: Api, st: State, id: string): Promise { } async function mainPlan($: Api, st: State, e: StepIn): Promise { - const set = mainRoute(st) - const effort = set?.route.effort ?? e.effort - const wanted = set?.route.model + const { effort } = mainEffort(st, e.effort) + const wanted = mainModel(st) if (wanted === undefined || !st.cfg.mainModelSwitch) { return { model: e.model, effort } } @@ -751,8 +913,10 @@ function noteMain($: Api, st: State, plan: Plan): void { } function endMainTurn($: Api, st: State): void { - st.turnMain = st.pendingPrompt + st.turnFloor = st.pendingPrompt st.pendingPrompt = null + st.turnMain = null + st.typedSlash = false st.explicitEffort.clear() st.lastMain = '' st.windowWarned = false @@ -773,6 +937,9 @@ function registerSession(on: On, st: State): void { }) on('session.end', async ($, e, next) => { Object.assign(st, newState(st.cfg, st.source)) + // session.start never fires after /clear: re-apply the config's + // `enabled` so a config-disabled router (offConfig) stays off. + applyEnabled(st, st.cfg.enabled) return next(e) }).catch(($, e, next) => { warnOnce(st, $, 'session.end', next.error.kind) @@ -823,7 +990,10 @@ function registerSkills(on: On, st: State): void { }) on('skill.prompt', async ($, e, next) => { if (st.off || st.skillCalls > 0) return next(e) - return slashEffort(st, e.skill, e.text) ?? next(e) + const out = guardedSlash(st, e.skill, e.text) + if (!out) return next(e) + refresh($, st) + return out }).catch(($, e, next) => { warnOnce(st, $, 'skill.prompt', next.error.kind) return next(e) @@ -891,6 +1061,15 @@ function registerTurns(on: On, st: State): void { }) } +/** + * A prompt's level is a floor now; typed mid-turn (`wait` is ignored, the + * engine queues either way) it is also kept for the next turn. + */ +function floorFromPrompt(st: State, midTurn: boolean, routed: Routed): void { + st.turnFloor = higherFloor(st.turnFloor, routed) + if (midTurn) st.pendingPrompt = higherFloor(st.pendingPrompt, routed) +} + function registerPrompt(on: On, st: State): void { on('prompt.submit', async ($, e, next) => { if (st.off || e.origin.kind !== 'composer') return next(e) @@ -899,11 +1078,10 @@ function registerPrompt(on: On, st: State): void { const route = rule ? phaseRoute(st.cfg, rule.phase) : undefined if (rule && route) { const routed: Routed = { phase: rule.phase, route, source: 'prompt' } - // Typed mid-turn and asked to wait: it belongs to the NEXT turn. - if (e.turnId !== undefined && e.wait) st.pendingPrompt = routed - else st.turnMain = routed + floorFromPrompt(st, e.turnId !== undefined, routed) refresh($, st) } + if (e.text.trimStart().startsWith('/effort-')) st.typedSlash = true return next(e) }).catch(($, e, next) => { warnOnce(st, $, 'prompt.submit', next.error.kind) From 24e180ade0189c2e0184166a66d404e38caf6504 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 10:13:03 +0200 Subject: [PATCH 033/547] =?UTF-8?q?chore(tasks):=20model-router=20B1=20don?= =?UTF-8?q?e=20=E2=80=94=20contract=20evidence,=20TODO,=20journal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 3 ++- .../2026-10-08-model-router-floor-1835.md | 18 ++++++++++++++---- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 0af5f38..c8e2ae8 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -582,3 +582,4 @@ rules: - model-router wave 1-A (/feat, user go): mod built in `mods/model-router/` (4 files, 834 + 202 lines, 11 plugin tests). Plan r1 → r3: 3 challengers (simplicity CONCERNS, robustness CONCERNS(6), correctness FATAL(8)) + 1 confirmation CONCERNS(4); converged on: agents table = built-ins only in wave 1 (frontmatter stays single writer), agent model written once at spawn, explicit Agent params frozen per loop, every sub-agent write on its own loop, Skill bridge answers in the Skill tool's OUTPUT schema (string result refused → skill would load), config validated before merge, state in closure, `/route off`. feater DONE first pass; GATE 0 MET; verifier CONFORME 6/6; security PASS (4 MEDIUM + 5 LOW parked in TODO for user go). Commits b721c94 (mod) + e8ca713 (contract/plan). Override `~/.claude/model-router.json` {verbose:true} written (pass B). Doc-sync deferred to 1-B. - model-router W1-A hardening (user go): fresh feater on contract criteria 7-11 → gap round (dead `Loop.frozen`, spawn returns `started` verbatim, tool description) → verifier CONFORME 11/11 → security PASS (1 MEDIUM residual: ReDoS size-bounded only, self-inflicted config; 5 LOW parked). Registries BDR-115, LRN-205, LRN-206, EVAL-040 written on user go (64702d5). Next: live swap of the real mod into the hot-reload folder, then W1-B install + docs. - model-router live checks on Opus 5.5 (user /model, uncommitted settings.json change left to the user): Skill(effort-low) bridge answered in place → next request low; ultrathink turn ran max (engine base medium); Explore without params → claude-sonnet-5-5, 3 steps medium. Loading switched to tracked symlink skills/model-router → @skills-dir (PLUGIN_DIRS non-portable: absolute path, no $HOME expansion, tracked settings); isolated-HOME probe listed/enabled/loaded. User chose floor semantics for ultrathink + typed /effort-. W1-B split: B1 floor (register.ts) + B2 wiring (symlink, gitignore, mods suite, doctor, CLAUDE.md); 6 challengers in flight. Effort shifters skipped this turn: the bridge would overwrite the user's ultrathink until B1 lands. +- model-router W1-B1 floor landed (1ff608a): plan r2 from 3 lenses (0 BLOCKER, 4 MAJOR: one decision helper, typed level = default + minimum, mid-turn prompt now + next, per-machine enabled:false), feater DONE, gap round (/clear lost enabled:false, 'ultrathink rule' label, per-axis effort base), hardening round (kill switch keeps previous cfg on failed reload, typed slash attested at prompt.submit vs sub-agent preload). 30 tests, verifier CONFORME 6/6, security PASS ×2 with parked residuals. B2 wiring dispatched next. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index d1b2620..4e8ac1e 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -8,7 +8,8 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [x] W1-A the mod in `mods/model-router/` (b721c94, contract `2026-10-08-model-router-w1a-1533`, plan r3): challenge 3 lenses + 1 confirmation (2 BLOCKER + 10 MAJOR closed by named changes), feater DONE first pass, GATE 0 MET 5/5, verifier CONFORME 6/6, security PASS (4 MEDIUM + 5 LOW reported, below) - [x] W1-A hardening (user go "oui durcis", contract criteria 7-11): `/route` composer-only; no agent model axis (effort only after spawn); pattern ≤ 200 / scan ≤ 4096 / phase keys `^[a-z][a-z0-9_-]{0,31}$` / config ≤ 64 KB / `additionalProperties: false` / `typeof e.skill`; `warnOnce` in all 14 catches + config-drop logs; `safely` around post-`next` bookkeeping. feater DONE, gap round (dead `Loop.frozen`, spawn returns `started` verbatim, tool description), GATE 0 MET 9/9, verifier CONFORME 11/11, security PASS. - [ ] W1-A residuals (security, accepted, none exploitable from outside the user's own files): ReDoS is size-bounded only (`(a+)+$` in `~/.claude/model-router.json` + a 4 KB paste hangs the hook; fix = nested-quantifier rejection or a far lower scan cap); `stat().size` trusted (FIFO/device path in ~/.claude); unrestricted `models`/`agents`/`skills` KEYS echoed raw in logs (log flood); `agentId` read from the flat tool event (engine strip unverified); 5 closures without a kit test (no fs in the kit, LRN-206); "nothing routed" catch text after a state write. -- [ ] W1-B1 floor precedence (contract `2026-10-08-model-router-floor-1835`): `ultrathink` + typed `/effort-` = floor for the main turn (user choice 2026-10-08) +- [x] W1-B1 floor precedence (contract `2026-10-08-model-router-floor-1835`, 2026-10-09): `ultrathink` + typed `/effort-` = the main turn's default AND minimum (r2 after 3 lenses: a pure floor made /effort-low a no-op); one helper `mainEffort`; per-axis precedence; mid-turn prompt floors now + next turn; `"enabled": false` per machine, kept across /clear and failed reload; typed slash attested. 30 tests; verifier CONFORME 6/6 (after 1 gap round); security PASS ×2 +- [ ] W1-B1 residuals (security 2026-10-09, accepted): first-load failure of the override falls to defaults (`enabled: true`); non-boolean `enabled` drops to the default on reload; `skill.prompt` preload guard is a heuristic (`loops.size > 0`; a preload during spawn or a non-composer `/effort-*` while idle still writes the floor); marker not bound to a valid level; `/route reload` answers "config reloaded" even when the previous config was kept; transient missing override lifts a config-set off; `String(err)` of a JSON parse in the local log. Display: `/route show` folds the floor into the effort while off; model-axis text with a model-only sticky and the switch on. - [ ] W1-B2 wiring (contract `2026-10-08-model-router-wiring-1835`): tracked symlink `skills/model-router` → `../mods/model-router` (loads as `@skills-dir`; PLUGIN_DIRS dropped: absolute paths in tracked settings), `.gitignore` engine-laid files, `lib/tests/mods.test.sh`, doctor `── Mods ──`, CLAUDE.md `## mods/`; then doc-sync (README/USAGE/CHANGELOG), live swap (remove the hot-reload link, `/reload-plugins`), BDR-115 amendment - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B diff --git a/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md b/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md index 30943eb..450452d 100644 --- a/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md +++ b/.claude/tasks/contracts/2026-10-08-model-router-floor-1835.md @@ -21,16 +21,26 @@ Q: who clears the floor / A: main turn end (a queued prompt's floor is then prom 1. Suite green with the new tests: `claude plugin test` passes with at least 22 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 22 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo FLOOR-SUITE-OK EXPECT: FLOOR-SUITE-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: 30 pass 0 fail Ran 30 tests across 1 file. [1.05s] FLOOR-SUITE-OK 2. Type-check clean against this build's declarations. CHECK: T=/Users/b.chanot/.claude/dev-mods/385f7190-70f5-4bdd-b0d8-e4566cd412fd/model-router/.claude-plugin/types; [ -d "$T" ] || T=/Users/b.chanot/Documents/claude/mods/model-router/.claude-plugin/types; W=$(mktemp -d) && printf '{"compilerOptions":{"target":"es2023","lib":["es2023"],"types":[],"module":"esnext","moduleResolution":"bundler","strict":true,"noUncheckedIndexedAccess":true,"noEmit":true,"skipLibCheck":true,"jsx":"react","jsxFactory":"h","jsxFragmentFactory":"Fragment"},"include":["%s/claude-code/index.d.ts","%s/claude-code-tools/index.d.ts","%s/hooks"]}' "$T" "$T" "$PWD/mods/model-router" > "$W/tsconfig.json" && (cd "$W" && npx --yes -p typescript@5 tsc -p tsconfig.json) && echo TSC-OK EXPECT: TSC-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: TSC-OK 3. The floor is its own slot: `turnFloor` is declared in `State`, initialised in `newState`, written by the prompt rule and by a typed `/effort-`, cleared by `/route clear` and at main turn end; the suite carries at least 8 tests whose name contains `floor`; one helper `mainEffort` decides the main effort; the config key `enabled` exists. CHECK: cd mods/model-router/hooks && [ "$(grep -c 'turnFloor' register.ts)" -ge 6 ] && [ "$(grep -cE "^\s*test\('[^']*floor" register.test.ts)" -ge 8 ] && grep -q 'mainEffort' register.ts && grep -q 'enabled' register.ts && echo FLOOR-SLOT-OK EXPECT: FLOOR-SLOT-OK - EVIDENCE: pending -4. Judged by reading: effective main effort comes from ONE helper `mainEffort` used by `mainPlan` and by every answer text: base `(userMain ?? turnMain)?.route.effort ?? turnFloor?.route.effort ?? e.effort`, then floored by `turnFloor` (LEVELS order; a numeric or absent value is replaced); the floor never applies to a sub-agent step; `turnMain` only ever holds 'model' or 'skill' sources; the prompt rule writes `turnFloor` (keeping the higher of two) and, when typed mid-turn (`turnId` set, `wait` ignored), also `pendingPrompt`, promoted into `turnFloor` at main turn end; `"enabled": false` in the override file makes every hook pass through after each config load (`/route on` re-enables for the session); a non-effort skill load resets `turnMain` only; a model `route({clear})` clears `turnMain` only; every answer that the floor overrides says so truthfully (Skill bridge context, route tool text, `/effort-` text); `/route show` and the status line display the floor; every criterion of `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md` still holds; no function over 25 logic lines. + EVIDENCE: MET exit=0 marker-found :: FLOOR-SLOT-OK +4. Judged by reading: effective main effort comes from ONE helper `mainEffort` used by `mainPlan` and by every answer text: base `userMain?.route.effort ?? turnMain?.route.effort ?? turnFloor?.route.effort ?? e.effort` (per-axis, like the model rule: a model-only sticky never hides a turn route's effort; gap round 2026-10-09), then floored by `turnFloor` (LEVELS order; a numeric or absent value is replaced); the floor never applies to a sub-agent step; `turnMain` only ever holds 'model' or 'skill' sources; the prompt rule writes `turnFloor` (keeping the higher of two) and, when typed mid-turn (`turnId` set, `wait` ignored), also `pendingPrompt`, promoted into `turnFloor` at main turn end; `"enabled": false` in the override file makes every hook pass through after each config load AND survives `/clear` (`session.end` rebuilds the state but re-applies the config's `enabled`; `/route on` re-enables for the session); a prompt-rule floor is labelled by its matched phase (`prompt rule `), never by a fixed word; a non-effort skill load resets `turnMain` only; a model `route({clear})` clears `turnMain` only; every answer that the floor overrides says so truthfully (Skill bridge context, route tool text, `/effort-` text); `/route show` and the status line display the floor; every criterion of `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md` still holds; no function over 25 logic lines. + +Hardening round (security gate 2026-10-09, 2 MEDIUM) — criteria 5-6, same ledger: +5. The kill switch fails closed: a failed override read on `/route reload` (unreadable, oversized, invalid JSON) keeps the PREVIOUS config (and therefore the previous `enabled`) instead of falling back to the defaults; a non-boolean `enabled` value is dropped WITH a log line; at session start with no previous config the defaults still apply. + CHECK: cd mods/model-router && grep -q "previous" hooks/register.ts && grep -qE "enabled.*(not a boolean|non-boolean|ignored)" hooks/register.ts && grep -qE "test\('[^']*(reload|previous|kill)" hooks/register.test.ts && echo KILL-CLOSED-OK + EXPECT: KILL-CLOSED-OK + EVIDENCE: MET exit=0 marker-found :: KILL-CLOSED-OK +6. `skill.prompt` writes the floor only for a typed `/effort-`: a one-shot marker set at `prompt.submit` (composer origin, text starting with `/effort-`) attests the typing; without the marker the write is refused while any sub-agent loop is live (a preload fires inside an agent's life), and accepted otherwise (no agent can be preloading); the refused case returns the text unchanged with a one-line note. Tests: preload simulation (spawned agent live, no marker → no floor), typed with marker → floor, typed with no marker and no agent → floor. + CHECK: cd mods/model-router && grep -q "slashMarker\|typedSlash" hooks/register.ts && [ "$(grep -cE "test\('[^']*(preload|marker|typed)" hooks/register.test.ts)" -ge 2 ] && echo SLASH-ATTEST-OK + EXPECT: SLASH-ATTEST-OK + EVIDENCE: MET exit=0 marker-found :: SLASH-ATTEST-OK ## FILE SCOPE mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts From 6430ac65ecaa4154e45f76a163f3f8d7f8a39356 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 10:51:13 +0200 Subject: [PATCH 034/547] =?UTF-8?q?feat(mods):=20model-router=20active=20i?= =?UTF-8?q?n=20every=20session=20=E2=80=94=20skills-dir=20link,=20mods=20s?= =?UTF-8?q?uite,=20doctor=20section,=20CLAUDE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tracked relative symlink skills/model-router -> ../mods/model-router: Claude Code loads the mod in place as model-router@skills-dir wherever link.sh links ~/.claude/skills (no CLAUDE_CODE_PLUGIN_DIRS: absolute paths in the tracked settings.json). Engine-laid mods/*/tsconfig.json gitignored. lib/tests/mods.test.sh: manifest name, link target, claude plugin validate and test per mod, capability-probed, time-bounded, SKIP with reason. doctor.sh: fail-soft Mods section (link by -ef, one guarded plugin list). CLAUDE.md: mods/ section (loading, per-machine enabled:false switch, dev-copy shadowing, tests). --- .gitignore | 4 ++ CLAUDE.md | 22 +++++++++++ doctor.sh | 58 ++++++++++++++++++++++++++++ lib/tests/mods.test.sh | 87 ++++++++++++++++++++++++++++++++++++++++++ skills/model-router | 1 + 5 files changed, 172 insertions(+) create mode 100644 lib/tests/mods.test.sh create mode 120000 skills/model-router diff --git a/.gitignore b/.gitignore index a45eacc..42c29f2 100644 --- a/.gitignore +++ b/.gitignore @@ -262,3 +262,7 @@ skills-external/.higgsfield-stage.*/ # ── gitflow standard socle (added by gitflow_init; additive, safe to edit) ── *.log !.claude/deploy/ + +# mods/: the engine lays tsconfig.json beside a loaded mod; its +# .claude-plugin/types/ ignores itself +mods/*/tsconfig.json diff --git a/CLAUDE.md b/CLAUDE.md index 5e0bfcf..c58878d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,6 +59,28 @@ Gotcha, learned the hard way: `git rm --cached` keeps the working file, but if the branch you merge into still tracks it, the merge deletes it from disk. Untrack and merge, then restore with the command above. +## mods/ — function-hooks plugins (Claude Code mods) + +A mod lives in `mods//` (`.claude-plugin/plugin.json` + hooks). It +loads through the tracked relative symlink `skills/` -> `../mods/` +(`~/.claude/skills` links to `skills/`) as `@skills-dir`, in place, +live at the next session or `/reload-plugins`. New mod: `ln -s ../mods/ +skills/` from the repo root (guard with `[ -L ]`, a re-run nests a link). +Not `CLAUDE_CODE_PLUGIN_DIRS` (absolute path, settings `env` has no `$HOME` +expansion, settings.json is tracked), nor a local marketplace (`add` writes +an absolute path into settings.json). +- The engine lays `mods//tsconfig.json` and `.claude-plugin/types/`; + both are gitignored. +- Optional user config: `~/.claude/.json`. Its `"enabled": false` is the + per-machine off switch (untracked). `"@skills-dir": false` in + `enabledPlugins` also works but lands in the TRACKED settings.json and + dirties every machine's tree. +- A dev copy of the same name (`--plugin-dir`, hot-reload link in + `~/.claude/dev-mods//`) shadows the skills-dir copy for that + session: remove it before reading `/reload-plugins` as a test of the link. +- Tests: `make test suite=lib/tests/mods.test.sh` (manifest, link, + `claude plugin validate`, `claude plugin test`). `doctor.sh` has a Mods section. + ## Transient planning artifacts `docs/superpowers/specs/**` and `docs/superpowers/plans/**` are run-time diff --git a/doctor.sh b/doctor.sh index 63f281b..8bfe308 100644 --- a/doctor.sh +++ b/doctor.sh @@ -155,6 +155,64 @@ unset _dv_active_profile _dv_profile_file echo "" +# ──────────────────────────────────────────────────────────── +# 2c. Mods (mods// plugins, loaded through the tracked +# skills/ symlink as @skills-dir). Fail-soft: a missing link +# is info (the user may have removed it on purpose), never an error. +# ──────────────────────────────────────────────────────────── +echo "── Mods ──" + +# Prints enabled|disabled|absent|unknown for $1 read from the JSON on stdin; +# always exits 0 so a bad payload cannot abort doctor under set -e. +mod_state() { + python3 -c ' +import json, sys +try: + rows = json.load(sys.stdin) + row = [r for r in rows if r.get("id") == sys.argv[1] + "@skills-dir"] + print("absent" if not row else + "enabled" if row[0].get("enabled") is True else "disabled") +except Exception: + print("unknown") +' "$1" 2>/dev/null || true +} + +_mods_list="" +if command -v claude &>/dev/null; then + if ! _mods_list=$(claude plugin list --json 2>/dev/null); then + warn "mods: claude plugin list failed — load state not checked" + _mods_list="" + fi +fi + +_mods_seen=0 +for _mod_manifest in "$REPO"/mods/*/.claude-plugin/plugin.json; do + [ -f "$_mod_manifest" ] || continue + _mods_seen=$((_mods_seen + 1)) + _mod=$(basename "$(dirname "$(dirname "$_mod_manifest")")") + _mod_link="$HOME/.claude/skills/$_mod" + if ! { [ -L "$_mod_link" ] || [ -e "$_mod_link" ]; }; then + info "mod $_mod: not linked (skills/$_mod absent) — git checkout skills/$_mod if wanted" + continue + fi + if [ "$_mod_link" -ef "$REPO/mods/$_mod" ]; then + pass "mod $_mod: loading link ~/.claude/skills/$_mod" + else + warn "mod $_mod: ~/.claude/skills/$_mod does not resolve to $REPO/mods/$_mod" + fi + [ -n "$_mods_list" ] || continue + case "$(printf '%s' "$_mods_list" | mod_state "$_mod")" in + enabled) pass "mod $_mod: enabled as $_mod@skills-dir" ;; + disabled) warn "mod $_mod: disabled (\"$_mod@skills-dir\": false in enabledPlugins)" ;; + absent) warn "mod $_mod: not listed as @skills-dir — run: claude plugin validate mods/$_mod (policy, manifest or name conflict)" ;; + *) warn "mod $_mod: claude plugin list output not understood" ;; + esac +done +[ "$_mods_seen" -gt 0 ] || info "no mods" +unset _mods_list _mods_seen _mod_manifest _mod _mod_link + +echo "" + # ── Playwright browsers (read-only report; NOT nested under gstack — 2 of # the 3 registered installs are gsd-pi, not gstack) ── echo "── Playwright browsers ──" diff --git a/lib/tests/mods.test.sh b/lib/tests/mods.test.sh new file mode 100644 index 0000000..dcc7f9c --- /dev/null +++ b/lib/tests/mods.test.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# lib/tests/mods.test.sh — every mods// plugin: the manifest name +# equals the folder, skills/ is the relative loading symlink +# ../mods/, and (when the CLI offers `claude plugin test`) the mod +# passes `claude plugin validate` without warning and `claude plugin test`. +# MODS_ROOT overrides the repo root (fixture controls). Fails when no mod +# is found, so it can never pass vacuously. +set -u +ROOT="${MODS_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)}" +CLI_TIMEOUT=120 +pass=0; fail=0 +ok() { pass=$((pass+1)); echo "PASS $1"; } +ko() { fail=$((fail+1)); echo "FAIL $1"; } +check() { if [ "$2" = "$3" ]; then ok "$1"; else ko "$1: got[$2] want[$3]"; fi; } + +# bounded CMD...: stdout+stderr on stdout, rc 124 on timeout. +bounded() { + local t + t=$(command -v timeout || command -v gtimeout || true) + if [ -n "$t" ]; then "$t" "$CLI_TIMEOUT" "$@" 2>&1; return; fi + local out rc=0 pid i=0 + out=$(mktemp) || return 1 + "$@" >"$out" 2>&1 & pid=$! + while kill -0 "$pid" 2>/dev/null && [ "$i" -lt "$CLI_TIMEOUT" ]; do + sleep 1; i=$((i+1)) + done + if kill -0 "$pid" 2>/dev/null; then kill "$pid" 2>/dev/null; rc=124 + else wait "$pid" || rc=$?; fi + cat "$out"; rm -f "$out"; return "$rc" +} + +manifest_name() { + python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("name",""))' \ + "$1" 2>/dev/null +} + +# cli_unavailable: prints the reason and returns 0 when the capability is missing. +cli_unavailable() { + command -v claude >/dev/null 2>&1 || { echo "claude not found"; return 0; } + local rc=0 + bounded claude plugin test --help >/dev/null || rc=$? + [ "$rc" -eq 124 ] && { echo "probe timed out after ${CLI_TIMEOUT}s"; return 0; } + [ "$rc" -ne 0 ] && { echo "no 'claude plugin test' command"; return 0; } + return 1 +} + +check_cli() { + local name="$1" dir="$2" out rc=0 + out=$(bounded claude plugin validate "$dir") || rc=$? + if [ "$rc" -eq 124 ]; then ko "$name: validate timed out after ${CLI_TIMEOUT}s" + elif ! printf '%s' "$out" | grep -q 'Validation passed'; then + ko "$name: validate did not pass: $(printf '%s' "$out" | head -3 | tr '\n' ' ')" + elif printf '%s' "$out" | grep -qi 'warning'; then + ko "$name: validate printed a warning" + else ok "$name: validate passed, no warning"; fi + rc=0 + out=$(bounded claude plugin test "$dir") || rc=$? + if [ "$rc" -eq 124 ]; then ko "$name: plugin test timed out after ${CLI_TIMEOUT}s" + elif [ "$rc" -ne 0 ]; then + ko "$name: plugin test rc=$rc: $(printf '%s' "$out" | tail -3 | tr '\n' ' ')" + else ok "$name: plugin test passed"; fi +} + +manifests=() +for m in "$ROOT"/mods/*/.claude-plugin/plugin.json; do + [ -f "$m" ] && manifests+=("$m") +done +if [ "${#manifests[@]}" -eq 0 ]; then ko "no mod found under $ROOT/mods"; fi + +use_cli=1 +if reason=$(cli_unavailable); then + use_cli=0 + echo "SKIP: claude plugin test unavailable ($reason) — validate/test not run" +fi + +for m in ${manifests[@]+"${manifests[@]}"}; do + dir="$(dirname "$(dirname "$m")")"; name="$(basename "$dir")" + check "$name: manifest name matches folder" "$(manifest_name "$m")" "$name" + link="$ROOT/skills/$name" + if [ -L "$link" ]; then + check "$name: loading link target" "$(readlink "$link")" "../mods/$name" + else ko "$name: skills/$name is not a symlink"; fi + [ "$use_cli" -eq 1 ] && check_cli "$name" "$dir" +done + +echo "mods: $pass pass, $fail fail" +[ "$fail" -eq 0 ] diff --git a/skills/model-router b/skills/model-router new file mode 120000 index 0000000..e051553 --- /dev/null +++ b/skills/model-router @@ -0,0 +1 @@ +../mods/model-router \ No newline at end of file From 3c44dd00d3f31b55060c79344c3cf19a2c6377a4 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 10:51:51 +0200 Subject: [PATCH 035/547] =?UTF-8?q?chore(tasks):=20model-router=20B2=20don?= =?UTF-8?q?e=20=E2=80=94=20contract=20evidence,=20TODO=20close-out=20queue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/tasks/TODO.md | 4 +++- .../2026-10-08-model-router-wiring-1835.md | 16 ++++++++-------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 4e8ac1e..400a906 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -10,7 +10,9 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [ ] W1-A residuals (security, accepted, none exploitable from outside the user's own files): ReDoS is size-bounded only (`(a+)+$` in `~/.claude/model-router.json` + a 4 KB paste hangs the hook; fix = nested-quantifier rejection or a far lower scan cap); `stat().size` trusted (FIFO/device path in ~/.claude); unrestricted `models`/`agents`/`skills` KEYS echoed raw in logs (log flood); `agentId` read from the flat tool event (engine strip unverified); 5 closures without a kit test (no fs in the kit, LRN-206); "nothing routed" catch text after a state write. - [x] W1-B1 floor precedence (contract `2026-10-08-model-router-floor-1835`, 2026-10-09): `ultrathink` + typed `/effort-` = the main turn's default AND minimum (r2 after 3 lenses: a pure floor made /effort-low a no-op); one helper `mainEffort`; per-axis precedence; mid-turn prompt floors now + next turn; `"enabled": false` per machine, kept across /clear and failed reload; typed slash attested. 30 tests; verifier CONFORME 6/6 (after 1 gap round); security PASS ×2 - [ ] W1-B1 residuals (security 2026-10-09, accepted): first-load failure of the override falls to defaults (`enabled: true`); non-boolean `enabled` drops to the default on reload; `skill.prompt` preload guard is a heuristic (`loops.size > 0`; a preload during spawn or a non-composer `/effort-*` while idle still writes the floor); marker not bound to a valid level; `/route reload` answers "config reloaded" even when the previous config was kept; transient missing override lifts a config-set off; `String(err)` of a JSON parse in the local log. Display: `/route show` folds the floor into the effort while off; model-axis text with a model-only sticky and the switch on. -- [ ] W1-B2 wiring (contract `2026-10-08-model-router-wiring-1835`): tracked symlink `skills/model-router` → `../mods/model-router` (loads as `@skills-dir`; PLUGIN_DIRS dropped: absolute paths in tracked settings), `.gitignore` engine-laid files, `lib/tests/mods.test.sh`, doctor `── Mods ──`, CLAUDE.md `## mods/`; then doc-sync (README/USAGE/CHANGELOG), live swap (remove the hot-reload link, `/reload-plugins`), BDR-115 amendment +- [x] W1-B2 wiring (contract `2026-10-08-model-router-wiring-1835`, 2026-10-09): tracked symlink `skills/model-router` → `../mods/model-router` loads as `model-router@skills-dir` (fresh-process `claude plugin list --json` proves it), `.gitignore` `mods/*/tsconfig.json`, `lib/tests/mods.test.sh` (4 checks, capability probe, bounded, SKIP), doctor `── Mods ──` fail-soft, CLAUDE.md `## mods/`. Plan r2 from 3 lenses (5 MAJOR), feater DONE, gap round (4b label + unbounded probe), verifier CONFORME 8/8, security PASS +- [ ] W1-B2 residuals (accepted): `claude plugin --help` returns 0 → the suite's capability probe can pass on a CLI without `plugin test` and then FAIL instead of SKIP (fail-closed; fix = grep the probe output for the test usage line); doctor `claude plugin list --json` unbounded; doctor `echo -e` helpers interpolate `$_mod` (tracked folder names only); fallback timeout guard orphans grandchildren (only without coreutils timeout); `update-all.sh` runs `claude plugin update` over `@skills-dir` → one recurring warn (needs an update-all edit) +- [ ] W1 close-out: doc-sync (README / USAGE / CHANGELOG), live swap (remove the hot-reload link in `~/.claude/dev-mods//`, user runs `/reload-plugins`), BDR-115 amendment (loading = skills-dir link; floor semantics), journal - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B diff --git a/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md b/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md index 6f887de..8c32fac 100644 --- a/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md +++ b/.claude/tasks/contracts/2026-10-08-model-router-wiring-1835.md @@ -18,31 +18,31 @@ Q: doctor scope / A: per mod: the loading link resolves into the repo mod dir; ` 1. `skills/model-router` is a symlink whose target is exactly `../mods/model-router`, and git does not ignore it. CHECK: [ -L skills/model-router ] && [ "$(readlink skills/model-router)" = "../mods/model-router" ] && ! git check-ignore -q skills/model-router && echo LINK-OK EXPECT: LINK-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: LINK-OK 2. Engine-laid files are ignored for ANY mod: a mod's root `tsconfig.json` (root `.gitignore`; the `.claude-plugin/types/` folder ignores itself); the tracked mod files are not ignored. CHECK: git check-ignore -q mods/model-router/tsconfig.json && git check-ignore -q mods/zz-future/tsconfig.json && ! git check-ignore -q mods/model-router/hooks/register.ts && ! git check-ignore -q mods/model-router/.claude-plugin/plugin.json && [ -z "$(git status --short mods/)" ] && echo IGNORE-OK EXPECT: IGNORE-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: IGNORE-OK 3. `lib/tests/mods.test.sh` passes on the repo, fails on a fixture that lacks the loading link, fails on an empty `mods/`, and SKIPs (exit 0) the CLI checks when `claude plugin test` is unavailable (probe by capability, PATH-shadowed `claude` in the control). CHECK: make test suite=lib/tests/mods.test.sh >/dev/null 2>&1 && W=$(mktemp -d) && mkdir -p "$W/mods" "$W/skills" "$W/bin" && cp -R mods/model-router "$W/mods/" && ! MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && ln -s ../mods/model-router "$W/skills/model-router" && MODS_ROOT="$W" bash lib/tests/mods.test.sh >/dev/null 2>&1 && printf '#!/bin/sh\nexit 1\n' > "$W/bin/claude" && chmod +x "$W/bin/claude" && PATH="$W/bin:$PATH" MODS_ROOT="$W" bash lib/tests/mods.test.sh 2>&1 | grep -q '^SKIP' && E=$(mktemp -d) && mkdir -p "$E/mods" "$E/skills" && ! MODS_ROOT="$E" bash lib/tests/mods.test.sh >/dev/null 2>&1 && echo MODS-SUITE-OK EXPECT: MODS-SUITE-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: MODS-SUITE-OK 4. `doctor.sh` prints a `── Mods ──` section with a ✓ line for model-router; with the link absent (HOME pointed at a scratch `.claude` whose `skills/` lacks the link) the section prints an info line, doctor reaches its summary and exits 0 for that section's sake (no new error). CHECK: out=$(bash doctor.sh 2>&1); echo "$out" | sed -n '/── Mods ──/,/^$/p' | grep -q '✓.*model-router' && H=$(mktemp -d) && mkdir -p "$H/.claude/skills" && o2=$(HOME="$H" bash doctor.sh 2>&1); echo "$o2" | sed -n '/── Mods ──/,/^$/p' | grep -qi 'not linked' && echo "$o2" | grep -q '═══' && echo DOCTOR-MODS-OK EXPECT: DOCTOR-MODS-OK - EVIDENCE: pending -4b. The mod is enabled through the tracked link in a FRESH process: `claude plugin list --json` lists `model-router@skills-dir` with `enabled: true` (run after the dev-mods link is removed, see W6). + EVIDENCE: MET exit=0 marker-found :: DOCTOR-MODS-OK +8. The mod is enabled through the tracked link in a FRESH process: `claude plugin list --json` lists `model-router@skills-dir` with `enabled: true` (run after the dev-mods link is removed, see W6). CHECK: claude plugin list --json 2>/dev/null | python3 -c 'import json,sys; rows=json.load(sys.stdin); ok=any(r.get("id")=="model-router@skills-dir" and r.get("enabled") is True for r in rows); sys.exit(0 if ok else 1)' && echo LOADED-OK EXPECT: LOADED-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: LOADED-OK 5. `CLAUDE.md` has a `## mods/` section naming the `skills/` relative symlink, the `@skills-dir` origin, why not `CLAUDE_CODE_PLUGIN_DIRS`, the gitignored engine-laid files, `~/.claude/.json`, the suite command and how to turn a mod off. CHECK: grep -q '^## mods/' CLAUDE.md && grep -q '@skills-dir' CLAUDE.md && grep -q 'CLAUDE_CODE_PLUGIN_DIRS' CLAUDE.md && grep -q 'mods.test.sh' CLAUDE.md && grep -q '.json' CLAUDE.md && grep -q '@skills-dir": false' CLAUDE.md && echo CLAUDEMD-OK EXPECT: CLAUDEMD-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: CLAUDEMD-OK 6. Health stack on the touched shell files, doctrine census green. CHECK: shellcheck lib/tests/mods.test.sh doctor.sh && make test suite=lib/tests/doctrine-citers.test.sh >/dev/null 2>&1 && echo HEALTH-OK EXPECT: HEALTH-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: HEALTH-OK 7. Judged by reading: no change to settings.json, link.sh or any install script; the suite probes the CAPABILITY (`claude plugin test --help`), bounds every CLI call in time, captures `2>&1`, SKIPs with a reason, fails when no mod is found; doctor's section is fail-soft under `set -euo pipefail` (existence test before readlink, `-ef` comparison, one guarded `claude plugin list --json`, python exits 0 with `unknown` on any parse error), never increments `_LINK_PASS`, says "enabled" not "loaded", treats a missing link as info; the link step is idempotent; CLAUDE.md names the per-machine `"enabled": false` switch, the tracked-settings cost of `enabledPlugins`, and the dev-copy shadowing rule; the CLAUDE.md section is terse English matching the file's style. Q (r2): ordering / A: this contract runs after the floor contract (`2026-10-08-model-router-floor-1835`) is committed and green. [orchestrator] Q (r2): update-all `claude plugin update` over `@skills-dir` / A: accepted residual (one recurring warn), logged in TODO; out of FILE SCOPE. [orchestrator] From a6e200392ca9a5bc12c863924245a52be44db0c8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 10:52:28 +0200 Subject: [PATCH 036/547] chore(memory): BDR-115 amendment (skills-dir load, floor, kill switch) + journal B2 --- .claude/memory/decisions.md | 1 + .claude/memory/journal.md | 1 + 2 files changed, 2 insertions(+) diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 1dc23fb..e3ddd31 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1401,4 +1401,5 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: agents table copying the 21 frontmatter pins in wave 1 (third source of truth, silent override of a frontmatter edit); `scope: agents` / `/route agents` bulk lever (no requirement, sixth precedence tier); `model` param on the model-facing tool (typo → LRN-203 404 class); per-step agent model rewrite (fights engine fallback, beat explicit params); `userConfig` (one config file instead); marketplace install (live symlink repo model); `source`-dependent skill-load reset (kept stale shifts). - **Gates**: plan r1 → r3 through 3 challengers + 1 confirmation (2 BLOCKER + 10 MAJOR closed, [[EVAL-040]]); feater DONE first pass; GATE 0 MET; verifier CONFORME 6/6; security PASS + hardening round (criteria 7-11). - **Refs**: plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`, contract `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md`, [[BDR-107]], [[BDR-108]], [[BLK-029]], [[LRN-205]], [[LRN-206]]. +- **Amendment (2026-10-09, user decisions 2026-10-08 evening)**: (a) LOAD supersedes the "Load:" line: tracked relative symlink `skills/model-router` → `../mods/model-router`, loaded in place as `model-router@skills-dir` wherever link.sh links `~/.claude/skills`; `CLAUDE_CODE_PLUGIN_DIRS` dropped (absolute path, settings `env` has no `$HOME` expansion, settings.json tracked), local marketplace dropped (`add` writes an absolute path into settings.json). Proven by fresh-process `claude plugin list --json`. (b) PRECEDENCE amended: `ultrathink` and a typed `/effort-` are the main turn's DEFAULT and MINIMUM (floor slot `turnFloor`): sticky `/route` effort > turn route effort > floor > engine, then floored; per axis; mid-turn prompt floors the running turn and the next (`wait` ignored). Rationale: user "un choix explicite bat la phase déduite"; a pure floor made `/effort-low` a no-op (challenge finding). (c) Per-machine kill switch `"enabled": false` in the untracked `~/.claude/model-router.json` (survives `/clear`, a failed reload keeps the previous config); `enabledPlugins` would dirty the tracked settings.json on every machine. (d) Hardening: `/route` composer-only; agent loops effort-only (model fixed at spawn); config caps; typed slash attested at `prompt.submit`. Commits 346d6ae, 1ff608a, 6430ac6; contracts `2026-10-08-model-router-floor-1835`, `2026-10-08-model-router-wiring-1835`; residuals parked in TODO. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index c8e2ae8..7ae00aa 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -583,3 +583,4 @@ rules: - model-router W1-A hardening (user go): fresh feater on contract criteria 7-11 → gap round (dead `Loop.frozen`, spawn returns `started` verbatim, tool description) → verifier CONFORME 11/11 → security PASS (1 MEDIUM residual: ReDoS size-bounded only, self-inflicted config; 5 LOW parked). Registries BDR-115, LRN-205, LRN-206, EVAL-040 written on user go (64702d5). Next: live swap of the real mod into the hot-reload folder, then W1-B install + docs. - model-router live checks on Opus 5.5 (user /model, uncommitted settings.json change left to the user): Skill(effort-low) bridge answered in place → next request low; ultrathink turn ran max (engine base medium); Explore without params → claude-sonnet-5-5, 3 steps medium. Loading switched to tracked symlink skills/model-router → @skills-dir (PLUGIN_DIRS non-portable: absolute path, no $HOME expansion, tracked settings); isolated-HOME probe listed/enabled/loaded. User chose floor semantics for ultrathink + typed /effort-. W1-B split: B1 floor (register.ts) + B2 wiring (symlink, gitignore, mods suite, doctor, CLAUDE.md); 6 challengers in flight. Effort shifters skipped this turn: the bridge would overwrite the user's ultrathink until B1 lands. - model-router W1-B1 floor landed (1ff608a): plan r2 from 3 lenses (0 BLOCKER, 4 MAJOR: one decision helper, typed level = default + minimum, mid-turn prompt now + next, per-machine enabled:false), feater DONE, gap round (/clear lost enabled:false, 'ultrathink rule' label, per-axis effort base), hardening round (kill switch keeps previous cfg on failed reload, typed slash attested at prompt.submit vs sub-agent preload). 30 tests, verifier CONFORME 6/6, security PASS ×2 with parked residuals. B2 wiring dispatched next. +- model-router W1-B2 landed (6430ac6): tracked symlink skills/model-router → ../mods/model-router (mode 120000), gitignore, lib/tests/mods.test.sh, doctor Mods section, CLAUDE.md § mods/. Plan r2 (3 lenses, 5 MAJOR), feater DONE, gap round (my `4b.` label unparsed by gates.sh + unbounded probe), verifier CONFORME 8/8, security PASS (LOW: `claude plugin --help` rc 0 weakens the SKIP probe, fail-closed). Dev hot-reload link removed from ~/.claude/dev-mods; user to run /reload-plugins. BDR-115 amended (load, floor, kill switch, hardening). Doc audit (opus) in flight. From b22f8947f9618bdcccf201fb1305d9bfd0052479 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 11:04:10 +0200 Subject: [PATCH 037/547] =?UTF-8?q?docs:=20README=20effort=20routing=20+?= =?UTF-8?q?=20/route,=20USAGE,=20ARCHITECTURE=20mods/,=20CHANGELOG=20?= =?UTF-8?q?=E2=80=94=20model-router=20wave=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ARCHITECTURE.md | 2 ++ CHANGELOG.md | 1 + README.md | 23 +++++++++++++++++++---- USAGE.md | 3 +++ 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3c0d2d0..c0d616a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -26,6 +26,7 @@ claude-config/ ├── rules/ # Rule files deployed to ~/.claude/rules (path-scoped or always-on) ├── agents/ # Execution units called by skills (never invoked directly) ├── skills/ # Entry points invoked via /skill-name +├── mods/ # Claude Code mods (function-hooks plugins), loaded through the skills/ symlink ├── skills-external/ # Vendored skill packs: gstack submodule, design skills, superpowers, agent-skills, MengTo scroll skills, 21st and Higgsfield packs (machine-owned copies gitignored) ├── templates/ # Per-project templates (CLAUDE.md, settings, memory registries, deploy runbook, gitignore) └── lib/ # Shared libs: gitflow, profiles, vendoring, effort pins, gates, archetypes, tests @@ -35,5 +36,6 @@ claude-config/ - `skills/` = entry points you invoke via `/skill-name` - `agents/` = execution units called by skills (never invoked directly by user) +- `mods/` = Claude Code mods (function-hooks plugins); each loads through the tracked symlink `skills/` as `@skills-dir`, live at the next session - `templates/` = symlinked to `~/.claude/templates/` — copy into projects via `/onboard` or manually - **Graphify** builds a knowledge graph of any codebase (`/graphify query`), producing a navigable wiki in `graphify-out/wiki/`. This map helps Claude understand project structure, find relevant code faster, and reason across files. Essential for large-scope tasks (multi-file features, complex bugs, architectural changes). Small tasks should skip it and read files directly. Proposed only from 200 tracked code files: the session-start banner informs, the user decides; nothing builds a graph without that go. diff --git a/CHANGELOG.md b/CHANGELOG.md index 26db705..4dac3e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project ## [Unreleased] ### Added +- **model-router mod**: `mods/model-router/`, a Claude Code mod (function-hooks plugin), routes the effort of every main-loop request from a phase table, along with the model and effort of the built-in sub-agents (Explore on sonnet/medium, Plan on opus/xhigh). It answers `Skill(effort-*)` itself, so the five `effort-*` skills no longer load while it is on. `ultrathink` in a prompt and a typed `/effort-` set the main turn's default and minimum effort. The model gets a `route` tool and the user a `/route` command (`show|clear|off|on|reload||model= effort=|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: the main loop switches model only with `mainModelSwitch` on (default off, one cold-cache step per switch into another model), and the hooks send full model ids, so the `models` table has to follow new versions. - **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
` 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. In manual mode it over-blocks any command where a `push` word follows a `git` token; 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/
..
` 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). ### Changed diff --git a/README.md b/README.md index 1c47c19..801d907 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ every call site. | doc-syncer | sonnet pin; audit mode dispatched `model="opus"` | two-mode: audit (drift judgment, opus) / patch (mechanical apply, sonnet) | | handover-doc-writer | sonnet pin; synthesize mode dispatched `model="opus"` | two-mode: synthesize (opus) / render (sonnet) — client deliverable | | interviewer, client-handover-writer | unpinned (inline-load = session model) | they ARE the main loop — a frontmatter pin would be inert | -| Explore (built-in) | inherit session (Fable/Opus) | search feeds reflection — kept on the big model, not pinned down | +| Explore, Plan (built-in) | model-router mod: Explore → sonnet/medium, Plan → opus/xhigh, set at spawn; an explicit `model=` on the call wins; mod off: inherit session | built-ins routed per phase by the mod | The pure-execution skills `/doc`, `/status`, `/commit-change`, `/release-candidate` **dispatch** their agent (instead of inline-loading it) @@ -108,12 +108,26 @@ entry level (`/status` low … `/ship-feature` xhigh); the vendored externals `lib/effort-pins.txt`, re-applied by `lib/effort-pins.sh` after every vendoring step. Orchestrators shift per phase through the `effort-low` … `effort-max` skills (`lib/effort-shift.md`, always sent with another tool -call: a lone Skill call applies nothing). Model pins stay tier aliases +call: a lone Skill call applies nothing (mod off)). Model pins stay tier aliases (`sonnet`, `opus`, `haiku`, `fable`): the latest version of a tier is also the cheapest or same-priced, so the quality/price trade-off is tier × effort, never version. Census `lib/tests/effort-routing.test.sh`; transcript audit `python3 lib/effort-audit.py`. +### model-router mod + +`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 effort of the phase in force. The mod answers `Skill(effort-*)` itself and applies the level from the next request on, so the five `effort-*` skills no longer load while it is on. +- Built-in sub-agents: Explore runs on sonnet/medium, Plan on opus/xhigh. An explicit `model` on the Agent call wins. +- User floor: `ultrathink` in a prompt, or a typed `/effort-`, sets the main turn's default and minimum effort. +- `/route` (user command) shows or sets the route: `show`, `clear`, `off`, `on`, `reload`, a phase name, `model= effort=`, `switch on|off`, `verbose on|off`. The model sets routes through a `route` tool. +- The spinner suffix and the status line under the prompt show the route in force. + +Optional per-machine config: `~/.claude/model-router.json`. Keys: `models` (alias → full id), `windows` (context window per full id), `phases`, `agents`, `skills`, `prompt` (rules), `mainModelSwitch` (default `false`), `verbose` (default `false`), `spinner` (default `true`), `enabled` (default `true`; `false` turns the mod off on that machine). `/route reload` re-reads it. + +Limits: the main loop changes model only with `mainModelSwitch` on, and each switch into another model costs one cold-cache step. The hooks send full model ids, so the `models` table has to follow new model versions. + --- ## Install notes @@ -204,7 +218,8 @@ a different package, ships its own conflicting `graphify` bin) — see | `/profile` | Activate a skill profile (web / seo / web-full / full / max / backend / design / dev / qa / audit / minimal) (default: full) | | `/tour` | Grouped all-axes sweep — cleanup + security + reconcile + doc, fix and loop until clean | | `/site-motion` | Site-level motion: scroll engine choice, page transitions, pin/scrub sequencing across a page or Astro route (design stack) | -| `/effort-low` … `/effort-max` | Effort shifters the orchestrators send per phase; type `/effort-max` to re-run a stuck turn at maximum | +| `/effort-low` … `/effort-max` | Effort shifters the orchestrators send per phase (answered by the model-router mod when on); typed by you, they set the main turn's default and minimum effort | +| `/route` | model-router mod: show or set the main-loop route (show, clear, off, on, reload, , model=… effort=…, switch on\|off, verbose on\|off) | > This table lists personal skills. Gstack skills (investigate, review, retro, > office-hours, cso…) and marketplace plugins add many more — run @@ -452,7 +467,7 @@ make profile-reset # go to the default profile (full) make new-skill name=myskill # scaffold agent + skill files ``` -`doctor.sh` checks: symlinks, GStack submodule, vendored skills (curl-pinned externals in `plugins.lock.json` + `link.sh`'s `EXTERNAL_SKILLS`, per the active profile), Playwright browser cache, prerequisites (git, Node, Cargo, Python, Claude Code), plugins, permissions, token budget, config consistency, git hooks (global core.hooksPath + generated githooks/), scratchpad (TMPDIR quota), Higgsfield CLI and session, seo-data layer. +`doctor.sh` checks: symlinks, GStack submodule, vendored skills (curl-pinned externals in `plugins.lock.json` + `link.sh`'s `EXTERNAL_SKILLS`, per the active profile), Playwright browser cache, prerequisites (git, Node, Cargo, Python, Claude Code), plugins, permissions, token budget, config consistency, git hooks (global core.hooksPath + generated githooks/), mods (loading link and `@skills-dir` state), scratchpad (TMPDIR quota), Higgsfield CLI and session, seo-data layer. --- diff --git a/USAGE.md b/USAGE.md index 24a2c54..3a002d1 100644 --- a/USAGE.md +++ b/USAGE.md @@ -163,6 +163,7 @@ Tu veux... | `/pdf-translate` | Traduire un PDF vers une autre langue | Sortie HTML fidèle (images, layout, style préservés) | | `/impeccable` | Audit/polish design + détecteur anti-slop déterministe | 23 verbes ; `npx impeccable detect` (exit 0/2) | | `/tour` | Sweep groupé sur un ou plusieurs projets | Sécu + nettoyage + reconcile + doc, boucle jusqu'à un pass propre | +| `/route` | Voir ou fixer la route du mod model-router | show / clear / off / on / reload / / model=… effort=… / switch on\|off / verbose on\|off | | `/profile` | Changer le profil de skills | web / seo / web-full / full / max / backend / design / dev / qa / audit / minimal | > Cette table couvre les skills personnels principaux. Les plugins (gstack, @@ -185,6 +186,8 @@ la main relance un tour bloqué au maximum. Les skills externes vendorés `lib/effort-pins.txt`. Un skill chargé seul par Claude n'applique pas son niveau : il doit partir avec un autre appel d'outil dans le même message. +Avec le mod model-router (`mods/model-router/`, actif dans chaque session), le niveau suit la phase à chaque requête. Le mod répond lui-même à `Skill(effort-*)` : le niveau s'applique dès la requête suivante et le texte des skills `effort-*` n'est plus chargé. Écrire `ultrathink` dans un prompt, ou taper `/effort-`, fixe le niveau par défaut et le minimum du tour principal. Les sous-agents intégrés suivent leur route : Explore en sonnet/medium, Plan en opus/xhigh. `/route` affiche ou fixe la route (`/route show`, `/route clear`, `/route off`). La config par machine, optionnelle, vit dans `~/.claude/model-router.json` ; `"enabled": false` y coupe le mod sur cette machine. + ## Les plugins — décision rapide ``` From e79db7e6df8ff2bc6c2c7ba388f53adc4edc7a8a Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 11:16:32 +0200 Subject: [PATCH 038/547] =?UTF-8?q?chore(memory):=20model-router=20wave=20?= =?UTF-8?q?1=20closed=20=E2=80=94=20TODO=20W2=20queued,=20journal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 7ae00aa..3ccf88d 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -584,3 +584,4 @@ rules: - model-router live checks on Opus 5.5 (user /model, uncommitted settings.json change left to the user): Skill(effort-low) bridge answered in place → next request low; ultrathink turn ran max (engine base medium); Explore without params → claude-sonnet-5-5, 3 steps medium. Loading switched to tracked symlink skills/model-router → @skills-dir (PLUGIN_DIRS non-portable: absolute path, no $HOME expansion, tracked settings); isolated-HOME probe listed/enabled/loaded. User chose floor semantics for ultrathink + typed /effort-. W1-B split: B1 floor (register.ts) + B2 wiring (symlink, gitignore, mods suite, doctor, CLAUDE.md); 6 challengers in flight. Effort shifters skipped this turn: the bridge would overwrite the user's ultrathink until B1 lands. - model-router W1-B1 floor landed (1ff608a): plan r2 from 3 lenses (0 BLOCKER, 4 MAJOR: one decision helper, typed level = default + minimum, mid-turn prompt now + next, per-machine enabled:false), feater DONE, gap round (/clear lost enabled:false, 'ultrathink rule' label, per-axis effort base), hardening round (kill switch keeps previous cfg on failed reload, typed slash attested at prompt.submit vs sub-agent preload). 30 tests, verifier CONFORME 6/6, security PASS ×2 with parked residuals. B2 wiring dispatched next. - model-router W1-B2 landed (6430ac6): tracked symlink skills/model-router → ../mods/model-router (mode 120000), gitignore, lib/tests/mods.test.sh, doctor Mods section, CLAUDE.md § mods/. Plan r2 (3 lenses, 5 MAJOR), feater DONE, gap round (my `4b.` label unparsed by gates.sh + unbounded probe), verifier CONFORME 8/8, security PASS (LOW: `claude plugin --help` rc 0 weakens the SKIP probe, fail-closed). Dev hot-reload link removed from ~/.claude/dev-mods; user to run /reload-plugins. BDR-115 amended (load, floor, kill switch, hardening). Doc audit (opus) in flight. +- model-router wave 1 CLOSED on feature/model-router-mod (15 commits ahead of develop, nothing pushed: manual mode). Docs: opus audit SIGNIFICANT (README Explore row false, no mention of the mod) → user go all 10 → first patch self-reverted by the MINOR-envelope oracle (plan carried MINOR labels; a new heading exceeds the envelope) → re-dispatched with SIGNIFICANT provenance → b22f894. Full `make test`: every suite green except the pre-existing env red design-tool-gate (21st CLI present, not hermetic). Open for the user: /reload-plugins here; merge decision (gitflow finish); settings.json own change; W2 migration queued. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 400a906..962d6d9 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -12,7 +12,8 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [ ] W1-B1 residuals (security 2026-10-09, accepted): first-load failure of the override falls to defaults (`enabled: true`); non-boolean `enabled` drops to the default on reload; `skill.prompt` preload guard is a heuristic (`loops.size > 0`; a preload during spawn or a non-composer `/effort-*` while idle still writes the floor); marker not bound to a valid level; `/route reload` answers "config reloaded" even when the previous config was kept; transient missing override lifts a config-set off; `String(err)` of a JSON parse in the local log. Display: `/route show` folds the floor into the effort while off; model-axis text with a model-only sticky and the switch on. - [x] W1-B2 wiring (contract `2026-10-08-model-router-wiring-1835`, 2026-10-09): tracked symlink `skills/model-router` → `../mods/model-router` loads as `model-router@skills-dir` (fresh-process `claude plugin list --json` proves it), `.gitignore` `mods/*/tsconfig.json`, `lib/tests/mods.test.sh` (4 checks, capability probe, bounded, SKIP), doctor `── Mods ──` fail-soft, CLAUDE.md `## mods/`. Plan r2 from 3 lenses (5 MAJOR), feater DONE, gap round (4b label + unbounded probe), verifier CONFORME 8/8, security PASS - [ ] W1-B2 residuals (accepted): `claude plugin --help` returns 0 → the suite's capability probe can pass on a CLI without `plugin test` and then FAIL instead of SKIP (fail-closed; fix = grep the probe output for the test usage line); doctor `claude plugin list --json` unbounded; doctor `echo -e` helpers interpolate `$_mod` (tracked folder names only); fallback timeout guard orphans grandchildren (only without coreutils timeout); `update-all.sh` runs `claude plugin update` over `@skills-dir` → one recurring warn (needs an update-all edit) -- [ ] W1 close-out: doc-sync (README / USAGE / CHANGELOG), live swap (remove the hot-reload link in `~/.claude/dev-mods//`, user runs `/reload-plugins`), BDR-115 amendment (loading = skills-dir link; floor semantics), journal +- [x] W1 close-out (2026-10-09): doc-sync opus audit SIGNIFICANT → user go all 10 → patched (README effort routing + Explore row + /route, USAGE, ARCHITECTURE mods/, CHANGELOG Unreleased) b22f894; hot-reload link removed from `~/.claude/dev-mods//`; BDR-115 amended (a6e2003). Pending user: `/reload-plugins` in this session (new sessions load the skills-dir copy by themselves); merge decision on feature/model-router-mod (`gitflow finish`, human signal) +- [ ] W2 migration (after wave 1 proven in daily use): 15 skills `Skill(effort-*)` → `route` tool calls; remove `skills/effort-*`, `lib/effort-pins.txt/.sh`, install/update steps, `effort:` frontmatter on skills and agents; repo agents into the mod's `agents` table (verify the spawn/first-step ordering first); `lib/model-gate.md` + `lib/model-check.sh` → mod rule; census tests repointed; `lib/effort-shift.md` rewritten; docs - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B From 2d8cd6bf4c040b6062ac338e074c91ef03494578 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 12:40:19 +0200 Subject: [PATCH 039/547] chore(tasks): model-router W1-C contract + plan (absolute tiers, breaker fallback, derived phases) --- .claude/tasks/TODO.md | 1 + .../2026-10-09-model-router-tiers-1237.md | 37 ++++ .../plans/2026-10-08-model-router-mod.md | 15 ++ .../2026-10-09-model-router-tiers-1237.md | 188 ++++++++++++++++++ 4 files changed, 241 insertions(+) create mode 100644 .claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md create mode 100644 .claude/tasks/plans/2026-10-09-model-router-tiers-1237.md diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 962d6d9..321aaf4 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -13,6 +13,7 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [x] W1-B2 wiring (contract `2026-10-08-model-router-wiring-1835`, 2026-10-09): tracked symlink `skills/model-router` → `../mods/model-router` loads as `model-router@skills-dir` (fresh-process `claude plugin list --json` proves it), `.gitignore` `mods/*/tsconfig.json`, `lib/tests/mods.test.sh` (4 checks, capability probe, bounded, SKIP), doctor `── Mods ──` fail-soft, CLAUDE.md `## mods/`. Plan r2 from 3 lenses (5 MAJOR), feater DONE, gap round (4b label + unbounded probe), verifier CONFORME 8/8, security PASS - [ ] W1-B2 residuals (accepted): `claude plugin --help` returns 0 → the suite's capability probe can pass on a CLI without `plugin test` and then FAIL instead of SKIP (fail-closed; fix = grep the probe output for the test usage line); doctor `claude plugin list --json` unbounded; doctor `echo -e` helpers interpolate `$_mod` (tracked folder names only); fallback timeout guard orphans grandchildren (only without coreutils timeout); `update-all.sh` runs `claude plugin update` over `@skills-dir` → one recurring warn (needs an update-all edit) - [x] W1 close-out (2026-10-09): doc-sync opus audit SIGNIFICANT → user go all 10 → patched (README effort routing + Explore row + /route, USAGE, ARCHITECTURE mods/, CHANGELOG Unreleased) b22f894; hot-reload link removed from `~/.claude/dev-mods//`; BDR-115 amended (a6e2003). Pending user: `/reload-plugins` in this session (new sessions load the skills-dir copy by themselves); merge decision on feature/model-router-mod (`gitflow finish`, human signal) +- [ ] W1-C adaptive tiers (user 2026-10-09: "un système logique et optimisé", no /route typed, works on a haiku session, falls back when fable has no credit): contract `2026-10-09-model-router-tiers-1237`, plan same slug. Phases name absolute tiers (best/big/work/cheap), availability breaker (turn error/refusal + engine auto switch, 15 min cooldown), fallback chain fable→opus→sonnet→haiku, main upgrade on / downgrade gated, prompt default rules (plan/reflect keywords FR+EN) + dispatch push/pop + optional classifier - [ ] W2 migration (after wave 1 proven in daily use): 15 skills `Skill(effort-*)` → `route` tool calls; remove `skills/effort-*`, `lib/effort-pins.txt/.sh`, install/update steps, `effort:` frontmatter on skills and agents; repo agents into the mod's `agents` table (verify the spawn/first-step ordering first); `lib/model-gate.md` + `lib/model-check.sh` → mod rule; census tests repointed; `lib/effort-shift.md` rewritten; docs - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B diff --git a/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md new file mode 100644 index 0000000..57eb85d --- /dev/null +++ b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md @@ -0,0 +1,37 @@ +# CONTRACT — model-router-tiers (wave 1-C: absolute tiers, availability fallback, derived phases) +- date: 2026-10-09 | flow: feat | branch: feature/model-router-mod +- status: active + +## REQUEST (verbatim — IMMUTABLE) +User (fr): "j'aimerais ne pas avoir a reflechir a tout ca, donc ne pas lancer les /route moi meme par exemple. On vois le reflect, orchestratm escalate et plan session (fable) par du preincipe que la sessino est sur fable de base ? Si on est sur haiku j'aimerias que ca fonctionne aussi avec les models adapte. et d'ailleurs que se passe til quand on a plus de credit fable, cela passe sur opus xhigh ? il faut se fallback. ET surtout oui avec un systeme adaptatif et pour la reflexion pour trouver une solution ou des idees, il faut le meilleur, pour en faire le plan en se basant sur cette reflexion. Bref un systeme logique et optimise. /ultrathink . ensuite je reload puginm tu test, on commit puis on passe a la vague 2" + +## CLARIFICATIONS +Q: "session" phases / A: no phase keeps "the session model" any more: every phase names a TIER (`best`, `big`, `work`, `cheap`), an ordered list of aliases; the first AVAILABLE alias wins. plan/reflect/orchestrate/escalate → `best` (fable, then opus, then sonnet). A haiku session asked to plan runs the plan on fable. [user: "si on est sur haiku j'aimerais que ca fonctionne aussi avec les models adaptés"] +Q: what is "available" / A: the mod cannot read per-model quota (rateLimits are account windows: five_hour, seven_day). Availability = a circuit breaker: a model is DOWN for `cooldownMinutes` (default 15) after a main or agent turn ends with `reason: 'error'` or `'refusal'` on it, or when the engine itself switched away from it (`classic.PostModelSwitch`, `source: 'auto'`). A down model is skipped in every tier and in the `fallback` chain; `/route show` lists down models with their reset time; `/route reload` clears the breaker. [orchestrator — derived from the engine's declarations] +Q: no credit left on fable / A: main loop on a down model → next available alias of the `fallback` chain (`fable, opus, sonnet, haiku`), effort unchanged (plan stays xhigh → "opus xhigh"), always allowed (a down model yields nothing), logged and shown. [user: "il faut se fallback"] +Q: main-loop model moves / A: UPGRADE (phase tier ranks above the current model) allowed by default (`mainUpgrade: true`); DOWNGRADE (cheaper model) still gated by `mainModelSwitch` (default false: one cold-cache step per switch, and haiku's window may not fit); same rank → no switch. [orchestrator — cost/quality trade-off, stated to the user] +Q: no `/route` typed by the user / A: phases come from (1) prompt rules at turn start (keyword → phase as the turn's DEFAULT route, source 'prompt', overridable; `ultrathink` stays a FLOOR), (2) the model's own `route` calls and the skills table, (3) derived: an Agent dispatch from main pushes `orchestrate` and the previous route is restored when the last live agent ends, (4) optional classifier (`classifier: false` by default) that asks the engine's small model for a phase label when no rule matched. [user: "ne pas lancer les /route moi-même"] +Q: default prompt rules / A: floor: `\bultrathink\b` → escalate. Defaults: `\b(plan|planifie|planning|brainstorm|architecture|con[cç]ois|design)\b` → plan; `\b(pourquoi|why|explique|explain|analyse|analyze|comprendre|understand|review|audit)\b` → reflect. No default rule lowers a turn (no `mechanical` rule): lowering is explicit (route tool, skills). [orchestrator — conservative defaults, user-editable in the override] +Q: typed `/effort-` / A: unchanged (floor + default of the turn, B1). + +## ACCEPTANCE CRITERIA +1. Suite green: `claude plugin test` passes with at least 40 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. + CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 40 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo TIERS-SUITE-OK + EXPECT: TIERS-SUITE-OK + EVIDENCE: pending +2. Type-check clean against this build's declarations. + CHECK: T=/Users/b.chanot/Documents/claude/mods/model-router/.claude-plugin/types; W=$(mktemp -d) && printf '{"compilerOptions":{"target":"es2023","lib":["es2023"],"types":[],"module":"esnext","moduleResolution":"bundler","strict":true,"noUncheckedIndexedAccess":true,"noEmit":true,"skipLibCheck":true,"jsx":"react","jsxFactory":"h","jsxFragmentFactory":"Fragment"},"include":["%s/claude-code/index.d.ts","%s/claude-code-tools/index.d.ts","%s/hooks"]}' "$T" "$T" "$PWD/mods/model-router" > "$W/tsconfig.json" && (cd "$W" && npx --yes -p typescript@5 tsc -p tsconfig.json) && echo TSC-OK + EXPECT: TSC-OK + EVIDENCE: pending +3. Tiers in the config: `tiers` (best/big/work/cheap), `fallback`, `cooldownMinutes`, `mainUpgrade`, `classifier` exist in DEFAULT_CONFIG; every default phase names a tier, none a bare model; `/route show` prints the resolved model of each phase and a `down:` line. + CHECK: cd mods/model-router/hooks && grep -q "tiers:" register.ts && grep -q "fallback:" register.ts && grep -q "cooldownMinutes" register.ts && grep -q "mainUpgrade" register.ts && grep -q "classifier" register.ts && [ "$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -cE "tier: '(best|big|work|cheap)'")" -ge 10 ] && ! awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -qE "^\s+[a-z]+: \{ model: '" && grep -q "down:" register.ts && echo TIERS-CONFIG-OK + EXPECT: TIERS-CONFIG-OK + EVIDENCE: pending +4. Tests prove (names contain the quoted word): `tier` — a `plan` route on a session model `claude-haiku-4-5-20251001` makes the main step run on `claude-fable-5-1` at xhigh (upgrade, default on); `downgrade` — a `mechanical` route on a fable session leaves the model unchanged while `mainModelSwitch` is off; `fallback` — after a main `turn.complete` with `reason: 'error'` on fable, the next main step runs on `claude-opus-5-5` with its effort unchanged, and after `/route reload` fable is used again; `breaker` — a `classic.PostModelSwitch` with `source: 'auto'` from fable marks fable down and `/route show` lists it; `spawn` — `Explore` spawns on `claude-opus-5-5` while sonnet is down; `derived` — an Agent tool call from main sets `orchestrate` and the previous route (`plan`) is back after the last agent's `turn.complete`; `default rule` — a prompt "planifie la migration" sets the `plan` route as the turn default and a later `route` tool call overrides it; `floor` tests from B1 still pass. + CHECK: cd mods/model-router/hooks && for w in tier downgrade fallback breaker spawn derived "default rule"; do grep -qE "test\('[^']*$w" register.test.ts || { echo "missing test: $w"; exit 1; }; done && echo TIERS-TESTS-OK + EXPECT: TIERS-TESTS-OK + EVIDENCE: pending +5. Judged by reading: ONE resolver (`resolveModel`) turns a tier name, an alias or a full id into the first AVAILABLE full id (tier → list → skip down → alias → id; a bare alias or id passes through even when down, since explicit means explicit); rank = position in `fallback`; the main-loop decision is: route model wanted → upgrade allowed by `mainUpgrade`, downgrade gated by `mainModelSwitch` + window, same rank → keep; no route and current model down → next available in `fallback`; the breaker is fed only by `turn.complete` `reason` in `error|refusal` (main: the last main step's model; agent: the loop's spawn model) and by `classic.PostModelSwitch` `source: 'auto'` (from_model), never by an aborted turn; the derived `orchestrate` push/pop never overrides a route the model declared after the dispatch; prompt default rules write `turnMain` (source 'prompt'), floor rules write `turnFloor`; the classifier runs only when `classifier` is true and no rule matched, through `$.model.classify`, labels limited to the phase names plus `other`, any failure → no route; explicit Agent params still win; agent model fixed at spawn; every B1/1-A criterion still holds; no function over 25 logic lines; truthful texts name the resolved model and say "fallback" when the breaker chose it. + +## FILE SCOPE +mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts diff --git a/.claude/tasks/plans/2026-10-08-model-router-mod.md b/.claude/tasks/plans/2026-10-08-model-router-mod.md index b5ff7a6..6dab05a 100644 --- a/.claude/tasks/plans/2026-10-08-model-router-mod.md +++ b/.claude/tasks/plans/2026-10-08-model-router-mod.md @@ -116,6 +116,21 @@ does many different things inside one run. So: Explore without params spawned on `claude-sonnet-5-5`, all 3 steps `medium` (no spawn/step race observed). +## Decisions 2026-10-09 (user, after the wave-1 table was shown) +- No "session model" phase: every phase names an ABSOLUTE tier (best = fable, + opus, sonnet · big = opus, fable, sonnet · work = sonnet, opus · cheap = haiku, + sonnet); a haiku session asked to plan runs on fable. Reflection and planning + always on the best available model. +- Availability = circuit breaker (turn error/refusal, engine auto switch), not + quota reading (rateLimits are account windows). Fallback fable → opus → + sonnet → haiku, effort unchanged ("plus de crédit fable → opus xhigh"). +- The user never types /route: prompt default rules, dispatch push/pop + (orchestrate while agents run, previous route restored), skills table + (wave 2), optional classifier. Main upgrade allowed by default, downgrade + still gated (cold-cache cost). +- Sequence agreed: 1-C lands → user /reload-plugins → live test → commit → + wave 2. + ## Wave 0 — spike (dev-mods folder, hot reload, this session) - [x] W0.1 minimal mod: `/route` command, `route` tool, `turn.step` logging + rewrite, `agent.spawn` rewrite, `ultrathink` → max, spinner suffix diff --git a/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md b/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md new file mode 100644 index 0000000..639d822 --- /dev/null +++ b/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md @@ -0,0 +1,188 @@ +# PLAN — model-router wave 1-C: absolute tiers, availability fallback, derived phases (dispatch-ready) +Contract: .claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md +Code: mods/model-router/hooks/register.ts (read in full) and register.test.ts. +API truth: mods/model-router/.claude-plugin/types/claude-code/index.d.ts +(TurnStepInput, TurnCompleteInput + TurnCompleteReason, SessionRateLimit, +`classic.PostModelSwitch` → PostModelSwitchHookInput, `$.session.model`, +`$.model.classify`, 'claude-code/testing'), .../claude-code-tools/index.d.ts. + +## Why (user, 2026-10-09) +1. "Session model" phases assumed Fable. On a haiku session, `plan` at xhigh on + haiku is wrong. Phases must name ABSOLUTE tiers. +2. When Fable has no credit left, routing must fall back (plan → opus xhigh). +3. The user never types `/route`: phases are derived (prompt wording, + dispatch spans, skills) or declared by the model. +4. Reflection and planning always get the best available model. + +## Engine facts (read in the declarations today) +- `SessionRateLimit.kind` ∈ five_hour | seven_day | spend_limit: account + windows, NOT per model → availability cannot be read from quotas. +- A dead request: `turn.step` result `usage: null`, `stopReason: null`; + `turn.complete` `reason: 'error'` (retries exhausted) or `'refusal'` + (refused, no fallback model); `'aborted'` = the user interrupted. +- `classic.PostModelSwitch` fires on every main-model change with + `from_model`, `to_model`, `source` ∈ command|picker|sdk|auto|resume, + `context_tokens`, `prompt_cache_warm`. +- `turn.step` `e.model` = the id the engine resolved (session's or a + fallback's); `$.session.model()` = the main loop's model as `/model` shows. +- `$.model.classify(text, labels, { model? })` → label | undefined, rejects + on failure; default = the engine's small fast model. + +## Config (additions; everything else unchanged) +```ts +type Route = { model?: string; effort?: Level } // model: TIER name, alias or full id +type PromptRule = { pattern: string; phase: string; mode?: 'floor' | 'default' } +type Config = { + …existing… + tiers: Record // tier → ordered alias preference + fallback: string[] // alias order, best first; = rank + cooldownMinutes: number // breaker hold + mainUpgrade: boolean // main loop may switch UP to a phase's tier + classifier: boolean // ask the small model when no rule matched +} +``` +DEFAULT_CONFIG changes: +- `tiers`: best `['fable','opus','sonnet']`, big `['opus','fable','sonnet']`, + work `['sonnet','opus']`, cheap `['haiku','sonnet']`. +- `fallback`: `['fable','opus','sonnet','haiku']`. `cooldownMinutes: 15`. + `mainUpgrade: true`. `classifier: false`. +- phases: plan `{ model: 'best', effort: 'xhigh' }`, reflect `{ best, high }`, + orchestrate `{ best, medium }`, escalate `{ best, max }`, judge `{ big, xhigh }`, + implement `{ work, medium }`, write `{ work, medium }`, verify `{ work, xhigh }`, + explore `{ work, medium }`, mechanical `{ cheap, low }`. (Keep the `model` + field name: a tier name is a model NAME the resolver understands; no new + `tier` field. AC3 greps `tier: '…'`?? NO: AC3 is written against + `model: 'best'`-style entries? → see AC3 note below.) +- prompt: `[{ pattern: '\\bultrathink\\b', phase: 'escalate', mode: 'floor' }, + { pattern: '\\b(plan|planifie|planning|brainstorm|architecture|con[cç]ois|design)\\b', phase: 'plan', mode: 'default' }, + { pattern: '\\b(pourquoi|why|explique|explain|analyse|analyze|comprendre|understand|review|audit)\\b', phase: 'reflect', mode: 'default' }]`. + `mode` absent → 'default'. +AC3 note for the executor: the contract's CHECK counts `tier: '(best|big|work|cheap)'` +in DEFAULT_CONFIG and refuses `model: '` entries there. So the PHASE type gets +an explicit `tier?: string` field: `type Route = { tier?: string; model?: string; +effort?: Level }`; a route resolves `tier` first, then `model`. Default phases +use `tier:`. `/route model=` keeps writing `model` (alias or id). The route +tool keeps `phase`/`effort`/`clear` only. +Validation: `tiers` values = non-empty arrays of `models` keys (bad entries +dropped, logged); `fallback` = array of `models` keys, deduplicated, non-empty +(else default); phase `tier` must be a `tiers` key; `cooldownMinutes` positive +integer; `mode` ∈ floor|default. + +## Resolution (ONE resolver, used by spawn, main plan and texts) +```ts +function availableIn(st, aliases: string[]): string | undefined + // first alias whose full id is not down (st.down.get(id) > now → down) +function resolveModel(st, name: string): string + // tier name → availableIn(tiers[name]) ?? first alias → id + // alias → id (explicit: never skipped when down); full id → itself +function resolveRoute(st, route: Route): string | undefined + // route.tier ? resolveModel(st, route.tier) : route.model ? resolveModel(st, route.model) : undefined +function rank(st, id: string): number + // index in cfg.fallback of the alias whose id prefixes `id` (strip "[1m]"); unknown → fallback.length +``` +`now` comes from `$.clock.now()` (read once per hook call that needs it). + +## Breaker (`st.down: Map` full id → until ms; `st.lastMainModel: string`) +- `turn.complete`: main (`e.agentId` undefined) with `reason` ∈ error|refusal → + `markDown(st, st.lastMainModel)`; agent with that reason → `markDown(loop.model)` + (Loop gains `model: string`, the model the engine reported at spawn, + `started.model`). `aborted`/`answer` → nothing. +- `classic.PostModelSwitch` with `e.source === 'auto'` → `markDown(e.from_model)`. +- `markDown` logs ALWAYS (not only verbose): `model-router: unavailable + until ; routing falls back`. `/route reload` and `session.end` clear + the map. `show()` gets a `down: until , …` or `down: none` line. + +## Main-loop model decision (`mainModel` rewritten) +``` +wanted = resolveRoute(st, (userMain ?? turnMain ?? turnFloor)?.route) // per-axis as today +cur = e.model +if cur is down and wanted is undefined → wanted = nextAvailable(st, cur) // fallback chain after cur's alias +if wanted undefined or sameRank(wanted, cur) → cur +if rank(wanted) < rank(cur) (better) → cfg.mainUpgrade ? wanted : cur +if rank(wanted) > rank(cur) (cheaper) → cfg.mainModelSwitch && windowOk ? wanted : cur +if cur is down and wanted defined → wanted (always: nothing to lose) +``` +`st.lastMainModel = plan.model` at every main step. `sameRank` compares +aliases (so `claude-fable-5-1` vs `claude-fable-5-1[1m]` never flips). +The log/status show `→ fallback` when the breaker chose the model. + +## Spawn (`spawnRoute` / `registerSpawn`) +`wanted = resolveRoute(st, route)`; explicit `e.model` still wins. Store +`loop.model = started.model`. (Explicit alias given by the caller while down: +left alone, explicit means explicit; note in the tool description.) + +## Derived phases (no user action) +D1. Dispatch push/pop: in the Agent `tool.call` hook, when `e.agentId` is + undefined (main) and `st.turnMain?.source !== 'model'` written AFTER the + dispatch… simpler rule: on a main Agent call, if `st.resumeMain` is + unset, `st.resumeMain = st.turnMain ?? NONE` and `st.turnMain = { phase: + 'orchestrate', route: phases.orchestrate, source: 'derived' }`. When an + agent's `turn.complete` leaves `st.loops` empty AND `st.turnMain?.source + === 'derived'` → `st.turnMain = st.resumeMain` (NONE → null), clear + `resumeMain`. A `route` call or skill load in between replaces turnMain + (source model/skill) so the pop is skipped and `resumeMain` cleared at + the next main `turn.complete` (endMainTurn clears both). Source type gains + `'derived'`. +D2. Prompt default rules (`mode: 'default'`): write `turnMain = { phase, + route, source: 'prompt' }` (NOT the floor) — overridable by routes and + skills; floor rules unchanged. Mid-turn prompt with a default rule → only + `pendingPrompt`-like handling for FLOOR rules stays; a default rule typed + mid-turn is ignored (the running turn has its own routes). +D3. Classifier: when `cfg.classifier` and no rule matched and the prompt is + composer-origin and idle (no `turnId`): `label = await + $.model.classify(e.text.slice(0, MAX_PROMPT_SCAN), [...phaseNames, + 'other'])` in try/catch; a phase label → default route (source 'prompt'); + anything else → nothing. Document the cost in the config comment. + +## Texts +`routedText`/`mainNote`/`show`: print the RESOLVED id and `(fallback)` when +the breaker skipped a better alias; `(tier best → claude-fable-5-1)`. +Spinner/status unchanged shape. + +## Tests (register.test.ts; names must contain the contract's words) +Reuse the boot helper; full typed inputs; bottom hooks (`agent.spawn`, +`turn.complete`, `classic.PostModelSwitch` — read its input type for the +required fields; `prompt.submit`). Engine effort `high` in steps. +- `tier: a plan route upgrades a haiku session to fable at xhigh` — route tool + `plan`, step with `model: 'claude-haiku-4-5-20251001'` → bottom sees + `claude-fable-5-1` and `xhigh`. +- `downgrade: mechanical on fable keeps the model while the switch is off`. +- `fallback: an error turn on fable moves the next main step to opus` — step on + fable (sets lastMainModel), `$.turn.complete({ reason: 'error', agentId + undefined, … })`, step on fable → bottom sees `claude-opus-5-5`, effort + unchanged; then `/route reload` → step on fable stays fable. +- `breaker: PostModelSwitch auto marks the old model down` — `$.classic.PostModelSwitch({ from_model: 'claude-fable-5-1', to_model: 'claude-opus-5-5', source: 'auto', … })` → `/route show` lists `claude-fable-5-1` under `down:`. +- `spawn: Explore goes to opus while sonnet is down` — mark sonnet down + through an agent error turn (spawn Explore via bottom hook returning a1, + `$.turn.complete({ agentId: 'a1', reason: 'error' })`), spawn again → bottom + `e.model === 'claude-opus-5-5'`. +- `derived: a dispatch pushes orchestrate and pops the previous plan route` + — route tool `plan`, `$.tool.call({ tool: 'Agent', … })` with a bottom hook, + `/route show` main line shows `derived orchestrate`; `$.turn.complete({ + agentId: 'a1', reason: 'answer' })` (loop registered via spawn) → main line + shows `model plan` again. +- `default rule: "planifie la migration" routes the turn to plan, a route call overrides`. +- Keep every B1 `floor` test and all earlier tests green (≥ 40 tests total). + +## Constraints +- ≤ 25 logic lines per function (extract helpers: `availableIn`, `rank`, + `markDown`, `nextAvailable`, `decideMain`, `pushOrchestrate`, `popOrchestrate`, + `applyDefaultRule`, `classifyPrompt`), 80 chars/line, no `any`, state in + the closure, fail-open `.catch` with `warnOnce` on every new hook + (`classic.PostModelSwitch`), the route tool schema unchanged. +- Do not touch: the hardening (caps, `safely`, attestation), the Skill + bridge, the floor slot semantics. +- Verify: validate, the contract's tsc CHECK, `claude plugin test .`, AC3/AC4 + greps, `gates.sh run` on the contract. + +## Disposition +- honors BDR-115 and its amendment (one resolver, calling-loop writes, + truthful texts, per-machine config); supersedes "a phase without model + keeps the loop's model" (every default phase now names a tier). +- honors BDR-076 (dispatched judgment on opus first: `big` = opus, fable, + sonnet) and BDR-066 (execution on sonnet: `work`). +- LRN-203: hooks still write full ids (the resolver's output). +- LRN-204: downgrade on main stays gated; upgrade accepted (quality over one + cold-cache step). +- Deferred: repo agents' frontmatter pins cannot fall back (the mod does not + see them in wave 1) → wave 2 moves them into the table with tiers. From 140c16a67f85071529da68b4dd65c15a120b0501 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 12:55:14 +0200 Subject: [PATCH 040/547] chore(tasks): model-router W1-C plan r2 + contract amendments after the FATAL round --- .../2026-10-09-model-router-tiers-1237.md | 18 +- .../2026-10-09-model-router-tiers-1237.md | 164 ++++++++++++++++++ 2 files changed, 175 insertions(+), 7 deletions(-) diff --git a/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md index 57eb85d..62754b7 100644 --- a/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md +++ b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md @@ -13,25 +13,29 @@ Q: main-loop model moves / A: UPGRADE (phase tier ranks above the current model) Q: no `/route` typed by the user / A: phases come from (1) prompt rules at turn start (keyword → phase as the turn's DEFAULT route, source 'prompt', overridable; `ultrathink` stays a FLOOR), (2) the model's own `route` calls and the skills table, (3) derived: an Agent dispatch from main pushes `orchestrate` and the previous route is restored when the last live agent ends, (4) optional classifier (`classifier: false` by default) that asks the engine's small model for a phase label when no rule matched. [user: "ne pas lancer les /route moi-même"] Q: default prompt rules / A: floor: `\bultrathink\b` → escalate. Defaults: `\b(plan|planifie|planning|brainstorm|architecture|con[cç]ois|design)\b` → plan; `\b(pourquoi|why|explique|explain|analyse|analyze|comprendre|understand|review|audit)\b` → reflect. No default rule lowers a turn (no `mechanical` rule): lowering is explicit (route tool, skills). [orchestrator — conservative defaults, user-editable in the override] Q: typed `/effort-` / A: unchanged (floor + default of the turn, B1). +Q (r2): breaker signal / A: `classic.StopFailure` error kinds `rate_limit | overloaded | billing_error | model_not_found` (+ the engine's own fallback detected at the step), NOT `turn.complete` reasons (a context-limit or network error is not unavailability); backoff 15 → 300 min; `/clear` keeps the marks (account-wide), `/route reload` and a user `/model` clear them. [orchestrator — challenge r1] +Q (r2): classifier / A: deferred to wave 2 (dead code by default, no test can reach it, no timeout on the call). [orchestrator — challenge r1] +Q (r2): upgrade cost / A: an upgrade is skipped above `upgradeMaxTokens` (default 200000 context tokens): one cold read of the whole context per switch into a model. [orchestrator — LRN-204] +Q (r2): superseded clauses / A: floor AC4 (`turnMain` sources gain 'derived' and 'prompt'), W1-A AC6 (the switch gates downgrades only), BDR-115 (6) (window guard on every switch). [orchestrator] ## ACCEPTANCE CRITERIA -1. Suite green: `claude plugin test` passes with at least 40 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. - CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 40 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo TIERS-SUITE-OK +1. Suite green: `claude plugin test` passes with at least 43 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. + CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 43 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo TIERS-SUITE-OK EXPECT: TIERS-SUITE-OK EVIDENCE: pending 2. Type-check clean against this build's declarations. CHECK: T=/Users/b.chanot/Documents/claude/mods/model-router/.claude-plugin/types; W=$(mktemp -d) && printf '{"compilerOptions":{"target":"es2023","lib":["es2023"],"types":[],"module":"esnext","moduleResolution":"bundler","strict":true,"noUncheckedIndexedAccess":true,"noEmit":true,"skipLibCheck":true,"jsx":"react","jsxFactory":"h","jsxFragmentFactory":"Fragment"},"include":["%s/claude-code/index.d.ts","%s/claude-code-tools/index.d.ts","%s/hooks"]}' "$T" "$T" "$PWD/mods/model-router" > "$W/tsconfig.json" && (cd "$W" && npx --yes -p typescript@5 tsc -p tsconfig.json) && echo TSC-OK EXPECT: TSC-OK EVIDENCE: pending -3. Tiers in the config: `tiers` (best/big/work/cheap), `fallback`, `cooldownMinutes`, `mainUpgrade`, `classifier` exist in DEFAULT_CONFIG; every default phase names a tier, none a bare model; `/route show` prints the resolved model of each phase and a `down:` line. - CHECK: cd mods/model-router/hooks && grep -q "tiers:" register.ts && grep -q "fallback:" register.ts && grep -q "cooldownMinutes" register.ts && grep -q "mainUpgrade" register.ts && grep -q "classifier" register.ts && [ "$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -cE "tier: '(best|big|work|cheap)'")" -ge 10 ] && ! awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -qE "^\s+[a-z]+: \{ model: '" && grep -q "down:" register.ts && echo TIERS-CONFIG-OK +3. Tiers in the config: `tiers` (best/big/work/cheap), `fallback`, `cooldownMinutes`, `mainUpgrade`, `upgradeMaxTokens` exist in DEFAULT_CONFIG; every default phase names a tier, none a bare model; `/route show` prints the resolved model of each phase and a `down:` line; no `classifier` (deferred to wave 2); no `Loop.model` / `spawnModel` / `loop.model` identifier (W1-A AC8). + CHECK: cd mods/model-router/hooks && grep -q "tiers:" register.ts && grep -q "fallback:" register.ts && grep -q "cooldownMinutes" register.ts && grep -q "mainUpgrade" register.ts && grep -q "upgradeMaxTokens" register.ts && ! grep -q "classifier" register.ts && [ "$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -cE "tier: '(best|big|work|cheap)'")" -ge 10 ] && ! awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -qE "model: '(haiku|sonnet|opus|fable)'" && ! grep -qE "loop\.model|explicitModel|spawnModel" register.ts && grep -q "down:" register.ts && echo TIERS-CONFIG-OK EXPECT: TIERS-CONFIG-OK EVIDENCE: pending -4. Tests prove (names contain the quoted word): `tier` — a `plan` route on a session model `claude-haiku-4-5-20251001` makes the main step run on `claude-fable-5-1` at xhigh (upgrade, default on); `downgrade` — a `mechanical` route on a fable session leaves the model unchanged while `mainModelSwitch` is off; `fallback` — after a main `turn.complete` with `reason: 'error'` on fable, the next main step runs on `claude-opus-5-5` with its effort unchanged, and after `/route reload` fable is used again; `breaker` — a `classic.PostModelSwitch` with `source: 'auto'` from fable marks fable down and `/route show` lists it; `spawn` — `Explore` spawns on `claude-opus-5-5` while sonnet is down; `derived` — an Agent tool call from main sets `orchestrate` and the previous route (`plan`) is back after the last agent's `turn.complete`; `default rule` — a prompt "planifie la migration" sets the `plan` route as the turn default and a later `route` tool call overrides it; `floor` tests from B1 still pass. - CHECK: cd mods/model-router/hooks && for w in tier downgrade fallback breaker spawn derived "default rule"; do grep -qE "test\('[^']*$w" register.test.ts || { echo "missing test: $w"; exit 1; }; done && echo TIERS-TESTS-OK +4. Tests prove (names contain the quoted word; plan r2 R14 lists them): `tier` — a `plan` route on a session model `claude-haiku-4-5-20251001` makes the main step run on `claude-fable-5-1` at xhigh (upgrade, default on); `downgrade` — a `mechanical` route on a fable session leaves the model unchanged while `mainModelSwitch` is off; `fallback` — with a `plan` route, a `classic.StopFailure` `rate_limit` on main after a fable step makes the next main step run on `claude-opus-5-5` at xhigh, and after `/route reload` fable is used again; `breaker` — an `invalid_request` failure never marks a model down, backoff expiry restores it, a `/model` command (`PostModelSwitch` source `command`) clears it; `engine fallback` — a step arriving on a model other than `$.session.model()` is never upgraded back and the session model is marked down; `unknown` — a session model absent from the table is never switched; `spawn` — `Explore` spawns on `claude-opus-5-5` while sonnet is down (agent StopFailure with `agent_id`); `derived` — a main Agent call sets `orchestrate` and the previous `plan` route is back when the spawned agent ends; a route declared after the dispatch is not overwritten by the pop; `default rule` — "planifie la migration" sets `plan` as the turn default and a later route call overrides it; a typed `/analyze …` and a `/effort-low pourquoi …` prompt get no default rule; `per axis` — a model-less sticky never hides a turn route's tier; `floor` tests from B1 still pass. + CHECK: cd mods/model-router/hooks && for w in tier downgrade fallback breaker "engine fallback" unknown spawn derived "default rule" "per axis"; do grep -qE "test\('[^']*$w" register.test.ts || { echo "missing test: $w"; exit 1; }; done && [ "$(grep -cE "test\('[^']*(breaker|derived|default rule)" register.test.ts)" -ge 7 ] && echo TIERS-TESTS-OK EXPECT: TIERS-TESTS-OK EVIDENCE: pending -5. Judged by reading: ONE resolver (`resolveModel`) turns a tier name, an alias or a full id into the first AVAILABLE full id (tier → list → skip down → alias → id; a bare alias or id passes through even when down, since explicit means explicit); rank = position in `fallback`; the main-loop decision is: route model wanted → upgrade allowed by `mainUpgrade`, downgrade gated by `mainModelSwitch` + window, same rank → keep; no route and current model down → next available in `fallback`; the breaker is fed only by `turn.complete` `reason` in `error|refusal` (main: the last main step's model; agent: the loop's spawn model) and by `classic.PostModelSwitch` `source: 'auto'` (from_model), never by an aborted turn; the derived `orchestrate` push/pop never overrides a route the model declared after the dispatch; prompt default rules write `turnMain` (source 'prompt'), floor rules write `turnFloor`; the classifier runs only when `classifier` is true and no rule matched, through `$.model.classify`, labels limited to the phase names plus `other`, any failure → no route; explicit Agent params still win; agent model fixed at spawn; every B1/1-A criterion still holds; no function over 25 logic lines; truthful texts name the resolved model and say "fallback" when the breaker chose it. +5. Judged by reading (plan r2 R1-R15 are binding): ONE resolver turns a tier name, an alias or a full id into an AVAILABLE canonical id (tier → list → skip down → id; an exhausted tier → the global chain; a bare alias or id passes through even when down); ids are canonical everywhere (`[1m]` stripped for comparison and carried on the replacement, alias → id, two-way prefix); ONE decision `decideMain(cur, wanted, ctx)` in the binding order (off → unknown cur: no switch → cur down: wanted or next available, windowOk → same alias: keep → better: `mainUpgrade` and `upgradeMaxTokens` → cheaper: `mainModelSwitch` and windowOk), used by `mainPlan` AND by every text; the engine's own fallback is respected (a step arriving off the session model marks the session model down and is never upgraded back); the breaker is fed only by `classic.StopFailure` errors `rate_limit | overloaded | billing_error | model_not_found` (main → the last main plan's model, agent → `agentModels`) and by the engine-fallback detection; `turn.complete` reasons and `PostModelSwitch` `auto` never mark (auto is logged); a user `/model` (`PostModelSwitch` command|picker|sdk) clears the target's mark; backoff 15 → 30 → 60 → 120 → 300 min per id, `model_not_found` until reload; the breaker survives `/clear` and is cleared by `/route reload` before the config read; the derived `orchestrate` push/pop tracks this turn's spawns and never overwrites a route the model declared after the dispatch; default prompt rules (two passes, absent `mode` = floor, `iu` flags, Unicode guards) write `turnMain` (source 'prompt') and are skipped for a leading `/`, for a prompt carrying a floor or a typed slash, and mid-turn; floor rules write `turnFloor`; no classifier; explicit Agent params still win; agent model fixed at spawn; every B1/1-A criterion still holds EXCEPT the three clauses R15 names (turnMain sources, the switch clause, the window-guard scope); no function over 25 logic lines; truthful texts come from `decideMain` and say `upgrade`, `fallback`, `switch off` or `unchanged`. ## FILE SCOPE mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts diff --git a/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md b/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md index 639d822..2e309c1 100644 --- a/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md +++ b/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md @@ -186,3 +186,167 @@ required fields; `prompt.submit`). Engine effort `high` in steps. cold-cache step). - Deferred: repo agents' frontmatter pins cannot fall back (the mod does not see them in wave 1) → wave 2 moves them into the table with tiers. + +## r2 — challenge round (3 lenses, all FATAL: 4 BLOCKER, 20 MAJOR): BINDING, overrides every section above where they conflict +R1. ONE phase field for the fallback-aware choice: `Route = { tier?: string; + model?: string; effort?: Level }`. Default phases use `tier:` only (plan, + reflect, orchestrate, escalate → best; judge → big; implement, write, + verify, explore → work; mechanical → cheap). `acceptPhase` refuses a route + carrying both `tier` and `model`, and refuses a `tiers` key that collides + with a `models` alias. The earlier "model: 'best'" drafts and the "no new + tier field" sentence are VOID. `/route model=` keeps writing + `model`; the route tool schema is unchanged. +R2. Ids: `canonical(st, id)` = strip a trailing `[1m]`, then alias → table id, + then two-way prefix match against the table ids (`id.startsWith(tableId) + || tableId.startsWith(id)`), else the id itself. `aliasOf(st, id)` and + `modelRank(st, id)` (= index of the alias in `fallback`, `undefined` when + unknown) work on canonical ids. The existing effort `rank` keeps its name. + Breaker keys, `agentModels` values and comparisons are canonical. When the + current main model carries `[1m]`, a resolved replacement carries `[1m]` + too (the long-context tier is a property of the session, not of the + alias); log the first time it happens (unverified live: see Verify). +R3. Model axis per slot: `routeModelName(route) = route.tier ?? route.model`; + the main model axis is the FIRST defined `routeModelName` across + userMain, turnMain, turnFloor (per-axis, like B1's effort). `resolveName` + turns that name into an available id: a `tiers` key → first alias of the + list not down → `models` id; a tier whose every alias is down → + `nextAvailable(st, cur)` (global chain) → may be `undefined` (keep cur); + an alias or full id → canonical id, never skipped (explicit means explicit). +R4. Main decision `decideMain(st, cur, wanted, ctx)` → `{ model, why }`, used + by `mainPlan` AND by every text (texts pass `cur = canonical(await + $.session.model())`); order is BINDING: + 1. `st.off` → cur. + 2. `rankCur = modelRank(cur)`; UNKNOWN cur (not in the table) → cur, log + once per session (`model-router: unknown to the models table; no + model switch`), the breaker still applies at step 3 if it is down. + 3. cur DOWN → `wanted` if defined and not down, else `nextAvailable(cur)`; + apply `windowOk`; if nothing fits → cur (why `fallback`). + 4. `wanted` undefined or `aliasOf(wanted) === aliasOf(cur)` → cur. + 5. `modelRank(wanted) < rankCur` (better) → `cfg.mainUpgrade && + ctx.tokens <= cfg.upgradeMaxTokens` ? wanted (why `upgrade`) : cur + (why `upgrade skipped: context tokens over ` or `switch off`). + 6. cheaper → `cfg.mainModelSwitch && windowOk` ? wanted (why `downgrade`) + : cur (why `switch off`). + New config scalar `upgradeMaxTokens` (default 200000): an upgrade pays a + cold read of the whole context on the new model (LRN-204); above the + threshold it is skipped and logged once per turn. `ctx.tokens` comes from + `$.session.usage()` read once per main step (fail → treat as 0). +R5. Engine fallback respected: at every main step `sess = canonical(await + $.session.model())`; when `canonical(e.model) !== sess`, the engine is on + a fallback → `markDown(sess, 'engine fallback')` and `cur = e.model` (the + router never upgrades back to the model the engine just left). +R6. Breaker inputs (replace the r1 list): (a) `classic.StopFailure` with + `error` ∈ rate_limit | overloaded | billing_error | model_not_found → + `markDown(target)` where target = `st.agentModels.get(e.agent_id)` when + `e.agent_id` is set, else `st.lastPlan?.model`; other errors (context + limit = invalid_request, server_error, auth, max_output_tokens…) → nothing; + (b) R5's engine-fallback detection; (c) `classic.PostModelSwitch`: source + `command | picker | sdk` → `st.down.delete(canonical(to_model))` and reset + its strikes (the user's explicit `/model` wins); source `auto` → LOG only + (`requested_model`, from, to), never a mark (unverified semantics). + `turn.complete` `reason` is NOT a breaker input any more (context-limit + and network errors are not availability); refusal → nothing. + Backoff per canonical id: strikes 1, 2, 3… → 15, 30, 60, 120, 300 min + (cap); `model_not_found` → until `/route reload`. `markDown` logs ALWAYS: + `model-router: unavailable () until ; routing falls + back`. Inert while `st.off`. + Lifecycle: `/route reload` clears `down` and strikes BEFORE loading the + config (whatever the read result); `session.end` (/clear) KEEPS `down`, + strikes and `agentModels` (availability is account-wide); expired + entries are pruned at the start of any hook that reads them, with `now` + read ONLY when `st.down.size > 0` (`$.clock.now()`), passed explicitly to + the helpers (no clock read in sync text functions: they receive the + pruned map). +R7. Agent models: `st.agentModels: Map` set at spawn + from `started.model` (canonicalized; an alias answered by a hook above is + mapped through the table); deleted with the loop. No `Loop.model`, + `spawnModel` or `loop.model` identifier anywhere (W1-A AC8 grep). + `spawnRoute` resolves `route.tier ?? route.model` through `resolveName` + (skips down aliases); explicit `e.model` still wins even when down. + Deferred (noted): agents without a table row and no explicit model follow + `parentModel`; forks always inherit; neither falls back in wave 1. +R8. Derived orchestrate (D1) made exact: state `pushed: { prev: Routed | null; + spawnIds: Set } | null`. In the main Agent `tool.call` hook: + before `next`, if `st.turnMain?.source` is not 'model' or 'skill' and + `st.pushed` is null → `st.pushed = { prev: st.turnMain, spawnIds: new Set() }` + and `st.turnMain = { phase: 'orchestrate', route: phases.orchestrate, + source: 'derived' }`; after `next` resolves: the spawned `agentId` (from + `st.spawnByCall: Map` filled at `agent.spawn`) is + added to `pushed.spawnIds`; if NO agent was registered for this + `tool_use_id` (foreground run already finished, or denied) → nothing to + wait for from this call. Pop rule: when `pushed.spawnIds` is empty after + the Agent call returned, or when the LAST id of `pushed.spawnIds` ends + (`turn.complete` with that agentId, deleted from the set), and + `st.turnMain?.source === 'derived'` → `st.turnMain = pushed.prev`, + `st.pushed = null`. A route/skill write in between (source model/skill) + replaces turnMain; the pop then only clears `pushed`. `endMainTurn` + clears `pushed` and `spawnByCall`. In `turn.complete` for an agent, delete + the loop and the maps FIRST, inside `safely`, before any other work. +R9. Prompt default rules (D2) made safe: rules scanned in two passes (floor + rules, then default rules), each pass first match; absent `mode` → + 'floor' (B1 override files keep their meaning). Default rules are SKIPPED + when the trimmed text starts with `/` (slash commands and skills route + themselves), when the same prompt carries a floor match or sets + `typedSlash` (the user's explicit level wins), or when typed mid-turn. + Patterns compile with flags `iu` and the defaults use Unicode-aware + guards instead of `\b`: `(? until + () …| none`, each phase as `name=→/`. + Existing test 3f (`/route model=sonnet` shows `claude-sonnet-5-5`) is + adapted: on the kit's session model the line reads `asked claude-sonnet-5-5, + keeps (switch off)`; the alias→id resolution is asserted on the + `asked` part. +R12. `st.lastPlan: Plan | null` replaces `lastMain` and `lastMainModel`; the + spinner text is derived at render; `endMainTurn` resets it. +R13. Config validation additions: `tiers` values non-empty arrays of alias + keys (bad entries dropped, logged), `fallback` deduplicated non-empty + alias list (else default, logged), `cooldownMinutes` and + `upgradeMaxTokens` positive integers, `mode` ∈ floor|default, a log at + load when `tiers.best[0] !== fallback[0]` (rank comes from `fallback` + alone). `mainModelSwitch` documented as DOWNGRADE-only in the Config + comment. +R14. Tests (≥ 43 total, names carry the contract words): keep all 30; add: + `tier` (plan on a haiku session → fable xhigh, with mock.clock installed + where the breaker is touched), `downgrade` (mechanical on fable keeps + fable, switch off), `fallback` (plan route + `$.classic.StopFailure({ + error: 'rate_limit', … })` on main after a fable step → next step + `claude-opus-5-5` at xhigh; `/route reload` → fable again), `breaker` + ×3 (an aborted/`invalid_request` failure never marks down; backoff expiry + via `mock.clock` advance restores fable; `/model` command + `PostModelSwitch source: 'command'` clears a down model), `engine fallback` + (`$.session.model` mocked/answered as fable while the step arrives on + opus → no upgrade back, fable marked down), `unknown` (cur + `claude-zz-9` never switches), `spawn` (Explore → opus while sonnet is + down through an agent StopFailure with `agent_id`), `derived` ×2 (push on + dispatch, pop when the spawned agent ends → plan back; a route call after + the dispatch is NOT overwritten by the pop), `default rule` ×3 (planifie + → plan then a route call overrides; `/analyze …` typed → no rule; + `/effort-low pourquoi …` → no default rule, floor low), `per axis` + (`/route effort=low` sticky + turn `plan` tier → model axis = best). + Read `mock.clock` and how `$.session.model` is answered in the kit + (a bottom `on('session.model', …)` hook) before writing them. +R15. Disposition, superseded clauses named: floor contract AC4 "`turnMain` + only ever holds 'model' or 'skill' sources" → now also 'derived' and + 'prompt'; W1-A AC6 "main-loop model changes happen only when + `mainModelSwitch` is true" → true for DOWNGRADES only; upgrades follow + `mainUpgrade` + `upgradeMaxTokens`, and the breaker/engine-fallback path + moves off a dead model unconditionally; BDR-115 (6) window guard → applied + to every switch (up, down, fallback) through `windowOk`. The tiers + contract AC5 reads "every B1/1-A criterion still holds EXCEPT the three + clauses above". +R16. Live verification after reload (orchestrator, not the executor): the + `[1m]` carry-over on a fallback id, `PostModelSwitch` `source: 'auto'` + semantics, `StopFailure` reaching the mod with `agent_id`. From 977be7cad899b8b4bc9bf2e11e672717e6d96e66 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 13:22:07 +0200 Subject: [PATCH 041/547] chore(tasks): model-router W1-C plan r3 + r4 after two confirmation passes --- .../2026-10-09-model-router-tiers-1237.md | 6 +- .../2026-10-09-model-router-tiers-1237.md | 126 ++++++++++++++++++ 2 files changed, 129 insertions(+), 3 deletions(-) diff --git a/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md index 62754b7..8c55109 100644 --- a/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md +++ b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md @@ -28,14 +28,14 @@ Q (r2): superseded clauses / A: floor AC4 (`turnMain` sources gain 'derived' and EXPECT: TSC-OK EVIDENCE: pending 3. Tiers in the config: `tiers` (best/big/work/cheap), `fallback`, `cooldownMinutes`, `mainUpgrade`, `upgradeMaxTokens` exist in DEFAULT_CONFIG; every default phase names a tier, none a bare model; `/route show` prints the resolved model of each phase and a `down:` line; no `classifier` (deferred to wave 2); no `Loop.model` / `spawnModel` / `loop.model` identifier (W1-A AC8). - CHECK: cd mods/model-router/hooks && grep -q "tiers:" register.ts && grep -q "fallback:" register.ts && grep -q "cooldownMinutes" register.ts && grep -q "mainUpgrade" register.ts && grep -q "upgradeMaxTokens" register.ts && ! grep -q "classifier" register.ts && [ "$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -cE "tier: '(best|big|work|cheap)'")" -ge 10 ] && ! awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -qE "model: '(haiku|sonnet|opus|fable)'" && ! grep -qE "loop\.model|explicitModel|spawnModel" register.ts && grep -q "down:" register.ts && echo TIERS-CONFIG-OK + CHECK: cd mods/model-router/hooks && D=$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts) && echo "$D" | grep -q "tiers:" && echo "$D" | grep -q "fallback:" && grep -q "cooldownMinutes" register.ts && grep -q "mainUpgrade" register.ts && grep -q "upgradeMaxTokens" register.ts && ! grep -q "classifier" register.ts && [ "$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -cE "tier: '(best|big|work|cheap)'")" -ge 10 ] && ! awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -qE "model: '(haiku|sonnet|opus|fable)'" && ! grep -qE "loop\.model|explicitModel|spawnModel" register.ts && grep -q "down:" register.ts && echo TIERS-CONFIG-OK EXPECT: TIERS-CONFIG-OK EVIDENCE: pending -4. Tests prove (names contain the quoted word; plan r2 R14 lists them): `tier` — a `plan` route on a session model `claude-haiku-4-5-20251001` makes the main step run on `claude-fable-5-1` at xhigh (upgrade, default on); `downgrade` — a `mechanical` route on a fable session leaves the model unchanged while `mainModelSwitch` is off; `fallback` — with a `plan` route, a `classic.StopFailure` `rate_limit` on main after a fable step makes the next main step run on `claude-opus-5-5` at xhigh, and after `/route reload` fable is used again; `breaker` — an `invalid_request` failure never marks a model down, backoff expiry restores it, a `/model` command (`PostModelSwitch` source `command`) clears it; `engine fallback` — a step arriving on a model other than `$.session.model()` is never upgraded back and the session model is marked down; `unknown` — a session model absent from the table is never switched; `spawn` — `Explore` spawns on `claude-opus-5-5` while sonnet is down (agent StopFailure with `agent_id`); `derived` — a main Agent call sets `orchestrate` and the previous `plan` route is back when the spawned agent ends; a route declared after the dispatch is not overwritten by the pop; `default rule` — "planifie la migration" sets `plan` as the turn default and a later route call overrides it; a typed `/analyze …` and a `/effort-low pourquoi …` prompt get no default rule; `per axis` — a model-less sticky never hides a turn route's tier; `floor` tests from B1 still pass. +4. Tests prove (names contain the quoted word; plan r2 R14 lists them): `tier` — a `plan` route on a session model `claude-haiku-4-5-20251001` makes the main step run on `claude-fable-5-1` at xhigh (upgrade, default on); `downgrade` — a `mechanical` route on a fable session leaves the model unchanged while `mainModelSwitch` is off; `fallback` — with a `plan` route, a `classic.StopFailure` `rate_limit` on main after a fable step makes the next main step run on `claude-opus-5-5` at xhigh, and after `/route reload` fable is used again; `breaker` — an `invalid_request` failure never marks a model down, backoff expiry restores it, a `/model` command (`PostModelSwitch` source `command`) clears it; `engine fallback` — a `PostModelSwitch` with source `auto` marks the model the engine left (one strike, idempotent within the hold) and a plan route does not go back to it; `unknown` — a session model absent from the table is never switched; `spawn` — `Explore` spawns on `claude-opus-5-5` while sonnet is down (agent StopFailure with `agent_id`); `derived` — a main Agent call sets `orchestrate` and the previous `plan` route is back when the spawned agent ends; a route declared after the dispatch is not overwritten by the pop; `default rule` — "planifie la migration" sets `plan` as the turn default and a later route call overrides it; a typed `/analyze …` and a `/effort-low pourquoi …` prompt get no default rule; `per axis` — a model-less sticky never hides a turn route's tier; `floor` tests from B1 still pass. CHECK: cd mods/model-router/hooks && for w in tier downgrade fallback breaker "engine fallback" unknown spawn derived "default rule" "per axis"; do grep -qE "test\('[^']*$w" register.test.ts || { echo "missing test: $w"; exit 1; }; done && [ "$(grep -cE "test\('[^']*(breaker|derived|default rule)" register.test.ts)" -ge 7 ] && echo TIERS-TESTS-OK EXPECT: TIERS-TESTS-OK EVIDENCE: pending -5. Judged by reading (plan r2 R1-R15 are binding): ONE resolver turns a tier name, an alias or a full id into an AVAILABLE canonical id (tier → list → skip down → id; an exhausted tier → the global chain; a bare alias or id passes through even when down); ids are canonical everywhere (`[1m]` stripped for comparison and carried on the replacement, alias → id, two-way prefix); ONE decision `decideMain(cur, wanted, ctx)` in the binding order (off → unknown cur: no switch → cur down: wanted or next available, windowOk → same alias: keep → better: `mainUpgrade` and `upgradeMaxTokens` → cheaper: `mainModelSwitch` and windowOk), used by `mainPlan` AND by every text; the engine's own fallback is respected (a step arriving off the session model marks the session model down and is never upgraded back); the breaker is fed only by `classic.StopFailure` errors `rate_limit | overloaded | billing_error | model_not_found` (main → the last main plan's model, agent → `agentModels`) and by the engine-fallback detection; `turn.complete` reasons and `PostModelSwitch` `auto` never mark (auto is logged); a user `/model` (`PostModelSwitch` command|picker|sdk) clears the target's mark; backoff 15 → 30 → 60 → 120 → 300 min per id, `model_not_found` until reload; the breaker survives `/clear` and is cleared by `/route reload` before the config read; the derived `orchestrate` push/pop tracks this turn's spawns and never overwrites a route the model declared after the dispatch; default prompt rules (two passes, absent `mode` = floor, `iu` flags, Unicode guards) write `turnMain` (source 'prompt') and are skipped for a leading `/`, for a prompt carrying a floor or a typed slash, and mid-turn; floor rules write `turnFloor`; no classifier; explicit Agent params still win; agent model fixed at spawn; every B1/1-A criterion still holds EXCEPT the three clauses R15 names (turnMain sources, the switch clause, the window-guard scope); no function over 25 logic lines; truthful texts come from `decideMain` and say `upgrade`, `fallback`, `switch off` or `unchanged`. +5. Judged by reading (plan r2 R1-R15, r3 S1-S11 and r4 T1-T8 are binding; r4 wins over r3, r3 over r2 where they conflict: two fields `turnModel` (sticky, per turn) and `lastPlan` (breaker target, kept), unrouted steps pass `e.model` verbatim, auto marks target the model actually sent and skip when the engine landed where the router was, `sessionModel` preserved across /clear and never prefix-matched when empty, tokens `number | undefined` with windowOk failing closed, episode strikes with `model_not_found` lengthening a hold; no per-step engine-fallback detection, `PostModelSwitch` auto DOES mark one idempotent strike, the main model is sticky within a turn, `sessionModel` cached at start and on PostModelSwitch, D1 for background dispatches via the Agent result status, breaker targets kept until replaced): ONE resolver turns a tier name, an alias or a full id into an AVAILABLE canonical id (tier → list → skip down → id; an exhausted tier → the global chain; a bare alias or id passes through even when down); ids are canonical everywhere (`[1m]` stripped for comparison and carried on the replacement, alias → id, two-way prefix); ONE decision `decideMain(cur, wanted, ctx)` in the binding order (off → unknown cur: no switch → cur down: wanted or next available, windowOk → same alias: keep → better: `mainUpgrade` and `upgradeMaxTokens` → cheaper: `mainModelSwitch` and windowOk), used by `mainPlan` AND by every text; the breaker is fed only by `classic.StopFailure` errors `rate_limit | overloaded | billing_error | model_not_found` (main → the last main plan's model, agent → `agentModels`) and by `PostModelSwitch` `source: 'auto'` (the model the engine left, one strike, idempotent while down); `turn.complete` reasons never mark; a user `/model` (`PostModelSwitch` command|picker|sdk) clears the target's mark; backoff 15 → 30 → 60 → 120 → 300 min per id, `model_not_found` until reload; the breaker survives `/clear` and is cleared by `/route reload` before the config read; the derived `orchestrate` push/pop tracks this turn's spawns and never overwrites a route the model declared after the dispatch; default prompt rules (two passes, absent `mode` = floor, `iu` flags, Unicode guards) write `turnMain` (source 'prompt') and are skipped for a leading `/`, for a prompt carrying a floor or a typed slash, and mid-turn; floor rules write `turnFloor`; no classifier; explicit Agent params still win; agent model fixed at spawn; every B1/1-A criterion still holds EXCEPT the three clauses R15 names (turnMain sources, the switch clause, the window-guard scope); no function over 25 logic lines; truthful texts come from `decideMain` and say `upgrade`, `fallback`, `switch off` or `unchanged`. ## FILE SCOPE mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts diff --git a/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md b/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md index 2e309c1..ac52a11 100644 --- a/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md +++ b/.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md @@ -350,3 +350,129 @@ R15. Disposition, superseded clauses named: floor contract AC4 "`turnMain` R16. Live verification after reload (orchestrator, not the executor): the `[1m]` carry-over on a fallback id, `PostModelSwitch` `source: 'auto'` semantics, `StopFailure` reaching the mod with `agent_id`. + +## r3 — confirmation pass (FATAL(8): 1 BLOCKER, 6 MAJOR): BINDING over r2 where they conflict +S1. R5 (engine-fallback detection at every step) is REMOVED: no comparison of + `e.model` with `$.session.model()` at steps, no mark from it. The + engine's own fallback is learned ONLY through `classic.PostModelSwitch` + `source: 'auto'`, which now MARKS `canonical(from_model)` down with one + strike (15 min) when `from_model` is a table id, logging + `requested_model`, `to_model`. (R6(c) "auto → log only" is void.) A mark + is idempotent per episode: `markDown` on an id already down adds NO + strike and logs nothing; strikes count episodes (a mark after expiry). +S2. `st.sessionModel` (raw string) is read once at `session.start` through + `$.session.model()` inside try/catch ('' on failure) and refreshed in the + `PostModelSwitch` hook from `e.to_model` (any source). No other + `$.session.model()` call anywhere; texts use `st.sessionModel`. +S3. Within a turn the main model is STICKY once moved: `cur` for the decision + is `st.lastPlan?.model ?? e.model` (the model actually sent last; lastPlan + is reset at `endMainTurn` so each turn starts from the engine's model). + After an upgrade (plan → fable), a later cheaper phase in the same turn + (implement → work) goes through the CHEAPER branch against cur = fable: + gated by `mainModelSwitch` + windowOk, so no return trip and no second + cold read. After a fallback (fable down → opus), later steps stay on opus + for the turn. "Keep cur" returns the exact string last sent (`e.model` + verbatim on the first step), so `[1m]` is preserved; a resolved + replacement carries `[1m]` only when the raw session string carries it + AND the target alias is not haiku. +S4. decideMain spelled out (order binding): off → cur · unknown cur (no table + alias) → cur, logged once · cur down → first available of [wanted (if + a table id and not down), nextAvailable(cur)] that passes windowOk, else + cur · wanted undefined → cur · wanted unknown to the table (explicit full + id such as `claude-x-9`) → treated as CHEAPER (gated by `mainModelSwitch`, + windowOk) · same alias → cur · better → `mainUpgrade && tokens ≤ + upgradeMaxTokens && windowOk` ? wanted : cur · cheaper → `mainModelSwitch + && windowOk` ? wanted : cur. `ctx.tokens` from `$.session.usage()` read + once per main step (catch → 0); texts read it the same way (async), so a + text and the step agree. `nextAvailable(cur)` walks `fallback` from the + alias after cur's (unknown cur → from the top) skipping down ids; at + spawn, `nextAvailable` walks from the tier's last alias. + `model_not_found` marks show `until reload` in texts. +S5. Derived orchestrate (R8 rewritten): D1 affects BACKGROUND dispatches only. + In the main Agent `tool.call` hook: push as in R8 (source not model/skill, + `pushed` null) BEFORE `next`; after `next`: read the RESULT — `status === + 'async_launched'` → add `result.agentId` to `pushed.spawnIds`; any other + status or a deny → nothing to wait for from this call. Pop rule unchanged + (spawnIds empty after the call, or the last id's `turn.complete`); no + `spawnByCall` map. Documented: a foreground dispatch pushes and pops + inside one call, so no main step runs at orchestrate for it (fine: main + is blocked meanwhile). +S6. Breaker targets keep their value until replaced: `st.lastPlan` is NOT + reset at `endMainTurn` (only the spinner text is cleared via a separate + `st.spinner` string); `agentModels` entries are deleted at `session.end` + only, never at an agent's `turn.complete` (the StopFailure/turn.complete + order is unverified; R16 gains it). +S7. R9 patterns: compile with `iu`; on a SyntaxError retry with `i` (B1 + override files keep working); a pattern failing both is dropped, logged. +S8. R11: the route tool description is STATIC text (registered once): "the + main loop moves up to a phase's tier by itself (below the context cap), + down only with the switch on; a sub-agent's model is fixed at spawn". + `show`, `routedText`, `mainNote`, `statusLine` call `decideMain` with + `cur = st.lastPlan?.model ?? st.sessionModel` and the same tokens read. +S9. Tests, kit recipe (replaces R14 details): `boot(model = 'claude-fable-5-1')` + registers, before the first `$` call, bottom hooks `on('session.model', + () => ({ value: model }))` (answer shape per the Op results in the + declarations), `on('classic.StopFailure', ($, e) => )`, + `on('classic.PostModelSwitch', …)`, and installs `mock.clock(on)`; every + breaker test advances the mock clock. `derived` recipe: prompt + "planifie …" (source 'prompt'), then `$.tool.call({ tool: 'Agent', … })` + whose bottom hook returns `{ result: { status: 'async_launched', + agentId: 'a1', … } }` (read the Agent RESULT type for the required + fields) → `/route show` main line says `derived orchestrate`; then + `$.turn.complete({ agentId: 'a1', … })` → main line says `prompt plan`. + Second derived test: same, but a route tool call `reflect` after the + dispatch → the pop does not overwrite `model reflect`. `engine fallback` + test: `$.classic.PostModelSwitch({ from_model: 'claude-fable-5-1', + to_model: 'claude-opus-5-5', source: 'auto', … })` → fable listed under + `down:`; a plan route step does not go back to fable; a second auto + switch inside the hold adds no strike (show prints the same until). + Strikes test: expire (advance clock) → mark again → until doubles. +S10. AC3 fix: the `fallback:` and `tiers:` greps run inside the + DEFAULT_CONFIG awk range. +S11. R16 gains: the order of `classic.StopFailure` vs `turn.complete`; whether + the engine's fallback on a hook-rewritten request raises `PostModelSwitch`. + +## r4 — second confirmation (FATAL(4): 1 BLOCKER, 3 MAJOR): BINDING over r3 where they conflict; the last revision, executor dispatched on it +T1. Two fields, no contradiction: `st.turnModel: string | undefined` is the + STICKY cur, set ONLY when `decideMain` moved the model (upgrade, + downgrade or fallback), reset in `endMainTurn` and at `session.end`; + `st.lastPlan` (the plan actually sent last, breaker target) is KEPT across + turns and never used as cur. `cur = st.turnModel ?? e.model`. "Keep cur" + returns `st.turnModel` when set, else `e.model` VERBATIM: an unrouted step + never re-sends a model the router did not choose this turn, so an + engine fallback that lands in `e.model` is respected by construction. + S3's "lastPlan is reset at endMainTurn" is void (S6 stands). +T2. Auto switch marking (S1 refined): on `PostModelSwitch` `source: 'auto'`, + let `sent = canonical(st.lastPlan?.model)` and `to = canonical(to_model)`. + If `to === sent` → nothing (the engine landed where the router already + was, or the router's own rewrite surfaced as a switch). Else the mark + target is `sent` when it is a table id (the model actually sent), else + `canonical(from_model)` when THAT is a table id, else nothing. Always + log `from_model`, `to_model`, `requested_model`. R16 gains: which + `from_model` the event carries after a router upgrade, and whether a + router rewrite itself raises an `auto` switch. +T3. `st.sessionModel` is PRESERVED through the `session.end` rebuild (listed + with `down`, strikes, `agentModels`). `canonical()` never prefix-matches + an empty string or a string that does not start with `claude-`: both + map to UNKNOWN (returned unchanged, no table id). The `[1m]` carry reads + the raw string of the step (`e.model`, or `st.turnModel`), never + `sessionModel`. `sessionModel` is used by texts only; when it is '' or + unknown, texts print the engine word `session model` instead of an id. +T4. Tokens: `ctx.tokens: number | undefined` (undefined on a failed or absent + read). The upgrade cap treats undefined as 0 (upgrade allowed: the targets + are fable/opus, no window entry); `windowOk` treats undefined as NOT + fitting (fail closed, as today). +T5. Marks: strikes are per EPISODE (a mark on an id already down adds no + strike and no log), but a `model_not_found` arriving during a timed hold + LENGTHENS it to "until reload" (logged once). Auto marks use the same + episode backoff (15 → 30 → 60 → 120 → 300 min). +T6. S5 race: on an `async_launched` result with `st.pushed === null`, push + again first (if `turnMain?.source` still allows it), then add the id. +T7. Tests assert hold DURATIONS (minutes until, computed from the mock clock) + or the presence of the id under `down:`, never a literal `HH:MM`. + `show` prints `down: for min ()` (and `until reload`), + computed from the pruned map and the clock value passed in. +T8. R16 final list (live, orchestrator): StopFailure vs turn.complete order; + PostModelSwitch on a rewritten-request fallback and its `from_model`; + whether a router rewrite raises `auto`; `[1m]` carry validity on opus; + `$.session.model()` string form. From d0fa1001bb91171dadebbf33413623d62a7cdecd Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:08:49 +0200 Subject: [PATCH 042/547] =?UTF-8?q?feat(mods):=20model-router=20adaptive?= =?UTF-8?q?=20tiers=20=E2=80=94=20absolute=20tiers,=20availability=20break?= =?UTF-8?q?er,=20derived=20phases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phases name absolute tiers (best fable>opus>sonnet, big opus>fable>sonnet, work sonnet>opus, cheap haiku>sonnet) resolved to the first available full id; per-model circuit breaker fed by StopFailure kinds (rate_limit, overloaded, billing_error, model_not_found) and PostModelSwitch auto, with episode backoff 15→300 min, cleared by a user /model or /route reload and kept across /clear; fallback chain fable→opus→sonnet→haiku with the effort unchanged; main loop upgrades to a phase's tier by itself under a context cap (fails closed on unknown usage), downgrades only with the switch on, sticky within a turn; derived orchestrate on background dispatches; prompt default rules (plan/reflect, Unicode guards, skipped on slash commands, floor matches and mid-turn). 58 plugin tests. --- mods/model-router/hooks/register.test.ts | 408 +++++++++- mods/model-router/hooks/register.ts | 995 +++++++++++++++++++---- 2 files changed, 1248 insertions(+), 155 deletions(-) diff --git a/mods/model-router/hooks/register.test.ts b/mods/model-router/hooks/register.test.ts index b1074d5..d85b9a2 100644 --- a/mods/model-router/hooks/register.test.ts +++ b/mods/model-router/hooks/register.test.ts @@ -1,11 +1,32 @@ -import { test, expect } from 'claude-code/testing' -import type { Engine } from 'claude-code/testing' +import { test, expect, mock } from 'claude-code/testing' +import type { Engine, MockClock } from 'claude-code/testing' import type { On, TurnStepInput } from 'claude-code' -/** Fires session.start so the mod loads its config and registers /route. */ -async function boot($: Engine, on: On): Promise { +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' + +/** + * 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: + * the session model, the classic failure and switch events, a mock clock, + * a small context (`tokens`; null = usage unanswered, size unknown). + */ +async function boot( + $: Engine, + on: On, + model: string = FABLE, + tokens: number | null = 1000, +): Promise { + const clock = mock.clock(on) + on('session.model', () => ({ value: model })) + on('classic.StopFailure', () => ({})) + on('classic.PostModelSwitch', () => ({})) + if (tokens !== null) usageOf(on, tokens) on('session.start', ($, e) => ({ cwd: e.cwd })) await $.session.start({ cwd: '/tmp', surface: null, isInteractive: false }) + return clock } /** Runs `/route ` as the user would type it. */ @@ -99,7 +120,7 @@ test('/route model: alias resolved, id passed, typo refused', async ( $, on) => { await boot($, on) const alias = await route($, 'model=sonnet') - expect(mainLine(alias)).toContain('claude-sonnet-5-5') + expect(mainLine(alias)).toContain('asked claude-sonnet-5-5, keeps ') const id = await route($, 'model=claude-x-9') expect(mainLine(id)).toContain('claude-x-9') expect(await route($, 'model=sonet')).toContain('unknown') @@ -446,3 +467,380 @@ test('typed slash with no agent and no marker writes the floor', async ( await $.skill.prompt({ skill: 'effort-max', text: 'x' }) expect(mainLine(await route($, 'show'))).toContain('floor max') }) + +// ---- tiers, breaker, derived phases ------------------------------------- + +type Rig = { seen: Seen[]; clock: MockClock; specs: (string | undefined)[] } + +type Failure = 'rate_limit' | 'overloaded' | 'invalid_request' + +/** Bottom hooks for a routed run, then the boot; `specs` records spawns. */ +async function bootRig( + $: Engine, + on: On, + model: string = FABLE, + tokens: number | null = 1000, +): Promise { + const seen: Seen[] = [] + const specs: (string | undefined)[] = [] + recordSteps(on, seen) + on('prompt.submit', ($, e) => ({ text: e.text })) + on('turn.complete', () => ({ text: '' })) + on('agent.spawn', ($, e) => { + specs.push(e.model) + return { model: e.model ?? e.parentModel, agentId: 'a1' } + }) + on('tool.call', { tool: 'Agent' }, () => ({ + result: { + status: 'async_launched' as const, + agentId: 'a1', + description: 'd', + prompt: 'p', + outputFile: '/tmp/o', + }, + })) + const clock = await boot($, on, model, tokens) + return { seen, clock, specs } +} + +/** One main step on `model`; returns what reached the bottom hook. */ +async function stepOn($: Engine, rig: Rig, model: string): Promise { + await runStep($, { ...highStep(), model }) + return rig.seen[rig.seen.length - 1] ?? { model: '', effort: undefined } +} + +const failWith = ($: Engine, error: Failure, agentId?: string) => + $.classic.StopFailure({ + error, + ...(agentId === undefined ? {} : { agent_id: agentId }), + }) + +const switchTo = ( + $: Engine, + from: string, + to: string, + source: 'command' | 'auto', +) => $.classic.PostModelSwitch({ + from_model: from, + to_model: to, + requested_model: null, + source, + context_tokens: 0, + prompt_cache_warm: false, + cache_ttl: '5m', + estimated_cache_write_usd: 0, + pricing: 'catalog', +}) + +const planRoute = ($: Engine) => + $.tool.call({ tool: ROUTE_TOOL, phase: 'plan' }) + +/** A bottom `session.usage` answering a context of `tokens`. */ +function usageOf(on: On, tokens: number): void { + on('session.usage', () => ({ + value: { + startedAt: 0, + context: { window: 1000000, tokens }, + rateLimits: [], + }, + })) +} + +test('tier: a plan route upgrades a haiku session to fable xhigh', async ( + $, on) => { + const rig = await bootRig($, on, HAIKU) + await planRoute($) + expect(await stepOn($, rig, HAIKU)).toEqual({ + model: FABLE, + effort: 'xhigh', + }) +}) + +test('tier: show prints the resolved id of each phase and a down line', async ( + $, on) => { + await bootRig($, on) + const text = await route($, 'show') + expect(text).toContain('plan=best→claude-fable-5-1/xhigh') + expect(text).toContain('judge=big→claude-opus-5-5/xhigh') + expect(text).toContain('down: none') +}) + +test('tier: an upgrade is skipped above the context cap', async ($, on) => { + const rig = await bootRig($, on, SONNET, 300000) + await planRoute($) + expect(await stepOn($, rig, SONNET)).toEqual({ + model: SONNET, + effort: 'xhigh', + }) +}) + +test('cap: unknown usage blocks the upgrade', async ($, on) => { + const rig = await bootRig($, on, HAIKU, null) + await planRoute($) + expect((await stepOn($, rig, HAIKU)).model).toBe(HAIKU) +}) + +test('cap: a down model leaves for a better wanted only under the cap', async ( + $, on) => { + const rig = await bootRig($, on, OPUS, 300000) + await planRoute($) + await stepOn($, rig, OPUS) + await failWith($, 'rate_limit') + expect((await stepOn($, rig, OPUS)).model).toBe(SONNET) +}) + +test('breaker: model_not_found on a non-table id marks nothing', async ( + $, on) => { + const rig = await bootRig($, on) + await planRoute($) + await stepOn($, rig, 'claude-zz-9') + await $.classic.StopFailure({ error: 'model_not_found' }) + expect(await route($, 'show')).toContain('down: none') +}) + +test('downgrade: mechanical on fable keeps the model, switch off', async ( + $, on) => { + const rig = await bootRig($, on) + await $.tool.call({ tool: ROUTE_TOOL, phase: 'mechanical' }) + expect(await stepOn($, rig, FABLE)).toEqual({ model: FABLE, effort: 'low' }) +}) + +test('downgrade: the switch on moves main to the cheap tier', async ( + $, on) => { + const rig = await bootRig($, on) + await route($, 'switch on') + await $.tool.call({ tool: ROUTE_TOOL, phase: 'mechanical' }) + const sent = await stepOn($, rig, FABLE) + expect(sent.model).toBe(HAIKU) + expect(sent.effort).toBeUndefined() +}) + +test('fallback: a rate limit on fable moves plan to opus xhigh', async ( + $, on) => { + const rig = await bootRig($, on) + await planRoute($) + expect((await stepOn($, rig, FABLE)).model).toBe(FABLE) + await failWith($, 'rate_limit') + expect(await stepOn($, rig, FABLE)).toEqual({ model: OPUS, effort: 'xhigh' }) + expect(await route($, 'show')).toContain('claude-fable-5-1 for 15 min') + await route($, 'reload') + expect((await stepOn($, rig, FABLE)).model).toBe(FABLE) +}) + +test('breaker: an invalid_request or a turn error never marks down', async ( + $, on) => { + const rig = await bootRig($, on) + await planRoute($) + await stepOn($, rig, FABLE) + await failWith($, 'invalid_request') + await $.turn.complete({ + turnId: 'u1', + answer: '', + durationMs: 1, + isAborted: false, + reason: 'error', + }) + expect((await stepOn($, rig, FABLE)).model).toBe(FABLE) + expect(await route($, 'show')).toContain('down: none') +}) + +test('breaker: the hold lapses with the clock, a second one doubles', async ( + $, on) => { + const rig = await bootRig($, on) + await planRoute($) + await stepOn($, rig, FABLE) + await failWith($, 'overloaded') + await rig.clock.advance(15 * 60000) + expect(await route($, 'show')).toContain('down: none') + await endTurn($) + await planRoute($) + expect((await stepOn($, rig, FABLE)).model).toBe(FABLE) + await failWith($, 'overloaded') + expect(await route($, 'show')).toContain('claude-fable-5-1 for 30 min') +}) + +test('breaker: a /model command clears the mark of its target', async ( + $, on) => { + const rig = await bootRig($, on) + await planRoute($) + await stepOn($, rig, FABLE) + await failWith($, 'rate_limit') + expect(await route($, 'show')).toContain('claude-fable-5-1 for') + await switchTo($, OPUS, FABLE, 'command') + expect(await route($, 'show')).toContain('down: none') + expect((await stepOn($, rig, FABLE)).model).toBe(FABLE) +}) + +test('breaker: model_not_found holds until the reload', async ($, on) => { + const rig = await bootRig($, on) + await planRoute($) + await stepOn($, rig, FABLE) + await $.classic.StopFailure({ error: 'model_not_found' }) + await rig.clock.advance(24 * 3600000) + expect(await route($, 'show')).toContain('until reload (model_not_found)') +}) + +test('engine fallback: an auto switch marks the model it left, once', async ( + $, on) => { + const rig = await bootRig($, on) + await switchTo($, FABLE, OPUS, 'auto') + const first = await route($, 'show') + expect(first).toContain('claude-fable-5-1 for 15 min (engine fallback)') + await planRoute($) + expect((await stepOn($, rig, OPUS)).model).toBe(OPUS) + await rig.clock.advance(60000) + await switchTo($, FABLE, OPUS, 'auto') + expect(await route($, 'show')).toContain('claude-fable-5-1 for 14 min') +}) + +test('unknown: a session model absent from the table is never switched', async ( + $, on) => { + const rig = await bootRig($, on) + await planRoute($) + expect((await stepOn($, rig, 'claude-zz-9')).model).toBe('claude-zz-9') +}) + +test('spawn: Explore goes to opus while sonnet is down', async ($, on) => { + const rig = await bootRig($, on) + await $.agent.spawn(spawnInput()) + await failWith($, 'overloaded', 'a1') + await $.agent.spawn(spawnInput()) + expect(rig.specs).toEqual([SONNET, OPUS]) +}) + +/** Types a plain prompt, idle, in the composer. */ +const typed = ($: Engine, text: string) => $.prompt.submit({ + text, + wait: false, + origin: { kind: 'composer' }, +}) + +const dispatch = ($: Engine) => + $.tool.call({ tool: 'Agent', description: 'd', prompt: 'p' }) + +const agentEnds = ($: Engine) => $.turn.complete({ + turnId: 'a1', + agentId: 'a1', + answer: '', + durationMs: 1, + isAborted: false, + reason: 'answer', +}) + +test('derived: a dispatch pushes orchestrate, the end pops the prompt', async ( + $, on) => { + await bootRig($, on) + await typed($, 'planifie la migration') + expect(mainLine(await route($, 'show'))).toContain('prompt plan') + await dispatch($) + expect(mainLine(await route($, 'show'))).toContain('derived orchestrate') + await agentEnds($) + expect(mainLine(await route($, 'show'))).toContain('prompt plan') +}) + +test('derived: a route declared after the dispatch survives the pop', async ( + $, on) => { + await bootRig($, on) + await typed($, 'planifie la migration') + await dispatch($) + await $.tool.call({ tool: ROUTE_TOOL, phase: 'reflect' }) + await agentEnds($) + expect(mainLine(await route($, 'show'))).toContain('model reflect') +}) + +test('default rule: planifie sets plan, a later route overrides', async ( + $, on) => { + const rig = await bootRig($, on, HAIKU) + await typed($, 'planifie la migration') + expect(await stepOn($, rig, HAIKU)).toEqual({ model: FABLE, effort: 'xhigh' }) + await $.tool.call({ tool: ROUTE_TOOL, phase: 'implement' }) + const line = mainLine(await route($, 'show')) + expect(line).toContain('model implement') + expect(line).not.toContain('prompt') +}) + +test('default rule: a typed slash command gets no default rule', async ( + $, on) => { + await bootRig($, on) + await typed($, '/analyze pourquoi ça plante') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('default rule: /effort-low pourquoi sets the floor, no default', async ( + $, on) => { + await bootRig($, on) + await typed($, '/effort-low pourquoi ça plante') + await $.skill.prompt({ skill: 'effort-low', text: 'x' }) + const line = mainLine(await route($, 'show')) + expect(line).toContain('floor low') + expect(line).not.toContain('reflect') +}) + +test('per axis: a model-less sticky never hides a turn route tier', async ( + $, on) => { + const rig = await bootRig($, on, HAIKU) + await route($, 'effort=low') + await planRoute($) + expect(await stepOn($, rig, HAIKU)).toEqual({ model: FABLE, effort: 'low' }) +}) + +// ---- texts follow the decision, from the turn's model ------------------ + +test('text: effort-only route on a down model says fallback', async ( + $, on) => { + const rig = await bootRig($, on) + await stepOn($, rig, FABLE) + await failWith($, 'rate_limit') + const out = await $.tool.call({ tool: ROUTE_TOOL, effort: 'low' }) + expect(JSON.stringify(out)).toContain(`model ${OPUS} (fallback)`) +}) + +test('text: /route effort= on a down model names the fallback', async ( + $, on) => { + const rig = await bootRig($, on) + await stepOn($, rig, FABLE) + await failWith($, 'rate_limit') + await route($, 'effort=low') + expect(mainLine(await route($, 'show'))).toContain(`${OPUS} (fallback)`) +}) + +test('text: show names the session model after the turn ended', async ( + $, on) => { + const rig = await bootRig($, on, HAIKU) + await planRoute($) + expect((await stepOn($, rig, HAIKU)).model).toBe(FABLE) + await endTurn($) + await route($, 'mechanical') + const line = mainLine(await route($, 'show')) + expect(line).toContain(`model ${HAIKU}`) + expect(line).not.toContain(FABLE) +}) + +test('text: show reflects a /model command to opus', async ($, on) => { + const rig = await bootRig($, on) + await stepOn($, rig, FABLE) + await switchTo($, FABLE, OPUS, 'command') + await route($, 'mechanical') + const line = mainLine(await route($, 'show')) + expect(line).toContain(OPUS) + expect(line).not.toContain(FABLE) +}) + +test('text: an unknown session model prints "session model"', async ( + $, on) => { + await bootRig($, on, 'mystery-model') + await route($, 'plan') + expect(mainLine(await route($, 'show'))).toContain('keeps session model') +}) + +test('text: show names the model a floor upgrade moves to', async ( + $, on) => { + await bootRig($, on, HAIKU) + await $.prompt.submit({ + text: 'ultrathink please', + wait: false, + origin: { kind: 'composer' }, + }) + const line = mainLine(await route($, 'show')) + expect(line).toContain(`${FABLE} (upgrade)`) +}) diff --git a/mods/model-router/hooks/register.ts b/mods/model-router/hooks/register.ts index 4d757b8..09f2d3b 100644 --- a/mods/model-router/hooks/register.ts +++ b/mods/model-router/hooks/register.ts @@ -1,14 +1,22 @@ // model-router: routes each model request (main loop and sub-agents) to the -// model and effort its phase deserves. Phases, agents, skills and prompt -// rules come from DEFAULT_CONFIG, overridable by ~/.claude/model-router.json. +// model and effort its phase deserves. Phases name a TIER (an ordered list of +// aliases, the first available wins); a circuit breaker fed by the engine's +// own failure events marks a model down for a while. Phases, agents, skills +// and prompt rules come from DEFAULT_CONFIG, overridable by +// ~/.claude/model-router.json. // 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' type Api = EngineInterface type Level = 'low' | 'medium' | 'high' | 'xhigh' | 'max' -type Route = { model?: string; effort?: Level } // model: alias or full id -type PromptRule = { pattern: string; phase: string } +type Route = { + tier?: string // a `tiers` key: the first AVAILABLE alias of its list + model?: string // alias or full id: explicit, never skipped when down + effort?: Level +} +type PromptMode = 'floor' | 'default' +type PromptRule = { pattern: string; phase: string; mode?: PromptMode } type Config = { models: Record // alias -> full id windows: Record // full id -> context window (tokens) @@ -16,14 +24,21 @@ type Config = { agents: Record // built-in subagentType -> phase skills: Record // skill name -> phase prompt: PromptRule[] - mainModelSwitch: boolean + tiers: Record // tier -> alias preference, best first + fallback: string[] // alias order, best first: the rank and the fallback chain + cooldownMinutes: number // breaker hold at the first strike + mainUpgrade: boolean // main may move UP to a phase's tier by itself + upgradeMaxTokens: number // above this context an upgrade is skipped + mainModelSwitch: boolean // gates DOWNGRADES only verbose: boolean spinner: boolean enabled: boolean // false: every hook passes through (per machine) } -type Rule = { re: RegExp; phase: string } -type Source = 'user' | 'model' | 'skill' | 'prompt' | 'slash' +type Rule = { re: RegExp; phase: string; mode: PromptMode } +type Source = 'user' | 'model' | 'skill' | 'prompt' | 'slash' | 'derived' type Routed = { phase: string; route: Route; source: Source } +type Hold = { until: number; reason: string } // until: ms, Infinity = reload +type Pushed = { prev: Routed | null; spawnIds: Set } type Loop = { effort?: Level // an agent's model is fixed at spawn: effort is its only axis explicitEffort: boolean // Agent call gave an effort: axis frozen @@ -34,7 +49,7 @@ type State = { source: string // 'defaults' or the override path userMain: Routed | null // /route by the user, sticky until /route clear turnMain: Routed | null // model route tool, skill table row, Skill(effort-*) - // bridge; dropped at turn end + // bridge, prompt default rule, derived orchestrate; dropped at turn end turnFloor: Routed | null // user-explicit level for this turn (prompt rule, // typed /effort-): a floor, main loop only pendingPrompt: Routed | null // typed mid-turn: the next turn's floor @@ -44,8 +59,16 @@ type State = { skillCalls: number // Skill tool calls in flight off: boolean // /route off or config: every hook passes through offConfig: boolean // `off` comes from the config key `enabled` - lastMain: string // "model/effort" of the last main step (spinner) - windowWarned: boolean // context-window warning already logged this turn + spinner: string // "model/effort" of the last main step of this turn + lastPlan: Plan | null // the plan last sent on main: the breaker's target + turnModel: string | undefined // sticky main model, set when the router moved + sessionModel: string // the main loop's model as /model shows it, '' unknown + down: Map // canonical id -> unavailable until (breaker) + strikes: Map // canonical id -> episodes, drives the backoff + agentModels: Map // agentId -> exact id sent at spawn + pushed: Pushed | null // derived orchestrate in force (background dispatch) + logged: Set // session-once log lines + turnLogged: Set // turn-once log lines warned: Set // hooks whose fail-open was already logged } type Log = (text: string) => void @@ -71,6 +94,16 @@ const HAIKU = 'claude-haiku' const MAX_PATTERN = 200 // chars of a prompt-rule pattern const MAX_PROMPT_SCAN = 4096 // chars of a prompt a rule is run against const MAX_CONFIG_BYTES = 65536 // override file size +const MAX_AGENT_MODELS = 256 // agent -> model entries kept (oldest dropped) +const PREFIX = 'claude-' +const ONE_M = /\[1m\]$/ // the long-context variant of a model id +// Hold = cooldownMinutes x step: 15 -> 30 -> 60 -> 120 -> 300 by default. +const BACKOFF_STEPS: readonly number[] = [1, 2, 4, 8, 20] +// StopFailure kinds that mean "this model cannot serve now". The others +// (context limit, network, auth...) are not availability. +const UNAVAILABLE: ReadonlySet = new Set([ + 'rate_limit', 'overloaded', 'billing_error', 'model_not_found', +]) const PHASE_KEY = /^[a-z][a-z0-9_-]{0,31}$/ const DEFAULT_CONFIG: Config = { @@ -81,22 +114,49 @@ const DEFAULT_CONFIG: Config = { fable: 'claude-fable-5-1', }, windows: { 'claude-haiku-4-5-20251001': 200000 }, + // A tier is an ordered alias list: the first one not down is used. + tiers: { + best: ['fable', 'opus', 'sonnet'], + big: ['opus', 'fable', 'sonnet'], + work: ['sonnet', 'opus'], + cheap: ['haiku', 'sonnet'], + }, + fallback: ['fable', 'opus', 'sonnet', 'haiku'], // rank = index, best first + cooldownMinutes: 15, + mainUpgrade: true, + upgradeMaxTokens: 200000, // an upgrade re-reads the whole context cold phases: { - plan: { effort: 'xhigh' }, - reflect: { effort: 'high' }, - orchestrate: { effort: 'medium' }, - escalate: { effort: 'max' }, - judge: { model: 'opus', effort: 'xhigh' }, - implement: { model: 'sonnet', effort: 'medium' }, - write: { model: 'sonnet', effort: 'medium' }, - verify: { model: 'sonnet', effort: 'xhigh' }, - explore: { model: 'sonnet', effort: 'medium' }, - mechanical: { model: 'haiku', effort: 'low' }, + plan: { tier: 'best', effort: 'xhigh' }, + reflect: { tier: 'best', effort: 'high' }, + orchestrate: { tier: 'best', effort: 'medium' }, + escalate: { tier: 'best', effort: 'max' }, + judge: { tier: 'big', effort: 'xhigh' }, + implement: { tier: 'work', effort: 'medium' }, + write: { tier: 'work', effort: 'medium' }, + verify: { tier: 'work', effort: 'xhigh' }, + explore: { tier: 'work', effort: 'medium' }, + mechanical: { tier: 'cheap', effort: 'low' }, }, // Built-ins only: repo agents keep their frontmatter pin (wave 2). agents: { Explore: 'explore', Plan: 'judge' }, skills: {}, - prompt: [{ pattern: '\\bultrathink\\b', phase: 'escalate' }], + // `floor` rules set the turn's minimum effort; `default` rules set the + // turn's route, which a route call or a skill overrides. Neither lowers. + prompt: [ + { pattern: '\\bultrathink\\b', phase: 'escalate', mode: 'floor' }, + { + pattern: '(?, v: unknown): v is string { return typeof v === 'string' && (hasKey(models, v) || isFullId(v)) } -function resolveModel(cfg: Config, name: string): string { - return hasKey(cfg.models, name) ? (cfg.models[name] ?? name) : name -} - function phaseRoute(cfg: Config, phase: string): Route | undefined { return hasKey(cfg.phases, phase) ? cfg.phases[phase] : undefined } @@ -156,9 +212,14 @@ const acceptWindow = (key: string, v: unknown): number | undefined => ? v : undefined -function acceptPhase(models: Record) { +/** A phase names a tier OR a model, never both; a tier must exist. */ +function acceptPhase( + models: Record, + tiers: Record, +) { return (key: string, v: unknown): Route | undefined => { if (!PHASE_KEY.test(key) || !isRecord(v)) return undefined + if (v.tier !== undefined && v.model !== undefined) return undefined const route: Route = {} if (v.effort !== undefined) { if (!isLevel(v.effort)) return undefined @@ -168,10 +229,66 @@ function acceptPhase(models: Record) { if (!isModelName(models, v.model)) return undefined route.model = v.model } - return route.effort || route.model ? route : undefined + if (v.tier !== undefined) { + if (typeof v.tier !== 'string' || !hasKey(tiers, v.tier)) return undefined + route.tier = v.tier + } + return route.effort || route.model || route.tier ? route : undefined } } +/** A tier: a non-empty alias list; unknown aliases dropped, duplicates too. */ +function acceptTier(models: Record, log: Log) { + return (key: string, v: unknown): string[] | undefined => { + // a tier named like an alias would make a bare name ambiguous + if (!PHASE_KEY.test(key) || hasKey(models, key)) return undefined + if (!Array.isArray(v)) return undefined + const items = v as unknown[] + const kept = items.filter( + (a): a is string => typeof a === 'string' && hasKey(models, a)) + if (kept.length < items.length) { + log(`model-router: config tiers.${key} entries dropped`) + } + return kept.length > 0 ? [...new Set(kept)] : undefined + } +} + +/** Appends the `models` aliases a user's chain omits, so all are ranked. */ +function withEveryAlias( + chain: string[], + models: Record, + log: Log, +): string[] { + const missing = Object.keys(models).filter(a => !chain.includes(a)) + if (missing.length > 0) { + log(`model-router: config fallback lacks ${missing.join(', ')}; appended`) + } + return [...chain, ...missing] +} + +/** The fallback chain: deduplicated aliases of `models`, else the default. */ +function pickFallback( + user: unknown, + base: string[], + models: Record, + log: Log, +): string[] { + if (user === undefined) return base + const items = Array.isArray(user) ? (user as unknown[]) : [] + const kept = items.filter( + (a): a is string => typeof a === 'string' && hasKey(models, a)) + if (kept.length > 0) return withEveryAlias([...new Set(kept)], models, log) + log('model-router: config fallback ignored: need a list of model aliases') + return base +} + +function pickPositive(v: unknown, fallback: number, name: string, log: Log) { + if (v === undefined) return fallback + if (typeof v === 'number' && Number.isInteger(v) && v > 0) return v + log(`model-router: config ${name} ignored: not a positive integer`) + return fallback +} + function acceptPhaseRef(phases: Record) { return (_key: string, v: unknown): string | undefined => typeof v === 'string' && PHASE_KEY.test(v) && hasKey(phases, v) @@ -179,22 +296,32 @@ function acceptPhaseRef(phases: Record) { : undefined } -function compiles(pattern: string): boolean { - try { - new RegExp(pattern, 'i') - return true - } catch { - return false +/** Unicode-aware first; a pattern only valid without `u` still works. */ +function buildRegex(pattern: string): RegExp | undefined { + for (const flags of ['iu', 'i']) { + try { + return new RegExp(pattern, flags) + } catch { + // retry with the next flag set + } } + return undefined } -function acceptRule(phases: Record, v: unknown) { +/** Absent `mode` = floor: override files written before modes keep meaning. */ +function acceptRule( + phases: Record, + v: unknown, +): PromptRule | undefined { if (!isRecord(v)) return undefined - const { pattern, phase } = v + const { pattern, phase, mode } = v if (typeof pattern !== 'string' || typeof phase !== 'string') return undefined + if (mode !== undefined && mode !== 'floor' && mode !== 'default') { + return undefined + } if (pattern.length > MAX_PATTERN) return undefined - return hasKey(phases, phase) && compiles(pattern) - ? { pattern, phase } + return hasKey(phases, phase) && buildRegex(pattern) + ? { pattern, phase, mode: mode ?? 'floor' } : undefined } @@ -231,6 +358,34 @@ function pickEnabled(v: unknown, fallback: boolean, log: Log): boolean { return pickBool(v, fallback) } +type Routing = Pick + +/** Tiers, fallback chain and breaker knobs, validated against `models`. */ +function mergeRouting( + base: Config, + user: Record, + models: Record, + log: Log, +): Routing { + const tiers = mergeTable( + base.tiers, user.tiers, 'tiers', acceptTier(models, log), log) + const fallback = pickFallback(user.fallback, base.fallback, models, log) + if (tiers.best?.[0] !== fallback[0]) { + log('model-router: tiers.best does not lead the fallback chain; rank ' + + 'comes from the fallback list alone') + } + return { + tiers, + fallback, + cooldownMinutes: pickPositive( + user.cooldownMinutes, base.cooldownMinutes, 'cooldownMinutes', log), + mainUpgrade: pickBool(user.mainUpgrade, base.mainUpgrade), + upgradeMaxTokens: pickPositive( + user.upgradeMaxTokens, base.upgradeMaxTokens, 'upgradeMaxTokens', log), + } +} + /** Defaults overlaid with the user's entries, each validated first. */ function mergeConfig(user: unknown, log: Log): Config { const base = structuredClone(DEFAULT_CONFIG) @@ -240,11 +395,13 @@ function mergeConfig(user: unknown, log: Log): Config { } const models = mergeTable( base.models, user.models, 'models', acceptModel, log) - const phases = mergeTable( - base.phases, user.phases, 'phases', acceptPhase(models), log) + const routing = mergeRouting(base, user, models, log) + const phases = mergeTable(base.phases, user.phases, 'phases', + acceptPhase(models, routing.tiers), log) const ref = acceptPhaseRef(phases) return { models, + ...routing, windows: mergeTable( base.windows, user.windows, 'windows', acceptWindow, log), phases, @@ -310,11 +467,15 @@ async function loadConfig( return { cfg: mergeConfig(found.data, log), source: found.path } } -function compileRules(cfg: Config): Rule[] { - return cfg.prompt.map(r => ({ - re: new RegExp(r.pattern, 'i'), - phase: r.phase, - })) +/** Compiles the prompt rules; one that fails to compile is dropped, logged. */ +function compileRules(cfg: Config, log: Log): Rule[] { + const rules: Rule[] = [] + for (const r of cfg.prompt) { + const re = buildRegex(r.pattern) + if (re) rules.push({ re, phase: r.phase, mode: r.mode ?? 'floor' }) + else log(`model-router: prompt rule for ${r.phase} does not compile`) + } + return rules } // ---- state ----------------------------------------------------------- @@ -322,7 +483,7 @@ function compileRules(cfg: Config): Rule[] { function newState(cfg: Config, source: string): State { return { cfg, - rules: compileRules(cfg), + rules: compileRules(cfg, () => undefined), source, userMain: null, turnMain: null, @@ -334,12 +495,34 @@ function newState(cfg: Config, source: string): State { skillCalls: 0, off: false, offConfig: false, - lastMain: '', - windowWarned: false, + spinner: '', + lastPlan: null, + turnModel: undefined, + sessionModel: '', + down: new Map(), + strikes: new Map(), + agentModels: new Map(), + pushed: null, + logged: new Set(), + turnLogged: new Set(), warned: new Set(), } } +/** + * /clear rebuilds the state but keeps what is account- or process-wide: + * the breaker (a model's quota outlives the conversation) and the model. + */ +function resetSession(st: State): void { + const kept = { + down: st.down, + strikes: st.strikes, + agentModels: st.agentModels, + sessionModel: st.sessionModel, + } + Object.assign(st, newState(st.cfg, st.source), kept) +} + /** Logs a hook's fail-open once per session; never throws itself. */ function warnOnce(st: State, $: Api, hook: string, kind: string): void { if (st.warned.has(hook)) return @@ -361,6 +544,289 @@ function safely(st: State, $: Api, hook: string, work: () => void): void { } } +// ---- models: ids, tiers, breaker, the main decision ------------------- + +/** The table id an alias, a `[1m]` variant or a dated id stands for. */ +function canonical(cfg: Config, id: string): string { + const bare = id.replace(ONE_M, '') + if (hasKey(cfg.models, bare)) return cfg.models[bare] ?? bare + if (!bare.startsWith(PREFIX) || bare.length <= PREFIX.length) return bare + const hit = Object.values(cfg.models).find( + known => bare.startsWith(known)) + return hit ?? bare +} + +/** The table alias of a canonical id; undefined for an id the table lacks. */ +const aliasOf = (cfg: Config, id: string): string | undefined => + Object.keys(cfg.models).find(alias => cfg.models[alias] === id) + +/** Position in the fallback chain, best first; undefined when unranked. */ +function modelRank(cfg: Config, id: string): number | undefined { + const alias = aliasOf(cfg, id) + const at = alias === undefined ? -1 : cfg.fallback.indexOf(alias) + return at < 0 ? undefined : at +} + +const routeName = (r: Route | null | undefined): string | undefined => + r?.tier ?? r?.model + +/** First alias of the list whose model is not down. */ +function availableIn(st: State, aliases: readonly string[]) { + for (const alias of aliases) { + const id = st.cfg.models[alias] + if (id !== undefined && !st.down.has(id)) return id + } + return undefined +} + +/** The first model not down in the fallback chain, after `after`'s place. */ +function nextAvailable(st: State, after: string | undefined) { + const { fallback, models } = st.cfg + const at = fallback.findIndex(alias => models[alias] === after) + return availableIn(st, fallback.slice(at + 1)) +} + +/** + * A tier, alias or id as an id to run on. A tier skips down aliases, then + * walks the global chain (from `after`, default the tier's last alias); an + * alias or id is explicit and never skipped. + */ +function resolveName(st: State, name: string, after?: string) { + const tier = hasKey(st.cfg.tiers, name) ? st.cfg.tiers[name] : undefined + if (tier === undefined) return canonical(st.cfg, name) + const last = tier[tier.length - 1] + const from = after ?? (last === undefined ? undefined : st.cfg.models[last]) + return availableIn(st, tier) ?? nextAvailable(st, from) +} + +function resolveRoute(st: State, route: Route | undefined) { + const name = routeName(route) + return name === undefined ? undefined : resolveName(st, name) +} + +/** Drops lapsed holds; the clock is read only while something is held. */ +async function prune($: Api, st: State): Promise { + if (st.down.size === 0) return 0 + const now = await $.clock.now() + for (const [id, hold] of st.down) { + if (hold.until <= now) st.down.delete(id) + } + return now +} + +const holdWord = (until: number, now: number): string => + until === Infinity + ? 'until reload' + : `for ${Math.max(1, Math.ceil((until - now) / 60000))} min` + +function holdMinutes(cfg: Config, strikes: number, reason: string): number { + if (reason === 'model_not_found') return Infinity + const step = BACKOFF_STEPS[Math.min(strikes, BACKOFF_STEPS.length) - 1] ?? 1 + return cfg.cooldownMinutes * step +} + +/** + * Marks a table model down for an episode. A mark on a model already down + * adds no strike and no log, except `model_not_found`, which lengthens a + * timed hold to "until reload". Inert while the router is off. + */ +function markDown( + $: Api, + st: State, + id: string, + reason: string, + now: number, +): void { + if (st.off || aliasOf(st.cfg, id) === undefined) return + const held = st.down.get(id) + const lengthen = reason === 'model_not_found' && held?.until !== Infinity + if (held && !lengthen) return + const strikes = (st.strikes.get(id) ?? 0) + (held ? 0 : 1) + st.strikes.set(id, strikes) + const until = now + holdMinutes(st.cfg, strikes, reason) * 60000 + st.down.set(id, { until, reason }) + $.ui.log(`model-router: ${id} unavailable (${reason}) ${ + holdWord(until, now)}; routing falls back`) +} + +/** `/route reload` and a user /model: the marks are stale. */ +function clearBreaker(st: State, id?: string): void { + if (id === undefined) { + st.down.clear() + st.strikes.clear() + } else { + st.down.delete(id) + st.strikes.delete(id) + } + st.turnModel = undefined +} + +type Call = { + model: string // exact string to send: `cur` verbatim when not moved + why: string + moved: boolean + log?: string // turn-once line + logKey?: string // its dedupe key when the text varies; default the text + once?: string // session-once line +} + +const keep = (cur: string, why = 'unchanged', log?: string): Call => + ({ model: cur, why, moved: false, ...(log === undefined ? {} : { log }) }) + +/** The replacement keeps the session's `[1m]` tier, haiku has none. */ +function moveTo(cur: string, target: string, why: string): Call { + const carried = ONE_M.test(cur) && !target.startsWith(HAIKU) + const model = carried ? `${target}[1m]` : target + const once = carried + ? `model-router: ${why} to ${model}: the [1m] variant is carried over` + : undefined + return { model, why, moved: true, ...(once === undefined ? {} : { once }) } +} + +/** True when the context still fits the target model's known window. */ +function fits(st: State, id: string, tokens: number | undefined): boolean { + const limit = hasKey(st.cfg.windows, id) ? st.cfg.windows[id] : undefined + return limit === undefined || (tokens !== undefined && tokens < limit) +} + +const noFit = (id: string): string => + `model-router: no switch to ${id}: context not known to fit` + +/** Why the upgrade cap blocks a move, or undefined. Unknown size = blocked. */ +function capBlock(st: State, tokens: number | undefined): string | undefined { + if (tokens === undefined) return 'context size unknown' + const max = st.cfg.upgradeMaxTokens + return tokens > max ? `context ${tokens} tokens over ${max}` : undefined +} + +/** True when `wanted` ranks above `id` in the fallback chain. */ +function ranksAbove(st: State, wanted: string, id: string): boolean { + const rw = modelRank(st.cfg, wanted) + const rc = modelRank(st.cfg, id) + return rw !== undefined && rc !== undefined && rw < rc +} + +/** + * `cur` is down: `wanted`, else the next model of the chain that fits. A + * better `wanted` is an upgrade and passes the same switch and cap. + */ +function leaveDown( + st: State, + cur: string, + wanted: string | undefined, + tokens: number | undefined, +): Call { + const id = canonical(st.cfg, cur) + const upOk = st.cfg.mainUpgrade && capBlock(st, tokens) === undefined + for (const option of [wanted, nextAvailable(st, id)]) { + if (option === undefined || st.down.has(option)) continue + if (aliasOf(st.cfg, option) === undefined) continue + if (option === wanted && !upOk && ranksAbove(st, option, id)) continue + if (fits(st, option, tokens)) return moveTo(cur, option, 'fallback') + } + return keep(cur, 'fallback unavailable') +} + +/** `wanted` ranks above `cur`: upgrade, under the switch and the cap. */ +function upgradeCall( + st: State, + cur: string, + wanted: string, + tokens: number | undefined, +): Call { + if (!st.cfg.mainUpgrade) return keep(cur, 'switch off') + const block = capBlock(st, tokens) + if (block !== undefined) { + const why = `upgrade skipped: ${block}` + const call = keep(cur, why, `model-router: ${why}`) + return { ...call, logKey: 'upgrade-skipped' } + } + if (!fits(st, wanted, tokens)) return keep(cur, 'no fit', noFit(wanted)) + return moveTo(cur, wanted, 'upgrade') +} + +/** `wanted` is cheaper (or unranked): only with the downgrade switch on. */ +function downgradeCall( + st: State, + cur: string, + wanted: string, + tokens: number | undefined, +): Call { + if (!st.cfg.mainModelSwitch) return keep(cur, 'switch off') + if (!fits(st, wanted, tokens)) return keep(cur, 'no fit', noFit(wanted)) + return moveTo(cur, wanted, 'downgrade') +} + +/** A model the table does not rank is never switched; said once. */ +function unknownCall(cur: string, id: string): Call { + const call = keep(cur, 'model unknown to the table') + if (id === '') return call + const once = `model-router: ${id} unknown to the models table; no switch` + return { ...call, once } +} + +/** + * The one decision of the main loop's model, in this order: router off, a + * model the table does not rank (never touched), `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. + */ +function decideMain( + st: State, + cur: string, + wanted: string | undefined, + tokens: number | undefined, +): Call { + const id = canonical(st.cfg, cur) + if (st.off) return keep(cur) + if (modelRank(st.cfg, id) === undefined) return unknownCall(cur, id) + if (st.down.has(id)) return leaveDown(st, cur, wanted, tokens) + if (wanted === undefined) return keep(cur) + if (aliasOf(st.cfg, wanted) === aliasOf(st.cfg, id)) return keep(cur) + return ranksAbove(st, wanted, id) + ? upgradeCall(st, cur, wanted, tokens) + : downgradeCall(st, cur, wanted, tokens) +} + +/** Model axis: sticky, then turn route, then the floor's own model. */ +const mainModel = (st: State): string | undefined => + routeName(st.userMain?.route) ?? + routeName(st.turnMain?.route) ?? + routeName(st.turnFloor?.route) + +async function readTokens($: Api): Promise { + try { + return (await $.session.usage()).context.tokens + } catch { + return undefined + } +} + +type Verdict = { call: Call; wanted: string | undefined } + +/** What the main loop would run on from `cur`: wanted model + decision. */ +async function decideFor($: Api, st: State, cur: string): Promise { + const name = mainModel(st) + const wanted = name === undefined + ? undefined + : resolveName(st, name, canonical(st.cfg, cur)) + const needsTokens = wanted !== undefined || st.down.size > 0 + const tokens = needsTokens ? await readTokens($) : undefined + return { call: decideMain(st, cur, wanted, tokens), wanted } +} + +function logCall($: Api, st: State, call: Call): void { + const key = call.logKey ?? call.log + if (call.log !== undefined && key !== undefined && !st.turnLogged.has(key)) { + st.turnLogged.add(key) + $.ui.log(call.log) + } + if (call.once !== undefined && !st.logged.has(call.once)) { + st.logged.add(call.once) + $.ui.log(call.once) + } +} + /** The main loop's effective route: user /route > latest turn route. */ const mainRoute = (st: State): Routed | null => st.userMain ?? st.turnMain @@ -396,12 +862,6 @@ function mainEffort(st: State, engine: Effort): Decision { return { effort, by: sticky === undefined ? 'turn' : 'sticky' } } -/** Model axis: sticky, then turn route, then the floor's own model. */ -const mainModel = (st: State): string | undefined => - st.userMain?.route.model ?? - st.turnMain?.route.model ?? - st.turnFloor?.route.model - const floorSource = (f: Routed): string => f.source === 'prompt' ? `prompt rule ${f.phase}` : `typed /${f.phase}` @@ -463,9 +923,6 @@ const routerWord = (st: State): string => // ---- text ------------------------------------------------------------ -const modelText = (cfg: Config, model: string | undefined): string => - model === undefined ? '-' : resolveModel(cfg, model) - /** The floor's level when it carries one and the router is on. */ function liveFloor(st: State): { f: Routed; level: Level } | undefined { const f = st.turnFloor @@ -473,44 +930,92 @@ function liveFloor(st: State): { f: Routed; level: Level } | undefined { return st.off || !f || level === undefined ? undefined : { f, level } } -/** True when the switch would put the main loop on a haiku model. */ -function mainOnHaiku(st: State): boolean { - const model = mainModel(st) - return st.cfg.mainModelSwitch && model !== undefined && - resolveModel(st.cfg, model).startsWith(HAIKU) +/** An id the table knows, else "session model": '' and foreign ids alike. */ +function idWord(st: State, model: string): string { + const known = aliasOf(st.cfg, canonical(st.cfg, model)) !== undefined + return known ? model : 'session model' } -function effortWord(st: State): string { - if (mainOnHaiku(st)) return '- (haiku takes none)' +/** The router left a down model, or wanted to and found nowhere to go. */ +const isFallback = (call: Call): boolean => call.why.startsWith('fallback') + +/** Model words of the main line, from the decision a step would take. */ +function modelWord(st: State, v: Verdict): string { + const id = idWord(st, v.call.model) + if (v.call.moved) return `${id} (${v.call.why})` + if (v.wanted === undefined) { + return isFallback(v.call) ? `${id} (${v.call.why})` : '-' + } + if (canonical(st.cfg, v.call.model) === v.wanted) return id + return `asked ${v.wanted}, keeps ${id} (${v.call.why})` +} + +/** The tier a route names, shown beside the model it resolved to. */ +function tierWord(st: State, word: string): string { + const name = mainModel(st) + const tier = name !== undefined && hasKey(st.cfg.tiers, name) + return tier ? `${word} [tier ${name}]` : word +} + +/** Haiku takes no effort: the main line says so when it will run there. */ +function effortWord(st: State, v: Verdict): string { + if (v.call.model.startsWith(HAIKU)) return '- (haiku takes none)' return String(mainEffort(st, undefined).effort ?? '-') } -function mainText(st: State): string { +function mainText(st: State, v: Verdict): string { const r = mainRoute(st) const live = liveFloor(st) const floor = live ? ` · floor ${live.level} (${live.f.phase})` : '' - if (!r) return 'main: session defaults' + floor - const model = modelText(st.cfg, mainModel(st)) + if (!r) { + const left = v.call.moved || isFallback(v.call) + ? ` · model ${modelWord(st, v)}` + : '' + return 'main: session defaults' + left + floor + } + const model = tierWord(st, modelWord(st, v)) return `main: ${r.source} ${r.phase} · model ${model} · effort ${ - effortWord(st)}${floor}` + effortWord(st, v)}${floor}` } -function phasesText(cfg: Config): string { - const entries = Object.entries(cfg.phases).map(([name, r]) => - `${name}=${r.model ? resolveModel(cfg, r.model) : 'session'}/${ - r.effort ?? 'session'}`) +/** `name=→/` for every phase. */ +function phasesText(st: State): string { + const entries = Object.entries(st.cfg.phases).map(([name, r]) => { + const asked = routeName(r) + const id = asked === undefined ? undefined : resolveName(st, asked) + const model = asked === undefined + ? 'session' + : asked === id ? asked : `${asked}→${id ?? '-'}` + return `${name}=${model}/${r.effort ?? 'session'}` + }) return `phases: ${entries.join(' ')}` } -function show(st: State): string { +function downText(st: State, now: number): string { + const held = [...st.down].map(([id, h]) => + `${id} ${holdWord(h.until, now)} (${h.reason})`) + return `down: ${held.length > 0 ? held.join(', ') : 'none'}` +} + +/** The verdict a text reports: what the next main step would decide. */ +async function snapshot($: Api, st: State) { + const now = await prune($, st) + const cur = st.turnModel ?? st.sessionModel + return { now, ...(await decideFor($, st, cur)) } +} + +async function show($: Api, st: State): Promise { const c = st.cfg const flag = (b: boolean) => (b ? 'on' : 'off') + const s = await snapshot($, st) return [ - mainText(st), - `router: ${routerWord(st)} · switch: ${flag(c.mainModelSwitch)} · ` + - `verbose: ${flag(c.verbose)} · spinner: ${flag(c.spinner)}`, + mainText(st, s), + `router: ${routerWord(st)} · switch: ${flag(c.mainModelSwitch)} ` + + `(downgrade) · upgrade: ${flag(c.mainUpgrade)} · verbose: ${ + flag(c.verbose)} · spinner: ${flag(c.spinner)}`, + downText(st, s.now), `live loops: ${st.loops.size}`, - phasesText(c), + phasesText(st), `config: ${st.source}`, ].join('\n') } @@ -565,19 +1070,24 @@ function parseRoute(cfg: Config, args: string): Routed | string { return { phase: 'custom', route, source: 'user' } } -function toggle(st: State, what: string, arg: string | undefined): string { +async function toggle( + $: Api, + st: State, + what: string, + arg: string | undefined, +): Promise { if (arg !== 'on' && arg !== 'off') return `usage: /route ${what} on|off` if (what === 'switch') st.cfg.mainModelSwitch = arg === 'on' else st.cfg.verbose = arg === 'on' - return show(st) + return show($, st) } -function setUserRoute($: Api, st: State, args: string): string { +async function setUserRoute($: Api, st: State, args: string) { const parsed = parseRoute(st.cfg, args) if (typeof parsed === 'string') return parsed st.userMain = parsed refresh($, st) - return show(st) + return show($, st) } /** @@ -589,7 +1099,7 @@ async function reloadConfig($: Api, st: State): Promise { const loaded = await loadConfig($, text => $.ui.log(text)) if (loaded) { st.cfg = loaded.cfg - st.rules = compileRules(loaded.cfg) + st.rules = compileRules(loaded.cfg, text => $.ui.log(text)) st.source = loaded.source applyEnabled(st, loaded.cfg.enabled) } else { @@ -598,29 +1108,35 @@ async function reloadConfig($: Api, st: State): Promise { await registerTool($, st) } +/** The breaker is cleared first, whatever the config read then does. */ +async function reloadCommand($: Api, st: State): Promise { + clearBreaker(st) + await reloadConfig($, st) + refresh($, st) + return 'config reloaded\n' + (await show($, st)) +} + async function handleCommand($: Api, st: State, args: string): Promise { const [head = '', ...rest] = args.trim().split(/\s+/) switch (head) { case '': case 'show': - return show(st) + return show($, st) case 'clear': clearRoutes(st) refresh($, st) - return 'route cleared\n' + show(st) + return 'route cleared\n' + (await show($, st)) case 'on': case 'off': st.off = head === 'off' st.offConfig = false refresh($, st) - return show(st) + return show($, st) case 'reload': - await reloadConfig($, st) - refresh($, st) - return 'config reloaded\n' + show(st) + return reloadCommand($, st) case 'switch': case 'verbose': - return toggle(st, head, rest[0]) + return toggle($, st, head, rest[0]) default: return setUserRoute($, st, args) } @@ -634,10 +1150,11 @@ async function registerTool($: Api, st: State): Promise { name: 'route', description: 'Declare the phase of the work ahead so the next requests of THIS ' + - 'loop run at the right effort (and, on the main loop, the model ' + - 'when the switch is on). Call it before a span of work changes ' + - 'nature (planning, orchestrating, mechanical work). Effort only ' + - 'for a sub-agent; the model of a sub-agent is fixed at spawn. ' + + 'loop run at the right effort and model. Call it before a span of ' + + 'work changes nature (planning, orchestrating, mechanical work). ' + + 'The main loop moves up to a phase\'s tier by itself (below the ' + + 'context cap), down only with the switch on; a sub-agent\'s model ' + + 'is fixed at spawn. ' + `Phases: ${Object.keys(st.cfg.phases).join(', ')}.`, inputSchema: { type: 'object', @@ -708,25 +1225,34 @@ function clearLoop(st: State, agentId: string | undefined): string { return 'route cleared for this agent' } +/** What the main loop's model will do, in the words of the decision. */ +async function mainAnswer($: Api, st: State): Promise { + const { call, wanted } = await snapshot($, st) + if (call.moved) return `${idWord(st, call.model)} (${call.why})` + const quiet = call.why === 'unchanged' || + (wanted === undefined && !isFallback(call)) + return quiet ? 'unchanged' : `unchanged (${call.why})` +} + /** Truthful answer: states what the calling loop will actually do. */ -function routedText(st: State, agentId: string | undefined, p: Picked): string { +async function routedText( + $: Api, + st: State, + agentId: string | undefined, + p: Picked, +): Promise { const note = agentId === undefined ? mainNote(st, p.route.effort) : '' if (note) return `recorded ${p.phase} for this turn, but ${note}` const loop = agentId === undefined ? undefined : st.loops.get(agentId) const effort = loop?.explicitEffort ? undefined : p.route.effort - const model = agentId === undefined && st.cfg.mainModelSwitch - ? p.route.model - : undefined - const modelNote = !p.route.model || model !== undefined - ? '' - : agentId === undefined ? ' (switch off)' : ' (fixed at spawn)' + const model = agentId === undefined + ? await mainAnswer($, st) + : routeName(p.route) ? 'unchanged (fixed at spawn)' : 'unchanged' return `routed ${agentId === undefined ? 'main' : 'this agent'} to ` + - `${p.phase}: effort ${effort ?? 'unchanged'}, model ` + - `${model === undefined ? 'unchanged' : resolveModel(st.cfg, model)}` + - modelNote + `${p.phase}: effort ${effort ?? 'unchanged'}, model ${model}` } -function handleRouteTool(st: State, e: RouteInput) { +async function handleRouteTool($: Api, st: State, e: RouteInput) { if (st.off) { return { result: 'model-router is off (/route on to resume); nothing routed', @@ -736,7 +1262,7 @@ function handleRouteTool(st: State, e: RouteInput) { const picked = pickRoute(st.cfg, e.phase, e.effort) if (typeof picked === 'string') return { deny: picked } applyRoute(st, e.agentId, picked) - return { result: routedText(st, e.agentId, picked) } + return { result: await routedText($, st, e.agentId, picked) } } // ---- skills ---------------------------------------------------------- @@ -839,6 +1365,11 @@ function spawnRoute(cfg: Config, e: SpawnIn, frozen: boolean) { return phase === undefined ? undefined : phaseRoute(cfg, phase) } +/** The model a spawn is rewritten to; an explicit `model` param wins. */ +function spawnTarget(st: State, e: SpawnIn, route: Route | undefined) { + return e.model === undefined ? resolveRoute(st, route) : undefined +} + function trackLoop(st: State, e: SpawnIn, started: { agentId?: string }, route: Route | undefined): void { @@ -851,6 +1382,62 @@ function trackLoop(st: State, e: SpawnIn, started: { }) } +/** The breaker's target for an agent's failure; oldest entries dropped. */ +function rememberAgent(st: State, agentId: string, model: string): void { + st.agentModels.set(agentId, model.replace(ONE_M, '')) + if (st.agentModels.size <= MAX_AGENT_MODELS) return + const oldest = st.agentModels.keys().next().value + if (oldest !== undefined) st.agentModels.delete(oldest) +} + +// ---- derived orchestrate --------------------------------------------- + +/** + * A main Agent dispatch is orchestration: the turn's route becomes + * `orchestrate` until the spawned agents end. A route the model or a skill + * declared is never replaced. + */ +function pushOrchestrate(st: State): void { + const src = st.turnMain?.source + const route = phaseRoute(st.cfg, 'orchestrate') + if (st.pushed !== null || !route) return + if (src === 'model' || src === 'skill') return + st.pushed = { prev: st.turnMain, spawnIds: new Set() } + st.turnMain = { phase: 'orchestrate', route: { ...route }, source: 'derived' } +} + +/** Restores the route from before the dispatch, unless one replaced it. */ +function popOrchestrate(st: State): void { + if (st.pushed && st.turnMain?.source === 'derived') { + st.turnMain = st.pushed.prev + } + st.pushed = null +} + +/** The agent id of a background launch, from the Agent tool's result. */ +function launchedId(result: unknown): string | undefined { + if (!isRecord(result) || result.status !== 'async_launched') return undefined + return typeof result.agentId === 'string' ? result.agentId : undefined +} + +/** After the Agent call: wait for a background agent, else pop at once. */ +function afterDispatch(st: State, result: unknown): void { + const id = launchedId(result) + if (id !== undefined) { + pushOrchestrate(st) + st.pushed?.spawnIds.add(id) + } else if (st.pushed && st.pushed.spawnIds.size === 0) { + popOrchestrate(st) + } +} + +/** An agent's loop ended: forget it, pop when it was the last awaited. */ +function endAgent(st: State, agentId: string): void { + st.loops.delete(agentId) + const awaited = st.pushed?.spawnIds + if (awaited?.delete(agentId) && awaited.size === 0) popOrchestrate(st) +} + // ---- turn steps ------------------------------------------------------ function agentPlan(st: State, e: StepIn): Plan { @@ -858,32 +1445,19 @@ function agentPlan(st: State, e: StepIn): Plan { return { model: e.model, effort: loop?.effort ?? e.effort } } -/** True when the context still fits the target model's known window. */ -async function windowOk($: Api, st: State, id: string): Promise { - const limit = hasKey(st.cfg.windows, id) ? st.cfg.windows[id] : undefined - if (limit === undefined) return true - let tokens: number | undefined - try { - tokens = (await $.session.usage()).context.tokens - } catch { - tokens = undefined - } - if (typeof tokens === 'number' && tokens < limit) return true - if (!st.windowWarned) { - st.windowWarned = true - $.ui.log(`model-router: no switch to ${id}: context not known to fit`) - } - return false -} - +/** + * The main loop's plan: effort from the floor/sticky/turn decision, model + * from `decideMain`. `cur` is the model the router moved this turn, else + * the engine's own (verbatim: an engine fallback is respected). + */ async function mainPlan($: Api, st: State, e: StepIn): Promise { const { effort } = mainEffort(st, e.effort) - const wanted = mainModel(st) - if (wanted === undefined || !st.cfg.mainModelSwitch) { - return { model: e.model, effort } - } - const id = resolveModel(st.cfg, wanted) - return { model: (await windowOk($, st, id)) ? id : e.model, effort } + await prune($, st) + const cur = st.turnModel ?? e.model + const { call } = await decideFor($, st, cur) + logCall($, st, call) + if (call.moved) st.turnModel = call.model + return { model: call.model, effort } } async function planStep($: Api, st: State, e: StepIn): Promise { @@ -908,7 +1482,8 @@ function stepLog(e: StepIn, plan: Plan): string { } function noteMain($: Api, st: State, plan: Plan): void { - st.lastMain = `${plan.model.replace(/^claude-/, '')}/${plan.effort ?? '-'}` + st.lastPlan = plan + st.spinner = `${plan.model.replace(/^claude-/, '')}/${plan.effort ?? '-'}` refresh($, st) } @@ -916,18 +1491,88 @@ function endMainTurn($: Api, st: State): void { st.turnFloor = st.pendingPrompt st.pendingPrompt = null st.turnMain = null + st.pushed = null + st.turnModel = undefined st.typedSlash = false st.explicitEffort.clear() - st.lastMain = '' - st.windowWarned = false + st.spinner = '' + st.turnLogged.clear() refresh($, st) } +// ---- breaker inputs -------------------------------------------------- + +/** The exact id a failure is charged to: the agent's, else main's plan. */ +function failureTarget(st: State, agentId: string | undefined) { + if (agentId !== undefined) return st.agentModels.get(agentId) + return st.lastPlan?.model.replace(ONE_M, '') +} + +/** An engine StopFailure of an availability kind marks its model down. */ +async function onStopFailure( + $: Api, + st: State, + e: { error: string; agent_id?: string }, +): Promise { + if (st.off || !UNAVAILABLE.has(e.error)) return + const sent = failureTarget(st, e.agent_id) + if (sent === undefined) return + if (e.error === 'model_not_found' && aliasOf(st.cfg, sent) === undefined) { + $.ui.log(`model-router: model_not_found for ${sent}: not a table id; ` + + 'no mark') + return + } + await prune($, st) + markDown($, st, canonical(st.cfg, sent), e.error, await $.clock.now()) +} + +type SwitchIn = { + from_model: string + to_model: string + requested_model: string | null + source: string +} + +/** + * The engine switched the model by itself. The model it left is marked, one + * strike, unless it landed where the router already was; the mark targets + * the model actually sent, else the model reported as left. + */ +async function onAutoSwitch($: Api, st: State, e: SwitchIn): Promise { + const cfg = st.cfg + const from = canonical(cfg, e.from_model) + const to = canonical(cfg, e.to_model) + $.ui.log(`model-router: engine switched ${from} → ${to} ` + + `(requested ${e.requested_model ?? '-'})`) + const sent = st.lastPlan ? canonical(cfg, st.lastPlan.model) : undefined + if (to === sent) return + const target = sent !== undefined && aliasOf(cfg, sent) ? sent : from + await prune($, st) + markDown($, st, target, 'engine fallback', await $.clock.now()) +} + +/** Any model change: keeps `sessionModel`; a user choice clears its mark. */ +async function onModelSwitch($: Api, st: State, e: SwitchIn): Promise { + st.sessionModel = e.to_model + if (st.off || e.source === 'resume') return + if (e.source === 'auto') await onAutoSwitch($, st, e) + else clearBreaker(st, canonical(st.cfg, e.to_model)) +} + // ---- registration ---------------------------------------------------- +async function readSessionModel($: Api): Promise { + try { + return await $.session.model() + } catch { + return '' + } +} + function registerSession(on: On, st: State): void { on('session.start', async ($, e, next) => { await reloadConfig($, st) + st.sessionModel = await readSessionModel($) await registerCommand($) refresh($, st) return next(e) @@ -936,7 +1581,7 @@ function registerSession(on: On, st: State): void { return next(e) }) on('session.end', async ($, e, next) => { - Object.assign(st, newState(st.cfg, st.source)) + resetSession(st) // session.start never fires after /clear: re-apply the config's // `enabled` so a config-disabled router (offConfig) stays off. applyEnabled(st, st.cfg.enabled) @@ -947,6 +1592,23 @@ function registerSession(on: On, st: State): void { }) } +function registerBreaker(on: On, st: State): void { + on('classic.StopFailure', async ($, e, next) => { + await onStopFailure($, st, e) + return next(e) + }).catch(($, e, next) => { + warnOnce(st, $, 'StopFailure', next.error.kind) + return next(e) + }) + on('classic.PostModelSwitch', async ($, e, next) => { + await onModelSwitch($, st, e) + return next(e) + }).catch(($, e, next) => { + warnOnce(st, $, 'PostModelSwitch', next.error.kind) + return next(e) + }) +} + function registerCommandHook(on: On, st: State): void { on('command.run', { command: 'route' }, async ($, e) => { if (e.origin.kind !== 'composer') { @@ -961,7 +1623,7 @@ function registerCommandHook(on: On, st: State): void { function registerRouteTool(on: On, st: State): void { on('tool.call', { tool: TOOL }, async ($, e) => { - const out = handleRouteTool(st, e) + const out = await handleRouteTool($, st, e) refresh($, st) vlog($, st, `route ${e.agentId ?? 'main'}: ${JSON.stringify(out)}`) return out @@ -1002,10 +1664,15 @@ function registerSkills(on: On, st: State): void { function registerAgents(on: On, st: State): void { on('tool.call', { tool: 'Agent' }, async ($, e, next) => { - if (!st.off && isLevel(e.effort) && typeof e.tool_use_id === 'string') { + if (st.off) return next(e) + if (isLevel(e.effort) && typeof e.tool_use_id === 'string') { st.explicitEffort.set(e.tool_use_id, e.effort) } - return next(e) + if (e.agentId !== undefined) return next(e) + pushOrchestrate(st) + const out = await next(e) + safely(st, $, 'Agent', () => afterDispatch(st, out.result)) + return out }).catch(($, e, next) => { warnOnce(st, $, 'Agent', next.error.kind) return next(e) @@ -1015,16 +1682,18 @@ function registerAgents(on: On, st: State): void { function registerSpawn(on: On, st: State): void { on('agent.spawn', async ($, e, next) => { if (st.off) return next(e) + await prune($, st) const frozen = e.fork || e.workflow !== undefined const route = spawnRoute(st.cfg, e, frozen) - // An explicit model param on the Agent call always wins. - const wanted = e.model === undefined ? route?.model : undefined + const wanted = spawnTarget(st, e, route) const started = await next(wanted === undefined ? e - : { ...e, model: resolveModel(st.cfg, wanted) }) + : { ...e, model: wanted }) if (typeof started.agentId === 'string') { + const agentId = started.agentId safely(st, $, 'agent.spawn', () => { trackLoop(st, e, started, route) + rememberAgent(st, agentId, started.model) vlog($, st, `spawn ${e.subagentType}: ${e.model ?? '-'} → ${started.model}`) }) @@ -1052,7 +1721,9 @@ function registerTurns(on: On, st: State): void { return yield* next(e) }) on('turn.complete', async ($, e, next) => { - if (e.agentId !== undefined) st.loops.delete(e.agentId) + const agentId = e.agentId + if (agentId !== undefined) safely(st, $, 'turn.complete', () => + endAgent(st, agentId)) else endMainTurn($, st) return next(e) }).catch(($, e, next) => { @@ -1070,26 +1741,49 @@ function floorFromPrompt(st: State, midTurn: boolean, routed: Routed): void { if (midTurn) st.pendingPrompt = higherFloor(st.pendingPrompt, routed) } +const firstRule = (st: State, mode: PromptMode, text: string) => + st.rules.find(r => r.mode === mode && r.re.test(text)) + +/** A default rule sets the idle turn's route; routes and skills override. */ +function defaultFromPrompt(st: State, scanned: string): void { + const rule = firstRule(st, 'default', scanned) + const route = rule ? phaseRoute(st.cfg, rule.phase) : undefined + if (rule && route) { + st.turnMain = { phase: rule.phase, route: { ...route }, source: 'prompt' } + } +} + +/** + * Floor rules first (the user's explicit minimum). Default rules run only + * on an idle, plain prompt: not mid-turn, not a slash command or skill + * (they route themselves), not one that already carries a floor. + */ +function routeFromPrompt(st: State, text: string, midTurn: boolean): void { + const scanned = text.slice(0, MAX_PROMPT_SCAN) + const floor = firstRule(st, 'floor', scanned) + const route = floor ? phaseRoute(st.cfg, floor.phase) : undefined + if (floor && route) { + const routed: Routed = { phase: floor.phase, route, source: 'prompt' } + floorFromPrompt(st, midTurn, routed) + } + const slash = text.trimStart().startsWith('/') + if (text.trimStart().startsWith('/effort-')) st.typedSlash = true + if (!midTurn && !slash && !floor) defaultFromPrompt(st, scanned) +} + function registerPrompt(on: On, st: State): void { on('prompt.submit', async ($, e, next) => { if (st.off || e.origin.kind !== 'composer') return next(e) - const scanned = e.text.slice(0, MAX_PROMPT_SCAN) - const rule = st.rules.find(r => r.re.test(scanned)) - const route = rule ? phaseRoute(st.cfg, rule.phase) : undefined - if (rule && route) { - const routed: Routed = { phase: rule.phase, route, source: 'prompt' } - floorFromPrompt(st, e.turnId !== undefined, routed) - refresh($, st) - } - if (e.text.trimStart().startsWith('/effort-')) st.typedSlash = true + routeFromPrompt(st, e.text, e.turnId !== undefined) + refresh($, st) return next(e) }).catch(($, e, next) => { warnOnce(st, $, 'prompt.submit', next.error.kind) return next(e) }) on('ui.render', { component: 'Spinner' }, async ($, e, next) => { - if (st.off || !st.cfg.spinner || !st.lastMain) return next(e) - const suffix = ` · ${st.lastMain}…` + if (st.off || !st.cfg.spinner || !st.spinner) return next(e) + const suffix = ` · ${st.spinner}…` return next({ ...e, props: { ...e.props, suffix } }) }).catch(($, e, next) => { warnOnce(st, $, 'ui.render', next.error.kind) @@ -1100,6 +1794,7 @@ function registerPrompt(on: On, st: State): void { export const register: Register = on => { const st = newState(mergeConfig(undefined, () => undefined), 'defaults') registerSession(on, st) + registerBreaker(on, st) registerCommandHook(on, st) registerRouteTool(on, st) registerSkills(on, st) From 6f31f49d7ceda8d9ea3dbbc50dfd33ed27682ef3 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:09:07 +0200 Subject: [PATCH 043/547] =?UTF-8?q?chore(tasks):=20model-router=20W1-C=20d?= =?UTF-8?q?one=20=E2=80=94=20contract=20evidence,=20TODO=20(accepted=20MED?= =?UTF-8?q?IUMs,=20residuals,=20live=20checks),=20journal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 4 +++- .../2026-10-09-model-router-tiers-1237.md | 15 +++++++++++---- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 3ccf88d..8de9176 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -585,3 +585,4 @@ rules: - model-router W1-B1 floor landed (1ff608a): plan r2 from 3 lenses (0 BLOCKER, 4 MAJOR: one decision helper, typed level = default + minimum, mid-turn prompt now + next, per-machine enabled:false), feater DONE, gap round (/clear lost enabled:false, 'ultrathink rule' label, per-axis effort base), hardening round (kill switch keeps previous cfg on failed reload, typed slash attested at prompt.submit vs sub-agent preload). 30 tests, verifier CONFORME 6/6, security PASS ×2 with parked residuals. B2 wiring dispatched next. - model-router W1-B2 landed (6430ac6): tracked symlink skills/model-router → ../mods/model-router (mode 120000), gitignore, lib/tests/mods.test.sh, doctor Mods section, CLAUDE.md § mods/. Plan r2 (3 lenses, 5 MAJOR), feater DONE, gap round (my `4b.` label unparsed by gates.sh + unbounded probe), verifier CONFORME 8/8, security PASS (LOW: `claude plugin --help` rc 0 weakens the SKIP probe, fail-closed). Dev hot-reload link removed from ~/.claude/dev-mods; user to run /reload-plugins. BDR-115 amended (load, floor, kill switch, hardening). Doc audit (opus) in flight. - model-router wave 1 CLOSED on feature/model-router-mod (15 commits ahead of develop, nothing pushed: manual mode). Docs: opus audit SIGNIFICANT (README Explore row false, no mention of the mod) → user go all 10 → first patch self-reverted by the MINOR-envelope oracle (plan carried MINOR labels; a new heading exceeds the envelope) → re-dispatched with SIGNIFICANT provenance → b22f894. Full `make test`: every suite green except the pre-existing env red design-tool-gate (21st CLI present, not hermetic). Open for the user: /reload-plugins here; merge decision (gitflow finish); settings.json own change; W2 migration queued. +- model-router W1-C adaptive tiers landed (d0fa100): plan r1→r4 through 3 lenses (all FATAL: 4 BLOCKER + 20 MAJOR) + 2 confirmations (1 BLOCKER each, in my own r2 then r3) → deviation from the one-confirmation cap, stated. Design: absolute tiers, StopFailure-kind breaker + PostModelSwitch auto, fallback chain, main upgrade under a 200k cap (fails closed), sticky turnModel, derived orchestrate (background dispatches), prompt default rules with skip rules; classifier deferred. feater DONE → 2 gap rounds (texts) → hardening (leaveDown gates, cap fail-closed, one-way prefix, log key) → verifier CONFORME, security PASS (LOW only). 58 tests. Lesson: I sent iteration history in a security brief; the auditor contract forbids it (blind scan) — scope only next time. Live checks pending after /reload-plugins (R16/T8). Next: user reload, live test, wave 2. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 321aaf4..76874d6 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -13,7 +13,9 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [x] W1-B2 wiring (contract `2026-10-08-model-router-wiring-1835`, 2026-10-09): tracked symlink `skills/model-router` → `../mods/model-router` loads as `model-router@skills-dir` (fresh-process `claude plugin list --json` proves it), `.gitignore` `mods/*/tsconfig.json`, `lib/tests/mods.test.sh` (4 checks, capability probe, bounded, SKIP), doctor `── Mods ──` fail-soft, CLAUDE.md `## mods/`. Plan r2 from 3 lenses (5 MAJOR), feater DONE, gap round (4b label + unbounded probe), verifier CONFORME 8/8, security PASS - [ ] W1-B2 residuals (accepted): `claude plugin --help` returns 0 → the suite's capability probe can pass on a CLI without `plugin test` and then FAIL instead of SKIP (fail-closed; fix = grep the probe output for the test usage line); doctor `claude plugin list --json` unbounded; doctor `echo -e` helpers interpolate `$_mod` (tracked folder names only); fallback timeout guard orphans grandchildren (only without coreutils timeout); `update-all.sh` runs `claude plugin update` over `@skills-dir` → one recurring warn (needs an update-all edit) - [x] W1 close-out (2026-10-09): doc-sync opus audit SIGNIFICANT → user go all 10 → patched (README effort routing + Explore row + /route, USAGE, ARCHITECTURE mods/, CHANGELOG Unreleased) b22f894; hot-reload link removed from `~/.claude/dev-mods//`; BDR-115 amended (a6e2003). Pending user: `/reload-plugins` in this session (new sessions load the skills-dir copy by themselves); merge decision on feature/model-router-mod (`gitflow finish`, human signal) -- [ ] W1-C adaptive tiers (user 2026-10-09: "un système logique et optimisé", no /route typed, works on a haiku session, falls back when fable has no credit): contract `2026-10-09-model-router-tiers-1237`, plan same slug. Phases name absolute tiers (best/big/work/cheap), availability breaker (turn error/refusal + engine auto switch, 15 min cooldown), fallback chain fable→opus→sonnet→haiku, main upgrade on / downgrade gated, prompt default rules (plan/reflect keywords FR+EN) + dispatch push/pop + optional classifier +- [x] W1-C adaptive tiers (user 2026-10-09, contract `2026-10-09-model-router-tiers-1237`, plan r4 after 3 lenses + 2 confirmations: 6 BLOCKER + 29 MAJOR closed by named changes): phases name absolute tiers (best fable>opus>sonnet · big opus>fable>sonnet · work sonnet>opus · cheap haiku>sonnet); breaker fed by `classic.StopFailure` kinds rate_limit|overloaded|billing_error|model_not_found + `PostModelSwitch` auto (episode backoff 15→300 min, `/model` clears, `/clear` keeps, `/route reload` clears); fallback chain fable→opus→sonnet→haiku; main UPGRADE by default under `upgradeMaxTokens` 200k (fails closed on unknown usage), DOWNGRADE gated by `mainModelSwitch`; sticky `turnModel` per turn; derived `orchestrate` on background dispatches; prompt default rules (plan/reflect FR+EN, Unicode guards, skipped on `/…`, floor match, mid-turn). 58 tests; verifier CONFORME then 3 gap/hardening rounds; security PASS +- [ ] W1-C accepted-by-design (security 2026-10-09, MEDIUM, not coded around): (1) the model itself can raise the main loop to fable for the rest of a turn through the `route` tool (plan/reflect/escalate/judge) or a background dispatch (derived orchestrate = best tier) — bounded by the turn and `upgradeMaxTokens`, no sticky route is model-callable; (2) `ultrathink` and the default keyword rules now mean "best tier" (fable) at the phase's effort, so an incidental keyword in a pasted composer prompt costs a fable turn (origin composer only). Residuals: `PostModelSwitch` `auto` covers "other programmatic change" (a healthy model could be marked 15 min); strikes never decay inside a session; a `[1m]` variant's `model_not_found` marks the base model until reload; a `models` alias added by the override without a `fallback` key stays unranked (`withEveryAlias` not applied to the default chain) so `leaveDown` skips the upgrade gates for it; `canonical` prefix match has no segment boundary (`claude-sonnet-5-50` would map to sonnet); classifier deferred to W2 +- [ ] W1-C live verification (after `/reload-plugins`, R16/T8): StopFailure vs turn.complete order; `PostModelSwitch` on a rewritten-request fallback and its `from_model`; whether a router rewrite raises `auto`; `[1m]` carry validity on opus; `$.session.model()` string form; the derived orchestrate on a real background dispatch - [ ] W2 migration (after wave 1 proven in daily use): 15 skills `Skill(effort-*)` → `route` tool calls; remove `skills/effort-*`, `lib/effort-pins.txt/.sh`, install/update steps, `effort:` frontmatter on skills and agents; repo agents into the mod's `agents` table (verify the spawn/first-step ordering first); `lib/model-gate.md` + `lib/model-check.sh` → mod rule; census tests repointed; `lib/effort-shift.md` rewritten; docs - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B diff --git a/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md index 8c55109..538ff43 100644 --- a/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md +++ b/.claude/tasks/contracts/2026-10-09-model-router-tiers-1237.md @@ -22,20 +22,27 @@ Q (r2): superseded clauses / A: floor AC4 (`turnMain` sources gain 'derived' and 1. Suite green: `claude plugin test` passes with at least 43 `test(` calls; `claude plugin validate` passes with no warning; no line over 80 chars; no `any` type. CHECK: cd mods/model-router && out=$(claude plugin test . 2>&1); rc=$?; echo "$out" | tail -n 3; [ $rc -eq 0 ] && [ "$(grep -cE '^\s*test\(' hooks/register.test.ts)" -ge 43 ] && v=$(claude plugin validate . 2>&1) && echo "$v" | grep -q 'Validation passed' && ! echo "$v" | grep -qi 'warning' && ! grep -nE '.{81,}' hooks/register.ts hooks/register.test.ts && ! grep -nE ':\s*any\b||as any\b' hooks/register.ts && echo TIERS-SUITE-OK EXPECT: TIERS-SUITE-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: 58 pass 0 fail Ran 58 tests across 1 file. [2.03s] TIERS-SUITE-OK 2. Type-check clean against this build's declarations. CHECK: T=/Users/b.chanot/Documents/claude/mods/model-router/.claude-plugin/types; W=$(mktemp -d) && printf '{"compilerOptions":{"target":"es2023","lib":["es2023"],"types":[],"module":"esnext","moduleResolution":"bundler","strict":true,"noUncheckedIndexedAccess":true,"noEmit":true,"skipLibCheck":true,"jsx":"react","jsxFactory":"h","jsxFragmentFactory":"Fragment"},"include":["%s/claude-code/index.d.ts","%s/claude-code-tools/index.d.ts","%s/hooks"]}' "$T" "$T" "$PWD/mods/model-router" > "$W/tsconfig.json" && (cd "$W" && npx --yes -p typescript@5 tsc -p tsconfig.json) && echo TSC-OK EXPECT: TSC-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: TSC-OK 3. Tiers in the config: `tiers` (best/big/work/cheap), `fallback`, `cooldownMinutes`, `mainUpgrade`, `upgradeMaxTokens` exist in DEFAULT_CONFIG; every default phase names a tier, none a bare model; `/route show` prints the resolved model of each phase and a `down:` line; no `classifier` (deferred to wave 2); no `Loop.model` / `spawnModel` / `loop.model` identifier (W1-A AC8). CHECK: cd mods/model-router/hooks && D=$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts) && echo "$D" | grep -q "tiers:" && echo "$D" | grep -q "fallback:" && grep -q "cooldownMinutes" register.ts && grep -q "mainUpgrade" register.ts && grep -q "upgradeMaxTokens" register.ts && ! grep -q "classifier" register.ts && [ "$(awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -cE "tier: '(best|big|work|cheap)'")" -ge 10 ] && ! awk '/^const DEFAULT_CONFIG/,/^}/' register.ts | grep -qE "model: '(haiku|sonnet|opus|fable)'" && ! grep -qE "loop\.model|explicitModel|spawnModel" register.ts && grep -q "down:" register.ts && echo TIERS-CONFIG-OK EXPECT: TIERS-CONFIG-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: TIERS-CONFIG-OK 4. Tests prove (names contain the quoted word; plan r2 R14 lists them): `tier` — a `plan` route on a session model `claude-haiku-4-5-20251001` makes the main step run on `claude-fable-5-1` at xhigh (upgrade, default on); `downgrade` — a `mechanical` route on a fable session leaves the model unchanged while `mainModelSwitch` is off; `fallback` — with a `plan` route, a `classic.StopFailure` `rate_limit` on main after a fable step makes the next main step run on `claude-opus-5-5` at xhigh, and after `/route reload` fable is used again; `breaker` — an `invalid_request` failure never marks a model down, backoff expiry restores it, a `/model` command (`PostModelSwitch` source `command`) clears it; `engine fallback` — a `PostModelSwitch` with source `auto` marks the model the engine left (one strike, idempotent within the hold) and a plan route does not go back to it; `unknown` — a session model absent from the table is never switched; `spawn` — `Explore` spawns on `claude-opus-5-5` while sonnet is down (agent StopFailure with `agent_id`); `derived` — a main Agent call sets `orchestrate` and the previous `plan` route is back when the spawned agent ends; a route declared after the dispatch is not overwritten by the pop; `default rule` — "planifie la migration" sets `plan` as the turn default and a later route call overrides it; a typed `/analyze …` and a `/effort-low pourquoi …` prompt get no default rule; `per axis` — a model-less sticky never hides a turn route's tier; `floor` tests from B1 still pass. CHECK: cd mods/model-router/hooks && for w in tier downgrade fallback breaker "engine fallback" unknown spawn derived "default rule" "per axis"; do grep -qE "test\('[^']*$w" register.test.ts || { echo "missing test: $w"; exit 1; }; done && [ "$(grep -cE "test\('[^']*(breaker|derived|default rule)" register.test.ts)" -ge 7 ] && echo TIERS-TESTS-OK EXPECT: TIERS-TESTS-OK - EVIDENCE: pending + EVIDENCE: MET exit=0 marker-found :: TIERS-TESTS-OK 5. Judged by reading (plan r2 R1-R15, r3 S1-S11 and r4 T1-T8 are binding; r4 wins over r3, r3 over r2 where they conflict: two fields `turnModel` (sticky, per turn) and `lastPlan` (breaker target, kept), unrouted steps pass `e.model` verbatim, auto marks target the model actually sent and skip when the engine landed where the router was, `sessionModel` preserved across /clear and never prefix-matched when empty, tokens `number | undefined` with windowOk failing closed, episode strikes with `model_not_found` lengthening a hold; no per-step engine-fallback detection, `PostModelSwitch` auto DOES mark one idempotent strike, the main model is sticky within a turn, `sessionModel` cached at start and on PostModelSwitch, D1 for background dispatches via the Agent result status, breaker targets kept until replaced): ONE resolver turns a tier name, an alias or a full id into an AVAILABLE canonical id (tier → list → skip down → id; an exhausted tier → the global chain; a bare alias or id passes through even when down); ids are canonical everywhere (`[1m]` stripped for comparison and carried on the replacement, alias → id, two-way prefix); ONE decision `decideMain(cur, wanted, ctx)` in the binding order (off → unknown cur: no switch → cur down: wanted or next available, windowOk → same alias: keep → better: `mainUpgrade` and `upgradeMaxTokens` → cheaper: `mainModelSwitch` and windowOk), used by `mainPlan` AND by every text; the breaker is fed only by `classic.StopFailure` errors `rate_limit | overloaded | billing_error | model_not_found` (main → the last main plan's model, agent → `agentModels`) and by `PostModelSwitch` `source: 'auto'` (the model the engine left, one strike, idempotent while down); `turn.complete` reasons never mark; a user `/model` (`PostModelSwitch` command|picker|sdk) clears the target's mark; backoff 15 → 30 → 60 → 120 → 300 min per id, `model_not_found` until reload; the breaker survives `/clear` and is cleared by `/route reload` before the config read; the derived `orchestrate` push/pop tracks this turn's spawns and never overwrites a route the model declared after the dispatch; default prompt rules (two passes, absent `mode` = floor, `iu` flags, Unicode guards) write `turnMain` (source 'prompt') and are skipped for a leading `/`, for a prompt carrying a floor or a typed slash, and mid-turn; floor rules write `turnFloor`; no classifier; explicit Agent params still win; agent model fixed at spawn; every B1/1-A criterion still holds EXCEPT the three clauses R15 names (turnMain sources, the switch clause, the window-guard scope); no function over 25 logic lines; truthful texts come from `decideMain` and say `upgrade`, `fallback`, `switch off` or `unchanged`. +Hardening round (security gate 2026-10-09, 3 MEDIUM + 1 LOW accepted) — criteria 6-7, same ledger: +6. (a) `leaveDown` runs a `wanted` that ranks ABOVE cur through the upgrade checks (`mainUpgrade`, `upgradeMaxTokens`, windowOk) before taking it; (b) the upgrade cap fails CLOSED: unknown tokens (`undefined`) → no upgrade, logged once per turn; the test boot answers `session.usage` with a small context so the upgrade tests still run, and one test proves an unanswered usage blocks the upgrade; (c) `canonical` keeps ONE prefix direction only (`bare.startsWith(tableId)`, which covers `[1m]` and dated variants) and `markDown` charges `model_not_found` to the exact id the request carried when that id is not itself a table id (no mark); (d) the once-per-turn log key for "upgrade skipped: context N tokens" is fixed (no N in the key). + CHECK: cd mods/model-router/hooks && ! grep -qE "known\.startsWith\(bare\)|tableId\.startsWith\(bare\)|id\.startsWith\(bare\)" register.ts && grep -qE "test\('[^']*(cap|unknown tokens|usage)" register.test.ts && grep -q "upgrade skipped" register.ts && echo HARDEN-C-OK + EXPECT: HARDEN-C-OK + EVIDENCE: MET exit=0 marker-found :: HARDEN-C-OK +7. Judged by reading: criteria 1-5 still hold (tests ≥ 55 + the new ones green, validate, tsc, style); the `PostModelSwitch` `auto` handling is unchanged and listed for live verification; the two accepted-by-design MEDIUMs (model-initiated upgrades within a turn; `ultrathink` → best tier at max) are recorded in TODO, not coded around. + ## FILE SCOPE mods/model-router/hooks/register.ts · mods/model-router/hooks/register.test.ts From a4f660d0b6adbb48e033b01f90e9dda6bc0055ad Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:14:55 +0200 Subject: [PATCH 044/547] chore(tasks): model-router W1-C live checks part 1 done, part 2 queued; journal --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 8de9176..51d8498 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -586,3 +586,4 @@ rules: - model-router W1-B2 landed (6430ac6): tracked symlink skills/model-router → ../mods/model-router (mode 120000), gitignore, lib/tests/mods.test.sh, doctor Mods section, CLAUDE.md § mods/. Plan r2 (3 lenses, 5 MAJOR), feater DONE, gap round (my `4b.` label unparsed by gates.sh + unbounded probe), verifier CONFORME 8/8, security PASS (LOW: `claude plugin --help` rc 0 weakens the SKIP probe, fail-closed). Dev hot-reload link removed from ~/.claude/dev-mods; user to run /reload-plugins. BDR-115 amended (load, floor, kill switch, hardening). Doc audit (opus) in flight. - model-router wave 1 CLOSED on feature/model-router-mod (15 commits ahead of develop, nothing pushed: manual mode). Docs: opus audit SIGNIFICANT (README Explore row false, no mention of the mod) → user go all 10 → first patch self-reverted by the MINOR-envelope oracle (plan carried MINOR labels; a new heading exceeds the envelope) → re-dispatched with SIGNIFICANT provenance → b22f894. Full `make test`: every suite green except the pre-existing env red design-tool-gate (21st CLI present, not hermetic). Open for the user: /reload-plugins here; merge decision (gitflow finish); settings.json own change; W2 migration queued. - model-router W1-C adaptive tiers landed (d0fa100): plan r1→r4 through 3 lenses (all FATAL: 4 BLOCKER + 20 MAJOR) + 2 confirmations (1 BLOCKER each, in my own r2 then r3) → deviation from the one-confirmation cap, stated. Design: absolute tiers, StopFailure-kind breaker + PostModelSwitch auto, fallback chain, main upgrade under a 200k cap (fails closed), sticky turnModel, derived orchestrate (background dispatches), prompt default rules with skip rules; classifier deferred. feater DONE → 2 gap rounds (texts) → hardening (leaveDown gates, cap fail-closed, one-way prefix, log key) → verifier CONFORME, security PASS (LOW only). 58 tests. Lesson: I sent iteration history in a security brief; the auditor contract forbids it (blind scan) — scope only next time. Live checks pending after /reload-plugins (R16/T8). Next: user reload, live test, wave 2. +- W1-C live checks after the user's /reload-plugins (skills-dir copy, 12 hooks): derived orchestrate real (main high→medium during a background Explore→high after), Explore sonnet/medium, route plan → xhigh, Skill(effort-low) bridge → low, both confirmed in engine records; /route show resolves 10 phases to full ids, down none; steps carry bare ids (no [1m]) → suffix carry inert here. Breaker/auto/StopFailure order wait for a real incident. Branch feature/model-router-mod: 22 commits ahead, unpushed (manual), merge = human signal. Wave 2 queued. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 76874d6..94b4b08 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -15,7 +15,8 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [x] W1 close-out (2026-10-09): doc-sync opus audit SIGNIFICANT → user go all 10 → patched (README effort routing + Explore row + /route, USAGE, ARCHITECTURE mods/, CHANGELOG Unreleased) b22f894; hot-reload link removed from `~/.claude/dev-mods//`; BDR-115 amended (a6e2003). Pending user: `/reload-plugins` in this session (new sessions load the skills-dir copy by themselves); merge decision on feature/model-router-mod (`gitflow finish`, human signal) - [x] W1-C adaptive tiers (user 2026-10-09, contract `2026-10-09-model-router-tiers-1237`, plan r4 after 3 lenses + 2 confirmations: 6 BLOCKER + 29 MAJOR closed by named changes): phases name absolute tiers (best fable>opus>sonnet · big opus>fable>sonnet · work sonnet>opus · cheap haiku>sonnet); breaker fed by `classic.StopFailure` kinds rate_limit|overloaded|billing_error|model_not_found + `PostModelSwitch` auto (episode backoff 15→300 min, `/model` clears, `/clear` keeps, `/route reload` clears); fallback chain fable→opus→sonnet→haiku; main UPGRADE by default under `upgradeMaxTokens` 200k (fails closed on unknown usage), DOWNGRADE gated by `mainModelSwitch`; sticky `turnModel` per turn; derived `orchestrate` on background dispatches; prompt default rules (plan/reflect FR+EN, Unicode guards, skipped on `/…`, floor match, mid-turn). 58 tests; verifier CONFORME then 3 gap/hardening rounds; security PASS - [ ] W1-C accepted-by-design (security 2026-10-09, MEDIUM, not coded around): (1) the model itself can raise the main loop to fable for the rest of a turn through the `route` tool (plan/reflect/escalate/judge) or a background dispatch (derived orchestrate = best tier) — bounded by the turn and `upgradeMaxTokens`, no sticky route is model-callable; (2) `ultrathink` and the default keyword rules now mean "best tier" (fable) at the phase's effort, so an incidental keyword in a pasted composer prompt costs a fable turn (origin composer only). Residuals: `PostModelSwitch` `auto` covers "other programmatic change" (a healthy model could be marked 15 min); strikes never decay inside a session; a `[1m]` variant's `model_not_found` marks the base model until reload; a `models` alias added by the override without a `fallback` key stays unranked (`withEveryAlias` not applied to the default chain) so `leaveDown` skips the upgrade gates for it; `canonical` prefix match has no segment boundary (`claude-sonnet-5-50` would map to sonnet); classifier deferred to W2 -- [ ] W1-C live verification (after `/reload-plugins`, R16/T8): StopFailure vs turn.complete order; `PostModelSwitch` on a rewritten-request fallback and its `from_model`; whether a router rewrite raises `auto`; `[1m]` carry validity on opus; `$.session.model()` string form; the derived orchestrate on a real background dispatch +- [x] W1-C live verification part 1 (2026-10-09 after `/reload-plugins`, skills-dir copy loaded, 12 hooks): derived orchestrate on a real background Explore (main high → medium while it ran → high after its end); Explore on sonnet/medium; `route plan` → next request xhigh (engine record); `Skill(effort-low)` bridged → next request low (engine record); `/route show` resolves all 10 phases to full ids, `down: none`; steps arrive as bare `claude-fable-5-1` (no `[1m]`) so the suffix carry never fires on this session +- [ ] W1-C live verification part 2 (needs a real incident): StopFailure vs turn.complete order; `PostModelSwitch` `auto` semantics and its `from_model` after a router upgrade; whether a router rewrite raises `auto`; `[1m]` carry validity on opus (only on a session whose steps carry it) - [ ] W2 migration (after wave 1 proven in daily use): 15 skills `Skill(effort-*)` → `route` tool calls; remove `skills/effort-*`, `lib/effort-pins.txt/.sh`, install/update steps, `effort:` frontmatter on skills and agents; repo agents into the mod's `agents` table (verify the spawn/first-step ordering first); `lib/model-gate.md` + `lib/model-check.sh` → mod rule; census tests repointed; `lib/effort-shift.md` rewritten; docs - [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B From ff741e3a82d8d7e0c79725ab8198072ff011239b Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:25:39 +0200 Subject: [PATCH 045/547] =?UTF-8?q?chore(memory):=20journal=20=E2=80=94=20?= =?UTF-8?q?model-router=20wave=201=20merged=20into=20develop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 51d8498..be391c9 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -587,3 +587,4 @@ rules: - model-router wave 1 CLOSED on feature/model-router-mod (15 commits ahead of develop, nothing pushed: manual mode). Docs: opus audit SIGNIFICANT (README Explore row false, no mention of the mod) → user go all 10 → first patch self-reverted by the MINOR-envelope oracle (plan carried MINOR labels; a new heading exceeds the envelope) → re-dispatched with SIGNIFICANT provenance → b22f894. Full `make test`: every suite green except the pre-existing env red design-tool-gate (21st CLI present, not hermetic). Open for the user: /reload-plugins here; merge decision (gitflow finish); settings.json own change; W2 migration queued. - model-router W1-C adaptive tiers landed (d0fa100): plan r1→r4 through 3 lenses (all FATAL: 4 BLOCKER + 20 MAJOR) + 2 confirmations (1 BLOCKER each, in my own r2 then r3) → deviation from the one-confirmation cap, stated. Design: absolute tiers, StopFailure-kind breaker + PostModelSwitch auto, fallback chain, main upgrade under a 200k cap (fails closed), sticky turnModel, derived orchestrate (background dispatches), prompt default rules with skip rules; classifier deferred. feater DONE → 2 gap rounds (texts) → hardening (leaveDown gates, cap fail-closed, one-way prefix, log key) → verifier CONFORME, security PASS (LOW only). 58 tests. Lesson: I sent iteration history in a security brief; the auditor contract forbids it (blind scan) — scope only next time. Live checks pending after /reload-plugins (R16/T8). Next: user reload, live test, wave 2. - W1-C live checks after the user's /reload-plugins (skills-dir copy, 12 hooks): derived orchestrate real (main high→medium during a background Explore→high after), Explore sonnet/medium, route plan → xhigh, Skill(effort-low) bridge → low, both confirmed in engine records; /route show resolves 10 phases to full ids, down none; steps carry bare ids (no [1m]) → suffix carry inert here. Breaker/auto/StopFailure order wait for a real incident. Branch feature/model-router-mod: 22 commits ahead, unpushed (manual), merge = human signal. Wave 2 queued. +- User go 'ok merge': full make test green (except env red design-tool-gate), shellcheck clean → gitflow finish feature model-router-mod → develop abbdf79 (22 commits: waves 0, 1-A, 1-B1, 1-B2, 1-C + docs + registries). Manual mode: develop NOT pushed, the user publishes by hand from the terminal. Branch removed locally. User will /clear before wave 2. From efdd491d639b8bb8ff72a320799dc8f53a6f0bc6 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:31:26 +0200 Subject: [PATCH 046/547] fix(make): test target names every red suite and prints a summary A full make test printed only the == headers and an aggregate exit code, so finding the red suite meant re-running every suite one by one (the pre-merge check of 2026-10-09 took 7.5 min for that reason). The loop now prints FAIL as it happens and ends with 'all suites green' or ' suite(s) red: '; the exit code is unchanged. --- Makefile | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 2141a32..6aa49f1 100644 --- a/Makefile +++ b/Makefile @@ -34,12 +34,15 @@ test: ## Run deterministic tests hermetically (one: make test suite=lib/tests/x. @# fire inside the throwaway repos the suites build. The export lives @# HERE so nobody has to type the (denied) env-prefix form by hand. @export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null; \ - fail=0; for t in $(or $(suite),$(SUITES)); do \ + fail=0; red=""; for t in $(or $(suite),$(SUITES)); do \ echo "== $$t"; \ case "$$(basename "$$t")" in \ - run-release-candidate.sh) RC_WORK=$$(mktemp -d) RC_TAG=1 bash "$$t" || fail=1 ;; \ - *) bash "$$t" || fail=1 ;; \ - esac; done; exit $$fail + run-release-candidate.sh) RC_WORK=$$(mktemp -d) RC_TAG=1 bash "$$t" || { fail=1; red="$$red $$t"; echo "FAIL $$t"; } ;; \ + *) bash "$$t" || { fail=1; red="$$red $$t"; echo "FAIL $$t"; } ;; \ + esac; done; \ + if [ $$fail -eq 0 ]; then echo "all suites green"; \ + else echo "$$(echo $$red | wc -w | tr -d ' ') suite(s) red:$$red"; fi; \ + exit $$fail scan-secrets: ## Gitleaks sweep: this repo's history + ~/.claude. Extra repos: make scan-secrets repos="path1 path2" @command -v gitleaks >/dev/null 2>&1 || { echo "gitleaks not installed — https://github.com/gitleaks/gitleaks"; exit 1; } From b09e84497a85e0833eccdc274c12b835761408b3 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:31:27 +0200 Subject: [PATCH 047/547] =?UTF-8?q?chore(memory):=20journal=20=E2=80=94=20?= =?UTF-8?q?make=20test=20summary=20hotfix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + ...6-10-09-make-test-names-red-suites-1528.md | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 .claude/tasks/contracts/2026-10-09-make-test-names-red-suites-1528.md diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index be391c9..7d7de3e 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -588,3 +588,4 @@ rules: - model-router W1-C adaptive tiers landed (d0fa100): plan r1→r4 through 3 lenses (all FATAL: 4 BLOCKER + 20 MAJOR) + 2 confirmations (1 BLOCKER each, in my own r2 then r3) → deviation from the one-confirmation cap, stated. Design: absolute tiers, StopFailure-kind breaker + PostModelSwitch auto, fallback chain, main upgrade under a 200k cap (fails closed), sticky turnModel, derived orchestrate (background dispatches), prompt default rules with skip rules; classifier deferred. feater DONE → 2 gap rounds (texts) → hardening (leaveDown gates, cap fail-closed, one-way prefix, log key) → verifier CONFORME, security PASS (LOW only). 58 tests. Lesson: I sent iteration history in a security brief; the auditor contract forbids it (blind scan) — scope only next time. Live checks pending after /reload-plugins (R16/T8). Next: user reload, live test, wave 2. - W1-C live checks after the user's /reload-plugins (skills-dir copy, 12 hooks): derived orchestrate real (main high→medium during a background Explore→high after), Explore sonnet/medium, route plan → xhigh, Skill(effort-low) bridge → low, both confirmed in engine records; /route show resolves 10 phases to full ids, down none; steps carry bare ids (no [1m]) → suffix carry inert here. Breaker/auto/StopFailure order wait for a real incident. Branch feature/model-router-mod: 22 commits ahead, unpushed (manual), merge = human signal. Wave 2 queued. - User go 'ok merge': full make test green (except env red design-tool-gate), shellcheck clean → gitflow finish feature model-router-mod → develop abbdf79 (22 commits: waves 0, 1-A, 1-B1, 1-B2, 1-C + docs + registries). Manual mode: develop NOT pushed, the user publishes by hand from the terminal. Branch removed locally. User will /clear before wave 2. +- /hotfix make-test-names-red-suites (user: '9 min pour un merge?'): measured from transcript timestamps, the merge took <20 s; 454 s went to make test run TWICE (full + per-suite sweep to name the red suite, because the aggregate rc is silent). Fix: Makefile test prints FAIL + summary, rc unchanged (GNU make returns 2 on a failed recipe; my first oracle expected 1). hotfixer DONE, GATE 0 MET 2/2, security PASS. Branch bugfix/make-test-names-red-suites UNMERGED (human signal). Method note: a mods/-only diff needs only the mods suite + doctrine census, the full run once before merge. diff --git a/.claude/tasks/contracts/2026-10-09-make-test-names-red-suites-1528.md b/.claude/tasks/contracts/2026-10-09-make-test-names-red-suites-1528.md new file mode 100644 index 0000000..b9d93f1 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-09-make-test-names-red-suites-1528.md @@ -0,0 +1,24 @@ +# CONTRACT — make-test-names-red-suites +- date: 2026-10-09 | flow: hotfix | branch: bugfix/make-test-names-red-suites +- status: active + +## REQUEST (verbatim — IMMUTABLE) +Skill args: "Makefile `test` target: print `FAIL ` for every red suite and a final summary line (` suite(s) red: ` or `all suites green`) so a full `make test` names the failing suites itself; exit code unchanged (1 on any red). Today only `== ` headers print and the aggregate rc forces a second per-suite run to find the red one." +User (fr): "c'est quand meme long 9 min pour faire un merge non ? … ou est le bottlneck ?" → measured: the pre-merge `make test` (454 s) was a full run PLUS a per-suite re-run to name the red suite; "oui vas y fait le maintenant". + +## CLARIFICATIONS +Q: wording / A: given by the request: `FAIL ` per red suite right after it runs, then one summary line ` suite(s) red: ` or `all suites green`. [user] +Q: exit code / A: unchanged: 1 when any suite is red, 0 otherwise. [user] + +## ACCEPTANCE CRITERIA +1. Symptom gone: a run with one red suite prints `FAIL ` and `1 suite(s) red: ` and exits non-zero (GNU make reports a failed recipe as 2); a run with only green suites prints `all suites green` and exits 0. Checked on a two-suite fixture through `make test suite=" "`-style invocations (the `suite` variable already accepts a list). + CHECK: cd /Users/b.chanot/Documents/claude && W=$(mktemp -d) && printf '#!/usr/bin/env bash\nexit 0\n' > "$W/green.test.sh" && printf '#!/usr/bin/env bash\nexit 1\n' > "$W/red.test.sh" && out=$(make test suite="$W/green.test.sh $W/red.test.sh" 2>&1); rc=$?; [ $rc -ne 0 ] && echo "$out" | grep -q "^FAIL $W/red.test.sh" && echo "$out" | grep -q "1 suite(s) red: $W/red.test.sh" && out2=$(make test suite="$W/green.test.sh" 2>&1); rc2=$?; [ $rc2 -eq 0 ] && echo "$out2" | grep -q "all suites green" && echo SUMMARY-OK + EXPECT: SUMMARY-OK + EVIDENCE: MET exit=0 marker-found :: SUMMARY-OK +2. Build/tests green: the Makefile still runs the real suites (`make test suite=lib/tests/mods.test.sh` exits 0 and prints `all suites green`); `make -n test` parses. + CHECK: cd /Users/b.chanot/Documents/claude && make -n test >/dev/null && out=$(make test suite=lib/tests/mods.test.sh 2>&1); rc=$?; [ $rc -eq 0 ] && echo "$out" | grep -q "all suites green" && echo REAL-SUITE-OK + EXPECT: REAL-SUITE-OK + EVIDENCE: MET exit=0 marker-found :: REAL-SUITE-OK + +## FILE SCOPE +Makefile From ca9645833c3b271c63bfcb1043b1b27446960cb2 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:36:59 +0200 Subject: [PATCH 048/547] =?UTF-8?q?chore(memory):=20LRN-207/208/209=20+=20?= =?UTF-8?q?EVAL-041=20=E2=80=94=20availability=20signal,=20blind=20securit?= =?UTF-8?q?y=20brief,=20scoped=20test=20runs,=20W1-C=20challenge=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/evals.md | 8 ++++++++ .claude/memory/learnings.md | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index d0078a9..951f19b 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -61,6 +61,7 @@ rules: | EVAL-038 | 2026-09-29 | correction of EVAL-037: 94 % of sub-agent usage records carry no `output_tokens_details` (Fable subs at xhigh read 0 thinking, impossible with always-on thinking) → sub-agent thinking UNMEASURED, not ≈0; main loop 100 % counted; weighted-cost split (61/39) still holds | `effort-audit.py` prints coverage + CAVEAT; cite the cost split only; agent effort pins stay unmeasured; a tier move on a price argument = judgment, not figure | | EVAL-039 | 2026-09-30 | ship-feature run higgsfield-pack: plan dry-run in scratch → 0 executor failure on 7 tasks; challenge found 7 MAJOR I missed; floor-guard caught 2 shellcheck suppressions of mine; final review found README/code gap | keep | | EVAL-040 | 2026-10-08 | model-router w1a plan: 3 challengers + 1 confirmation found 2 BLOCKER + 14 MAJOR on a plan judged closed; executor then passed every gate first time | keep the round, never dispatch a mod plan without it | +| EVAL-041 | 2026-10-09 | model-router W1-C plan: 3 lenses FATAL (4 BLOCKER + 20 MAJOR) then 2 confirmations each FATAL with a NEW BLOCKER in my own revision; executor DONE first pass, 3 short text/hardening rounds | one confirmation is not enough when a revision removes a whole mechanism; the plan carried the risk, the code almost none | --- @@ -379,3 +380,10 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Anomaly**: r1 carried 2 BLOCKER (explicit Agent `model` overridden at every step; Skill bridge answer shape refused by the output schema → doublon kept) + 10 MAJOR, all invisible to me: spike levers carried over as design (`agentsNext`, per-step model rewrite), a table copying 21 pins = third source of truth, writes on main from sub-agent loops. Confirmation found 4 more MAJOR (explicit params vs in-agent writes, `e.wait`, vacuous test assertions, haiku effort). Executor then DONE first pass, verifier CONFORME 6/6, security PASS: the plan was the whole risk. - **Action**: a mod plan always goes through the full round + confirmation; test assertions must read the one line that carries the value; spike code is a FACT source, never a design source ([[BDR-115]], [[LRN-205]], [[LRN-206]]). +## EVAL-041 — model-router W1-C: the plan was the whole risk, two confirmations were needed +- **Date**: 2026-10-09 +- **Output checked**: plan `.claude/tasks/plans/2026-10-09-model-router-tiers-1237.md` r1 → r4 (absolute tiers, breaker, derived phases), written with every engine fact in hand. +- **Method**: 3 blind opus challengers (simplicity FATAL(6), correctness FATAL(11), robustness FATAL(11)) → r2; confirmation FATAL(8) with a NEW BLOCKER introduced by r2 (per-step engine-fallback detection climbing the backoff) → r3; second confirmation FATAL(4) with a NEW BLOCKER introduced by r3 (`lastPlan` reset vs kept) → r4; executor DONE first pass; verifier ECARTS ×2 on texts (3 gaps) + hardening (4 items) → CONFORME; security PASS. +- **Anomaly**: 6 BLOCKER + 29 MAJOR over four revisions, each confirmation found a flaw my own fix had introduced; the doctrine cap (one confirmation) would have shipped r2 with a 5-hour false outage. The executor never needed a re-dispatch for logic: all later rounds were text truthfulness and hardening. +- **Action**: when a revision REMOVES or REPLACES a mechanism, re-challenge once more (state the deviation); keep plan sections additive with an explicit precedence line (r4 > r3 > r2) so executors and verifiers read one law; name superseded clauses of prior contracts in the Disposition. Links [[EVAL-040]], [[LRN-207]], [[BDR-115]]. + diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 91110c6..60a6a7f 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1765,3 +1765,15 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s - **Context**: model-router tests. Kit `$` is `EngineCall = (e: Args)`: `command.run` needs `origin` + `presentation`, `prompt.submit` needs `wait` + `origin`, `agent.spawn` needs `tool_use_id, description, provider, parentModel, background, fork`; the test file is type-checked with the hooks (tsc include). `session.start` does NOT fire at load → every test boots with a bottom `on('session.start')` + `$.session.start({ cwd, surface: null, isInteractive: false })`. A hook calling `next` hits the kit's bottom which throws unless the test registered one (`on('agent.spawn', ($, e) => ({ model: e.model, agentId: 'a1' }))`). `$.turn.step` returns a stream: drain with `for await` then await `.result` (awaiting `.result` alone runs no hook). No fs/network/process: defaults path only. Assert on the ONE line that carries the value (a `show()` listing every phase always contains every id and level). - **Apply**: write the boot helper first, type every input from the declarations, never relax a test to dodge a type. Links [[BDR-115]]. +## LRN-207 — Model availability = typed API errors (`classic.StopFailure` rate_limit|overloaded|billing_error|model_not_found) + `PostModelSwitch auto`; never the turn-end reason, never `rateLimits`; sticky state and breaker target = two fields +- **Context**: model-router W1-C. `turn.complete reason: error` covers context-limit and network errors → a breaker fed by it marked fable down 15 min on a context overflow (challenge r1). `rateLimits` kinds are account windows (five_hour, seven_day, spend_limit), not per model. A per-step "engine fallback detection" (`e.model` ≠ `$.session.model()`) re-marked the session model at EVERY step → backoff climbed to the 5 h cap in one turn (confirmation r2). One field used both as sticky cur and as breaker target contradicted itself (reset at turn end vs kept). +- **Apply**: feed a breaker only from typed error kinds that name unavailability; mark per EPISODE (idempotent while down), backoff 15→300 min, `model_not_found` until reload; a user `/model` clears, `/clear` keeps (account-wide). Keep `turnModel` (sticky, reset per turn) and `lastPlan` (breaker target, kept) separate; unrouted steps pass `e.model` verbatim so the engine's own fallback is respected. Links [[BDR-115]], [[LRN-204]]. + +## LRN-208 — Security-auditor brief = scope only; iteration history and claimed closures violate the blind-scan contract +- **Context**: W1-C gate 2026-10-09. I sent "previous PASS with 6 MEDIUM, closed: …" in the brief. Auditor: "The auditor contract says that is never sent and must be ignored … Please do not send it next time" (it scanned blind anyway). Same rule as the verifier (lib/verify-secure-loop.md: fresh, no history). +- **Apply**: SCOPE + a neutral CONTEXT of what the code does; never prior verdicts, closures or accepted residuals. Residuals live in TODO, the auditor rediscovers them (that is the point). Links [[LRN-083]]. + +## LRN-209 — Scope the test run to the diff; one full `make test` before the merge; `make test` now names the red suite; GNU make rc 2 on a failed recipe +- **Context**: 2026-10-09 the pre-merge check took 454 s = full `make test` (48 suites) + a per-suite re-run to NAME the red one (aggregate rc, permanent env red design-tool-gate). Three more full passes earlier that day for mods/-only diffs. Hotfix efdd491: the recipe prints `FAIL ` + `all suites green` / ` suite(s) red: …`. My oracle expected rc 1; GNU make returns 2 when a recipe line fails. +- **Apply**: a diff confined to one component runs that component's suite + the doctrine census; the full suite runs ONCE before `gitflow finish`; read the FAIL lines, never re-run per suite. Oracles on `make` test `[ $rc -ne 0 ]`, not `-eq 1`. Links [[LRN-173]]. + From 862740da9da929335c54e679ff9386d2b790ca63 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 15:37:29 +0200 Subject: [PATCH 049/547] =?UTF-8?q?chore(memory):=20journal=20=E2=80=94=20?= =?UTF-8?q?make=20test=20hotfix=20merged,=20session=20close=20before=20wav?= =?UTF-8?q?e=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 7d7de3e..ed2aedc 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -589,3 +589,4 @@ rules: - W1-C live checks after the user's /reload-plugins (skills-dir copy, 12 hooks): derived orchestrate real (main high→medium during a background Explore→high after), Explore sonnet/medium, route plan → xhigh, Skill(effort-low) bridge → low, both confirmed in engine records; /route show resolves 10 phases to full ids, down none; steps carry bare ids (no [1m]) → suffix carry inert here. Breaker/auto/StopFailure order wait for a real incident. Branch feature/model-router-mod: 22 commits ahead, unpushed (manual), merge = human signal. Wave 2 queued. - User go 'ok merge': full make test green (except env red design-tool-gate), shellcheck clean → gitflow finish feature model-router-mod → develop abbdf79 (22 commits: waves 0, 1-A, 1-B1, 1-B2, 1-C + docs + registries). Manual mode: develop NOT pushed, the user publishes by hand from the terminal. Branch removed locally. User will /clear before wave 2. - /hotfix make-test-names-red-suites (user: '9 min pour un merge?'): measured from transcript timestamps, the merge took <20 s; 454 s went to make test run TWICE (full + per-suite sweep to name the red suite, because the aggregate rc is silent). Fix: Makefile test prints FAIL + summary, rc unchanged (GNU make returns 2 on a failed recipe; my first oracle expected 1). hotfixer DONE, GATE 0 MET 2/2, security PASS. Branch bugfix/make-test-names-red-suites UNMERGED (human signal). Method note: a mods/-only diff needs only the mods suite + doctrine census, the full run once before merge. +- User go 'all, merge le, et je clear': LRN-207/208/209 + EVAL-041 written (ca96458); gitflow finish bugfix/make-test-names-red-suites → develop 5e0e5c0, branch removed. develop 28 commits ahead of origin, NOT pushed (manual mode, user publishes). Only settings.json dirty (user's own /model change). Session closes; next: wave 2 of model-router (TODO W2 line). From bb56f3e41e0697b6d5b89cb61c2e4cca4b7a65ad Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 17:22:07 +0200 Subject: [PATCH 050/547] =?UTF-8?q?feat(model-router):=20wave=202-A=20?= =?UTF-8?q?=E2=80=94=20phase=20rows=20for=20every=20repo=20skill=20and=20a?= =?UTF-8?q?gent,=20run=20slot,=20typed-slash=20routing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rows by role replace the pins as the live source (frontmatter stays as the off-state floor): phases write=work/high and apply=work/low, 56 skill rows, 21 agent rows + Explore/Plan. Agents get the row's model at spawn (within the tier, upward only, explicit params win, project-defined agents skipped via agent.offer) and its effort per step. A typed slash of a rowed skill routes main through a name-bound marker (composer|sdk|bridge, pending slot mid-turn) or the idle fallback; a best-tier row lives in a runMain slot that survives turn end and route calls. An unrowed skill leaves the route. Typed /effort-* floor code removed (bridge kept until W2-B). The route answer always names the id. Override rows accept null. Kit suite 58 → 88. Contract .claude/tasks/contracts/2026-10-09-model-router-w2a-1546.md, plan r4 .claude/tasks/plans/2026-10-09-model-router-w2-1546.md: 3 lenses + 2 confirmations, feater + 4 rounds, GATE 0 MET, verifier 3x ECARTS on test coverage only (user-accepted at the cap), security PASS. --- mods/model-router/hooks/register.test.ts | 524 ++++++++++++++++++++--- mods/model-router/hooks/register.ts | 430 ++++++++++++++----- 2 files changed, 783 insertions(+), 171 deletions(-) diff --git a/mods/model-router/hooks/register.test.ts b/mods/model-router/hooks/register.test.ts index d85b9a2..bebc952 100644 --- a/mods/model-router/hooks/register.test.ts +++ b/mods/model-router/hooks/register.test.ts @@ -23,6 +23,8 @@ async function boot( on('session.model', () => ({ value: model })) on('classic.StopFailure', () => ({})) on('classic.PostModelSwitch', () => ({})) + on('skill.prompt', ($, e) => ({ text: e.text })) + on('agent.offer', () => ({ isOffered: true })) if (tokens !== null) usageOf(on, tokens) on('session.start', ($, e) => ({ cwd: e.cwd })) await $.session.start({ cwd: '/tmp', surface: null, isInteractive: false }) @@ -321,30 +323,14 @@ test('floor: ultrathink survives a model route', async ($, on) => { expect(await stepEffort($, seen)).toBe('max') }) -test('floor: typed /effort-medium clamps low, lets max pass', async ( +test('floor: survives a skill load; an unrowed skill keeps the route', async ( $, on) => { - const seen = await bootFloor($, on) - await $.skill.prompt({ skill: 'effort-medium', text: 'x' }) - await $.tool.call({ tool: ROUTE_TOOL, phase: 'mechanical' }) - expect(await stepEffort($, seen)).toBe('medium') - await $.tool.call({ tool: ROUTE_TOOL, phase: 'escalate' }) - expect(await stepEffort($, seen)).toBe('max') -}) - -test('floor: typed /effort-low lowers an unrouted turn', async ($, on) => { - const seen = await bootFloor($, on) - const out = await $.skill.prompt({ skill: 'effort-low', text: 'x' }) - expect(out.text).toContain('minimum') - expect(await stepEffort($, seen)).toBe('low') -}) - -test('floor: survives a skill load', async ($, on) => { const seen = await bootFloor($, on) await ultrathink($) await $.tool.call({ tool: ROUTE_TOOL, phase: 'orchestrate' }) await $.tool.call({ tool: 'Skill', skill: 'other' }) expect(await stepEffort($, seen)).toBe('max') - expect(mainLine(await route($, 'show'))).not.toContain('orchestrate') + expect(mainLine(await route($, 'show'))).toContain('model orchestrate') }) test('floor: lifts a lower sticky, then ends with the turn', async ( @@ -439,35 +425,6 @@ test('reload with an unreadable override keeps the previous config', async ( expect(await route($, 'show')).toContain('switch: on') }) -test('typed marker: a preload in a live agent is ignored', async ($, on) => { - const seen = await bootFloor($, on) - await $.agent.spawn(spawnInput()) - const out = await $.skill.prompt({ skill: 'effort-max', text: 'x' }) - expect(out.text?.startsWith('model-router: effort-max preload')).toBe(true) - expect(mainLine(await route($, 'show'))).not.toContain('floor') - expect(await stepEffort($, seen)).not.toBe('max') -}) - -test('typed marker: /effort-max seen at submit writes the floor', async ( - $, on) => { - await bootFloor($, on) - await $.agent.spawn(spawnInput()) - await $.prompt.submit({ - text: '/effort-max go', - wait: false, - origin: { kind: 'composer' }, - }) - await $.skill.prompt({ skill: 'effort-max', text: 'x' }) - expect(mainLine(await route($, 'show'))).toContain('floor max') -}) - -test('typed slash with no agent and no marker writes the floor', async ( - $, on) => { - await bootFloor($, on) - await $.skill.prompt({ skill: 'effort-max', text: 'x' }) - expect(mainLine(await route($, 'show'))).toContain('floor max') -}) - // ---- tiers, breaker, derived phases ------------------------------------- type Rig = { seen: Seen[]; clock: MockClock; specs: (string | undefined)[] } @@ -766,16 +723,6 @@ test('default rule: a typed slash command gets no default rule', async ( expect(mainLine(await route($, 'show'))).toContain('session defaults') }) -test('default rule: /effort-low pourquoi sets the floor, no default', async ( - $, on) => { - await bootRig($, on) - await typed($, '/effort-low pourquoi ça plante') - await $.skill.prompt({ skill: 'effort-low', text: 'x' }) - const line = mainLine(await route($, 'show')) - expect(line).toContain('floor low') - expect(line).not.toContain('reflect') -}) - test('per axis: a model-less sticky never hides a turn route tier', async ( $, on) => { const rig = await bootRig($, on, HAIKU) @@ -844,3 +791,466 @@ test('text: show names the model a floor upgrade moves to', async ( const line = mainLine(await route($, 'show')) expect(line).toContain(`${FABLE} (upgrade)`) }) + +// ---- wave 2: skill rows, run slot, agent rows --------------------------- + +const skillPrompt = ($: Engine, skill: string) => + $.skill.prompt({ skill, text: 'x' }) + +const loadSkill = ($: Engine, skill: string, agentId?: string) => + $.tool.call({ + tool: 'Skill', + skill, + ...(agentId === undefined ? {} : { agentId }), + }) + +/** bootRig plus a bottom Skill tool, so a model-loaded skill goes through. */ +async function bootRun($: Engine, on: On, model: string = FABLE) { + on('tool.call', { tool: 'Skill' }, () => ({ + result: { success: true, commandName: 'bottom' }, + })) + return bootRig($, on, model) +} + +const spawnOf = (agent: string, extra: object = {}) => + ({ ...spawnInput(), subagentType: agent, ...extra }) + +const offerOf = ($: Engine, agent: string, source: string) => + $.agent.offer({ + agent, + description: 'd', + source, + provider: { plugin: 'engine', tier: 'core' }, + }) + +/** + * A ui.log recorder. The kit refuses a bottom hook for a void event, so the + * hook sits on top and swallows the missing implementation below it. + */ +function recordLogs(on: On): string[] { + const lines: string[] = [] + on('ui.log', async ($, e, next) => { + lines.push(e.text) + try { + await next(e) + } catch { + // nothing implements ui.log below the recorder in the kit + } + }) + return lines +} + +test('typed /feat routes main to its row, best tier', async ($, on) => { + await bootRun($, on) + await typed($, '/feat add a thing') + await skillPrompt($, 'feat') + const line = mainLine(await route($, 'show')) + expect(line).toContain('skill reflect') + expect(line).toContain('effort high') + expect(line).toContain('[tier best]') +}) + +test('typed slash: a foreign origin arms nothing, fallback refused', async ( + $, on) => { + await bootRun($, on) + await $.prompt.submit({ + text: '/feat x', + wait: false, + origin: { kind: 'channel', server: 'slack' }, + }) + await skillPrompt($, 'feat') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('typed slash: a preload in a live sub-agent leaves main alone', async ( + $, on) => { + await bootRun($, on) + await typed($, 'hello') + await $.agent.spawn(spawnOf('feater')) + await skillPrompt($, 'feat') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('typed slash: no live loop and an allowed origin still routes', async ( + $, on) => { + await bootRun($, on) + await typed($, 'hello') + await skillPrompt($, 'feat') + expect(mainLine(await route($, 'show'))).toContain('skill reflect') +}) + +test('typed slash: an sdk origin arms the marker', async ($, on) => { + await bootRun($, on) + await $.prompt.submit({ + text: '/status', + wait: false, + origin: { kind: 'sdk' }, + }) + await $.agent.spawn(spawnOf('feater')) + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('skill mechanical') +}) + +test('typed slash: a mid-turn /status waits for the turn end', async ( + $, on) => { + await bootRun($, on) + await $.prompt.submit({ + text: '/status', + wait: true, + origin: { kind: 'composer' }, + turnId: 'u1', + }) + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('session defaults') + await endTurn($) + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('skill mechanical') +}) + +test('skill without a row keeps the route; a rowed one replaces it', async ( + $, on) => { + await bootRun($, on) + await $.tool.call({ tool: ROUTE_TOOL, phase: 'plan' }) + await loadSkill($, 'find-docs') + expect(mainLine(await route($, 'show'))).toContain('model plan') + await loadSkill($, 'gitflow') + expect(mainLine(await route($, 'show'))).toContain('skill implement') +}) + +test('run slot: survives route calls and the turn end', async ($, on) => { + await bootRun($, on) + await loadSkill($, 'feat') + await $.tool.call({ tool: ROUTE_TOOL, phase: 'orchestrate' }) + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('run reflect') + await $.tool.call({ tool: ROUTE_TOOL, phase: 'plan' }) + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('run reflect') +}) + +test('run slot: a model-loaded helper skill keeps it', async ($, on) => { + await bootRun($, on) + await loadSkill($, 'feat') + await loadSkill($, 'using-git-worktrees') + expect(mainLine(await route($, 'show'))).toContain('skill mechanical') + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('run reflect') +}) + +test('run slot: a typed non-best skill drops it', async ($, on) => { + await bootRun($, on) + await loadSkill($, 'feat') + await endTurn($) + await typed($, '/status') + await skillPrompt($, 'status') + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('run slot: /route clear and /route off drop it', async ($, on) => { + await bootRun($, on) + await loadSkill($, 'feat') + expect(await route($, 'clear')).toContain('run slot dropped') + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('session defaults') + await loadSkill($, 'feat') + await route($, 'off') + await route($, 'on') + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('run slot: a user /model switch drops it, an auto one does not', async ( + $, on) => { + await bootRun($, on) + await loadSkill($, 'feat') + await endTurn($) + await switchTo($, FABLE, OPUS, 'auto') + expect(mainLine(await route($, 'show'))).toContain('run reflect') + await switchTo($, FABLE, OPUS, 'command') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('run slot: a Skill call inside a sub-agent never touches it', async ( + $, on) => { + await bootRun($, on) + await loadSkill($, 'feat', 'a1') + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('run slot: route(clear) clears the turn and names the run', async ( + $, on) => { + await bootRun($, on) + await loadSkill($, 'feat') + const out = await $.tool.call({ tool: ROUTE_TOOL, clear: true }) + expect(JSON.stringify(out)).toContain('run reflect still holds') +}) + +test('Skill(effort-low) bridge is not sticky', async ($, on) => { + await bootRun($, on) + await loadSkill($, 'effort-low') + expect(mainLine(await route($, 'show'))).toContain('effort low') + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('route answer names the id even with a floor in force', async ( + $, on) => { + await bootRun($, on) + await ultrathink($) + const out = await $.tool.call({ tool: ROUTE_TOOL, phase: 'plan' }) + const text = JSON.stringify(out) + expect(text).toContain(`model ${FABLE}`) + expect(text).toContain('user floor max') +}) + +test('agent row: feater spawns on sonnet and steps at medium', async ( + $, on) => { + const rig = await bootRun($, on) + const out = await $.agent.spawn(spawnOf('feater')) + expect(rig.specs).toEqual([SONNET]) + expect(out.model).toBe(SONNET) + await runStep($, { ...highStep('a1'), model: SONNET }) + expect(rig.seen[rig.seen.length - 1]).toEqual({ + model: SONNET, + effort: 'medium', + }) +}) + +/** Spawn feater, load a skill inside it, return the effort of its step. */ +async function effortAfterSkill($: Engine, on: On, skill: string) { + const rig = await bootRun($, on) + await $.agent.spawn(spawnOf('feater')) + await loadSkill($, skill, 'a1') + await runStep($, { ...highStep('a1'), model: SONNET }) + return rig.seen[rig.seen.length - 1].effort +} + +test('agent skill: an unrowed one leaves the loop effort', async ($, on) => { + expect(await effortAfterSkill($, on, 'find-docs')).toBe('medium') +}) + +test('agent skill: a rowed one writes the loop effort', async ($, on) => { + expect(await effortAfterSkill($, on, 'status')).toBe('low') +}) + +test('agent row: judge moves up to fable when opus is down', async ( + $, on) => { + const rig = await bootRun($, on) + await switchTo($, OPUS, SONNET, 'auto') + await $.agent.spawn(spawnOf('plan-challenger')) + expect(rig.specs).toEqual([FABLE]) +}) + +test('agent row: opus and fable down, no write and one log line', async ( + $, on) => { + const logs = recordLogs(on) + const rig = await bootRun($, on) + await switchTo($, OPUS, SONNET, 'auto') + await switchTo($, FABLE, SONNET, 'auto') + await $.agent.spawn(spawnOf('plan-challenger')) + await $.agent.spawn(spawnOf('plan-challenger')) + expect(rig.specs).toEqual([undefined, undefined]) + const down = logs.filter(l => l.includes('frontmatter model kept')) + expect(down).toEqual([ + 'model-router: plan-challenger tier big down, frontmatter model kept', + ]) +}) + +test('agent row: explicit model, explicit effort and fork win', async ( + $, on) => { + const rig = await bootRun($, on) + await $.agent.spawn(spawnOf('feater', { model: 'opus' })) + await $.agent.spawn(spawnOf('feater', { fork: true })) + expect(rig.specs).toEqual(['opus', undefined]) + await $.tool.call({ + tool: 'Agent', + description: 'd', + prompt: 'p', + effort: 'low', + tool_use_id: 't1', + }) + await $.agent.spawn(spawnOf('feater')) + await runStep($, { ...highStep('a1'), model: SONNET }) + expect(rig.seen[rig.seen.length - 1]?.effort).toBe('high') +}) + +test('agent row: a project definition keeps its own model', async ($, on) => { + const rig = await bootRun($, on) + await offerOf($, 'verifier', 'projectSettings') + await offerOf($, 'feater', 'userSettings') + await $.agent.spawn(spawnOf('verifier')) + await $.agent.spawn(spawnOf('feater')) + expect(rig.specs).toEqual([undefined, SONNET]) +}) + +test('agent row: an override null drops the row', async ($, on) => { + on('env.get', () => ({ value: '/home/t' })) + on('fs.exists', () => ({ value: true })) + on('fs.stat', () => ({ + value: { kind: 'file' as const, size: 40, mtimeMs: 0, isLink: false }, + })) + on('fs.read', () => ({ value: '{"agents":{"verifier":null}}' })) + const rig = await bootRun($, on) + await $.agent.spawn(spawnOf('verifier')) + await $.agent.spawn(spawnOf('feater')) + expect(rig.specs).toEqual([undefined, SONNET]) +}) + +test('show lists the write and apply phases', async ($, on) => { + await bootRun($, on) + const text = await route($, 'show') + expect(text).toContain('apply=work→claude-sonnet-5-5/low') + expect(text).toContain('write=work→claude-sonnet-5-5/high') +}) + +// ---- wave 2: typed-slash origins, spawning counter, spawn exclusions ---- + +/** A promise the test settles by hand, to hold a hook in flight. */ +function deferred() { + let release: () => void = () => {} + const gate = new Promise(r => { release = r }) + return { gate, release } +} + +test('typed slash: an in-flight spawn refuses the fallback', async ( + $, on) => { + const hold = deferred() + const entered = deferred() + on('prompt.submit', ($, e) => ({ text: e.text })) + on('agent.spawn', async ($, e) => { + entered.release() + await hold.gate + return { model: e.model ?? e.parentModel, agentId: 'a1' } + }) + await boot($, on) + await typed($, 'hello') + const spawned = $.agent.spawn(spawnOf('feater')) + await entered.gate + await skillPrompt($, 'feat') + expect(mainLine(await route($, 'show'))).toContain('session defaults') + hold.release() + await spawned +}) + +test('typed slash: a bridge origin arms the marker', async ($, on) => { + await bootRun($, on) + await $.prompt.submit({ + text: '/feat x', + wait: false, + origin: { kind: 'bridge' }, + }) + await $.agent.spawn(spawnOf('feater')) + await skillPrompt($, 'feat') + expect(mainLine(await route($, 'show'))).toContain('skill reflect') +}) + +test('typed slash: a promoted mid-turn marker routes past a live loop', async ( + $, on) => { + await bootRun($, on) + await $.agent.spawn(spawnOf('feater')) + await $.prompt.submit({ + text: '/status', + wait: true, + origin: { kind: 'composer' }, + turnId: 'u1', + }) + await endTurn($) + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('skill mechanical') +}) + +test('agent row: any provider plugin applies, a local definition not', async ( + $, on) => { + const rig = await bootRun($, on) + const provider = { plugin: 'some-plugin', tier: 'core' as const } + await $.agent.spawn(spawnOf('feater', { provider })) + await offerOf($, 'verifier', 'localSettings') + await $.agent.spawn(spawnOf('verifier', { provider })) + expect(rig.specs).toEqual([SONNET, undefined]) +}) + +test('agent row: a workflow spawn is untouched, model and effort', async ( + $, on) => { + const rig = await bootRun($, on) + await $.agent.spawn(spawnOf('feater', { workflow: {} })) + expect(rig.specs).toEqual([undefined]) + await runStep($, { ...highStep('a1'), model: SONNET }) + expect(rig.seen[rig.seen.length - 1]?.effort).toBe('high') +}) + +test('typed slash: the marker binds to its skill name only', async ( + $, on) => { + await bootRun($, on) + await typed($, '/status') + await $.agent.spawn(spawnOf('feater')) + await skillPrompt($, 'feat') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('typed slash: the marker is one-shot', async ($, on) => { + await bootRun($, on) + await typed($, '/status') + await $.agent.spawn(spawnOf('feater')) + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('skill mechanical') + await route($, 'clear') + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('skill.prompt nested in a Skill call leaves the run slot', async ( + $, on) => { + on('tool.call', { tool: 'Skill' }, async (_api, e) => { + await skillPrompt($, 'status') + return { result: { success: true, commandName: String(e.skill) } } + }) + await bootRig($, on, FABLE) + await typed($, '/status') + await loadSkill($, 'feat') + await endTurn($) + expect(mainLine(await route($, 'show'))).toContain('run reflect') +}) + +/** Submits a prompt from `kind` over a running turn (mid-turn). */ +const queued = ($: Engine, kind: string, text: string) => + $.prompt.submit({ + text, + wait: true, + origin: { kind }, + turnId: 'u1', + }) + +test('idle fallback: a mid-turn foreign prompt never arms it', async ( + $, on) => { + await bootRun($, on) + await queued($, 'channel', 'hello') + await endTurn($) + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('session defaults') +}) + +test('idle fallback: a mid-turn composer prompt promotes the allowance', async ( + $, on) => { + await bootRun($, on) + await $.prompt.submit({ + text: 'hello', + wait: false, + origin: { kind: 'channel' }, + }) + await queued($, 'composer', 'hello') + await endTurn($) + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('skill mechanical') +}) + +test('spawning: a finished spawn no longer counts as a live loop', async ( + $, on) => { + await bootRun($, on) + await $.agent.spawn(spawnOf('feater')) + await agentEnds($) + await typed($, 'hello') + await skillPrompt($, 'status') + expect(mainLine(await route($, 'show'))).toContain('skill mechanical') +}) diff --git a/mods/model-router/hooks/register.ts b/mods/model-router/hooks/register.ts index 09f2d3b..8107cc5 100644 --- a/mods/model-router/hooks/register.ts +++ b/mods/model-router/hooks/register.ts @@ -21,7 +21,7 @@ type Config = { models: Record // alias -> full id windows: Record // full id -> context window (tokens) phases: Record - agents: Record // built-in subagentType -> phase + agents: Record // subagentType -> phase skills: Record // skill name -> phase prompt: PromptRule[] tiers: Record // tier -> alias preference, best first @@ -35,7 +35,7 @@ type Config = { enabled: boolean // false: every hook passes through (per machine) } type Rule = { re: RegExp; phase: string; mode: PromptMode } -type Source = 'user' | 'model' | 'skill' | 'prompt' | 'slash' | 'derived' +type Source = 'user' | 'model' | 'skill' | 'prompt' | 'run' | 'derived' type Routed = { phase: string; route: Route; source: Source } type Hold = { until: number; reason: string } // until: ms, Infinity = reload type Pushed = { prev: Routed | null; spawnIds: Set } @@ -50,10 +50,17 @@ type State = { userMain: Routed | null // /route by the user, sticky until /route clear turnMain: Routed | null // model route tool, skill table row, Skill(effort-*) // bridge, prompt default rule, derived orchestrate; dropped at turn end - turnFloor: Routed | null // user-explicit level for this turn (prompt rule, - // typed /effort-): a floor, main loop only + runMain: Routed | null // best-tier skill row: spans the turns of a run; + // only a skill, /route clear|off or a user /model write or drop it + turnFloor: Routed | null // user-explicit level for this turn (prompt rule): + // a floor, main loop only pendingPrompt: Routed | null // typed mid-turn: the next turn's floor - typedSlash: boolean // one-shot: prompt.submit saw a typed /effort- + typedSlash: string | null // the rowed skill the user typed at prompt.submit + pendingSlash: string | null // same, typed mid-turn: promoted at turn end + promptAllowed: boolean // this turn's prompt came from a typing origin + pendingAllowed: boolean // same, for the mid-turn prompt + spawning: number // agent.spawn hooks in flight (preloads fire inside) + offers: Map // subagentType -> definition source loops: Map // agentId -> that loop's routing explicitEffort: Map // Agent tool_use_id -> effort param skillCalls: number // Skill tool calls in flight @@ -89,6 +96,19 @@ const LEVELS: readonly Level[] = ['low', 'medium', 'high', 'xhigh', 'max'] const MODEL_ID = /^claude-[a-z0-9.-]+$/ const TOOL = 'mcp__model-router__route' const EFFORT_SKILL = /^effort-(low|medium|high|xhigh|max)$/ +const BEST = 'best' // the tier whose skill rows hold for a whole run +// Origins that are a person typing: only these arm a typed slash. +const TYPED_ORIGINS: ReadonlySet = new Set([ + 'composer', 'sdk', 'bridge', +]) +// Definition sources of a foreign repo's own agent: its row is skipped. +const PROJECT_SOURCES: ReadonlySet = new Set([ + 'projectSettings', 'localSettings', +]) +// PostModelSwitch sources a person chose (auto and resume are not). +const USER_SWITCH: ReadonlySet = new Set([ + 'command', 'picker', 'sdk', +]) const OVERRIDE = '.claude/model-router.json' const HAIKU = 'claude-haiku' const MAX_PATTERN = 200 // chars of a prompt-rule pattern @@ -132,14 +152,69 @@ const DEFAULT_CONFIG: Config = { escalate: { tier: 'best', effort: 'max' }, judge: { tier: 'big', effort: 'xhigh' }, implement: { tier: 'work', effort: 'medium' }, - write: { tier: 'work', effort: 'medium' }, + write: { tier: 'work', effort: 'high' }, verify: { tier: 'work', effort: 'xhigh' }, explore: { tier: 'work', effort: 'medium' }, + apply: { tier: 'work', effort: 'low' }, mechanical: { tier: 'cheap', effort: 'low' }, }, - // Built-ins only: repo agents keep their frontmatter pin (wave 2). - agents: { Explore: 'explore', Plan: 'judge' }, - skills: {}, + // phase = role; one row per routed repo skill/agent (wave 2); a + // project-level agent of the same name shadows its row (see spawnRoute). + agents: { + // explore + Explore: 'explore', + // judge + Plan: 'judge', 'plan-challenger': 'judge', 'plugin-advisor': 'judge', + 'seo-analyzer': 'judge', 'geo-analyzer': 'judge', analyzer: 'judge', + // implement + feater: 'implement', bugfixer: 'implement', 'code-cleaner': 'implement', + scaffolder: 'implement', onboarder: 'implement', + // write + 'commit-changer': 'write', 'doc-syncer': 'write', + 'handover-doc-writer': 'write', refactorer: 'write', + // apply + hotfixer: 'apply', 'release-executor': 'apply', 'plugin-probe': 'apply', + 'validator-analyzer': 'apply', + // verify + verifier: 'verify', 'security-auditor': 'verify', + // mechanical + 'status-reporter': 'mechanical', + }, + skills: { + // plan + 'ship-feature': 'plan', 'init-project': 'plan', onboard: 'plan', + tour: 'plan', 'audit-delta': 'plan', analyze: 'plan', + 'code-clean': 'plan', 'client-handover': 'plan', brainstorming: 'plan', + 'writing-plans': 'plan', 'requesting-code-review': 'plan', + '21st-ui-review': 'plan', + // reflect + feat: 'reflect', hotfix: 'reflect', bugfix: 'reflect', + refactor: 'reflect', 'web-validate': 'reflect', harden: 'reflect', + seo: 'reflect', geo: 'reflect', 'site-motion': 'reflect', + 'frontend-design': 'reflect', 'emil-design-eng': 'reflect', + 'design-motion-principles': 'reflect', '21st-ui-build': 'reflect', + 'scroll-world-storytelling': 'reflect', + 'build-threejs-scroll-worlds': 'reflect', + 'scroll-scrubbed-visual-sequence': 'reflect', + 'scroll-scrubbed-word-reveal': 'reflect', + 'scroll-progress-timeline': 'reflect', + 'subagent-driven-development': 'reflect', 'writing-skills': 'reflect', + 'deprecation-and-migration': 'reflect', '21st-ai': 'reflect', + '21st-ui-explore': 'reflect', + // implement + gitflow: 'implement', 'prune-memory': 'implement', + 'pdf-translate': 'implement', 'ci-cd-and-automation': 'implement', + 'observability-and-instrumentation': 'implement', + 'test-driven-development': 'implement', + // apply + 'commit-change': 'apply', 'release-candidate': 'apply', doc: 'apply', + capitalize: 'apply', close: 'apply', reconcile: 'apply', deploy: 'apply', + // mechanical + status: 'mechanical', profile: 'mechanical', 'plugin-check': 'mechanical', + 'skills-perso': 'mechanical', 'using-git-worktrees': 'mechanical', + '21st-cli-use': 'mechanical', '21st-registry': 'mechanical', + '21st-design-sync': 'mechanical', + }, // `floor` rules set the turn's minimum effort; `default` rules set the // turn's route, which a route call or a skill overrides. Neither lowers. prompt: [ @@ -386,6 +461,25 @@ function mergeRouting( } } +/** A row table: `name: null` in the override drops a default row. */ +function mergeRows( + base: Record, + user: unknown, + name: string, + ref: (key: string, value: unknown) => string | undefined, + log: Log, +): Record { + const entries = isRecord(user) ? Object.entries(user) : [] + const kept = isRecord(user) + ? Object.fromEntries(entries.filter(([, v]) => v !== null)) + : user + const rows = mergeTable(base, kept, name, ref, log) + for (const [key, value] of entries) { + if (value === null && key !== '__proto__') delete rows[key] + } + return rows +} + /** Defaults overlaid with the user's entries, each validated first. */ function mergeConfig(user: unknown, log: Log): Config { const base = structuredClone(DEFAULT_CONFIG) @@ -405,8 +499,8 @@ function mergeConfig(user: unknown, log: Log): Config { windows: mergeTable( base.windows, user.windows, 'windows', acceptWindow, log), phases, - agents: mergeTable(base.agents, user.agents, 'agents', ref, log), - skills: mergeTable(base.skills, user.skills, 'skills', ref, log), + agents: mergeRows(base.agents, user.agents, 'agents', ref, log), + skills: mergeRows(base.skills, user.skills, 'skills', ref, log), prompt: mergePrompt(base.prompt, user.prompt, phases, log), mainModelSwitch: pickBool(user.mainModelSwitch, base.mainModelSwitch), verbose: pickBool(user.verbose, base.verbose), @@ -487,9 +581,15 @@ function newState(cfg: Config, source: string): State { source, userMain: null, turnMain: null, + runMain: null, turnFloor: null, pendingPrompt: null, - typedSlash: false, + typedSlash: null, + pendingSlash: null, + promptAllowed: false, + pendingAllowed: false, + spawning: 0, + offers: new Map(), loops: new Map(), explicitEffort: new Map(), skillCalls: 0, @@ -511,7 +611,8 @@ function newState(cfg: Config, source: string): State { /** * /clear rebuilds the state but keeps what is account- or process-wide: - * the breaker (a model's quota outlives the conversation) and the model. + * the breaker (a model's quota outlives the conversation), the model and + * the agent definitions' sources (the listing is not offered again). */ function resetSession(st: State): void { const kept = { @@ -519,6 +620,7 @@ function resetSession(st: State): void { strikes: st.strikes, agentModels: st.agentModels, sessionModel: st.sessionModel, + offers: st.offers, } Object.assign(st, newState(st.cfg, st.source), kept) } @@ -788,10 +890,11 @@ function decideMain( : downgradeCall(st, cur, wanted, tokens) } -/** Model axis: sticky, then turn route, then the floor's own model. */ +/** Model axis: sticky, turn route, run slot, then the floor's own model. */ const mainModel = (st: State): string | undefined => routeName(st.userMain?.route) ?? routeName(st.turnMain?.route) ?? + routeName(st.runMain?.route) ?? routeName(st.turnFloor?.route) async function readTokens($: Api): Promise { @@ -827,8 +930,9 @@ function logCall($: Api, st: State, call: Call): void { } } -/** The main loop's effective route: user /route > latest turn route. */ -const mainRoute = (st: State): Routed | null => st.userMain ?? st.turnMain +/** The main loop's effective route: user /route > turn route > run slot. */ +const mainRoute = (st: State): Routed | null => + st.userMain ?? st.turnMain ?? st.runMain const rank = (l: Level | undefined): number => l === undefined ? -1 : LEVELS.indexOf(l) @@ -851,7 +955,8 @@ function higherFloor(cur: Routed | null, next: Routed): Routed { */ function mainEffort(st: State, engine: Effort): Decision { const sticky = st.userMain?.route.effort - const named = sticky ?? st.turnMain?.route.effort + const named = sticky ?? st.turnMain?.route.effort ?? + st.runMain?.route.effort const floor = st.turnFloor?.route.effort const base = named ?? floor ?? engine const effort = floored(base, floor) @@ -862,11 +967,8 @@ function mainEffort(st: State, engine: Effort): Decision { return { effort, by: sticky === undefined ? 'turn' : 'sticky' } } -const floorSource = (f: Routed): string => - f.source === 'prompt' ? `prompt rule ${f.phase}` : `typed /${f.phase}` - const floorWord = (f: Routed): string => - `user floor ${f.route.effort ?? '-'} (${floorSource(f)})` + `user floor ${f.route.effort ?? '-'} (prompt rule ${f.phase})` /** * Why main will not run at `asked`, or '' when it will. Truthful tail of @@ -903,6 +1005,7 @@ function writeLoop(loop: Loop, route: Route): void { function clearRoutes(st: State): void { st.userMain = null st.turnMain = null + st.runMain = null st.turnFloor = null st.pendingPrompt = null } @@ -1122,14 +1225,18 @@ async function handleCommand($: Api, st: State, args: string): Promise { case '': case 'show': return show($, st) - case 'clear': + case 'clear': { + const run = st.runMain !== null clearRoutes(st) refresh($, st) - return 'route cleared\n' + (await show($, st)) + return 'route cleared' + (run ? '; run slot dropped' : '') + + '\n' + (await show($, st)) + } case 'on': case 'off': st.off = head === 'off' st.offConfig = false + if (st.off) st.runMain = null refresh($, st) return show($, st) case 'reload': @@ -1218,20 +1325,28 @@ function clearLoop(st: State, agentId: string | undefined): string { const held = f && f.route.effort !== undefined ? `; ${floorWord(f)} still holds, /route clear drops it` : '' - return 'route cleared for main' + held + const run = st.runMain + ? `; run ${st.runMain.phase} still holds` + : '' + return 'route cleared for main' + held + run } const loop = st.loops.get(agentId) if (loop) writeLoop(loop, {}) return 'route cleared for this agent' } -/** What the main loop's model will do, in the words of the decision. */ +/** The id the next main step runs on, with the decision's reason. */ async function mainAnswer($: Api, st: State): Promise { - const { call, wanted } = await snapshot($, st) - if (call.moved) return `${idWord(st, call.model)} (${call.why})` - const quiet = call.why === 'unchanged' || - (wanted === undefined && !isFallback(call)) - return quiet ? 'unchanged' : `unchanged (${call.why})` + const { call } = await snapshot($, st) + return `${idWord(st, call.model)} (${call.why})` +} + +/** Main's answer: effort and model asked, the sticky/floor note appended. */ +async function mainRoutedText($: Api, st: State, p: Picked) { + const base = `routed main to ${p.phase}: effort ${ + p.route.effort ?? 'unchanged'}, model ${await mainAnswer($, st)}` + const note = mainNote(st, p.route.effort) + return note ? `${base}; but ${note}` : base } /** Truthful answer: states what the calling loop will actually do. */ @@ -1241,15 +1356,11 @@ async function routedText( agentId: string | undefined, p: Picked, ): Promise { - const note = agentId === undefined ? mainNote(st, p.route.effort) : '' - if (note) return `recorded ${p.phase} for this turn, but ${note}` - const loop = agentId === undefined ? undefined : st.loops.get(agentId) - const effort = loop?.explicitEffort ? undefined : p.route.effort - const model = agentId === undefined - ? await mainAnswer($, st) - : routeName(p.route) ? 'unchanged (fixed at spawn)' : 'unchanged' - return `routed ${agentId === undefined ? 'main' : 'this agent'} to ` + - `${p.phase}: effort ${effort ?? 'unchanged'}, model ${model}` + if (agentId === undefined) return mainRoutedText($, st, p) + const explicit = st.loops.get(agentId)?.explicitEffort + const model = routeName(p.route) ? 'unchanged (fixed at spawn)' : 'unchanged' + return `routed this agent to ${p.phase}: effort ${ + explicit ? 'unchanged' : p.route.effort ?? 'unchanged'}, model ${model}` } async function handleRouteTool($: Api, st: State, e: RouteInput) { @@ -1295,51 +1406,59 @@ function effortBridge(st: State, agentId: string | undefined, skill: string, `loop from the next request on; the ${skill} skill text was not loaded.`) } -/** A non-effort skill load: resets the loop's route, applies its table row. */ -function onSkillLoad(st: State, skill: string, agentId: string | undefined) { - const table = hasKey(st.cfg.skills, skill) ? st.cfg.skills[skill] : undefined - const route = table === undefined ? undefined : phaseRoute(st.cfg, table) - if (agentId === undefined) { - st.turnMain = null - if (table !== undefined && route) { - st.turnMain = { phase: table, route, source: 'skill' } - } - return - } - const loop = route ? loopOf(st, agentId) : st.loops.get(agentId) - if (loop) writeLoop(loop, { effort: route?.effort }) -} - -/** A user-typed /effort-: a floor for the turn, prepends one line. */ -function slashEffort(st: State, skill: string, text: string) { - const level = EFFORT_SKILL.exec(skill)?.[1] - if (!isLevel(level)) return undefined - const route: Route = { effort: level } - const slash: Routed = { phase: skill, route, source: 'slash' } - st.turnFloor = higherFloor(st.turnFloor, slash) - const note = mainNote(st, level) - const line = `Effort ${level} set by model-router for the main loop this ` + - 'turn (minimum; a higher route still applies).' + - (note ? ` But ${note}.` : '') - return { text: line + '\n' + text } +/** A skill's table row: its phase and that phase's route, if both exist. */ +function skillRow(st: State, skill: string): Picked | undefined { + const phase = hasKey(st.cfg.skills, skill) ? st.cfg.skills[skill] : undefined + const route = phase === undefined ? undefined : phaseRoute(st.cfg, phase) + return phase !== undefined && route ? { phase, route } : undefined } /** - * Floor write for a skill.prompt. Only a typed slash may write it: the - * marker from prompt.submit attests the typing. Without it, a live - * sub-agent means the prompt is a preload inside that agent: ignored. + * A rowed skill on main sets the turn route; a best-tier row also holds the + * run slot. A typed non-best row drops the run; one the model loads (a + * helper skill inside a run) leaves it. */ -function guardedSlash(st: State, skill: string, text: string) { - if (!EFFORT_SKILL.test(skill)) return undefined - if (st.typedSlash) { - st.typedSlash = false - } else if (st.loops.size > 0) { - return { - text: `model-router: ${skill} preload inside a live sub-agent is ` + - 'ignored on the main loop.\n' + text, - } +function routeMainBySkill(st: State, row: Picked, typed: boolean): void { + const turn: Routed = { phase: row.phase, route: { ...row.route }, + source: 'skill' } + st.turnMain = turn + if (row.route.tier === BEST) st.runMain = { ...turn, source: 'run' } + else if (typed) st.runMain = null +} + +/** A model-loaded skill: its row applies; an unrowed one changes nothing. */ +function onSkillLoad(st: State, skill: string, agentId: string | undefined) { + const row = skillRow(st, skill) + if (agentId === undefined) { + if (row) routeMainBySkill(st, row, false) + return } - return slashEffort(st, skill, text) + if (row) writeLoop(loopOf(st, agentId), row.route) +} + +type TypedPath = 'typed-marker' | 'typed-fallback' + +/** + * Whether a skill.prompt on main is the user's own typing. The marker from + * prompt.submit names the skill; failing that, an allowed-origin prompt with + * no live or spawning sub-agent (a preload fires inside one) still counts. + */ +function typedPath(st: State, skill: string): TypedPath | undefined { + if (st.typedSlash === skill) { + st.typedSlash = null + return 'typed-marker' + } + const idle = st.loops.size === 0 && st.spawning === 0 + return st.promptAllowed && idle ? 'typed-fallback' : undefined +} + +function applyTypedSkill($: Api, st: State, skill: string): void { + const row = skillRow(st, skill) + const path = typedPath(st, skill) + if (row === undefined || path === undefined) return + routeMainBySkill(st, row, true) + refresh($, st) + vlog($, st, `skill ${skill}: ${path} → ${row.phase}`) } // ---- agents ---------------------------------------------------------- @@ -1347,27 +1466,60 @@ function guardedSlash(st: State, skill: string, text: string) { type SpawnIn = { tool_use_id: string subagentType: string - provider: { plugin: string } model?: string fork: boolean workflow?: unknown } /** - * The table row of a built-in agent. Known limit: provider.plugin === - * 'engine' is the best built-in test at spawn; a user agent named Explore - * in a foreign project also matches (wave 1: sonnet/medium on it). + * The table row of an agent, for every provider. Skipped for a fork, a + * workflow agent, and an agent whose definition came from the project (a + * foreign repo's own verifier.md). Known limit: the source is recorded by + * name only, so an offer fired inside a sub-agent with another cwd + * overwrites it; no record = the row applies (fail-open on routing). */ -function spawnRoute(cfg: Config, e: SpawnIn, frozen: boolean) { - if (frozen || e.provider.plugin !== 'engine') return undefined - if (!hasKey(cfg.agents, e.subagentType)) return undefined - const phase = cfg.agents[e.subagentType] - return phase === undefined ? undefined : phaseRoute(cfg, phase) +function spawnRoute(st: State, e: SpawnIn, frozen: boolean) { + if (frozen || !hasKey(st.cfg.agents, e.subagentType)) return undefined + if (PROJECT_SOURCES.has(st.offers.get(e.subagentType) ?? '')) { + return undefined + } + const phase = st.cfg.agents[e.subagentType] + return phase === undefined ? undefined : phaseRoute(st.cfg, phase) +} + +/** Once per turn: a spawn whose tier has nothing at or above its head. */ +function tierDownLog($: Api, st: State, agent: string, tier: string): void { + const text = `model-router: ${agent} tier ${tier} down, ` + + 'frontmatter model kept' + const key = `spawn-down:${agent}:${tier}` + if (st.turnLogged.has(key)) return + st.turnLogged.add(key) + $.ui.log(text) +} + +/** + * The first model of the route's tier that is not down, only when it ranks + * at or above the tier's head: an agent moves UP from its frontmatter alias, + * never below. Nothing qualifies: no write, the frontmatter model runs. + */ +function inTier($: Api, st: State, agent: string, tier: string) { + const aliases = hasKey(st.cfg.tiers, tier) ? st.cfg.tiers[tier] : undefined + const head = aliases?.[0] + const headId = head === undefined ? undefined : st.cfg.models[head] + if (aliases === undefined || headId === undefined) return undefined + const id = availableIn(st, aliases) + if (id !== undefined && (id === headId || ranksAbove(st, id, headId))) { + return id + } + tierDownLog($, st, agent, tier) + return undefined } /** The model a spawn is rewritten to; an explicit `model` param wins. */ -function spawnTarget(st: State, e: SpawnIn, route: Route | undefined) { - return e.model === undefined ? resolveRoute(st, route) : undefined +function spawnTarget($: Api, st: State, e: SpawnIn, route: Route | undefined) { + if (e.model !== undefined || route === undefined) return undefined + if (route.tier === undefined) return resolveRoute(st, route) + return inTier($, st, e.subagentType, route.tier) } function trackLoop(st: State, e: SpawnIn, started: { @@ -1493,7 +1645,10 @@ function endMainTurn($: Api, st: State): void { st.turnMain = null st.pushed = null st.turnModel = undefined - st.typedSlash = false + st.typedSlash = st.pendingSlash + st.promptAllowed = st.pendingAllowed + st.pendingSlash = null + st.pendingAllowed = false st.explicitEffort.clear() st.spinner = '' st.turnLogged.clear() @@ -1554,6 +1709,7 @@ async function onAutoSwitch($: Api, st: State, e: SwitchIn): Promise { /** Any model change: keeps `sessionModel`; a user choice clears its mark. */ async function onModelSwitch($: Api, st: State, e: SwitchIn): Promise { st.sessionModel = e.to_model + if (USER_SWITCH.has(e.source)) st.runMain = null if (st.off || e.source === 'resume') return if (e.source === 'auto') await onAutoSwitch($, st, e) else clearBreaker(st, canonical(st.cfg, e.to_model)) @@ -1652,10 +1808,8 @@ function registerSkills(on: On, st: State): void { }) on('skill.prompt', async ($, e, next) => { if (st.off || st.skillCalls > 0) return next(e) - const out = guardedSlash(st, e.skill, e.text) - if (!out) return next(e) - refresh($, st) - return out + safely(st, $, 'skill.prompt', () => applyTypedSkill($, st, e.skill)) + return next(e) }).catch(($, e, next) => { warnOnce(st, $, 'skill.prompt', next.error.kind) return next(e) @@ -1679,26 +1833,47 @@ function registerAgents(on: On, st: State): void { }) } +/** Bookkeeping once the agent started: its loop, its model, a log line. */ +function afterSpawn( + $: Api, + st: State, + e: SpawnIn, + started: { agentId?: unknown; model: string }, + route: Route | undefined, +): void { + if (typeof started.agentId !== 'string') return + const agentId = started.agentId + safely(st, $, 'agent.spawn', () => { + trackLoop(st, e, { agentId }, route) + rememberAgent(st, agentId, started.model) + vlog($, st, + `spawn ${e.subagentType}: ${e.model ?? '-'} → ${started.model}`) + }) +} + function registerSpawn(on: On, st: State): void { + on('agent.offer', async ($, e, next) => { + if (!st.off) st.offers.set(e.agent, e.source) + return next(e) + }).catch(($, e, next) => { + warnOnce(st, $, 'agent.offer', next.error.kind) + return next(e) + }) on('agent.spawn', async ($, e, next) => { if (st.off) return next(e) - await prune($, st) - const frozen = e.fork || e.workflow !== undefined - const route = spawnRoute(st.cfg, e, frozen) - const wanted = spawnTarget(st, e, route) - const started = await next(wanted === undefined - ? e - : { ...e, model: wanted }) - if (typeof started.agentId === 'string') { - const agentId = started.agentId - safely(st, $, 'agent.spawn', () => { - trackLoop(st, e, started, route) - rememberAgent(st, agentId, started.model) - vlog($, st, - `spawn ${e.subagentType}: ${e.model ?? '-'} → ${started.model}`) - }) + st.spawning += 1 + try { + await prune($, st) + const route = spawnRoute(st, e, e.fork || e.workflow !== undefined) + const wanted = spawnTarget($, st, e, route) + const started = await next(wanted === undefined + ? e + : { ...e, model: wanted }) + afterSpawn($, st, e, started, route) + return started + } finally { + st.spawning = Math.max(0, st.spawning - 1) } - return started }).catch(($, e, next) => { warnOnce(st, $, 'agent.spawn', next.error.kind) return next(e) @@ -1767,14 +1942,41 @@ function routeFromPrompt(st: State, text: string, midTurn: boolean): void { floorFromPrompt(st, midTurn, routed) } const slash = text.trimStart().startsWith('/') - if (text.trimStart().startsWith('/effort-')) st.typedSlash = true if (!midTurn && !slash && !floor) defaultFromPrompt(st, scanned) } +/** The rowed skill a slash prompt names, else null. */ +function typedSkill(st: State, text: string): string | null { + const typed = text.trimStart() + if (!typed.startsWith('/')) return null + const name = typed.slice(1).split(/\s/, 1)[0] ?? '' + return hasKey(st.cfg.skills, name) ? name : null +} + +/** + * Records what skill.prompt needs to tell a typed slash from a preload: the + * skill named and whether a person typed it. A mid-turn prompt waits in the + * pending slots for the turn end; a foreign one leaves them alone. A later + * queued prompt replaces an earlier one (a shortcut: one pending slot). + */ +function noteTyped(st: State, kind: string, text: string, midTurn: boolean) { + const allowed = TYPED_ORIGINS.has(kind) + const slash = allowed ? typedSkill(st, text) : null + if (!midTurn) { + st.typedSlash = slash + st.promptAllowed = allowed + } else if (allowed) { + st.pendingSlash = slash + st.pendingAllowed = true + } +} + function registerPrompt(on: On, st: State): void { on('prompt.submit', async ($, e, next) => { - if (st.off || e.origin.kind !== 'composer') return next(e) - routeFromPrompt(st, e.text, e.turnId !== undefined) + if (st.off) return next(e) + const midTurn = e.turnId !== undefined + noteTyped(st, e.origin.kind, e.text, midTurn) + if (e.origin.kind === 'composer') routeFromPrompt(st, e.text, midTurn) refresh($, st) return next(e) }).catch(($, e, next) => { From 65dff0e768a3c8008380a8b45ac6374e18acbe9a Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 17:22:43 +0200 Subject: [PATCH 051/547] =?UTF-8?q?chore(memory):=20journal=20+=20TODO=20+?= =?UTF-8?q?=20contract=20w2a=20=E2=80=94=20feat=20model-router=20wave=202-?= =?UTF-8?q?A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/journal.md | 1 + .claude/tasks/TODO.md | 6 +- .../2026-10-09-model-router-w2a-1546.md | 44 +++ .claude/tasks/contracts/w2a-table-census.sh | 56 +++ .../plans/2026-10-09-model-router-w2-1546.md | 345 ++++++++++++++++++ 5 files changed, 450 insertions(+), 2 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-09-model-router-w2a-1546.md create mode 100755 .claude/tasks/contracts/w2a-table-census.sh create mode 100644 .claude/tasks/plans/2026-10-09-model-router-w2-1546.md diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index ed2aedc..05a4fb3 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -590,3 +590,4 @@ rules: - User go 'ok merge': full make test green (except env red design-tool-gate), shellcheck clean → gitflow finish feature model-router-mod → develop abbdf79 (22 commits: waves 0, 1-A, 1-B1, 1-B2, 1-C + docs + registries). Manual mode: develop NOT pushed, the user publishes by hand from the terminal. Branch removed locally. User will /clear before wave 2. - /hotfix make-test-names-red-suites (user: '9 min pour un merge?'): measured from transcript timestamps, the merge took <20 s; 454 s went to make test run TWICE (full + per-suite sweep to name the red suite, because the aggregate rc is silent). Fix: Makefile test prints FAIL + summary, rc unchanged (GNU make returns 2 on a failed recipe; my first oracle expected 1). hotfixer DONE, GATE 0 MET 2/2, security PASS. Branch bugfix/make-test-names-red-suites UNMERGED (human signal). Method note: a mods/-only diff needs only the mods suite + doctrine census, the full run once before merge. - User go 'all, merge le, et je clear': LRN-207/208/209 + EVAL-041 written (ca96458); gitflow finish bugfix/make-test-names-red-suites → develop 5e0e5c0, branch removed. develop 28 commits ahead of origin, NOT pushed (manual mode, user publishes). Only settings.json dirty (user's own /model change). Session closes; next: wave 2 of model-router (TODO W2 line). +- model-router W2-A landed (bb56f3e, feature/model-router-w2). User go 'lance la vague 2' + 4 pass-B answers: shifters deleted, pins reworked into phase rows (not copied), phases declared, slim gate. Plan r1→r4: 3 lenses (1 BLOCKER: mod off → agents inherit parent model → frontmatter kept as off-state floor), confirmation 1 FATAL (BLOCKER: route calls wiped the sticky slot → separate runMain), confirmation 2 CONCERNS (deviation: 2 confirmations, stated). Feater DONE + 4 gap rounds (A5 in-agent decision, 6+3+3 coverage tests, every one mutation-proven). GATE 0 MET; verifier ECARTS(3)/(1)/(1) all on coverage of criterion 3 clauses, never code → diagnosis at max: compound criterion → user accepted at the cap. Security PASS (2 MEDIUM pre-existing). Kit 58→88. Next: user /reload-plugins + live probe, then W2-B. Lesson for the next contract: one coverage clause per criterion, not twelve. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 94b4b08..9de2a5b 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -17,8 +17,10 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [ ] W1-C accepted-by-design (security 2026-10-09, MEDIUM, not coded around): (1) the model itself can raise the main loop to fable for the rest of a turn through the `route` tool (plan/reflect/escalate/judge) or a background dispatch (derived orchestrate = best tier) — bounded by the turn and `upgradeMaxTokens`, no sticky route is model-callable; (2) `ultrathink` and the default keyword rules now mean "best tier" (fable) at the phase's effort, so an incidental keyword in a pasted composer prompt costs a fable turn (origin composer only). Residuals: `PostModelSwitch` `auto` covers "other programmatic change" (a healthy model could be marked 15 min); strikes never decay inside a session; a `[1m]` variant's `model_not_found` marks the base model until reload; a `models` alias added by the override without a `fallback` key stays unranked (`withEveryAlias` not applied to the default chain) so `leaveDown` skips the upgrade gates for it; `canonical` prefix match has no segment boundary (`claude-sonnet-5-50` would map to sonnet); classifier deferred to W2 - [x] W1-C live verification part 1 (2026-10-09 after `/reload-plugins`, skills-dir copy loaded, 12 hooks): derived orchestrate on a real background Explore (main high → medium while it ran → high after its end); Explore on sonnet/medium; `route plan` → next request xhigh (engine record); `Skill(effort-low)` bridged → next request low (engine record); `/route show` resolves all 10 phases to full ids, `down: none`; steps arrive as bare `claude-fable-5-1` (no `[1m]`) so the suffix carry never fires on this session - [ ] W1-C live verification part 2 (needs a real incident): StopFailure vs turn.complete order; `PostModelSwitch` `auto` semantics and its `from_model` after a router upgrade; whether a router rewrite raises `auto`; `[1m]` carry validity on opus (only on a session whose steps carry it) -- [ ] W2 migration (after wave 1 proven in daily use): 15 skills `Skill(effort-*)` → `route` tool calls; remove `skills/effort-*`, `lib/effort-pins.txt/.sh`, install/update steps, `effort:` frontmatter on skills and agents; repo agents into the mod's `agents` table (verify the spawn/first-step ordering first); `lib/model-gate.md` + `lib/model-check.sh` → mod rule; census tests repointed; `lib/effort-shift.md` rewritten; docs -- [ ] W2 migration: 15 skills off `Skill(effort-*)`, remove shifters + effort-pins + model-gate, census repointed, docs +- [x] W2-A mod (2026-10-09, bb56f3e on feature/model-router-w2, contract `2026-10-09-model-router-w2a-1546`, plan r4 `2026-10-09-model-router-w2-1546`): user decisions — effort-* skills deleted (W2-B), pins REWORKED not deleted (rows = phases by role; frontmatter `model:`/`effort:` kept as census-locked off-state floor after a robustness BLOCKER), orchestrators declare phases, slim model gate. Phases `write` work/high + `apply` work/low; 56 skill rows, 21 agent rows; agents' model at spawn within tier, upward only, project-defined agents skipped (agent.offer); typed slash → name-bound marker (composer|sdk|bridge) + pending slot + idle fallback; best-tier rows in a `runMain` slot surviving turn end; unrowed skill leaves the route; route answer always names the id; `null` override rows. 3 lenses + 2 confirmations (1 BLOCKER each round closed), feater + 4 gap rounds, GATE 0 MET, verifier 3× ECARTS on coverage clauses only → user accepted at the cap, security PASS (2 MEDIUM pre-existing: first-load kill switch fails open, ReDoS size-bounded). Kit 58 → 88 tests. Doc-sync skipped for A (mod-only, docs at B). +- [ ] W2 gate A→B (user): `/reload-plugins`, then the live probe of plan § Gate (4 points: typed `/status` marker vs fallback in the verbose log; a real rowed spawn line + `step 0 agent` effort = spawn/first-step ordering; sonnet session typed `/feat` self-check + route answer; probe 1 again with a background agent alive). `typed-marker` never seen → W2-B blocked, A4 re-planned. +- [ ] W2-B repo migration (plan § W2-B B0-B7 + STEP 6/7): bridge removal, `lib/effort-shift.md` rewrite, 15 citers → `route`, `effort=` on opus general-purpose dispatches, slim `lib/model-gate.md`, delete `model-check.sh` + `effort-pins.*` + their tests + install/update blocks, delete `skills/effort-*`, analyzer `effort: xhigh`, census rewrite (drift lock rows ↔ frontmatter), docs + registries (BDR-115 amendment, LRN typed-slash/run slot, EVAL) +- [ ] W2-A residuals (security, accepted): first-load failure of the override activates the router despite `enabled:false` (fix = treat a failed first load as off); ReDoS on a self-authored prompt pattern (size-bounded); error text in the local log; model alias keys unvalidated (PHASE_KEY would do); `offers` map uncapped; `__proto__`/`constructor` override keys untested. Known limits: `skillCalls`/`spawning` counters are global; offers keyed by name only; builtin `/effort` is not a lever inside a run. - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B ## 2026-09-30 — Higgsfield pack: CLI + skills in the install process, off by default (feature/higgsfield-pack) diff --git a/.claude/tasks/contracts/2026-10-09-model-router-w2a-1546.md b/.claude/tasks/contracts/2026-10-09-model-router-w2a-1546.md new file mode 100644 index 0000000..13f5760 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-09-model-router-w2a-1546.md @@ -0,0 +1,44 @@ +# CONTRACT — model-router-w2a +- date: 2026-10-09 | flow: feat | branch: feature/model-router-w2 (to start off develop) +- status: active +- wave: W2-A (mod, plan r2). W2-B (repo migration + docs/registries as its STEP 6/7) gets its own contract after the live probe. + +## REQUEST (verbatim — IMMUTABLE) +tu peux lancer la vague 2 +(TODO W2 line: 15 skills `Skill(effort-*)` → `route` tool calls; remove `skills/effort-*`, `lib/effort-pins.txt/.sh`, install/update steps, `effort:` frontmatter on skills and agents; repo agents into the mod's `agents` table (verify the spawn/first-step ordering first); `lib/model-gate.md` + `lib/model-check.sh` → mod rule; census tests repointed; `lib/effort-shift.md` rewritten; docs) + +## CLARIFICATIONS +(pass A: none — outcome, scope and constraints come from the TODO W2 line + plan `2026-10-08-model-router-mod.md` § Wave 2) +Q: keep the five `effort-*` skills as typed floor levers? / A: "supprimer, j'utilise les commandes builtin si j'ai besoin" → deleted; the mod drops its `Skill(effort-*)` bridge and typed-slash floor code; `ultrathink` floor stays [gated 2026-10-09] +Q: table rows = bare level next to phases, or phases only? / A: "le pin était là car pas encore de système de routage fiable; maintenant qu'il y en a un, soit on le supprime, soit tu les remanies pour que ça fonctionne encore mieux" → reworked: rows are PHASES by role (plan/reflect/implement/write/verify/judge/mechanical), no level rows; agents routed on both axes by the mod while on (model written at spawn from the phase tier, upward only); the tracked `model:`/`effort:` frontmatter STAYS as the census-locked off-state floor (plan r3, confirmation 1/8) [gated 2026-10-09] +Q: orchestrators declare phases or effort only? / A: phases [gated 2026-10-09] +Q: (mid-run, feater NEED-DECISION, CLASS internal) a skill WITHOUT a row loaded INSIDE a sub-agent: keep the old reset of that loop's effort, or leave the loop untouched like main (A5)? / A: leave the agent loop untouched too — one rule for both loops, an unrowed helper skill (find-docs) never wipes an agent row's effort [gated 2026-10-09] +Q: GATE 1 cap (3 × ECARTS on test coverage of criterion 3 clauses, code correct ×3; last rows landed by a feater, unverified) / A: user "Accepter et commiter W2-A" — accepted on the three reports + 88-test kit suite; diagnosis: compound coverage criterion, not the code [gated 2026-10-09] +Q: model gate fate? / A: slim include (self-check + STOP when the mod could not raise), `lib/model-check.sh` + test deleted [gated 2026-10-09] + +## ACCEPTANCE CRITERIA +1. The mod's kit suite is green, including the new tests of criteria 3-5. + CHECK: cd mods/model-router && out="$(claude plugin test . 2>&1)" && printf '%s\n' "$out" | grep -qE '[0-9]+ pass' && printf '%s\n' "$out" | grep -qE '(^|[^0-9])0 fail' && ! printf '%s\n' "$out" | grep -qE '[1-9][0-9]* fail' && echo W2A-TESTS-GREEN + EXPECT: W2A-TESTS-GREEN + EVIDENCE: MET exit=0 marker-found :: W2A-TESTS-GREEN +2. `DEFAULT_CONFIG.phases` has `write` at work/high and a new `apply` at work/low; `DEFAULT_CONFIG.skills` and `.agents` carry exactly the phase rows of plan r2 § Row tables (56 skill rows, 21 agent rows + Explore/Plan), every value a phase key; the "Built-ins only" comment is gone. + CHECK: bash .claude/tasks/contracts/w2a-table-census.sh mods/model-router/hooks/register.ts + EXPECT: W2A-TABLE-COMPLETE + EVIDENCE: MET exit=0 marker-found :: W2A-TABLE-COMPLETE +3. A user-typed slash of a rowed skill routes main to its row (name-bound marker from `prompt.submit`, origins composer|sdk|bridge, pending slot mid-turn, or no live/spawning sub-agent); a preload inside a live sub-agent without the marker leaves main; a skill WITHOUT a row leaves the route in force; a best-tier skill row lives in a separate `runMain` slot that survives `turn.complete` and later `route` calls, and is dropped by `/route clear`, `/route off`, a user-typed non-best rowed skill, or a user `/model`; the `Skill(effort-*)` bridge is not sticky. Covered by kit tests. +4. Any rowed agent spawn (whatever `provider.plugin`) with `e.model` undefined gets the row's model written at spawn: full id resolved within the tier only and ranked ≥ the tier head (upward only); otherwise no write + one deduped log line; the row's effort applies on its loop from its first step unless the call carried `effort`; `fork`/`workflow` spawns and agents whose `agent.offer` source is a project definition are untouched; an override `agents: { name: null }` drops a row; the `route` tool answer always names the id the next main step runs on. Covered by kit tests. +5. Typed-floor code removed: no `slashEffort`, `guardedSlash`, `'slash'` Source, `typed /effort-` floor word in `register.ts`; `EFFORT_SKILL`/`effortBridge` (tool.call bridge) and the `ultrathink` floor kept until W2-B; `/route` unchanged (existing tests still green). + CHECK: ! grep -qE "slashEffort|guardedSlash|'slash'|typed /effort-" mods/model-router/hooks/register.ts && grep -q 'turnFloor' mods/model-router/hooks/register.ts && grep -q 'effortBridge' mods/model-router/hooks/register.ts && echo W2A-DEAD-CODE-GONE + EXPECT: W2A-DEAD-CODE-GONE + EVIDENCE: MET exit=0 marker-found :: W2A-DEAD-CODE-GONE +7. `claude plugin validate` passes. + CHECK: cd mods/model-router && claude plugin validate . 2>&1 | grep -qi 'valid' && echo W2A-VALID + EXPECT: W2A-VALID + EVIDENCE: MET exit=0 marker-found :: W2A-VALID +6. `make test suite=lib/tests/mods.test.sh` green. + CHECK: make test suite=lib/tests/mods.test.sh 2>&1 | tail -5 | grep -q 'mods' && ! make test suite=lib/tests/mods.test.sh 2>&1 | grep -q '^FAIL' && echo W2A-MODS-SUITE + EXPECT: W2A-MODS-SUITE + EVIDENCE: MET exit=0 marker-found :: W2A-MODS-SUITE + +## FILE SCOPE +mods/model-router/hooks/register.ts, mods/model-router/hooks/register.test.ts, .claude/tasks/contracts/w2a-table-census.sh (oracle, written by the orchestrator) diff --git a/.claude/tasks/contracts/w2a-table-census.sh b/.claude/tasks/contracts/w2a-table-census.sh new file mode 100755 index 0000000..7658b44 --- /dev/null +++ b/.claude/tasks/contracts/w2a-table-census.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# GATE 0 oracle, contract 2026-10-09-model-router-w2a: DEFAULT_CONFIG.skills +# and .agents in register.ts hold exactly the plan's phase rows (plan +# 2026-10-09-model-router-w2 § Row tables), every value a declared phase. +# Prints W2A-TABLE-COMPLETE only when every assertion passes. +set -u +F="${1:?register.ts path}" +python3 - "$F" <<'PY' +import re, sys +src = open(sys.argv[1]).read() +m = re.search(r'const DEFAULT_CONFIG: Config = \{(.*?)\n\}\n', src, re.S) +if not m: print("no DEFAULT_CONFIG block"); sys.exit(1) +cfg = m.group(1) +def block(name): + b = re.search(r'\n ' + name + r': \{([^\n]*)\},', cfg) \ + or re.search(r'\n ' + name + r': \{(.*?)\n \}', cfg, re.S) + if not b: print(f"no {name} block"); sys.exit(1) + rows = re.findall(r"(?:^|[{,])\s*'?([A-Za-z0-9_-]+)'?:\s*'([a-z]+)'", b.group(1), re.M) + return dict(rows) +phases = set( + re.findall(r"^\s*([a-z]+): \{ tier:", re.search(r'\n phases: \{(.*?)\n \}', cfg, re.S).group(1), re.M)) +want_skills = {} +for ph, names in { + 'plan': 'ship-feature init-project onboard tour audit-delta analyze code-clean client-handover brainstorming writing-plans requesting-code-review 21st-ui-review', + 'reflect': 'feat hotfix bugfix refactor web-validate harden seo geo site-motion frontend-design emil-design-eng design-motion-principles 21st-ui-build scroll-world-storytelling build-threejs-scroll-worlds scroll-scrubbed-visual-sequence scroll-scrubbed-word-reveal scroll-progress-timeline subagent-driven-development writing-skills deprecation-and-migration 21st-ai 21st-ui-explore', + 'implement': 'gitflow prune-memory pdf-translate ci-cd-and-automation observability-and-instrumentation test-driven-development', + 'apply': 'commit-change release-candidate doc capitalize close reconcile deploy', + 'mechanical': 'status profile plugin-check skills-perso using-git-worktrees 21st-cli-use 21st-registry 21st-design-sync', +}.items(): + for n in names.split(): want_skills[n] = ph +want_agents = {'Explore': 'explore', 'Plan': 'judge'} +for ph, names in { + 'implement': 'feater bugfixer code-cleaner scaffolder onboarder', + 'write': 'commit-changer doc-syncer handover-doc-writer refactorer', + 'apply': 'hotfixer release-executor plugin-probe validator-analyzer', + 'verify': 'verifier security-auditor', + 'judge': 'plan-challenger plugin-advisor seo-analyzer geo-analyzer analyzer', + 'mechanical': 'status-reporter', +}.items(): + for n in names.split(): want_agents[n] = ph +ok = True +for name, want in (('skills', want_skills), ('agents', want_agents)): + got = block(name) + for k in sorted(set(want) | set(got)): + if want.get(k) != got.get(k): + ok = False; print(f"{name}.{k}: want {want.get(k)} got {got.get(k)}") + bad = {k: v for k, v in got.items() if v not in phases} + if bad: ok = False; print(f"{name}: undeclared phases {bad}") +if len(want_skills) != 56 or len(want_agents) != 23: + ok = False; print(f"oracle self-check: {len(want_skills)} skill rows, {len(want_agents)} agent rows") +if 'Built-ins only' in cfg: ok = False; print("stale comment 'Built-ins only'") +ph = re.search(r'\n phases: \{(.*?)\n \}', cfg, re.S).group(1) +for want in ("write: { tier: 'work', effort: 'high' }", "apply: { tier: 'work', effort: 'low' }"): + if want not in ph: ok = False; print(f"phases: missing {want}") +print("W2A-TABLE-COMPLETE" if ok else "W2A-TABLE-INCOMPLETE"); sys.exit(0 if ok else 1) +PY diff --git a/.claude/tasks/plans/2026-10-09-model-router-w2-1546.md b/.claude/tasks/plans/2026-10-09-model-router-w2-1546.md new file mode 100644 index 0000000..fa58f7b --- /dev/null +++ b/.claude/tasks/plans/2026-10-09-model-router-w2-1546.md @@ -0,0 +1,345 @@ +# PLAN r4 — model-router wave 2 (migration), 2026-10-09 + +r1 → r2 after 3 lenses (simplicity CONCERNS(5), correctness CONCERNS(10), +robustness FATAL(8)); r2 → r3 after the confirmation pass (robustness +FATAL(8): 1 BLOCKER); r3 → r4 after a second confirmation (correctness +CONCERNS(3), wording-level). Every BLOCKER/MAJOR is closed by a NAMED change +(§ Challenge ledger). Mod = the router while on; the tracked frontmatter +(`model:` + `effort:` on agents, `effort:` on skills) STAYS as the +off-state floor, census-locked equal to the rows (r3). +Two sub-runs on `feature/model-router-w2`: W2-A (mod) then, after a user +`/reload-plugins` + live probe, W2-B (repo migration). Docs + registries = +W2-B's own STEP 6/7 (feat pipeline tail); W2-A runs no doc-sync (deviation, +stated: a mod-only diff has no public doc of its own until B lands). + +## Decisions (pass B, user 2026-10-09) — amended by the challenge +- D1 the five `effort-*` skills are DELETED in W2-B. The mod's + `Skill(effort-*)` bridge is deleted in W2-B too (same commit as the citers, + robustness 7: edits are live on the symlinked tree). The typed `/effort-` + floor code goes in W2-A (A1). The `ultrathink` floor stays. +- D2 pins reworked, not deleted (r3): rows are PHASES by ROLE, no bare + levels; the mod routes agents on both axes while on (model written at + spawn from the tier, only UPWARD in rank; effort per step; explicit + Agent params win). The tracked frontmatter stays as the OFF-STATE FLOOR + (mod off / `enabled:false` / unloaded / a hook failing open → the engine + applies the frontmatter as today: never the parent model, never session + effort on an xhigh gate agent; r2 robustness 1 + confirmation 8). The + census locks every row equal to its frontmatter (tier head == `model:` + alias, phase effort == `effort:`), so there is one declared value, two + carriers. Deleted: the five shifters, `lib/effort-pins.*` (vendored + levels become rows; off-state = session level for them, as before + BDR-108), the witness script. +- D3 the orchestrators declare PHASES: dispatch span → `route(phase= + "orchestrate")`; own level high → `reflect`, xhigh → `plan`; bookkeeping + tail → `route(phase="apply")` (work/low); escalation → `escalate`. + Judgment dispatches of BUILT-INS (`general-purpose` with `model="opus"` + or `"fable"`) carry an explicit `effort=` param (a main route never + reaches a child; correctness 8). A best-tier skill row SURVIVES the end + of the turn in its own slot (A6 `runMain`): a run spans prose gates; + turn-scoped routes (`route` calls, prompt rules, the bridge) never + touch it. +- D4 `lib/model-gate.md` = the mod rule; the witness is the `route` tool's + own answer (correctness 7): self-check big → silent; small → call + `route(phase=)` and STOP unless the answer names a fable or + opus id; tool absent or "is off" → STOP with the remedy. `model-check.sh` + + its test deleted. The route answer ALWAYS names the id the next main + step runs on (A3d). Relaunch levers in STOP texts: `ultrathink` in the + relaunch prompt (turn floor) or `/route effort=max` (sticky, `/route + clear` after). Builtin `/effort` is NOT a lever inside a run (rows and + routes rank above the engine effort; r2's engine-effort detector dropped + as unsafe, confirmation 4) — documented, named to the user. + +## Phase table (A2a) — two rows added to `phases` +| phase | tier | effort | role | +| plan | best | xhigh | brainstorm, plan, architecture, audit verdict | +| reflect | best | high | diagnosis, review, contract, day-to-day orchestrator entry | +| orchestrate | best | medium | between dispatches | +| escalate | best | max | stuck, cap reached | +| judge | big | xhigh | dispatched challengers, analyzers, audits | +| implement | work | medium | code from a closed plan | +| write | work | **high** (was medium) | docs, commits, refactors, handover prose on sonnet at high (BDR-107 "high judgment on sonnet") | +| verify | work | xhigh | verifier, security-auditor | +| explore | work | medium | Explore | +| **apply** (new) | work | low | low appliers (BDR-107): small fixes, release mechanics, probes, validators; bookkeeping tail of the main loop | +| mechanical | cheap | low | listing, status, profile toggles | + +## Row tables (A2b) +skills (56): +- plan: ship-feature init-project onboard tour audit-delta analyze + code-clean client-handover brainstorming writing-plans + requesting-code-review 21st-ui-review +- reflect: feat hotfix bugfix refactor web-validate harden seo geo + site-motion frontend-design emil-design-eng design-motion-principles + 21st-ui-build scroll-world-storytelling build-threejs-scroll-worlds + scroll-scrubbed-visual-sequence scroll-scrubbed-word-reveal + scroll-progress-timeline subagent-driven-development writing-skills + deprecation-and-migration 21st-ai 21st-ui-explore +- implement: gitflow prune-memory pdf-translate ci-cd-and-automation + observability-and-instrumentation test-driven-development +- apply: commit-change release-candidate doc capitalize close reconcile + deploy (work tier: never haiku on main even with the switch on, + robustness 15) +- mechanical: status profile plugin-check skills-perso using-git-worktrees + 21st-cli-use 21st-registry 21st-design-sync +agents (21 + 2 built-ins), model = frontmatter alias, unchanged everywhere; +`effort:` frontmatter updated where the row differs (analyzer → xhigh): +- implement (sonnet/medium): feater bugfixer code-cleaner scaffolder onboarder +- write (sonnet/high): commit-changer doc-syncer handover-doc-writer refactorer +- apply (sonnet/low): hotfixer release-executor plugin-probe validator-analyzer +- verify (sonnet/xhigh): verifier security-auditor +- judge (opus/xhigh): plan-challenger plugin-advisor seo-analyzer + geo-analyzer analyzer (the ONE level delta: high → xhigh, BDR-108 rung + "audit before validation"; named at the gate) +- mechanical (haiku/low): status-reporter +- built-ins: Explore explore, Plan judge +- no row: interviewer, client-handover-writer (inline-load), impeccable-* + (gitignored vendor output, untouched) +Deltas named at the gate: analyzer effort; best-tier raise now also reaches +refactor + the design/vendored reflect skills on a small session +(simplicity 6: the raise is the point of the mod). + +## W2-A — mod (contract 2026-10-09-model-router-w2a-1546) +- [ ] A1 `register.ts`: delete the typed-floor code — `slashEffort`, + `guardedSlash`, `Source` member `'slash'`, `floorSource`'s `typed /` + branch, the State comments on the typed `/effort-` floor. KEEP + `EFFORT_SKILL` + `effortBridge` (tool.call bridge, removed in W2-B) + and `turnFloor`/`higherFloor`/`floorWord` (ultrathink). +- [ ] A2 `DEFAULT_CONFIG`: phases per § Phase table (`write` high, `apply` + new); `skills` + `agents` per § Row tables; the "Built-ins only" + comment → "phase = role; one row per routed repo skill/agent (wave 2); + a project-level agent of the same name shadows its row (A3)". +- [ ] A3 spawn: (a) explicit model = `e.model !== undefined` at spawn (the + engine does not pre-fill the frontmatter; no tool_use_id map); + explicit effort as today (`explicitEffort`). (b) `spawnRoute`: + `frozen` → none; row lookup for every provider; a row is SKIPPED when + the agent's definition `source`, recorded per `subagentType` from the + `agent.offer` event, is `projectSettings` or `localSettings` (a + foreign repo's own `verifier.md`); `userSettings`, `built-in`, + `plugin` or no record → the row applies (fail-open on routing, as + W1). Known limit, stated in a comment: the record is keyed by name + only (an offer fired inside a sub-agent with another cwd overwrites it). (c) `spawnTarget` for a rowed spawn + without explicit model: resolve WITHIN the tier only, and write only + an alias ranked ≥ the tier head in `fallback` (agents move UP, never + below their frontmatter alias): `big` with opus down → fable; opus + + fable down → no write + one log line (deduped per agent+tier per + turn) "model-router: tier down, frontmatter model kept". + (d) `routedText`/`mainAnswer` always name the id the next main step + runs on (`model ()`), the sticky/floor note APPENDED, never + substituted (the gate reads this answer). +- [ ] A4 typed slash: `typedSlash: string | null` = the first token of a + slash prompt at `prompt.submit` when `origin.kind` ∈ {composer, sdk, + bridge} (allowlist; floor/default rules stay composer-only), stored + only when it is a `cfg.skills` key; mid-turn → `pendingSlash`, + promoted at `endMainTurn`. `prompt.submit` also records + `st.promptAllowed` (origin in the allowlist) for the turn it opens + (pending slot for a mid-turn prompt, like the marker). `skill.prompt` + on main (`skillCalls === 0`): apply the row when `e.skill === + typedSlash` (then null it) OR when `promptAllowed && loops.size === 0 + && spawning === 0` (`spawning` = a counter held from spawn-hook entry + to after `next`); otherwise `next(e)`. Verbose log names which path + fired (`typed-marker` / `typed-fallback`). +- [ ] A5 `onSkillLoad`: a skill WITHOUT a row leaves `turnMain` untouched + (find-docs / gstack / plugin skills mid-run no longer clear the + run's route; correctness 11); a rowed skill replaces it. Same rule + INSIDE a sub-agent (gated 2026-10-09, feater NEED-DECISION): an + unrowed skill leaves the agent loop's effort untouched; a rowed one + writes it (test: `feater` loop at medium, `Skill(find-docs)` with + that agentId → next step still medium). +- [ ] A6 run slot: new `runMain: Routed | null`. A rowed skill load ON + MAIN whose phase tier is `best` writes BOTH `turnMain` (source + `skill`, as today) and `runMain`; a non-best row loaded by the + model's `Skill` tool writes `turnMain` only (helper skills such as + `using-git-worktrees` inside SDD never drop the run); a USER-TYPED + rowed skill (marker path) replaces `runMain` with its row when best, + drops it when not. Precedence `userMain > turnMain > runMain > floor + > engine` (per axis, as today); `mainRoute` (statusline, spinner, + planStep) includes it; `endMainTurn` leaves it; `pushOrchestrate` + writes `turnMain` when empty exactly as today (derived orchestrate + overrides the run default for the dispatch span, like a `route + orchestrate` call); cleared by `/route clear` (text: "run slot + dropped" when one held), `/route off`, a user `/model` switch + (`PostModelSwitch` source command|picker|sdk); `route(clear=true)` + from the model clears `turnMain` only and its answer says "run + still holds". A `Skill` call inside a sub-agent never touches + it. `/route show` prints `run ` when no turn route is in force. +- [ ] A7 (dropped in r3: engine-effort detector, confirmation 4). +- [ ] A8 `mergeTable` accepts `null` in the override's `skills`/`agents` + to drop a default row (robustness 4). +- [ ] A9 `register.test.ts`: delete the typed `/effort-*` floor tests; + keep the bridge test; add — typed `/feat` (prompt.submit `/feat x`, + origin composer, then skill.prompt feat) → `main: skill reflect`, + `effort high`, `[tier best]`; origin `channel`: not armed AND the + idle fallback refused (main untouched); skill.prompt `feat` with a + live sub-agent and no marker → main untouched; same with no live loop + and an allowed origin → routed; a mid-turn `/status` → pending, + applied after turn.complete; `Skill(find-docs)` (no row) after + `route plan` keeps plan — the existing test 'floor: survives a skill + load' (register.test.ts:341-348) is REWRITTEN to assert orchestrate + KEPT (A5 behavior, authorized here); run slot: `Skill(feat)`, then + `route orchestrate`, then `turn.complete` → `/route show` back to + `run reflect`; `Skill(using-git-worktrees)` (mechanical, model path) + keeps `run reflect` under a mechanical turn route; a TYPED `/status` + drops the run slot; `/route clear` drops it; `/route off` drops it; + PostModelSwitch source `command` drops it; a `Skill(feat)` with an + agentId leaves `runMain`; `Skill(effort-low)` bridge then + `turn.complete` → session defaults (not sticky); `feater` spawn (provider + `{plugin:'engine',tier:'core'}`, no model) → `started.model` = sonnet + full id and the first `turn.step` of that agentId at medium; + `plan-challenger` with opus down → fable id; opus AND fable down → + no write, one log line; explicit `model`/`effort` win; `fork: true` + untouched; a project-source `agent.offer` record → no write; route + answer text names the id with a floor in force; override `agents: { + verifier: null }` drops the row (bottom `fs`/`env` mocked like + `session.model`; if the kit refuses, the case is dropped and said so). +- Disposition: honors BDR-115 (one writer per axis while on, full ids, + config tables, closure state; rule 4 closed, rule 5 amended by A5/A6), + BDR-107/108 (roles + levels preserved except analyzer), BDR-076/077 + (judge rows = opus, off-state floor kept), LRN-205, LRN-206, LRN-207 + (breaker feeds the tier resolution). + +## Gate between A and B — live probe (user runs `/reload-plugins`) +Evidence into the W2-B contract: (1) typed `/status` → `/route show` main +`skill mechanical`; (2) a real `plugin-probe` or `feater` dispatch with +verbose on → spawn log line (provider shape, model id written) + `step 0 +agent …` effort line = spawn/first-step ordering fact the TODO asks for; +(3) on a SONNET session (`/model sonnet`, then back): typed `/feat` → the +self-check wording of the system prompt + the `route` answer id (gate +witness fact); (4) probe (1) again with a background Explore alive (marker +path vs fallback path in the verbose log). The verbose log line (`typed-marker` / +`typed-fallback`, `spawn … → `, `step 0 agent …`) is the witness for +(1), (2), (4), not `/route show` after the turn (turn-scoped routes are +gone by then). Decision rules: (2) step 0 BEFORE the spawn bookkeeping → +step 0 runs on the frontmatter `effort:` (kept, D2), recorded as a known +limit; (4) `typed-marker` never seen → W2-B blocked, A4 re-planned (the +`prompt.submit` text fact does not hold). Only then W2-B. + +## W2-B — repo migration (own contract) +- [ ] B0 mod: delete `EFFORT_SKILL`, `effortBridge`, the Skill-hook branch, + their test; `agents/`+`skills/` rows unchanged. +- [ ] B1 `lib/effort-shift.md` rewritten (~40 lines): route doctrine, the + wiring points in `route` terms (D3), judgment built-ins carry + `effort=`, sticky skill route + `/route clear`, no pairing rule, + headless OK (hooks run under -p), levers = `ultrathink` / `/route + effort=max` (builtin `/effort` is not a lever inside a run), last ROWED + skill loaded wins + (an unrowed one changes nothing). +- [ ] B2 citers `Skill(effort-*)` → `route`: ship-feature 9, init-project + 5, feat 4, bugfix 4, web-validate 3, seo 3, hotfix 3, geo 3, + verify-secure-loop 3, harden 2, code-clean 2, audit-delta 2, onboard + 1, client-handover-writer 1; EFFORT SHIFTS header lines in the 13 + orchestrators + tour:33; `effort=` added to every `general-purpose` + judgment dispatch (`model="opus"`: ship-feature, init-project, + onboard ×7, tour; `model: "fable"` skill-runners in + client-handover-writer); STOP/remedy texts (challenge-plan.md:62, + verify-secure-loop.md:109) → the D4 levers; the 21 prose sites + stating "sonnet by frontmatter pin" / "`model: opus`-pinned, + session-independent" (challenge-plan:46, feat:146, bugfix:160, + hotfix:138, code-clean:175, seo:463, 6 agents…) reworded "routed by + the model-router row (frontmatter = off-state floor)". +- [ ] B3 `lib/model-gate.md` → D4 (≤ 25 lines, keeps `model: "fable"` for + skill-runners and the dispatch-tier table); delete + `lib/model-check.sh`, `lib/tests/model-check.test.sh`. +- [ ] B4 delete `lib/effort-pins.txt`, `lib/effort-pins.sh`, + `lib/tests/effort-pins.test.sh`; remove the re-apply blocks + comments + in `install-plugins.sh` (941-943, 1008 comment, 1131-1136) and + `update-all.sh` (472, 567-572); `lib/tests/higgsfield.test.sh` + :324 + the `before-pins` check (:330-356) dropped. +- [ ] B5 `skills/effort-*` deleted (5 dirs; `profile`/catalog lists + grepped). Tracked frontmatter KEPT and ALIGNED: `agents/analyzer.md` + `effort: xhigh`; the vendored tracked `design-motion-principles` + keeps `effort: high`; impeccable-* (gitignored) untouched; every + other `model:`/`effort:` value already equals its row. +- [ ] B6 census: `lib/tests/effort-routing.test.sh` rewritten — every + tracked `effort:` equals its row's phase effort and every agent + `model:` alias equals its row's tier head (drift lock, both + directions, parsed from `register.ts`; haiku rows exempt from the + effort direction: no effort on haiku); enumeration = tracked + `SKILL.md` under `skills/` + `skills-external/` (`git ls-files`), + no-row list = graphify, model-router, find-docs, impeccable, the + agents interviewer/client-handover-writer/impeccable-*; no + `Skill(effort-` anywhere in + skills/agents/lib; D3 wiring markers (orchestrate in the 11, apply + tail in the 5, escalate ×3 in verify-secure-loop + ship-feature, + `effort=` on every `model="opus"` general-purpose dispatch); every + tracked skill/agent (minus the no-row list) has a row in + `register.ts` with the EXPECTED PHASE (per-name asserts, not mere + presence); `model-routing.test.sh` :96-97 model-gate locks + updated (the 18 `model:` locks, loops-light.test.sh:74,79 and + plan-challenger.test.sh:20 stay valid: frontmatter kept); `CLAUDE.global.md` Design + work lines 299-301 → "rows in the mod, an unrowed member changes + nothing". +- [ ] B7 doctrine-citers census; full `make test` once before merge. +- [ ] STEP 6/7 of the B run: doc-syncer audit → README/USAGE/ARCHITECTURE/ + CHANGELOG; BDR-115 amendment (wave 2 closed, D1-D4, A5/A6), LRN + (typed-slash marker + sticky skill route), EVAL on the run; TODO W2 + lines checked. + +## Challenge ledger (r1 → r2) +- robustness 1 BLOCKER (mod off → agents inherit the parent model) → + D2: `model:` frontmatter kept as off-state floor; A3c row overrides it + while on. +- correctness 1/2, robustness 2 (marker unbound, ordering unproven) → A4 + name-bound marker + pending slot + loops-size fallback; live probe gate. +- correctness 3 (show text) → A9 asserts `skill reflect`. +- correctness 4 (56) → fixed everywhere. +- correctness 5, simplicity 1/2, robustness 13 (level deltas) → `write` + high + `apply` phase; one delta left (analyzer), named. +- correctness 6 (raise lasts one turn) → A6 sticky skill route. +- correctness 7, robustness 5, simplicity 8 (gate witness) → D4 route answer. +- correctness 8, robustness 11, simplicity 7 (point 5) → explicit `effort=`. +- correctness 9, robustness 6 (levers) → D4 texts (r2's A7 engine-effort + detector dropped again in r3). +- correctness 10, robustness 9/10 (census) → B6 per-phase asserts, suites + listed; no `effort="high"` call-site edits (write = high). +- correctness 11 (unrowed skill clears) → A5. +- correctness 12, robustness 12, simplicity 11 (counts, impeccable) → B5 + from `git ls-files`; impeccable untouched. +- correctness 13 (dead code) → A1 list; contract criterion 5 grep widened. +- correctness 14 (override test needs fs) → A9 bottom mocks or drop, stated. +- correctness 15, robustness 4/8 (provider shape, collisions) → A3b + source from `agent.offer` + A8 null rows; tests use `engine/core`. +- robustness 3 (haiku via fallback chain) → A3c tier-only + log. +- robustness 7 (live edits mid-migration) → bridge stays until B0; probe + gate before B. +- robustness 14 (tour:33, install comment) → B2/B4. +- robustness 15 (deploy on haiku) → `apply` rows. +- simplicity 3 (tail) → kept as `route(phase="apply")` (phases only; the + switch-on cost is the user's opt-in). [kept, reasoned] +- simplicity 4 (W2-C) → folded into W2-B STEP 6/7. +- simplicity 12 (two parsers) → contract oracle = one-shot values; B6 = + durable per-phase census. [kept, reasoned] + +## Confirmation ledger (r2 → r3) +- conf 1 BLOCKER (route calls wipe the sticky slot) → A6 separate `runMain` + slot, turn writers never touch it. +- conf 2 (low/haiku leaks across turns) → only best-tier rows enter `runMain`. +- conf 3 (bridge sticky in the A→B window) → bridge writes `turnMain` only. +- conf 4 (engine-effort detector) → A7 dropped; builtin `/effort` named as + a non-lever to the user; levers = `ultrathink`, `/route effort=max`. +- conf 5 (route answer without id) → A3d always names the id, note appended; + probe (3) on a sonnet session. +- conf 6 (fs/cwd shadow unreliable) → A3b definition source from + `agent.offer`; fs dropped. +- conf 7 (judge → sonnet in-tier) → A3c rank ≥ tier head, else no write + log. +- conf 8 (off-state quality drop, step-0 ordering) → D2 frontmatter kept + as floor on both axes, census-locked; probe decision rule written. +- conf 9 (pre-fill premise) → explicit = `e.model !== undefined`, no map. +- conf 10 (origin denylist) → allowlist composer|sdk|bridge. +- conf 11 (preload before trackLoop) → spawning counter; log names the path. +- conf 12 (kit has no fs) → fs dropped. conf 13 → deduped log. +- conf 14 (skill rows shadow) → accepted, named: skill rows affect main + only; a foreign skill of the same name gets the row for its turn. +- conf 15 (artefact drift) → contract clarification amended; status-reporter + listed under mechanical. + +## Confirmation 2 ledger (r3 → r4) +- conf2 1 (helper skill drops the run) → A6: model-loaded non-best rows + write turnMain only; typed rowed skills manage runMain. +- conf2 2 (test :347 goes red) → A9 authorizes its rewrite. +- conf2 3 (fallback ignores origin) → A4 `promptAllowed` flag on the fallback. +- conf2 4/5/6 (runMain wiring) → A6 names both slots, mainRoute, clearLoop + text, pushOrchestrate, `/model` + `/route off` + sub-agent cases in A9. +- conf2 7 (probe witnesses) → gate: verbose lines + decision rules. +- conf2 8 (grep) → contract criterion 5 narrowed. +- conf2 9 (source tokens) → A3b names projectSettings|localSettings + limit. +- conf2 10/11 (census) → B6 enumeration, haiku exemption, cites fixed. From 1f2d33b7a6df6df8e2565ad72f2e7ad1c47935b7 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 10 Oct 2026 11:24:54 +0200 Subject: [PATCH 052/547] =?UTF-8?q?feat(model-router):=20wave=202-B=20?= =?UTF-8?q?=E2=80=94=20orchestrators=20declare=20phases,=20shifters=20and?= =?UTF-8?q?=20pins=20removed,=20frontmatter=20=3D=20off-state=20floor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 15 Skill(effort-*) citers now call mcp__model-router__route per phase (orchestrate at a dispatch span, reflect/plan for the skill's own level, apply at the bookkeeping tail, escalate at the verify-secure caps); built-in judgment dispatches carry an explicit effort= param. lib/effort-shift.md is the route doctrine, lib/model-gate.md the mod rule (route answer = witness, /route on as remedy). Deleted: skills/effort-*, lib/effort-pins.txt/.sh, lib/model-check.sh, their tests, the installers' re-apply blocks. The mod drops its Skill(effort-*) bridge. The tracked model:/effort: frontmatter stays as the off-state floor, census-locked equal to the rows (lib/tests/effort-routing.test.sh rewritten, 140 checks; analyzer → xhigh). Contract .claude/tasks/contracts/2026-10-10-model-router-w2b-1045.md, plan r4 § W2-B: GATE 0 MET, verifier ECARTS(7) then CONFORME 10/10, security PASS, full make test green (design-tool-gate env red only). --- CLAUDE.global.md | 7 +- agents/analyzer.md | 2 +- agents/client-handover-writer.md | 20 +- agents/commit-changer.md | 2 +- agents/doc-syncer.md | 4 +- agents/geo-analyzer.md | 2 +- agents/handover-doc-writer.md | 2 +- agents/plan-challenger.md | 10 +- agents/seo-analyzer.md | 2 +- install-plugins.sh | 14 +- lib/challenge-plan.md | 10 +- lib/effort-pins.sh | 120 ------------ lib/effort-pins.txt | 46 ----- lib/effort-shift.md | 121 +++++------- lib/model-check.sh | 33 ---- lib/model-gate.md | 69 +++---- lib/tests/effort-pins.test.sh | 129 ------------ lib/tests/effort-routing.test.sh | 240 ++++++++++++----------- lib/tests/higgsfield.test.sh | 16 +- lib/tests/model-check.test.sh | 25 --- lib/verify-secure-loop.md | 9 +- mods/model-router/hooks/register.test.ts | 26 --- mods/model-router/hooks/register.ts | 35 +--- skills/audit-delta/SKILL.md | 6 +- skills/bugfix/SKILL.md | 12 +- skills/code-clean/SKILL.md | 8 +- skills/commit-change/SKILL.md | 2 +- skills/effort-high/SKILL.md | 6 - skills/effort-low/SKILL.md | 6 - skills/effort-max/SKILL.md | 6 - skills/effort-medium/SKILL.md | 6 - skills/effort-xhigh/SKILL.md | 6 - skills/feat/SKILL.md | 12 +- skills/geo/SKILL.md | 8 +- skills/harden/SKILL.md | 6 +- skills/hotfix/SKILL.md | 10 +- skills/init-project/SKILL.md | 16 +- skills/onboard/SKILL.md | 13 +- skills/seo/SKILL.md | 10 +- skills/ship-feature/SKILL.md | 26 +-- skills/tour/SKILL.md | 6 +- skills/web-validate/SKILL.md | 8 +- update-all.sh | 12 +- 43 files changed, 318 insertions(+), 811 deletions(-) delete mode 100755 lib/effort-pins.sh delete mode 100644 lib/effort-pins.txt delete mode 100644 lib/model-check.sh delete mode 100755 lib/tests/effort-pins.test.sh delete mode 100644 lib/tests/model-check.test.sh delete mode 100644 skills/effort-high/SKILL.md delete mode 100644 skills/effort-low/SKILL.md delete mode 100644 skills/effort-max/SKILL.md delete mode 100644 skills/effort-medium/SKILL.md delete mode 100644 skills/effort-xhigh/SKILL.md diff --git a/CLAUDE.global.md b/CLAUDE.global.md index c784bb1..b3c5419 100644 --- a/CLAUDE.global.md +++ b/CLAUDE.global.md @@ -295,10 +295,9 @@ design routing; the design-toolchain hook reinforces it. - Design system / brand → design-consultation first, then the build tools. - Review / audit → design-review + emil-design-eng + design-motion-principles + /impeccable audit|critique + `impeccable detect` floor. -- Load the stack paired with the first Read of the target file, never - alone (a lone Skill call applies no effort, `lib/effort-shift.md`); every - vendored member pins `high`, one level per stack (`lib/effort-pins.txt`); - plugin and gstack members run at the level in force. +- The vendored stack members route to `reflect` (high) through their + model-router rows (`mods/model-router`); the last rowed skill loaded + wins and an unrowed member (plugin, gstack) changes nothing. Scope doubt → ask or default to Build, never silently skip. Gate: light skills run `~/.claude/lib/design-gate.md`, orchestrators plugin-check. 21st = CLI (`npm i -g @21st-dev/cli`, `21st login`), no MCP, no key; search free, diff --git a/agents/analyzer.md b/agents/analyzer.md index 84b7f0a..5b94959 100644 --- a/agents/analyzer.md +++ b/agents/analyzer.md @@ -3,7 +3,7 @@ name: analyzer description: Analyze code, codebase, or problem before any modification. Produces a factual report without proposing solutions. Use proactively before any refactoring, design, or implementation. tools: Read, Grep, Glob, Bash model: opus -effort: high +effort: xhigh memory: project --- diff --git a/agents/client-handover-writer.md b/agents/client-handover-writer.md index c608bed..c444a2f 100644 --- a/agents/client-handover-writer.md +++ b/agents/client-handover-writer.md @@ -97,7 +97,7 @@ Parse `$ARGUMENTS` for optional flags: --- -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## STEP 1 — PRE-FLIGHT @@ -227,7 +227,7 @@ Store `DEPLOYED_URL` for STEP 7. If empty, ask user during STEP 6. --- ## STEP 3 — BASELINE AUDITS (parallel) -First: `Skill(effort-high)` (effort-shift: judgment dispatch; the fable skill-runners are built-ins and inherit the level in force; high is the entry level of the audits they run). +Every skill-runner dispatch below carries an explicit `effort="high"` (route: built-ins never inherit a main route; high is the entry level of the audits they run). Goal: capture `SCORE_*_BEFORE` so the client doc shows the delta. @@ -262,10 +262,10 @@ the gate. **Model routing (BDR-077):** EVERY `general-purpose` skill-runner dispatch in this pipeline (initial audits, fix-loop re-dispatches, commit-change, -web-validate) carries `model: "fable"` — the child hosts gated orchestration -on the pipeline's behalf; it must never inherit the session model. +web-validate) carries `model: "fable"` and `effort="high"` — the child hosts gated +orchestration on the pipeline's behalf; it must never inherit the session model. -For web projects, dispatch in **a single message with two parallel Agent calls** (each with `model: "fable"`): +For web projects, dispatch in **a single message with two parallel Agent calls** (each with `model: "fable"`, `effort="high"`): | Audit (web) | Subagent | Prompt template | |---------------|-------------------|-----------------| @@ -424,7 +424,7 @@ for CSO) in the format ### Re-dispatch prompt template (SEO + GEO loop) -Send to `general-purpose` subagent (`model: "fable"`): +Send to `general-purpose` subagent (`model: "fable"`, `effort="high"`): > Read `~/.claude/skills/seo/SKILL.md` and re-run it on this project in > **conservative (audit-only) intervention mode**: re-score and leave both @@ -455,7 +455,7 @@ Send to `general-purpose` subagent (`model: "fable"`): ### Re-dispatch prompt template (HARDEN loop) -Send to `general-purpose` subagent (`model: "fable"`): +Send to `general-purpose` subagent (`model: "fable"`, `effort="high"`): > Read `~/.claude/skills/harden/SKILL.md` and re-run it with `--fix` ONLY > up to the bundle: stop at `READY TO APPLY — awaiting dispatcher @@ -468,7 +468,7 @@ Send to `general-purpose` subagent (`model: "fable"`): ### Re-dispatch prompt template (CSO loop — non-web only) -Send to `general-purpose` subagent (`model: "fable"`): +Send to `general-purpose` subagent (`model: "fable"`, `effort="high"`): > Read `~/.claude/skills/cso/SKILL.md` and re-run it in **daily mode**. > Previous score: **``/20** — below threshold. @@ -557,7 +557,7 @@ listed changes by hand before deploy." Continue to STEP 6. If `PENDING_CHANGES` non-empty → invoke /commit-change skill via subagent: -> Dispatch `general-purpose` subagent (`model: "fable"`). Prompt: +> Dispatch `general-purpose` subagent (`model: "fable"`, `effort="high"`). Prompt: > > "Read `~/.claude/skills/commit-change/SKILL.md` and execute. All pending > changes were produced by the client-handover ship pipeline during the @@ -677,7 +677,7 @@ Skip if `VALIDATE_SKIPPED=true` or `PROJECT_TYPE != web` (in either case ensure `VALIDATE_SKIPPED=true` is set so the gate logic in STEP 8 treats VALIDATE as not-applicable rather than failed). -Dispatch `general-purpose` subagent (`model: "fable"`): +Dispatch `general-purpose` subagent (`model: "fable"`, `effort="high"`): > Read `~/.claude/skills/web-validate/SKILL.md` and execute against the > deployed URL: ``. Audit W3C HTML validity (validator.nu), diff --git a/agents/commit-changer.md b/agents/commit-changer.md index b74d68b..af624a0 100644 --- a/agents/commit-changer.md +++ b/agents/commit-changer.md @@ -10,7 +10,7 @@ effort: high > MODEL (BDR-077): `MODE: propose` is dispatched with `model="opus"` (the > call-site override — narrative reconstruction + capitalize routing are -> judgment); `MODE: apply` runs on the sonnet frontmatter pin (mechanical +> judgment); `MODE: apply` runs on its sonnet row (frontmatter = off-state floor; mechanical > staging/committing of an approved plan). Reconstruct the development narrative from a working directory. The goal diff --git a/agents/doc-syncer.md b/agents/doc-syncer.md index 08bf745..7fbaaaf 100644 --- a/agents/doc-syncer.md +++ b/agents/doc-syncer.md @@ -60,8 +60,8 @@ audit, report, and patch. Parse `$ARGUMENTS`: - **`MODE: patch`** — the dispatcher approved a PATCH PLAN and re-dispatches - this agent to APPLY it. Jump to MODE: PATCH section. Runs on the sonnet - frontmatter pin. + this agent to APPLY it. Jump to MODE: PATCH section. Runs on its sonnet + row (frontmatter = off-state floor). - **`MODE: audit`** (or no explicit MODE — audit is the default) — analysis half, dispatched with `model: "opus"` (judgment tier; the call-site override takes precedence over the sonnet pin). **READ-ONLY: Write and diff --git a/agents/geo-analyzer.md b/agents/geo-analyzer.md index 22f37d9..77d845b 100644 --- a/agents/geo-analyzer.md +++ b/agents/geo-analyzer.md @@ -104,7 +104,7 @@ Mirror of seo-analyzer's pipeline contract. Parse the MODE line: to the run-scoped, gitignored `.audit/geo-signals-.md`, terminated by `COLLECTION COMPLETE — RUNID: `; emit a `COLLECT REPORT` (`STATUS`, RUNID, COVERAGE counts) and STOP. -- **`MODE: judge`** — opus frontmatter pin. Fail-closed load of +- **`MODE: judge`** — opus row (frontmatter = off-state floor). Fail-closed load of `.audit/geo-signals-.md` (absent / RUNID mismatch / missing sentinel → `GEO JUDGE — VERDICT: ERROR()`, STOP — never score stale or partial signals). Then STEP 6-12 (schema, entity — including diff --git a/agents/handover-doc-writer.md b/agents/handover-doc-writer.md index 79b63dc..b2b0e79 100644 --- a/agents/handover-doc-writer.md +++ b/agents/handover-doc-writer.md @@ -57,7 +57,7 @@ The parent dispatches this agent TWICE, with the FULL PACKAGE both times (`STATUS: DONE | BLOCKED`, RUNID, phase-cluster count, per-chapter word counts) and STOPS — STEP 13-16, the final MD, HTML and PDF are NEVER this mode's job. -- **`MODE: render`** — runs on the sonnet frontmatter pin. FIRST loads the +- **`MODE: render`** — runs on its sonnet row (frontmatter = off-state floor). FIRST loads the draft: absent file, RUNID mismatch, or missing `DRAFT COMPLETE` sentinel → `STATUS: BLOCKED` naming the cause (fail closed — never synthesize a missing draft, never render a partial one). Then runs STEP 13 → 14 → diff --git a/agents/plan-challenger.md b/agents/plan-challenger.md index 58a8426..f09e1e0 100644 --- a/agents/plan-challenger.md +++ b/agents/plan-challenger.md @@ -106,11 +106,11 @@ the MAIN loop, never here): - Dispatch THREE fresh challengers IN PARALLEL, one per lens (correctness / robustness / simplicity), each blind to the others. - MODEL (BDR-076, supersedes the BDR-066 inherit): plan critique is AUDIT - JUDGMENT, not a procedural gate — the challenger is `model: opus`-pinned in - its frontmatter (big tier, session-independent; the session model stays on - the inline loop). Never `model: "sonnet"` — a silent judgment downgrade. - (Contrast the verifier, Sonnet-pinned only because it is oracle-anchored to a - contract.) + JUDGMENT, not a procedural gate — the challenger is routed to the `judge` + row (opus) by the model-router, the `model: opus` frontmatter being the off-state floor (big + tier; the session model stays on the inline loop). Never `model: "sonnet"` — + a silent judgment downgrade. (Contrast the verifier on its `verify` row and + the executors on their `implement` row, both sonnet, oracle-anchored to a contract.) - FAIL-SAFE — never fail open: a malformed/empty verdict, a missing `PROOF`, or a dead challenger → retry ONCE fresh; a 2nd failure → escalate to the human and NAME the lens. Never report "plan challenged" on a silently dropped lens (same diff --git a/agents/seo-analyzer.md b/agents/seo-analyzer.md index 9d5d580..7613567 100644 --- a/agents/seo-analyzer.md +++ b/agents/seo-analyzer.md @@ -38,7 +38,7 @@ The dispatcher (/seo) runs this agent as a 3-stage pipeline; /harden and terminated by the line `COLLECTION COMPLETE — RUNID: `, then emits a short `COLLECT REPORT` (`STATUS: DONE | BLOCKED`, RUNID, COVERAGE counts) and STOPS. No scoring, no findings, no bundle. -- **`MODE: judge`** — runs on the opus frontmatter pin (audit judgment). +- **`MODE: judge`** — runs on its opus row (audit judgment; frontmatter = off-state floor). FIRST loads `.audit/seo-signals-.md`: absent, RUNID mismatch, or missing `COLLECTION COMPLETE` sentinel → emit `SEO JUDGE — VERDICT: ERROR()` and STOP (fail closed — NEVER diff --git a/install-plugins.sh b/install-plugins.sh index c590355..3b6227a 100644 --- a/install-plugins.sh +++ b/install-plugins.sh @@ -937,10 +937,6 @@ for _ext_skill in "${EXT_SKILL_NAMES[@]}"; do done echo "" -# Effort pins (BDR-107, BDR-108): every vendored external gets its entry -# level from lib/effort-pins.txt, re-applied ONCE after the last vendoring -# step (the 21st pack, STEP 8.7) — see apply_effort_pins there. - # ============================================================ # STEP 8.5 — EXTERNAL SKILLS (npx skills add …) # ============================================================ @@ -1005,8 +1001,7 @@ echo "" # profile: `lib/toggle-external.sh enable higgsfield` turns the media skills # on, `enable higgsfield-websites` the landing-page aid. Keeping it out of # link.sh and of every profile is what stops a re-run from re-enabling it -# (BDR-093). This step runs before Step 8.7 so the effort pins are still -# re-applied after the last vendoring step (BDR-108). +# (BDR-093). echo "── Step 8.6: Higgsfield CLI + skill pack ───────────────────" echo "" # shellcheck source=lib/higgsfield-skills.sh disable=SC1091 @@ -1128,13 +1123,6 @@ if command -v 21st &>/dev/null; then rm -rf "$TFD_STAGE" fi -# Effort pins (BDR-107, BDR-108): the vendored externals carry no `effort:` -# upstream and every vendoring step above rewrites SKILL.md. Re-apply the -# entry levels from lib/effort-pins.txt once, after the LAST such step. -# shellcheck source=lib/effort-pins.sh disable=SC1091 -source "$REPO/lib/effort-pins.sh" -apply_effort_pins "$REPO" || warn "effort pins: map lines rejected — fix lib/effort-pins.txt" - # Auth — detect, then offer login ONLY in an interactive TTY. A non-interactive # run (CI / headless / re-run) must never open a browser or block on OAuth. # Search and logo lookup are free; retrieving component code and 21st AI need diff --git a/lib/challenge-plan.md b/lib/challenge-plan.md index 66d4cb1..56d454c 100644 --- a/lib/challenge-plan.md +++ b/lib/challenge-plan.md @@ -43,8 +43,9 @@ Agent(subagent_type="plan-challenger", description="challenge:", prompt="" ``` **MODEL (BDR-076, supersedes the BDR-066 inherit):** plan critique is AUDIT -JUDGMENT — the challengers are `model: opus`-pinned in their frontmatter: a big -tier, session-independent, off the session model. The session model (Fable) +JUDGMENT — the challengers are routed to the `judge` row (opus) by the model-router, +the `model: opus` frontmatter being the off-state floor: a big tier, off +the session model. The session model (Fable) keeps only this loop — synthesis, RE-THINK, gate. Never sonnet: that would silently downgrade the judgment. (The executor gates stay sonnet.) @@ -59,8 +60,9 @@ silently downgrade the judgment. (The executor gates stay sonnet.) A challenger that returns a malformed/empty verdict, a missing `PROOF`, or dies → retry ONCE with a fresh challenger; a 2nd failure on that lens → STOP and escalate -(the STOP text names the level reached, `$CLAUDE_EFFORT`, and suggests `/effort-max` -for the relaunch; no shift here: a mute challenger is an infrastructure failure) +(the STOP text names the level reached, `$CLAUDE_EFFORT`, and suggests relaunching with +`ultrathink` in the prompt (turn floor) or `/route effort=max` (sticky, +`/route clear` after); no shift here: a mute challenger is an infrastructure failure) to the human, NAMING the lens. Never carry "plan challenged" into the gate on a silently dropped lens (`verify-secure-loop.md`: "a mute verifier is NEVER a PASS"). diff --git a/lib/effort-pins.sh b/lib/effort-pins.sh deleted file mode 100755 index c8cc4d7..0000000 --- a/lib/effort-pins.sh +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env bash -# lib/effort-pins.sh — re-apply the entry effort level on vendored skills -# (BDR-107 second axis, extended to every vendored external by BDR-108). -# Upstream copies carry no `effort:` and every vendoring step rewrites -# SKILL.md, so the level lives in lib/effort-pins.txt and this helper puts -# it back after the last vendoring step of install-plugins.sh and -# update-all.sh. Idempotent: same level → untouched, other level → -# replaced inside the frontmatter only, skill not vendored → skipped, -# malformed map line → rejected loudly, never applied. Hardenings: a map -# whose last line lacks a newline is still read; a SKILL.md whose frontmatter -# never closes is skipped untouched; the level is re-read after every write -# and a mismatch counts as failed; the write goes through a mktemp sibling -# removed on any failure and on INT/TERM (previous traps restored, never an -# EXIT trap: the installer owns one); the rejected map line is printed -# shell-quoted so a caller's `echo -e` cannot interpret it. Placement inside -# the frontmatter has no effect on the harness, which reads the key anywhere. -# -# Usage: source it, then `apply_effort_pins [repo-root]` -# or standalone: bash lib/effort-pins.sh [repo-root] -# Exit 1 when at least one map line was rejected or a skill failed. - -EFFORT_PINS_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -EFFORT_PIN_LEVEL_RE='^(low|medium|high|xhigh|max)$' -EFFORT_PIN_NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]*$' - -# Callers (install-plugins.sh, update-all.sh) define these; standalone -# runs get plain fallbacks. -declare -F ok >/dev/null || ok() { printf ' ok %s\n' "$*"; } -declare -F info >/dev/null || info() { printf ' info %s\n' "$*"; } -declare -F err >/dev/null || err() { printf ' ERR %s\n' "$*" >&2; } - -# _effort_pin_current → prints the frontmatter effort, if any -_effort_pin_current() { - awk 'NR==1&&/^---$/{p=1;next} p&&/^---$/{exit} p' "$1" \ - | sed -n 's/^effort: //p' | head -1 -} - -# _effort_pin_closed → rc 0 when the frontmatter has a closing --- -_effort_pin_closed() { - awk 'NR==1&&/^---$/{p=1;next} p&&/^---$/{f=1;exit} END{exit !f}' "$1" -} - -# _effort_pin_traps_restore — drop the INT/TERM handlers set for the -# write and re-install the caller's saved ones. No exit-time handler here. -_effort_pin_traps_restore() { - trap - INT TERM - [ -z "$1" ] || eval "$1" -} - -# _effort_pin_write — replace the frontmatter -# `effort:` line, or insert one after `name: ` (before the closing -# `---` when the frontmatter has no name line). Body lines never change. -# Writes a mktemp sibling then renames; any failure leaves no temp behind. -_effort_pin_write() { - local file="$1" name="$2" level="$3" tmp prev rc - tmp="$(mktemp "$file.XXXXXX")" || return 1 - prev="$(trap -p INT TERM)" - trap 'rm -f "$tmp"; exit 130' INT TERM - cp -p "$file" "$tmp" && awk -v n="$name" -v lvl="$level" ' - NR==1 && /^---$/ { fm=1; print; next } - fm && /^---$/ { - if (!done) { print "effort: " lvl; done=1 } - fm=0; print; next - } - fm && /^effort: / { if (!done) { print "effort: " lvl; done=1 }; next } - fm && $0 == "name: " n { print; if (!done) { print "effort: " lvl; done=1 }; next } - { print } - ' "$file" > "$tmp" && mv "$tmp" "$file"; rc=$? - [ "$rc" -eq 0 ] || rm -f "$tmp" - _effort_pin_traps_restore "$prev" - return "$rc" -} - -# _effort_pin_apply_one → rc 0 applied, 2 already at -# level, 1 failed (err line printed, file untouched or write rolled back) -_effort_pin_apply_one() { - local file="$1" name="$2" level="$3" - if ! _effort_pin_closed "$file"; then - err "effort-pins: $file: frontmatter never closed — skipped"; return 1 - fi - [ "$(_effort_pin_current "$file")" = "$level" ] && return 2 - if ! _effort_pin_write "$file" "$name" "$level"; then - err "effort-pins: $file: write failed"; return 1 - fi - if [ "$(_effort_pin_current "$file")" != "$level" ]; then - err "effort-pins: $file: level not applied after write" - return 1 - fi - return 0 -} - -# apply_effort_pins [repo-root] — walk the map, pin every vendored skill -apply_effort_pins() { - local repo="${1:-$EFFORT_PINS_REPO}" map name level rest file rc - local applied=0 kept=0 rejected=0 failed=0 - map="$repo/lib/effort-pins.txt" - [ -f "$map" ] || { err "effort-pins: map missing: $map"; return 1; } - while read -r name level rest || [ -n "$name" ]; do - case "$name" in ''|'#'*) continue ;; esac - if [ -n "$rest" ] || ! [[ "$name" =~ $EFFORT_PIN_NAME_RE ]] \ - || ! [[ "$level" =~ $EFFORT_PIN_LEVEL_RE ]]; then - err "effort-pins: rejected map line $(printf '%q' "$name $level $rest")" - rejected=$((rejected + 1)); continue - fi - file="$repo/skills-external/$name/SKILL.md" - [ -f "$file" ] || continue - _effort_pin_apply_one "$file" "$name" "$level"; rc=$? - case "$rc" in - 0) applied=$((applied + 1)) ;; - 2) kept=$((kept + 1)) ;; - *) failed=$((failed + 1)) ;; - esac - done < "$map" - ok "effort-pins: $applied applied, $kept already at level, $failed failed" - [ "$rejected" -eq 0 ] && [ "$failed" -eq 0 ] -} - -if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then - apply_effort_pins "$@" -fi diff --git a/lib/effort-pins.txt b/lib/effort-pins.txt deleted file mode 100644 index 00b90dd..0000000 --- a/lib/effort-pins.txt +++ /dev/null @@ -1,46 +0,0 @@ -# lib/effort-pins.txt — entry effort level of the vendored skills -# (skills-external//SKILL.md). Upstream copies carry no `effort:` and -# every resync rewrites SKILL.md, so the pin lives here and -# lib/effort-pins.sh re-applies it after the last vendoring step of -# install-plugins.sh and update-all.sh. One line = ` `, -# level in low|medium|high|xhigh|max. The census -# lib/tests/effort-routing.test.sh checks every vendored file against this -# map. Rungs (BDR-107, BDR-108): low = fix a line, run a script · medium = -# day-to-day · high = refactor, resisting bug · xhigh = architecture, audit -# before validation · max = stuck. -# -# superpowers (obra/superpowers, plugins.lock.json "superpowers") -brainstorming xhigh -writing-plans xhigh -requesting-code-review xhigh -subagent-driven-development high -writing-skills high -test-driven-development medium -using-git-worktrees low -# -# agent-skills (addyosmani/agent-skills, plugins.lock.json "agent-skills") -deprecation-and-migration high -ci-cd-and-automation medium -observability-and-instrumentation medium -# -# design stack — ONE level for every member: these skills load stacked in a -# single UI build and the last loaded wins (lib/effort-shift.md), so two -# levels in the stack would make the effort depend on load order. -# skills/site-motion (repo-authored) pins the same level in its frontmatter. -frontend-design high -emil-design-eng high -design-motion-principles high -21st-ui-build high -scroll-world-storytelling high -build-threejs-scroll-worlds high -scroll-scrubbed-visual-sequence high -scroll-scrubbed-word-reveal high -scroll-progress-timeline high -# -# 21st pack (`21st skills install`): tooling low, generation high, critique xhigh -21st-cli-use low -21st-registry low -21st-design-sync low -21st-ai high -21st-ui-explore high -21st-ui-review xhigh diff --git a/lib/effort-shift.md b/lib/effort-shift.md index fe92b1a..dc487d0 100644 --- a/lib/effort-shift.md +++ b/lib/effort-shift.md @@ -1,85 +1,58 @@ -# Effort shift — phase-level reasoning effort on the main loop (BDR-107) +# Route doctrine — phase-level model and effort on the main loop (BDR-107) Shared include, companion of `lib/model-gate.md`: the gate fixes WHICH model -reflects, this include fixes HOW HARD each phase thinks. The rungs are the -user's: low (fix a line, run a script) · medium (day-to-day) · high -(refactor, resisting bug) · xhigh (architecture, audit before validation) · -max (stuck error, judged need). +reflects, the model-router mod (`mods/model-router`) fixes HOW HARD each +phase thinks. Rungs: low (fix a line, run a script) · medium (day-to-day) · +high (refactor, resisting bug) · xhigh (architecture, audit before +validation) · max (stuck error, judged need). -## Mechanics (verified on Claude Code 2.1.283) +## The tool -- **Pairing rule**: a `Skill(effort-)` call applies its effort only - when the same assistant message carries at least one other tool call - after it; a lone Skill call is a no-op. Send the shift together with the - step's first tool call, shift first. That paired call already runs at the - new level: pair a downward shift with a pinned-agent dispatch or a - Read/Bash, never with a built-in judgment dispatch (`general-purpose`, - `model: "opus"`), which would inherit it. -- Re-loading a shifter already loaded in the conversation re-applies its - effort (the harness only dedupes the skill text), so bounce-back - sequences such as medium → max → medium work. -- A skill's `effort:` frontmatter applies from the moment it loads to the - end of the turn: on the user's `/skill` unconditionally, and on a - `Skill(...)` call by Claude only under the pairing rule above (a skill - Claude loads alone, such as `brainstorming` or `writing-plans`, applies - nothing). Last loaded wins, both directions. The prompt cache survives a - shift. -- **Stacked skills share one level**: skills that load together in one - build (the design stack) all pin the same level, since the last loaded - wins. Vendored externals get their level from `lib/effort-pins.txt`, - re-applied by `lib/effort-pins.sh` after every vendoring step; repo - skills carry it in their frontmatter. -- Dispatched agents run on their own `effort:` pin, never on a shift. - Unpinned agents inherit the level in force at dispatch. -- Headless sessions (`-p`, `claude agents`, SDK) ignore skill-level effort: - the run stays at the session level. `CLAUDE_CODE_EFFORT_LEVEL` beats every - frontmatter; keep it unset (the session banner warns). +`mcp__model-router__route` (params `phase` | `effort` | `clear`). It is a +deferred tool: when not loaded, run +`ToolSearch("select:mcp__model-router__route")` once per session. A route +applies from the next request on, paired with +another tool call or not (pairing only saves a request). The answer always +names the id and effort main runs on. A skill with a row routes itself on +load; a skill without one changes nothing, the last ROWED skill wins. + +## Wiring points + +1. Dispatch span starts → `route(phase="orchestrate")`, sent with the + dispatch. +2. Reflection resumes (challenge synthesis, verdict, plan revision) → + `route(phase="reflect")` or `"plan"` per the skill's own level; the line + before every `lib/challenge-plan.md` call. +3. Bookkeeping tail (memory commit, doc commit) → `route(phase="apply")`. +4. Escalation → `route(phase="escalate")`: verify-secure loop caps and + ship-feature STEP 4b. Not automatic: the challenge fail-safe and "gone + WRONG → STOP"; their STOP text names the levers below. +5. Built-in judgment dispatch (`general-purpose` `model="opus"`, `model: + "fable"` skill-runners) → explicit `effort=` on the Agent call (`xhigh` + for opus reviewers, `high` for fable runners). A main route never + reaches a child. Typed agents run on their row, never on a shift. +6. After a prose gate that ends the turn, the resumed reflection phase + starts with its own route call. + +## Run slot and levers + +A best-tier skill row survives the end of the turn (a run spans prose +gates); `/route clear`, `/route off` and a user `/model` drop it. Levers for a +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. + +## Limits + +- A skill typed while a background agent is live routes only through the + typed marker (unverified live 2026-10-10). +- Headless (`-p`, SDK) runs the hooks, so routing works there too. +- Mod off: typed agents fall back to their `model:`/`effort:` frontmatter. Measure the split any time: `python3 ~/.claude/lib/effort-audit.py` (thinking/output/cache tokens per scope, model and effort). -## Shifters - -`Skill(effort-low)` · `Skill(effort-medium)` · `Skill(effort-high)` · -`Skill(effort-xhigh)` · `Skill(effort-max)`. One tool call, one-line body, -always sent with another tool call (Pairing rule). -Typed by the user, `/effort-max` is a turn-scoped max: the relaunch lever -after a STOP. `ultrathink` only adds an in-context nudge; the API level -does not move. - -## Wiring — per orchestrator - -1. A dispatch span starts (executor, collector, fan-out) → - `Skill(effort-medium)`. -2. Reflection resumes after a dispatch span (challenge synthesis, verdict, - plan revision) → `Skill(effort-)`. Concretely: - the line before every `lib/challenge-plan.md` call. -3. The bookkeeping tail (memory commit, doc commit) → `Skill(effort-low)`. -4. Escalation → `Skill(effort-max)`, then the skill's own level again once - the diagnosis is produced. Automatic points: verify-secure loop caps - (GATE 0 floor, GATE 1 conformity, GATE 2 security) and ship-feature - STEP 4b. Not automatic, by doctrine: the challenge fail-safe (a mute - challenger is an infrastructure failure) and "gone WRONG → STOP" (STOP - precedes any further reasoning); their STOP text names the level - reached and suggests `/effort-max` for the relaunch. -5. Before any built-in or unpinned dispatch that carries judgment (a - `general-purpose` with `model: "opus"` or `"fable"`, the code reviewer - of requesting-code-review, a skill-runner) → `Skill(effort-)` - paired with that dispatch: built-ins inherit the level in force, and a - medium set earlier in the span would downgrade them. - -## Re-assert - -- After any nested `Skill(...)` whose frontmatter carries a different - effort (feat → commit-change), reload the orchestrator's own level. -- After a prose gate that ends the turn, the resumed turn runs at the - session level. If the resumed phase is reflection, its first step is - `Skill(effort-)`; dispatch and orchestration phases need - nothing. - ## Never -- A shift never inside a dispatched agent: pins rule there. +- A route inside a dispatched agent: its row rules there. - Max is for diagnosis, not for retrying the same fix harder. -- A medium shift never precedes a judgment dispatch in the same span - without an own-level shift paired with that dispatch. diff --git a/lib/model-check.sh b/lib/model-check.sh deleted file mode 100644 index 1cd3cf5..0000000 --- a/lib/model-check.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -# lib/model-check.sh — classify the persisted session model: big | small | unknown -# -# Witness for lib/model-gate.md (reflection requires a big model). Reads the -# "model" key of the user-scope settings (the file /model rewrites — LRN-098). -# Override the source with MODEL_CHECK_SETTINGS (tests use fixtures). -# -# stdout : : (raw = value found, empty if none) -# exit : 0 = big (fable/opus) · 2 = small (sonnet/haiku) · 3 = unknown -set -u - -SETTINGS="${MODEL_CHECK_SETTINGS:-$HOME/.claude/settings.json}" - -raw="" -if [ -f "$SETTINGS" ]; then - raw="$(python3 - "$SETTINGS" 2>/dev/null <<'PY' -import json, sys -try: - v = json.load(open(sys.argv[1])).get("model", "") - print(v if isinstance(v, str) else "") -except Exception: - print("") -PY -)" -fi - -norm="$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]')" -case "$norm" in - *opusplan*) printf 'unknown:%s\n' "$raw"; exit 3 ;; # opus-for-plan, sonnet otherwise — ambiguous - *fable*|*opus*) printf 'big:%s\n' "$raw"; exit 0 ;; - *sonnet*|*haiku*) printf 'small:%s\n' "$raw"; exit 2 ;; - *) printf 'unknown:%s\n' "$raw"; exit 3 ;; -esac diff --git a/lib/model-gate.md b/lib/model-gate.md index 874cd23..85a5ab7 100644 --- a/lib/model-gate.md +++ b/lib/model-gate.md @@ -1,53 +1,30 @@ # Model gate — reflection requires a big model (BLOCKING) -Shared include. Runs FIRST in any orchestrator whose reflection — -brainstorming, planning, contract, audit judgment, loop decisions — -executes inline or in inherit-model subagents. Sonnet-pinned executors are -not what this gate protects; it protects the thinking around them (BDR-066). +Shared include, runs FIRST in an orchestrator whose reflection executes +inline (BDR-066). The witness is the model-router mod's own route tool. -## 1. Self-check +## Entry call +ALWAYS call `mcp__model-router__route` with `phase` = the skill's row phase +(reflect or plan), no self-check shortcut. Tool not loaded (deferred) → +`ToolSearch("select:mcp__model-router__route")` once per session, then +call. The answer names the id main runs on next. -Your system prompt names the model powering this session. Fable or Opus → -big. Sonnet, Haiku, anything else → small. +| answer | action | +|---|---| +| names a fable or opus id | proceed, SILENT | +| names sonnet, haiku, anything else; "is off"; tool absent | **STOP** | -## 2. Witness — deterministic check +**STOP means**: print exactly `⛔ MODEL GATE — session on . +Reflection steps of this skill require Fable or Opus. Switch with /model, +then relaunch the skill.` (mod off: say so, `/route on` resumes it), then +end +the turn. No later step runs, no agent is dispatched, nothing is edited. - bash "$HOME/.claude/lib/model-check.sh" - -Output `:`; exit 0 = big, 2 = small, 3 = unknown. The witness -reads the PERSISTED model (settings.json — the file `/model` rewrites, -LRN-098). It can lag reality (session launched with `--model`, settings not -yet rewritten) — that is why the self-check exists alongside it. - -## 3. Verdict - -| self-check | witness | action | -|---|---|---| -| big | big (0) | proceed, SILENT — the nominal path prints nothing | -| small | any | **STOP** | -| big | small (2) | disagreement — **STOP**, surface BOTH values; the user confirms or relaunches | -| big | unknown (3) | fail-visible: print `model gate: witness unknown () — self-check says ` and ask the user to confirm before continuing (BDR-025: unknown never silently passes) | - -**STOP means**: print exactly - - ⛔ MODEL GATE — session on . Reflection steps of this skill - require Fable or Opus. Switch with /model, then relaunch the skill. - -then end the turn. No later step runs, no agent is dispatched, nothing is -edited. - -## 4. Dispatch tiers (BDR-077 — no inherit) - -The gate guards the MAIN loop only. Dispatched work NEVER inherits the -session model: typed agents run on their frontmatter pin; built-ins +## Dispatch tiers (BDR-077 — no inherit) +The gate guards the MAIN loop only. Typed agents are routed by their +model-router row (`model:` frontmatter = off-state floor). Built-ins (general-purpose / Explore / Plan) carry an explicit `model=` at every call -site — `model: "fable"` when the child performs reflection/orchestration on -the main loop's behalf (skill-runners), otherwise its complexity tier -(opus = dispatched judgment, sonnet = execution/collection, haiku = short -mechanical probes). - -Effort is the second axis of the same table (BDR-107): every typed agent -carries an `effort:` pin next to `model:`, and the main loop shifts per phase -through `lib/effort-shift.md`. No typed agent inherits either axis; -built-ins inherit the effort in force at dispatch, so an orchestrator shifts -before dispatching them (`lib/effort-shift.md`, wiring point 5). +site: `model: "fable"` when the child reflects/orchestrates for the main +loop (skill-runners), else its tier (opus = dispatched judgment, sonnet = +execution, haiku = mechanical probes). A built-in judgment dispatch also +carries an explicit `effort=` (`lib/effort-shift.md`). diff --git a/lib/tests/effort-pins.test.sh b/lib/tests/effort-pins.test.sh deleted file mode 100755 index 329136c..0000000 --- a/lib/tests/effort-pins.test.sh +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env bash -# lib/tests/effort-pins.test.sh — lib/effort-pins.sh's apply_effort_pins(): -# insert after `name:`, keep an equal level untouched, replace a different -# level inside the frontmatter only (a prose `effort:` in the body stays), -# skip a skill not vendored, insert before the closing `---` when the -# frontmatter has no name line, run idempotently, reject a bad level, a -# traversal name and a three-field line before writing anything, and -# parse the real map without error; hardening: last map line without a -# newline, unterminated frontmatter, CRLF file and read-only directory. All on a throwaway fixture repo. -set -u -ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -LIB="$ROOT/lib/effort-pins.sh" -pass=0; fail=0 -check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); echo "PASS $1" - else fail=$((fail+1)); echo "FAIL $1: got[$2] want[$3]"; fi; } -fm_effort() { awk 'NR==1&&/^---$/{p=1;next} p&&/^---$/{exit} p' "$1" \ - | sed -n 's/^effort: //p' | head -1; } - -WORK="$(mktemp -d)" || exit 1; trap 'rm -rf "$WORK"' EXIT -REPO="$WORK/repo"; EXT="$REPO/skills-external" -mkdir -p "$REPO/lib" "$EXT/alpha" "$EXT/beta" "$EXT/gamma" "$EXT/noname" -printf -- '---\nname: alpha\ndescription: a\n---\nbody\n' > "$EXT/alpha/SKILL.md" -printf -- '---\nname: beta\neffort: low\n---\nprose says effort: max here\n' > "$EXT/beta/SKILL.md" -printf -- '---\nname: gamma\neffort: low\n---\nbody\n' > "$EXT/gamma/SKILL.md" -printf -- '---\ndescription: no name line\n---\nbody\n' > "$EXT/noname/SKILL.md" -printf '# map\nalpha high\nbeta medium\ngamma low\nghost xhigh\nnoname low\n' > "$REPO/lib/effort-pins.txt" -gamma_before="$(cat "$EXT/gamma/SKILL.md")" - -bash "$LIB" "$REPO" >/dev/null 2>&1; check T1-rc-clean "$?" 0 -check T2-insert-after-name "$(sed -n '3p' "$EXT/alpha/SKILL.md")" "effort: high" -check T3-replace-in-frontmatter "$(fm_effort "$EXT/beta/SKILL.md")" "medium" -check T3b-body-prose-untouched "$(grep -c 'effort: max' "$EXT/beta/SKILL.md")" 1 -check T3c-single-effort-line "$(grep -c '^effort:' "$EXT/beta/SKILL.md")" 1 -check T4-equal-level-untouched "$(cat "$EXT/gamma/SKILL.md")" "$gamma_before" -check T5-missing-skill-skipped "$([ -e "$EXT/ghost" ] && echo created || echo absent)" absent -check T6-no-name-inserts-before-closing "$(sed -n '3p' "$EXT/noname/SKILL.md")" "effort: low" -check T6b-no-name-still-frontmatter "$(fm_effort "$EXT/noname/SKILL.md")" "low" -snap="$(cat "$EXT"/*/SKILL.md)" -bash "$LIB" "$REPO" >/dev/null 2>&1 -check T7-idempotent "$(cat "$EXT"/*/SKILL.md)" "$snap" -check T7b-no-tmp-left "$(find "$EXT" -name '*.tmp' | wc -l | tr -d ' ')" 0 - -# rejections: nothing written, rc 1 -for bad in 'alpha turbo' '../evil high' 'alpha high extra'; do - printf '%s\n' "$bad" > "$REPO/lib/effort-pins.txt" - out="$(bash "$LIB" "$REPO" 2>&1)"; rc=$? - check "T8-rejected[$bad]-rc" "$rc" 1 - check "T8-rejected[$bad]-named" "$(printf '%s' "$out" | grep -c 'rejected map line')" 1 -done -check T8b-tree-unchanged-after-rejections "$(cat "$EXT"/*/SKILL.md)" "$snap" -check T8c-no-evil-dir "$([ -e "$WORK/evil" ] && echo created || echo absent)" absent - -# the real map parses: fixture repo with the real map and no vendored skill -mkdir -p "$WORK/real/lib" "$WORK/real/skills-external" -cp "$ROOT/lib/effort-pins.txt" "$WORK/real/lib/" -out="$(bash "$LIB" "$WORK/real" 2>&1)"; check T9-real-map-parses "$?" 0 -check T9b-real-map-nothing-applied "$(printf '%s' "$out" | grep -c '0 applied, 0 already')" 1 -check T10-missing-map-rc "$(bash "$LIB" "$WORK/nowhere" >/dev/null 2>&1; echo $?)" 1 - -# hardening: each case in its own fixture repo -mkrepo() { R="$WORK/$1"; mkdir -p "$R/lib" "$R/skills-external/$2"; } -mkrepo h11 alpha; mkdir "$WORK/h11/skills-external/beta" -printf -- '---\nname: alpha\n---\nb\n' > "$WORK/h11/skills-external/alpha/SKILL.md" -printf -- '---\nname: beta\n---\nb\n' > "$WORK/h11/skills-external/beta/SKILL.md" -printf 'alpha high\nbeta low' > "$WORK/h11/lib/effort-pins.txt" -bash "$LIB" "$WORK/h11" >/dev/null 2>&1 -check T11-last-line-no-newline "$(fm_effort "$WORK/h11/skills-external/beta/SKILL.md")" low - -mkrepo h12 open; f12="$WORK/h12/skills-external/open/SKILL.md" -printf -- '---\nname: open\nbody effort: max\n' > "$f12"; b12="$(cat "$f12")" -printf 'open high\n' > "$WORK/h12/lib/effort-pins.txt" -out="$(bash "$LIB" "$WORK/h12" 2>&1)"; rc=$? -check T12-unterminated-frontmatter-skipped \ - "$rc|$(cat "$f12" | cmp -s - <(printf '%s\n' "$b12") && echo same)|$(printf '%s' "$out" | grep -c "ERR .*$f12")" "1|same|1" - -mkrepo h13 crlf -printf -- '---\r\nname: crlf\r\n---\r\nbody\r\n' > "$WORK/h13/skills-external/crlf/SKILL.md" -printf 'crlf high\n' > "$WORK/h13/lib/effort-pins.txt" -out="$(bash "$LIB" "$WORK/h13" 2>&1)"; rc=$? -check T13-crlf-file-rejected \ - "$rc|$(printf '%s' "$out" | grep -c 'ERR ')|$(printf '%s' "$out" | grep -c ' 0 applied, ')" "1|1|1" - -# T13b: the post-write re-read branch, reached with a no-op write stub -mkrepo h13b nowrite; f13b="$WORK/h13b/skills-external/nowrite/SKILL.md" -printf -- '---\nname: nowrite\n---\nb\n' > "$f13b" -out="$(bash -c 'source "$1"; _effort_pin_write() { return 0; } - _effort_pin_apply_one "$2" nowrite high' _ "$LIB" "$f13b" 2>&1)"; rc=$? -check T13b-reread-mismatch-fails \ - "$rc|$(printf '%s' "$out" | grep -c 'level not applied after write')" "1|1" - -if [ "${EFFORT_PINS_TEST_FAKE_ROOT:-0}" = 1 ] || [ "$(id -u)" -eq 0 ]; then - echo "SKIP T14-write-failure-no-temp: chmod bits ignored as root" -else - mkrepo h14 ro; d14="$WORK/h14/skills-external/ro" - printf -- '---\nname: ro\n---\nb\n' > "$d14/SKILL.md" - printf 'ro high\n' > "$WORK/h14/lib/effort-pins.txt" - chmod 555 "$d14"; out="$(bash "$LIB" "$WORK/h14" 2>&1)"; rc=$?; chmod 755 "$d14" - check T14-write-failure-no-temp \ - "$rc|$(printf '%s' "$out" | grep -c 'ERR ')|$(find "$d14" -name 'SKILL.md.*' | wc -l | tr -d ' ')" "1|1|0" -fi - -# T15: SIGINT during the awk write removes the temp sibling, exit 130 -mkrepo h15 sig; d15="$WORK/h15/skills-external/sig" -printf -- '---\nname: sig\n---\nb\n' > "$d15/SKILL.md" -bash -c 'source "$1"; awk() { kill -INT $$; sleep 2; } - _effort_pin_write "$2" sig high' _ "$LIB" "$d15/SKILL.md" >/dev/null 2>&1 -rc=$? -check T15-sigint-removes-temp \ - "$rc|$(find "$d15" -name 'SKILL.md.*' | wc -l | tr -d ' ')" "130|0" - -# T15b: previous INT trap restored on a normal return, no EXIT trap set -mkrepo h15b tr; d15b="$WORK/h15b/skills-external/tr" -printf -- '---\nname: tr\n---\nb\n' > "$d15b/SKILL.md" -out="$(bash -c 'source "$1"; trap "echo prev" INT - _effort_pin_write "$2" tr high - printf "INT:%s\n" "$(trap -p INT)"; printf "EXIT:%s\n" "$(trap -p EXIT)"' \ - _ "$LIB" "$d15b/SKILL.md" 2>&1)" -check T15b-traps-restored \ - "$(printf '%s' "$out" | grep -c "^INT:trap -- 'echo prev' SIGINT")|$(printf '%s' "$out" | grep -c '^EXIT:$')" "1|1" - -# T16: a literal backslash-t in a map line is printed shell-quoted -mkrepo h16 q -printf 'bad\\tname high\n' > "$WORK/h16/lib/effort-pins.txt" -out="$(bash "$LIB" "$WORK/h16" 2>&1)"; rc=$? -check T16-rejected-line-quoted \ - "$rc|$(printf '%s' "$out" | grep -cF 'bad\\tname')" "1|1" - -echo "effort-pins: $pass pass, $fail fail" -[ "$fail" -eq 0 ] diff --git a/lib/tests/effort-routing.test.sh b/lib/tests/effort-routing.test.sh index e6edeed..e2b9214 100755 --- a/lib/tests/effort-routing.test.sh +++ b/lib/tests/effort-routing.test.sh @@ -1,9 +1,12 @@ #!/usr/bin/env bash -# lib/tests/effort-routing.test.sh — census: effort tiering (BDR-107) -# agent pins, skill entry levels, shifter skills, orchestrator wiring, settings. -# shellcheck disable=SC2015,SC2016 # A && ok || ko is deliberate (ok/ko never fail); '$REPO' locks are literal source text +# lib/tests/effort-routing.test.sh — wave-2 census of the model-router rows. +# Drift lock: every tracked skill/agent row in mods/model-router/hooks/ +# register.ts equals its frontmatter (the off-state floor), the D3 wiring +# markers sit in the orchestrators, no shifter citer survives. +# shellcheck disable=SC2015,SC2016 # A && ok || ko is deliberate (ok/ko never fail) set -u R="$(cd "$(dirname "$0")/../.." && pwd)" +REG="$R/mods/model-router/hooks/register.ts" pass=0; fail=0 ok() { pass=$((pass+1)); } ko() { fail=$((fail+1)); printf 'FAIL %s\n' "$1"; } @@ -11,120 +14,133 @@ has() { if grep -qF "$2" "$R/$1"; then ok; else ko "$1 missing: $2"; fi; } lacks() { if grep -qF "$2" "$R/$1"; then ko "$1 must NOT contain: $2"; else ok; fi; } # frontmatter = the lines between the first two '---' lines fm() { awk 'NR==1&&/^---$/{p=1;next} p&&/^---$/{exit} p' "$1"; } -fm_effort() { fm "$1" | grep -E '^effort: (low|medium|high|xhigh|max)$' | head -1 | cut -d' ' -f2; } -fm_has_effort() { - got="$(fm_effort "$R/$1")" - if [ "$got" = "$2" ]; then ok; else ko "$1 frontmatter effort must be '$2', got '${got:-none}'"; fi +fm_val() { fm "$1" | grep -E "^$2: [a-z]+$" | head -1 | cut -d' ' -f2; } + +# ── register.ts parsers (awk/sed on the DEFAULT_CONFIG literal) ────────── +# rows -> "name phase" per row +rows() { + awk -v s="$2" '$0 ~ "^ "s": \\{"{f=1;next} f&&/^ \},?$/{f=0} f' "$1" \ + | grep -v '^ *//' | grep -oE "('[^']+'|[A-Za-z0-9_-]+): '[a-z]+'" \ + | sed -E "s/'//g; s/: / /" } -fm_no_effort() { if fm "$R/$1" | grep -q '^effort:'; then ko "$1 must NOT pin effort"; else ok; fi; } +# phase_effort -> " " +phase_effort() { + awk '/^ phases: \{/{f=1;next} f&&/^ \},?$/{f=0} f' "$1" \ + | sed -nE "s/^ *$2: \{ tier: '([a-z]+)', effort: '([a-z]+)' \},?$/\1 \2/p" +} +# tier_head -> first alias of the tier list +tier_head() { + awk '/^ tiers: \{/{f=1;next} f&&/^ \},?$/{f=0} f' "$1" \ + | sed -nE "s/^ *$2: \['([a-z]+)'.*$/\1/p" +} +row_of() { rows "$REG" "$1" | awk -v n="$2" '$1==n{print $2}'; } -# ── flip-test: the frontmatter reader must accept a valid level and reject an invalid one +# ── flip-test: the parsers read a fixture, reject a missing key ────────── FIX="$(mktemp -d)"; trap 'rm -rf "$FIX"' EXIT -printf -- '---\nname: good\neffort: xhigh\n---\nbody with effort: low in prose\n' > "$FIX/good.md" -printf -- '---\nname: bad\neffort: turbo\n---\n' > "$FIX/bad.md" -[ "$(fm_effort "$FIX/good.md")" = "xhigh" ] && ok || ko "flip: valid level not read" -[ -z "$(fm_effort "$FIX/bad.md")" ] && ok || ko "flip: invalid level accepted" -[ "$(fm "$FIX/good.md" | grep -c 'prose')" -eq 0 ] && ok || ko "flip: body leaked into frontmatter" +cat > "$FIX/reg.ts" <<'FX' + tiers: { + big: ['opus', 'fable'], + }, + phases: { + judge: { tier: 'big', effort: 'xhigh' }, + }, + agents: { + // judge + Plan: 'judge', 'plan-challenger': 'judge', + }, + skills: { + 'ship-feature': 'plan', doc: 'apply', + }, +FX +[ "$(rows "$FIX/reg.ts" agents | tr '\n' ,)" = "Plan judge,plan-challenger judge," ] \ + && ok || ko "flip: agents rows misparsed" +[ "$(rows "$FIX/reg.ts" skills | tr '\n' ,)" = "ship-feature plan,doc apply," ] \ + && ok || ko "flip: skills rows misparsed" +[ "$(phase_effort "$FIX/reg.ts" judge)" = "big xhigh" ] && ok || ko "flip: phase" +[ -z "$(phase_effort "$FIX/reg.ts" nothere)" ] && ok || ko "flip: ghost phase" +[ "$(tier_head "$FIX/reg.ts" big)" = "opus" ] && ok || ko "flip: tier head" +[ "$(rows "$REG" skills | wc -l)" -gt 40 ] && ok || ko "register.ts: skills rows not parsed" +[ "$(rows "$REG" agents | wc -l)" -gt 15 ] && ok || ko "register.ts: agents rows not parsed" -# ── 1) session default (spec D1) +# ── (b) tracked skills: row exists, frontmatter effort equals the row ──── +NO_ROW_SKILLS=" find-docs graphify impeccable model-router " +check_skill() { + local f="$1" name phase want got + name="$(basename "$(dirname "$f")")" + case "$NO_ROW_SKILLS" in *" $name "*) return;; esac + phase="$(row_of skills "$name")" + [ -n "$phase" ] || { ko "skills/$name: no row in register.ts"; return; } + want="$(phase_effort "$REG" "$phase" | cut -d' ' -f2)" + got="$(fm_val "$R/$f" effort)" + [ -n "$got" ] || { ko "skills/$name: routed skill without effort:"; return; } + [ "$got" = "$want" ] && ok || ko "skills/$name: effort $got != row $phase ($want)" +} +while IFS= read -r f; do check_skill "$f"; done < <( + cd "$R" && git ls-files 'skills/*/SKILL.md' 'skills-external/*/SKILL.md') + +# ── (c) tracked agents with a row: tier head == model:, effort == effort: ─ +NO_ROW_AGENTS=" interviewer client-handover-writer " +tier_alias() { tier_head "$REG" "$(phase_effort "$REG" "$1" | cut -d' ' -f1)"; } +check_agent() { + local f="$1" name phase alias want got + name="$(basename "$f" .md)" + case "$NO_ROW_AGENTS" in *" $name "*) return;; esac + case "$name" in impeccable-*) return;; esac + phase="$(row_of agents "$name")" + [ -n "$phase" ] || { ko "agents/$name: no row in register.ts"; return; } + alias="$(tier_alias "$phase")"; got="$(fm_val "$R/$f" model)" + [ "$got" = "$alias" ] && ok || ko "agents/$name: model $got != row $phase ($alias)" + [ "$alias" = haiku ] && return + want="$(phase_effort "$REG" "$phase" | cut -d' ' -f2)" + got="$(fm_val "$R/$f" effort)" + [ "$got" = "$want" ] && ok || ko "agents/$name: effort $got != row $phase ($want)" +} +while IFS= read -r f; do check_agent "$f"; done < <( + cd "$R" && git ls-files 'agents/*.md' | grep -E '^agents/[^/]+\.md$' \ + | grep -v '/README\.md$') + +# ── (d) no shifter citer in skills, agents, lib ────────────────────────── +if (cd "$R" && git grep -qE 'Skill\(effort-|EFFORT SHIFT[S]:' -- skills agents lib ':!lib/tests'); then + ko "a shifter-skill or shift-header citer survives in skills/agents/lib" +else ok; fi +# paths split so this file itself matches no deleted-name grep +for s in skills/effort-low skills/effort-max lib/effort-""pins.txt lib/model-""check.sh; do + [ ! -e "$R/$s" ] && ok || ko "$s must be deleted" +done + +# ── (e) D3 wiring markers ──────────────────────────────────────────────── +mark() { # mark + local ph="$1" s; shift + for s in "$@"; do has "skills/$s/SKILL.md" "route(phase=\"$ph\")"; done +} +mark orchestrate feat hotfix bugfix ship-feature init-project code-clean seo geo harden web-validate audit-delta +mark apply feat hotfix bugfix ship-feature init-project +mark reflect feat hotfix bugfix seo geo harden web-validate +mark plan ship-feature init-project onboard code-clean audit-delta +mark escalate ship-feature +[ "$(grep -o 'route(phase="escalate")' "$R/lib/verify-secure-loop.md" | wc -l)" -eq 3 ] \ + && ok || ko "verify-secure-loop.md: escalate route must appear 3 times" +for s in ship-feature init-project; do has "skills/$s/SKILL.md" 'effort="xhigh"'; done +has "skills/tour/SKILL.md" 'effort="xhigh"' +n_opus="$(grep -c 'model="opus",$' "$R/skills/onboard/SKILL.md")" +n_eff="$(grep -c 'effort="xhigh",$' "$R/skills/onboard/SKILL.md")" +[ "$n_opus" -ge 7 ] && [ "$n_opus" -eq "$n_eff" ] && ok \ + || ko "onboard: $n_opus model=\"opus\" dispatches vs $n_eff effort=\"xhigh\"" +bad="$(grep 'model: "fable"' "$R/agents/client-handover-writer.md" | grep -vc 'effort="high"')" +[ "$bad" -eq 0 ] && ok || ko "client-handover-writer: $bad model: \"fable\" line(s) without effort=\"high\"" +for s in ship-feature init-project feat bugfix web-validate seo hotfix geo harden code-clean audit-delta tour onboard; do + has "skills/$s/SKILL.md" 'ROUTING: follow $HOME/.claude/lib/effort-shift.md' +done +has "agents/client-handover-writer.md" 'ROUTING: follow $HOME/.claude/lib/effort-shift.md' + +# ── (f) doctrine includes ──────────────────────────────────────────────── +has "lib/model-gate.md" 'mcp__model-router__route' +has "lib/effort-shift.md" 'ToolSearch' +has "CLAUDE.global.md" 'route to `reflect` (high) through their' + +# ── (g) session default and hooks (unchanged locks) ────────────────────── has "settings.json" '"effortLevel": "high"' - -# ── 2) hooks: env-var warning + live effort in the statusline (spec D1, D5) has "hooks/session-start.sh" 'CLAUDE_CODE_EFFORT_LEVEL' has "hooks/statusline.sh" 'CLAUDE_EFFORT' -# ── 3) agent pins (spec D2): one effort per agent file, judgment mode wins on mode-based agents -for a in hotfixer release-executor plugin-probe validator-analyzer; do fm_has_effort "agents/$a.md" low; done -for a in feater bugfixer code-cleaner onboarder scaffolder; do fm_has_effort "agents/$a.md" medium; done -for a in refactorer analyzer commit-changer doc-syncer handover-doc-writer; do fm_has_effort "agents/$a.md" high; done -for a in plan-challenger plugin-advisor verifier security-auditor seo-analyzer geo-analyzer; do fm_has_effort "agents/$a.md" xhigh; done -for a in interviewer client-handover-writer status-reporter; do fm_no_effort "agents/$a.md"; done -has "skills/init-project/SKILL.md" 'pin sonnet, effort medium' - -# ── 4) skill entry levels (spec D3): the user's invocation sets the run's level -for s in status commit-change release-candidate doc capitalize close reconcile deploy profile plugin-check; do fm_has_effort "skills/$s/SKILL.md" low; done -for s in gitflow prune-memory; do fm_has_effort "skills/$s/SKILL.md" medium; done -for s in feat hotfix bugfix refactor web-validate harden seo geo; do fm_has_effort "skills/$s/SKILL.md" high; done -for s in ship-feature init-project onboard tour audit-delta analyze code-clean client-handover; do fm_has_effort "skills/$s/SKILL.md" xhigh; done -# BDR-108 round: the three repo skills that had no level -fm_has_effort "skills/skills-perso/SKILL.md" low -fm_has_effort "skills/pdf-translate/SKILL.md" medium -fm_has_effort "skills/site-motion/SKILL.md" high - -# ── 9) vendored externals carry the level of lib/effort-pins.txt (BDR-108). The files live in -# skills-external/ (gitignored, machine-owned): the durable artifact is the map + the re-apply -# after the last vendoring step of install-plugins.sh AND update-all.sh; a skill not vendored -# yet SKIPs visibly (fresh clone before make plugin). -while read -r s lvl _; do - case "$s" in ''|'#'*) continue ;; esac - if [ -f "$R/skills-external/$s/SKILL.md" ]; then fm_has_effort "skills-external/$s/SKILL.md" "$lvl" - else printf 'SKIP skills-external/%s/SKILL.md not vendored yet (run make plugin)\n' "$s"; fi -done < "$R/lib/effort-pins.txt" -has "lib/effort-pins.txt" 'brainstorming xhigh'; has "lib/effort-pins.txt" 'writing-plans xhigh' -has "install-plugins.sh" 'apply_effort_pins "$REPO"'; has "update-all.sh" 'apply_effort_pins "$REPO"' -lacks "install-plugins.sh" 'for _s in brainstorming writing-plans; do' -ln_last() { grep -n "$2" "$R/$1" | tail -1 | cut -d: -f1; } -[ "$(ln_last install-plugins.sh 'apply_effort_pins "$REPO"')" -gt "$(ln_last install-plugins.sh 'rm -rf "$TFD_STAGE"')" ] \ - && ok || ko "install-plugins.sh: effort pins must be re-applied after the 21st pack refresh" -pins_ln=$(ln_last update-all.sh 'apply_effort_pins "$REPO"') -[ "$pins_ln" -gt "$(ln_last update-all.sh 'skills-external/$_tfd_name')" ] \ - && [ "$pins_ln" -gt "$(ln_last update-all.sh 'vendor_pinned_skills superpowers refresh')" ] \ - && ok || ko "update-all.sh: effort pins must be re-applied after the last vendoring step (21st pack)" -[ -x "$R/lib/effort-pins.sh" ] && ok || ko "lib/effort-pins.sh missing or not executable" -# 9b) design stack = ONE level (last loaded wins); site-motion (repo skill) pins the same one -stack_levels() { awk '/^# design stack/{f=1;next} f&&/^#$/{f=0} f&&!/^#/&&NF==2{print $2}' "$R/lib/effort-pins.txt" | sort -u; } -[ "$(stack_levels | wc -l)" -eq 1 ] && ok || ko "design stack must share ONE level in lib/effort-pins.txt (got: $(stack_levels | tr '\n' ' '))" -[ "$(stack_levels | wc -l)" -ge 1 ] && fm_has_effort "skills/site-motion/SKILL.md" "$(stack_levels | head -1)" -has "lib/effort-shift.md" 'Stacked skills share one level' -has "CLAUDE.global.md" 'lib/effort-pins.txt' - -# ── 5) shifter skills + include (spec D4) -for l in low medium high xhigh max; do fm_has_effort "skills/effort-$l/SKILL.md" "$l"; has "skills/effort-$l/SKILL.md" "name: effort-$l"; done -has "lib/effort-shift.md" 'Headless sessions' -has "lib/effort-shift.md" 'Skill(effort-max)' -has "lib/effort-shift.md" 'never inside a dispatched agent' -has "lib/model-gate.md" 'lib/effort-shift.md' - -# ── 6) orchestrator wiring (spec D4) -for s in feat hotfix bugfix ship-feature init-project onboard tour code-clean seo geo harden web-validate audit-delta; do - has "skills/$s/SKILL.md" 'lib/effort-shift.md'; has "skills/$s/SKILL.md" 'a lone Skill call is a no-op'; done -for s in feat hotfix bugfix ship-feature init-project code-clean seo geo harden web-validate audit-delta; do - has "skills/$s/SKILL.md" 'Skill(effort-medium)'; done -lacks "skills/onboard/SKILL.md" 'Skill(effort-medium)'; lacks "skills/tour/SKILL.md" 'Skill(effort-medium)' -has "agents/client-handover-writer.md" 'lib/effort-shift.md'; lacks "agents/client-handover-writer.md" 'Skill(effort-medium)'; has "agents/client-handover-writer.md" 'Skill(effort-high)' -for s in feat hotfix bugfix; do has "skills/$s/SKILL.md" 'Skill(effort-high)'; done -for s in ship-feature init-project onboard code-clean audit-delta; do has "skills/$s/SKILL.md" 'Skill(effort-xhigh)'; done -for s in seo geo harden web-validate; do has "skills/$s/SKILL.md" 'Skill(effort-high)'; done -for s in feat hotfix bugfix ship-feature init-project; do has "skills/$s/SKILL.md" 'Skill(effort-low)'; done -has "skills/feat/SKILL.md" 'effort-shift: nested commit-change' - -# ── 6b) pairing rule documented (R11) -has "lib/effort-shift.md" 'lone Skill call is a no-op' -has "lib/effort-shift.md" 're-applies its' -[ "$(grep -c 'a lone Skill call is a no-op' "$R/skills/feat/SKILL.md")" -ge 1 ] && ok || ko "feat INC line must carry the pairing rule" - -# ── 7) escalation at max (spec D4) -[ "$(grep -c 'Skill(effort-max)' "$R/lib/verify-secure-loop.md")" -eq 3 ] && ok || ko "verify-secure-loop.md must shift to max at its 3 caps" -has "skills/ship-feature/SKILL.md" 'Skill(effort-max)' -has "lib/challenge-plan.md" '/effort-max' -has "lib/verify-secure-loop.md" '/effort-max' - -# ── 8) turn-reset re-assert after a prose gate followed by reflection -has "skills/bugfix/SKILL.md" 'effort-shift: turn reset' - -# ── 11) audit tooling -has "lib/effort-shift.md" 'effort-audit.py' -[ -x "$R/lib/effort-audit.py" ] && ok || ko "lib/effort-audit.py missing or not executable" - -# ── 6c) judgment dispatches re-raised, planning re-asserts, stronger locks (final review I1/I2/M5) -for s in ship-feature init-project; do has "skills/$s/SKILL.md" 'effort-shift: judgment dispatch'; has "skills/$s/SKILL.md" 'effort-shift: turn reset'; done -has "agents/client-handover-writer.md" 'effort-shift: judgment dispatch' -has "lib/effort-shift.md" 'Before any built-in or unpinned dispatch' -has "lib/model-gate.md" 'built-ins inherit the effort in force' -has "skills/ship-feature/SKILL.md" 'effort-shift: error recovery' -for s in feat hotfix bugfix seo geo harden web-validate ship-feature init-project onboard code-clean audit-delta; do has "skills/$s/SKILL.md" 'effort-shift: own level before the challenge'; done -has "update-all.sh" 'source "$REPO/lib/effort-pins.sh"' - -# ── summary (later tasks insert their locks ABOVE this line) -printf 'effort-routing census: %d pass, %d fail\n' "$pass" "$fail" -[ "$fail" -eq 0 ] +printf 'PASS=%s FAIL=%s\n' "$pass" "$fail"; [ "$fail" -eq 0 ] diff --git a/lib/tests/higgsfield.test.sh b/lib/tests/higgsfield.test.sh index f6ab348..689218b 100644 --- a/lib/tests/higgsfield.test.sh +++ b/lib/tests/higgsfield.test.sh @@ -321,24 +321,20 @@ expect link-sh "$(count link.sh higgsfield)" 0 expect profile-sh "$(count lib/profile.sh higgsfield)" 0 expect profiles \ "$(cat "$ROOT"/lib/profiles/*.profile | grep -cF higgsfield)" 0 -expect pins-map "$(count lib/effort-pins.txt higgsfield)" 0 verdict OFF_BY_DEFAULT_WIRING # ln_first / ln_last — line number of a match. ln_first() { grep -nF -- "$2" "$ROOT/$1" | head -1 | cut -d: -f1; } ln_last() { grep -nF -- "$2" "$ROOT/$1" | tail -1 | cut -d: -f1; } -PINS="apply_effort_pins \"\$REPO\"" -# install-plugins.sh: the sync sits in Step 8.6, before the effort pins -# (BDR-108); the CLI is proven by a probe, not by its shim; every login -# offer tests stdin alone (stdout is the tee pipe). +# install-plugins.sh: the sync sits in Step 8.6; the CLI is proven by a +# probe, not by its shim; every login offer tests stdin alone (stdout is +# the tee pipe). sync_ln="$(ln_last install-plugins.sh 'higgsfield_sync_skills')" expect after-8.5 "$(yn test "$sync_ln" -gt \ "$(ln_first install-plugins.sh 'Step 8.5: External skills')")" yes expect before-8.7 "$(yn test "$sync_ln" -lt \ "$(ln_first install-plugins.sh 'Step 8.7: 21st.dev')")" yes -expect before-pins "$(yn test "$sync_ln" -lt \ - "$(ln_last install-plugins.sh "$PINS")")" yes expect probe-gates \ "$(yn test "$(count install-plugins.sh 'if higgsfield_cli_ok')" -ge 3)" yes expect control "$(echo 'if [ -t 0 ] && [ -t 1 ]; then' | grep -cF -- '-t 1')" 1 @@ -347,14 +343,12 @@ expect stdin-tests \ "$(yn test "$(count install-plugins.sh '[ -t 0 ]')" -ge 3)" yes verdict INSTALL_WIRING -# update-all.sh: refresh before the 21st block and before the pins re-apply, -# and the updated CLI is proven by the probe, after the npm call. +# update-all.sh: refresh before the 21st block, and the updated CLI is +# proven by the probe, after the npm call. NPM_UP="npm install -g \"\$HF_PKG\"" sync_ln="$(ln_last update-all.sh 'higgsfield_sync_skills')" expect before-21st "$(yn test "$sync_ln" -lt \ "$(ln_first update-all.sh '7.4. Update the 21st.dev')")" yes -expect before-pins "$(yn test "$sync_ln" -lt \ - "$(ln_last update-all.sh "$PINS")")" yes expect probe-after-npm "$(yn test \ "$(ln_first update-all.sh 'higgsfield_cli_ok')" -gt \ "$(ln_last update-all.sh "$NPM_UP")")" yes diff --git a/lib/tests/model-check.test.sh b/lib/tests/model-check.test.sh deleted file mode 100644 index 040a8f5..0000000 --- a/lib/tests/model-check.test.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -# lib/tests/model-check.test.sh — flip-tests for lib/model-check.sh (LRN-096) -set -u -S="$(cd "$(dirname "$0")/../.." && pwd)/lib/model-check.sh" -pass=0; fail=0 -check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); else fail=$((fail+1)); - printf 'FAIL %s: got[%s] want[%s]\n' "$1" "$2" "$3"; fi; } -T="$(mktemp -d)"; trap 'rm -rf "$T"' EXIT - -fx() { printf '{"model": "%s"}' "$1" > "$T/s.json"; } -run() { MODEL_CHECK_SETTINGS="$T/s.json" bash "$S" >"$T/out" 2>&1; echo "$?"; } - -fx 'claude-fable-5[1m]'; check T1-fable-exit "$(run)" 0 -check T1-fable-class "$(cut -d: -f1 <"$T/out")" big -fx 'claude-opus-4-8'; check T2-opus "$(run)" 0 -fx 'claude-sonnet-5'; check T3-sonnet "$(run)" 2 -fx 'claude-haiku-4-5-20251001'; check T4-haiku "$(run)" 2 -fx 'opusplan'; check T5-opusplan "$(run)" 3 -fx 'gpt-9-mega'; check T6-foreign "$(run)" 3 -printf '{"no_model": true}' > "$T/s.json"; check T7-no-key "$(run)" 3 -printf '{broken' > "$T/s.json"; check T8-malformed "$(run)" 3 -check T9-missing-file "$(MODEL_CHECK_SETTINGS="$T/absent.json" bash "$S" >/dev/null 2>&1; echo $?)" 3 - -printf 'model-check: %d pass, %d fail\n' "$pass" "$fail" -[ "$fail" -eq 0 ] diff --git a/lib/verify-secure-loop.md b/lib/verify-secure-loop.md index 2540670..78fc446 100644 --- a/lib/verify-secure-loop.md +++ b/lib/verify-secure-loop.md @@ -35,7 +35,7 @@ single `GATES — VERDICT:` line: - `UNMET(n)` → hand the dev the CONTRACT path + the `NOT-MET` rows verbatim, nothing else; re-run GATE 0. **No verifier is dispatched** — a red build or a red suite is not a judgement call, and paying an LLM to discover it is - waste. **Max 3 floor iterations** → `Skill(effort-max)` (effort-shift: cap reached, diagnose at max before escalating; send it in the same message as the first tool call that gathers the escalation evidence), then STOP + human escalation with the rows. + waste. **Max 3 floor iterations** → `mcp__model-router__route(phase="escalate")` (route: cap reached, diagnose at max before escalating; send it with the first tool call that gathers the escalation evidence), then STOP + human escalation with the rows. - `ABANDONED(n)` → floor green but a handoff stands. Continue to GATE 1; the verifier surfaces it and its `ABANDONED(n)` verdict routes to the human gate. @@ -74,7 +74,7 @@ Parse its single `VERIFY — VERDICT:` line: lines (NOT-MET / out-of-scope), nothing else: re-dispatch a FRESH executor with those inputs only, never redo the fix by hand. Then re-run GATE 0 and re-dispatch a FRESH verifier. Repeat. - **Max 3 conformity iterations** → `Skill(effort-max)` (effort-shift: cap reached, diagnose at max before escalating; send it in the same message as the first tool call that gathers the escalation evidence), then STOP + human escalation with the + **Max 3 conformity iterations** → `mcp__model-router__route(phase="escalate")` (route: cap reached, diagnose at max before escalating; send it with the first tool call that gathers the escalation evidence), then STOP + human escalation with the CRITERIA table (the contract-vs-realized diff). - `ABANDONED(n)` → direct human gate, never a dev loop (a dev cannot close what was proven impossible). The human lifts the abandonment or accepts @@ -104,9 +104,10 @@ Parse its single `SECURITY — VERDICT:` line: (re-dispatch a FRESH executor, never fix by hand). Then re-run GATE 0, then **re-verify the REQUEST first** (GATE 1, fresh verifier) — a security fix can drift the behavior — **then re-run GATE 2** (fresh auditor), in that - order. **Max 3 security iterations** → `Skill(effort-max)` (effort-shift: cap reached, diagnose at max before escalating; send it in the same message as the first tool call that gathers the escalation evidence), then STOP + human escalation with the + order. **Max 3 security iterations** → `mcp__model-router__route(phase="escalate")` (route: cap reached, diagnose at max before escalating; send it with the first tool call that gathers the escalation evidence), then STOP + human escalation with the BLOCKING table. Every STOP text names the level reached (`$CLAUDE_EFFORT`) - and suggests `/effort-max` for the relaunch. + and suggests relaunching with `ultrathink` in the prompt (turn floor) or + `/route effort=max` (sticky, `/route clear` after). - `DEGRADED` (semgrep absent) → does NOT block on the tool's absence; surface the checklist result + recommend `make plugin`. A DEGRADED run that still BLOCKs (grep-caught secret/injection) blocks like any other. diff --git a/mods/model-router/hooks/register.test.ts b/mods/model-router/hooks/register.test.ts index bebc952..7e8c9b4 100644 --- a/mods/model-router/hooks/register.test.ts +++ b/mods/model-router/hooks/register.test.ts @@ -59,24 +59,6 @@ const spawnInput = (model?: string) => ({ ...(model === undefined ? {} : { model }), }) -test('Skill(effort-low) is answered without next, route shows low', async ( - $, on) => { - let reached = false - on('tool.call', { tool: 'Skill' }, () => { - reached = true - return { result: { success: true, commandName: 'bottom' } } - }) - await boot($, on) - const out = await $.tool.call({ tool: 'Skill', skill: 'effort-low' }) - expect(out).toMatchObject({ - result: { success: true, commandName: 'effort-low' }, - }) - expect(reached).toBe(false) - const line = mainLine(await route($, 'show')) - expect(line).toContain('skill effort-low') - expect(line).toContain('effort low') -}) - test('route tool with phase orchestrate sets medium on main', async ( $, on) => { await boot($, on) @@ -987,14 +969,6 @@ test('run slot: route(clear) clears the turn and names the run', async ( expect(JSON.stringify(out)).toContain('run reflect still holds') }) -test('Skill(effort-low) bridge is not sticky', async ($, on) => { - await bootRun($, on) - await loadSkill($, 'effort-low') - expect(mainLine(await route($, 'show'))).toContain('effort low') - await endTurn($) - expect(mainLine(await route($, 'show'))).toContain('session defaults') -}) - test('route answer names the id even with a floor in force', async ( $, on) => { await bootRun($, on) diff --git a/mods/model-router/hooks/register.ts b/mods/model-router/hooks/register.ts index 8107cc5..a8ef430 100644 --- a/mods/model-router/hooks/register.ts +++ b/mods/model-router/hooks/register.ts @@ -48,8 +48,8 @@ type State = { rules: Rule[] source: string // 'defaults' or the override path userMain: Routed | null // /route by the user, sticky until /route clear - turnMain: Routed | null // model route tool, skill table row, Skill(effort-*) - // bridge, prompt default rule, derived orchestrate; dropped at turn end + turnMain: Routed | null // model route tool, skill table row, prompt + // default rule, derived orchestrate; dropped at turn end runMain: Routed | null // best-tier skill row: spans the turns of a run; // only a skill, /route clear|off or a user /model write or drop it turnFloor: Routed | null // user-explicit level for this turn (prompt rule): @@ -95,7 +95,6 @@ type Decision = { effort: Effort; by: EffortBy } const LEVELS: readonly Level[] = ['low', 'medium', 'high', 'xhigh', 'max'] const MODEL_ID = /^claude-[a-z0-9.-]+$/ const TOOL = 'mcp__model-router__route' -const EFFORT_SKILL = /^effort-(low|medium|high|xhigh|max)$/ const BEST = 'best' // the tier whose skill rows hold for a whole run // Origins that are a person typing: only these arm a typed slash. const TYPED_ORIGINS: ReadonlySet = new Set([ @@ -1378,34 +1377,6 @@ async function handleRouteTool($: Api, st: State, e: RouteInput) { // ---- skills ---------------------------------------------------------- -const skillResult = (skill: string, line: string) => ({ - result: { success: true, commandName: skill, status: 'inline' as const }, - context: [line], -}) - -/** Answers Skill(effort-) in place: one writer, the skill never loads. */ -function effortBridge(st: State, agentId: string | undefined, skill: string, - level: Level) { - if (agentId === undefined) { - const route = { ...st.turnMain?.route, effort: level } - st.turnMain = { phase: skill, route, source: 'skill' } - const note = mainNote(st, level) - return skillResult(skill, note - ? `model-router: ${skill} recorded, but ${note}; the ${skill} skill ` + - 'text was not loaded.' - : `model-router: effort → ${level} for this loop from the next ` + - `request on; the ${skill} skill text was not loaded.`) - } - const loop = loopOf(st, agentId) - if (loop.explicitEffort) { - return skillResult(skill, 'model-router: this agent was dispatched with ' + - 'an explicit effort; the shift does not apply.') - } - loop.effort = level - return skillResult(skill, `model-router: effort → ${level} for this ` + - `loop from the next request on; the ${skill} skill text was not loaded.`) -} - /** A skill's table row: its phase and that phase's route, if both exist. */ function skillRow(st: State, skill: string): Picked | undefined { const phase = hasKey(st.cfg.skills, skill) ? st.cfg.skills[skill] : undefined @@ -1793,8 +1764,6 @@ function registerSkills(on: On, st: State): void { on('tool.call', { tool: 'Skill' }, async ($, e, next) => { const skill = typeof e.skill === 'string' ? e.skill : undefined if (st.off || skill === undefined) return next(e) - const level = EFFORT_SKILL.exec(skill)?.[1] - if (isLevel(level)) return effortBridge(st, e.agentId, skill, level) st.skillCalls += 1 try { safely(st, $, 'Skill', () => onSkillLoad(st, skill, e.agentId)) diff --git a/skills/audit-delta/SKILL.md b/skills/audit-delta/SKILL.md index 4a13098..39de32d 100644 --- a/skills/audit-delta/SKILL.md +++ b/skills/audit-delta/SKILL.md @@ -29,7 +29,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). Audit only what changed since the last run, on the axes the user picks. Per axis: **audit → approval gate → fix → re-verify → marker update**, @@ -170,7 +170,7 @@ Then show the user the same compact table inline. ### 3b-bis. CHALLENGE THE PROPOSALS (before the gate) -`Skill(effort-xhigh)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="plan")` first (route: own level before the challenge; send it with the challenger dispatch). This axis' findings + proposed fixes are a proposal set worth attacking before the human gate. Persist THIS axis' finding list (not the whole append-only report) to `.claude/tasks/plans/--.md`, then run @@ -256,7 +256,7 @@ Then offer to capitalize (per CLAUDE.md): recurring finding patterns → below on the same delta (the SAST is a deterministic floor, the reasoned pass covers what grep/rules miss): ``` - Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message + mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="security-auditor", description="audit-delta security — semgrep SAST", prompt="MODE: audit\nSCOPE: \nREPORT: .claude/audits/.audit-delta-semgrep.md\nFollow agents/security-auditor.md exactly. Pinned rulesets, no login. Write ONLY to REPORT. End with REPORT_WRITTEN: .") ``` diff --git a/skills/bugfix/SKILL.md b/skills/bugfix/SKILL.md index 84051fd..25f3f3f 100644 --- a/skills/bugfix/SKILL.md +++ b/skills/bugfix/SKILL.md @@ -26,7 +26,7 @@ allowed-tools: MODEL GATE (blocking): run `$HOME/.claude/lib/model-gate.md` BEFORE any step below. Verdict `small` → STOP — print the gate's remedy, end the turn, dispatch nothing. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## REQUEST $ARGUMENTS @@ -119,14 +119,14 @@ RISK: obvious fix. - If the fix is significant (>10 lines, multiple files, behavior change): wait for user approval. - On resume: `Skill(effort-high)` first, sent with the next tool call (effort-shift: turn reset). + On resume: `mcp__model-router__route(phase="reflect")` first (route: resumed turn). - Then run pass B of `$HOME/.claude/lib/contract-interview.md` against the FIX PLAN: every VISIBLE / PUBLIC NAME / SCOPE choice it settles that the bug report left open → one batch of questions, before STEP 3b. The trivial fast-path is not exempt: a 1-line fix with a visible choice still asks. ## STEP 3b — CHALLENGE THE FIX PLAN (before the contract) -`Skill(effort-high)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="reflect")` first (route: own level before the challenge; send it with the challenger dispatch). Unless the fix is the trivial 1-2 line case STEP 3 already fast-paths, the DIAGNOSIS + FIX PLAN is a reflection worth attacking before it hardens into a contract. Persist it to `.claude/tasks/plans/--.md`, then run @@ -157,10 +157,10 @@ branch it's a no-op (commit in place). Never `finish`. ## STEP 5 — DISPATCH EXECUTOR -Dispatch the executor — sonnet by frontmatter pin, do not override: +Dispatch the executor — sonnet by its row (frontmatter = off-state floor), do not override: ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="bugfixer") prompt: "CONTRACT: DIAGNOSIS: @@ -282,7 +282,7 @@ A bugfix with an understood root cause is almost always worth one entry: If the bug was trivial and the root cause not transferable → skip with `CAPITALIZE: trivial, skip`. -`Skill(effort-low)` first (effort-shift: bookkeeping tail; send it in the same message as the memory-commit command). +`mcp__model-router__route(phase="apply")` first (route: bookkeeping tail; send it with the memory-commit command). **Then commit the memory** — follow `$HOME/.claude/lib/capitalize-commit.md`: it surgically commits what capitalize just wrote (`.claude/memory` + `.claude/tasks` diff --git a/skills/code-clean/SKILL.md b/skills/code-clean/SKILL.md index 72458cb..e3c429c 100644 --- a/skills/code-clean/SKILL.md +++ b/skills/code-clean/SKILL.md @@ -26,7 +26,7 @@ allowed-tools: MODEL GATE (blocking): run `$HOME/.claude/lib/model-gate.md` BEFORE any step below. Verdict `small` → STOP — print the gate's remedy, end the turn, dispatch nothing. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## TARGET $ARGUMENTS @@ -122,7 +122,7 @@ TOTALS: If no issues found: report clean state and stop. ## STEP 3b — CHALLENGE THE SCOPE (before approval) -`Skill(effort-xhigh)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="plan")` first (route: own level before the challenge; send it with the challenger dispatch). The STEP 3 report is the proposed cleanup scope — worth attacking before the human approves it. It is still inline, so FIRST persist it to `.claude/tasks/plans/--.md` (STEP 3 report format, one item @@ -172,10 +172,10 @@ is approved, stop — no dispatch. severity — proposed fix`. This is the executor's scope-of-work on disk — named, auditable, the same contract discipline as the dev gates (verifier reads its contract from disk). -2. **Dispatch the executor** — sonnet by frontmatter pin, do not override: +2. **Dispatch the executor** — sonnet by its row (frontmatter = off-state floor), do not override: ``` - Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message + mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="code-cleaner") prompt: "SCOPE: .claude/audits/CODE-CLEAN-SCOPE.md APPROVED: diff --git a/skills/commit-change/SKILL.md b/skills/commit-change/SKILL.md index 876b162..33f703b 100644 --- a/skills/commit-change/SKILL.md +++ b/skills/commit-change/SKILL.md @@ -73,7 +73,7 @@ $ARGUMENTS" (`model="opus"` — BDR-077: propose = narrative reconstruction + capitalize routing, judgment tier; the call-site override takes precedence over the -sonnet frontmatter pin. Apply, STEP 4, stays on the pin.) +sonnet row (frontmatter = off-state floor). Apply, STEP 4, stays on its row.) Read the returned `COMMIT PLAN` + `EDGE CASES` + `CAPITALIZE CANDIDATES`, terminated by `READY TO APPLY — awaiting dispatcher confirmation`. diff --git a/skills/effort-high/SKILL.md b/skills/effort-high/SKILL.md deleted file mode 100644 index cbeaeaa..0000000 --- a/skills/effort-high/SKILL.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: effort-high -description: Investigation shift. Deeper reasoning for diagnosis, LOCATE, contract drafting, refactor judgement inside feat, hotfix and bugfix runs. -effort: high ---- -Effort shifted to high for the rest of this turn (lib/effort-shift.md). Continue with the caller's next step. diff --git a/skills/effort-low/SKILL.md b/skills/effort-low/SKILL.md deleted file mode 100644 index 16da6a4..0000000 --- a/skills/effort-low/SKILL.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: effort-low -description: Bookkeeping shift. Lowers reasoning to the cheapest level for the rest of the turn: journal lines, memory commits, capitalize, release bookkeeping, status output. -effort: low ---- -Effort shifted to low for the rest of this turn (lib/effort-shift.md). Continue with the caller's next step. diff --git a/skills/effort-max/SKILL.md b/skills/effort-max/SKILL.md deleted file mode 100644 index 06de425..0000000 --- a/skills/effort-max/SKILL.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: effort-max -description: Escalation shift. Maximum reasoning when a verify or security loop hits its cap, a gate fails twice, or error recovery starts in ship-feature. -effort: max ---- -Effort shifted to max for the rest of this turn (lib/effort-shift.md). Continue with the caller's next step. diff --git a/skills/effort-medium/SKILL.md b/skills/effort-medium/SKILL.md deleted file mode 100644 index 6115c86..0000000 --- a/skills/effort-medium/SKILL.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: effort-medium -description: Orchestration shift. Standard reasoning between two dispatches: read a subagent report, pick the next step, relay a gate verdict, route a branch. -effort: medium ---- -Effort shifted to medium for the rest of this turn (lib/effort-shift.md). Continue with the caller's next step. diff --git a/skills/effort-xhigh/SKILL.md b/skills/effort-xhigh/SKILL.md deleted file mode 100644 index 6a60abd..0000000 --- a/skills/effort-xhigh/SKILL.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: effort-xhigh -description: Reflection shift. Deep reasoning for brainstorm, planning, challenge synthesis and audit verdicts before a human validation gate. -effort: xhigh ---- -Effort shifted to xhigh for the rest of this turn (lib/effort-shift.md). Continue with the caller's next step. diff --git a/skills/feat/SKILL.md b/skills/feat/SKILL.md index 4b10386..aecbde7 100644 --- a/skills/feat/SKILL.md +++ b/skills/feat/SKILL.md @@ -26,7 +26,7 @@ allowed-tools: MODEL GATE (blocking): run `$HOME/.claude/lib/model-gate.md` BEFORE any step below. Verdict `small` → STOP — print the gate's remedy, end the turn, dispatch nothing. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## REQUEST $ARGUMENTS @@ -124,7 +124,7 @@ in the contract's CLARIFICATIONS `[gated]` and in the plan. A choice that surfaces only during execution comes back as `NEED-DECISION` (STEP 3). ## STEP 1b — CHALLENGE THE PLAN (before branching) -`Skill(effort-high)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="reflect")` first (route: own level before the challenge; send it with the challenger dispatch). The STEP 1 plan is a reflection worth attacking before a branch is spent on it. Persist it to `.claude/tasks/plans/--.md`, then run `$HOME/.claude/lib/challenge-plan.md` with `PLAN` = that file, `KIND` = `build-plan`, @@ -143,10 +143,10 @@ branch it's a no-op (commit in place). Never `finish`. ## STEP 3 — DISPATCH EXECUTOR -Dispatch the executor — sonnet by frontmatter pin, do not override: +Dispatch the executor — sonnet by its row (frontmatter = off-state floor), do not override: ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="feater") prompt: "CONTRACT: PLAN: @@ -203,7 +203,7 @@ test), consider splitting into 2-3 atomic commits grouped by logical unit — or run `/commit-change` on the pending work (it dispatches the commit-changer (propose opus / apply sonnet, BDR-077); never inline-load the bare agent, it is now a propose/apply executor). -Then `Skill(effort-high)` (effort-shift: nested commit-change loaded at low; reload feat's level, sent with the next tool call). +Then `mcp__model-router__route(phase="reflect")` (route: nested commit-change loaded at apply; reload feat's level). Print summary: ``` @@ -254,7 +254,7 @@ Always append a 1-line entry to today's heading in `.claude/memory/journal.md`. If no substantive capture candidate → skip with `CAPITALIZE: nothing to log`. -`Skill(effort-low)` first (effort-shift: bookkeeping tail; send it in the same message as the memory-commit command). +`mcp__model-router__route(phase="apply")` first (route: bookkeeping tail; send it with the memory-commit command). **Then commit the memory** — follow `$HOME/.claude/lib/capitalize-commit.md`: it surgically commits what capitalize just wrote (`.claude/memory` + `.claude/tasks` diff --git a/skills/geo/SKILL.md b/skills/geo/SKILL.md index ee76ad9..7a5533a 100644 --- a/skills/geo/SKILL.md +++ b/skills/geo/SKILL.md @@ -29,7 +29,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). Dispatches the `geo-analyzer` subagent (audit + fix bundle), then applies the bundle from THIS main loop at **L1** — same shape as `/web-validate` @@ -47,7 +47,7 @@ every phase (LRN-126). Clean `.audit/geo-signals-.md` after apply. **A — collect (sonnet):** ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="geo-analyzer", model="sonnet") prompt: "MODE: collect RUNID: @@ -86,7 +86,7 @@ your bundle." ``` ## STEP 1b — CHALLENGE THE FIX BUNDLE (advisory, before apply) -`Skill(effort-high)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="reflect")` first (route: own level before the challenge; send it with the challenger dispatch). The analyzer returned a `## FIX BUNDLE` — worth attacking before any edit lands. **Skip if intervention mode = conservative** (nothing is applied). Else persist the bundle verbatim to `.claude/tasks/plans/--.md`, then run @@ -118,7 +118,7 @@ intent, not header wording: **AUTO** = no-confirmation items (G1–G4/G6); For each AUTO item, dispatch its `applier` at L1, passing the item verbatim: ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="hotfixer") # or "feater" per the item's applier prompt: ". diff --git a/skills/harden/SKILL.md b/skills/harden/SKILL.md index d6d53e3..27968fa 100644 --- a/skills/harden/SKILL.md +++ b/skills/harden/SKILL.md @@ -29,7 +29,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). This skill orchestrates a narrow-scope hardening audit: TLS + security headers + redirects + canonical + custom 404 + server configs. It @@ -261,7 +261,7 @@ seo-analyzer will run in parallel. Spawn a single seo-analyzer subagent with an explicit IN/OUT scope list. ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent( subagent_type="seo-analyzer", description="harden — narrow-scope web hardening audit", @@ -522,7 +522,7 @@ Extract the score and critical-alert count from `.claude/audits/HARDEN.md` for t --- ## STEP 2b — CHALLENGE THE FIX BUNDLE (MODE=fix only, advisory) -`Skill(effort-high)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="reflect")` first (route: own level before the challenge; send it with the challenger dispatch). Skip if MODE=audit (no bundle exists). Else, before the STEP 3 gate, harden the bundle: extract the `## 8. Fix bundle` section from HARDEN.md to `.claude/tasks/plans/--.md` (a clean, blind-judgeable artifact), then run diff --git a/skills/hotfix/SKILL.md b/skills/hotfix/SKILL.md index 61530b1..9ed5296 100644 --- a/skills/hotfix/SKILL.md +++ b/skills/hotfix/SKILL.md @@ -24,7 +24,7 @@ allowed-tools: MODEL GATE (blocking): run `$HOME/.claude/lib/model-gate.md` BEFORE any step below. Verdict `small` → STOP — print the gate's remedy, end the turn, dispatch nothing. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## REQUEST $ARGUMENTS @@ -94,7 +94,7 @@ point. Run it ONLY when the settled fix touches control flow or behaviour — an off-by-one, a wrong operator/variable, a behaviour-changing config value, or a missing import that alters execution. In doubt → it is probably a `/bugfix`. -`Skill(effort-high)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="reflect")` first (route: own level before the challenge; send it with the challenger dispatch). For a logic fix: persist the STEP 1 located fix (root cause + the exact edit) to `.claude/tasks/plans/--.md`, then run `$HOME/.claude/lib/challenge-plan.md` with `PLAN` = that file, `KIND` = @@ -135,10 +135,10 @@ mentioned: STOP and ask `"working tree dirty: stash and continue, or abort?"`. ## STEP 3 — DISPATCH EXECUTOR -Dispatch the executor — sonnet by frontmatter pin, do not override: +Dispatch the executor — sonnet by its row (frontmatter = off-state floor), do not override: ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="hotfixer") prompt: "CONTRACT: LOCATED: @@ -236,7 +236,7 @@ Always append a 1-line entry to today's heading in `.claude/memory/journal.md` ( **Language rule**: the journal line and any proposed BLK/LRN entries are ALWAYS written English AND caveman — fragments, articles dropped, code/IDs/quoted errors verbatim — per CLAUDE.md "Memory registries" (Always English, always caveman). -`Skill(effort-low)` first (effort-shift: bookkeeping tail; send it in the same message as the memory-commit command). +`mcp__model-router__route(phase="apply")` first (route: bookkeeping tail; send it with the memory-commit command). **Then commit the memory** — follow `$HOME/.claude/lib/capitalize-commit.md`: it surgically commits what capitalize just wrote (`.claude/memory` + `.claude/tasks` diff --git a/skills/init-project/SKILL.md b/skills/init-project/SKILL.md index a7bc5ff..fba9456 100644 --- a/skills/init-project/SKILL.md +++ b/skills/init-project/SKILL.md @@ -14,7 +14,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## REQUEST $ARGUMENTS @@ -181,12 +181,12 @@ This is the deterministic scaffold commit owner (closes BLK-010). The MVP is implemented on a `feature/*` branch off `develop` (STEP 8). ## STEP 6 — PLAN -`Skill(effort-xhigh)` first, sent with the next tool call (effort-shift: turn reset; gate #1 ended the turn and the vendored `writing-plans` pin applies only when the user invokes it). +`mcp__model-router__route(phase="plan")` first (route: resumed turn; gate #1 ended the turn). Invoke `writing-plans` (vendored superpowers skill) with BRIEF + skeleton. Granular tasks (2-5 min each), exact file paths, TDD: tests before code. ## STEP 6b — CHALLENGE THE PLAN (before the gate) -`Skill(effort-xhigh)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="plan")` first (route: own level before the challenge; send it with the challenger dispatch). Before the human sees the implementation plan, harden it. Run `$HOME/.claude/lib/challenge-plan.md` with `PLAN` = the plan STEP 6 wrote under `docs/superpowers/plans/`, `KIND` = `build-plan`, `SCOPE` = the skeleton + task file @@ -212,7 +212,7 @@ Approve and start? (yes / request changes) Changes → back to STEP 6. Approved → continue. ## STEP 8 — IMPLEMENT -First: `Skill(effort-medium)` (effort-shift: dispatch span starts; send it in the same message as this step's first dispatch). +First: `mcp__model-router__route(phase="orchestrate")` (route: dispatch span starts; send it with this step's first dispatch). Start the MVP feature branch off develop, then implement on it: ```bash bash "$HOME/.claude/lib/gitflow.sh" start feature mvp @@ -224,7 +224,8 @@ Invoke `subagent-driven-development` (vendored superpowers skill) for the per-ta finishing-a-development-branch", stop and return. **Model routing (BDR-066):** every subagent dispatched under SDD — per-task -implementers AND its reviewers — MUST carry `model: "sonnet"` in the Agent +implementers AND its reviewers — MUST carry `model: "sonnet"` and +`effort="medium"` (the `implement` level; a main route never reaches a child) in the Agent call. The plan is closed; execution and plan-conformity review are sonnet work. Reflection (task decomposition, review verdict arbitration) stays in this loop. @@ -261,9 +262,8 @@ against the founding contract. Distinct axis from STEP 10 code review ([[LRN-095]]) — both run. ## STEP 10 — CODE REVIEW -`Skill(effort-xhigh)` first, sent with the review dispatch (effort-shift: judgment dispatch; the reviewer is a built-in and inherits the level in force). Invoke `requesting-code-review` (vendored superpowers skill). **Model routing (BDR-077):** the -review subagent it dispatches MUST carry `model: "opus"` in the Agent call — +review subagent it dispatches MUST carry `model: "opus"` and `effort="xhigh"` in the Agent call — craft review is dispatched judgment, never inherited from the session. Fix all CRITICAL before proceeding. @@ -316,7 +316,7 @@ articles dropped, code/IDs/quoted errors verbatim — per CLAUDE.md "Memory registries" (Always English, always caveman). The gate may mirror the user's language; entries must not. -`Skill(effort-low)` first (effort-shift: bookkeeping tail; send it in the same message as the memory-commit command). +`mcp__model-router__route(phase="apply")` first (route: bookkeeping tail; send it with the memory-commit command). **Then commit the memory** — follow `$HOME/.claude/lib/capitalize-commit.md`: it surgically commits the approved founding decisions (`.claude/memory` + diff --git a/skills/onboard/SKILL.md b/skills/onboard/SKILL.md index bf7bc43..a4f10b8 100644 --- a/skills/onboard/SKILL.md +++ b/skills/onboard/SKILL.md @@ -14,7 +14,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## REQUEST $ARGUMENTS @@ -368,7 +368,7 @@ Lire le bloc `audit_stack:` du fichier `~/.claude/lib/project-archetypes//dev/null | grep -E "^gstack\s+ Agent( subagent_type="general-purpose", model="opus", + effort="xhigh", description="Onboard — security audit fallback (archetype-adaptive)", prompt=""" READ-ONLY security audit. No file modifications. @@ -546,6 +548,7 @@ flux de dev sont deux formes distinctes ([[BDR-050]] pipeline dev ≠ audit). Agent( subagent_type="doc-syncer", model="opus", + effort="xhigh", description="Onboard — doc drift audit only", prompt=""" MODE: audit — REPORT-ONLY, NO edits, NO auto-sync (no patch dispatch @@ -666,6 +669,7 @@ Si le skill ne supporte pas `--output`, capturer la sortie et écrire à la main Agent( subagent_type="general-purpose", model="opus", + effort="xhigh", description="Onboard — static design review fallback", prompt=""" AUDIT-ONLY mode — NO edits. Static design review du code UI. @@ -710,6 +714,7 @@ Puis parser le JSON Lighthouse (scores perf/a11y/bp/seo/pwa + top opportunities) Agent( subagent_type="general-purpose", model="opus", + effort="xhigh", description="Onboard — static perf audit", prompt=""" AUDIT-ONLY mode — NO edits. @@ -753,6 +758,7 @@ Parser axe-core résultats (violations, incomplete, inapplicable, passes) → `. Agent( subagent_type="general-purpose", model="opus", + effort="xhigh", description="Onboard — static a11y audit", prompt=""" AUDIT-ONLY mode — NO edits. @@ -799,6 +805,7 @@ Spawn un subagent synthétiseur (isolé, chargé uniquement du contenu de `.onbo Agent( subagent_type="general-purpose", model="opus", + effort="xhigh", description="Onboard — synthèse vers .claude/audits/", prompt=""" Lire tous les fichiers de /.onboard-audit/ : @@ -892,7 +899,7 @@ Vérifier que les 4 fichiers `.claude/audits/ONBOARD_REPORT.md`, `.claude/audits --- ## STEP 7b — CHALLENGE THE PROPOSALS (before the human gate) -`Skill(effort-xhigh)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="plan")` first (route: own level before the challenge; send it with the challenger dispatch). The 4 audit files are on disk; `AUDIT_PROPOSALS.md` is the artifact worth attacking before the human spends a gate on it. Run `$HOME/.claude/lib/challenge-plan.md` with `PLAN` = diff --git a/skills/seo/SKILL.md b/skills/seo/SKILL.md index ea3a82e..cb4c77e 100644 --- a/skills/seo/SKILL.md +++ b/skills/seo/SKILL.md @@ -30,7 +30,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). This skill orchestrates TWO specialist agents running in parallel, then merges their output into a single `.claude/audits/SEO.md` report. It is the main @@ -325,7 +325,7 @@ templating. **PHASE A — collect (both domains, one message):** ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="seo-analyzer", model="sonnet") prompt: """ MODE: collect @@ -460,7 +460,7 @@ sentinel, emit the COLLECT REPORT, stop. No scoring, no bundle. ``` **PHASE B — judge (both domains, one message, AFTER both COLLECT REPORTs -are DONE):** no `model=` override — the opus frontmatter pins apply. +are DONE):** no `model=` override — the opus rows apply (frontmatter = off-state floor). ``` Agent(subagent_type="seo-analyzer") @@ -510,7 +510,7 @@ the reports." ``` ## STEP 1b — CHALLENGE THE FIX BUNDLE (advisory, before apply) -`Skill(effort-high)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="reflect")` first (route: own level before the challenge; send it with the challenger dispatch). Both envelopes now carry a `## FIX BUNDLE` — worth attacking before any edit lands. **Skip if intervention mode = conservative** (nothing is applied). Else persist both bundles (seo + geo, verbatim) to `.claude/tasks/plans/--.md`, then run @@ -558,7 +558,7 @@ The two bundles may touch the same shared template (meta vs JSON-LD). Apply For each AUTO item, dispatch its `applier` at L1, passing the item verbatim: ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="hotfixer") # or "feater" per the item's applier prompt: ". diff --git a/skills/ship-feature/SKILL.md b/skills/ship-feature/SKILL.md index a941f35..6ae8ab6 100644 --- a/skills/ship-feature/SKILL.md +++ b/skills/ship-feature/SKILL.md @@ -14,7 +14,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). ## REQUEST $ARGUMENTS @@ -114,10 +114,10 @@ Inject ONLY what constrains: the NON-BINDING count does NOT enter the brainstorm (the injection inherits the OUTPUT filter — detail what binds, drop what doesn't). Consumption = INPUT INJECTION (we can't modify the external skill; we control its input). Refine request into validated design via Socratic questioning. Don't proceed until design approved. -Turns after a user reply run at the session level until a tool call is paired with `Skill(effort-xhigh)` (effort-shift: turn reset). +The first step of every turn after a user reply is `mcp__model-router__route(phase="plan")` (route: resumed turn). ## STEP 2 — PLAN -`Skill(effort-xhigh)` first, sent with the next tool call (effort-shift: turn reset; brainstorm turns after a user reply run at the session level, and the vendored `brainstorming` pin applies only when the user invokes it). +`mcp__model-router__route(phase="plan")` first (route: resumed turn after the brainstorm gate). Invoke `writing-plans` (vendored superpowers skill) with the validated design AND the 0d digest: every task must be consistent with the in-force constraints; where a task implements or affects one, note the ID inline. Break design into tasks (2-5 min each). Each task: exact file paths, full code, verification steps. @@ -127,7 +127,7 @@ request nor the STEP 1 brainstorm settled (check the contract's CLARIFICATIONS first) → one batch before STEP 2b; answers append to the contract `[gated]`. ## STEP 2b — CHALLENGE THE PLAN (adversarial, before the gate) -`Skill(effort-xhigh)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="plan")` first (route: own level before the challenge; send it with the challenger dispatch). Before the human sees the plan, harden it. Run `$HOME/.claude/lib/challenge-plan.md`: - `PLAN` = the plan STEP 2 wrote under `docs/superpowers/plans/` - `KIND` = `build-plan` @@ -174,7 +174,7 @@ judges the diff against this ENRICHED contract, not the STEP 0e seed — so a criterion the design introduced is verified, not lost. ## STEP 4 — IMPLEMENT -First: `Skill(effort-medium)` (effort-shift: dispatch span starts; send it in the same message as this step's first dispatch). +First: `mcp__model-router__route(phase="orchestrate")` (route: dispatch span starts; send it with this step's first dispatch). Start the feature branch off develop, then implement on it: ```bash bash "$HOME/.claude/lib/gitflow.sh" start feature @@ -186,14 +186,15 @@ Invoke `subagent-driven-development` (vendored superpowers skill) for the per-ta finishing-a-development-branch", stop and return. **Model routing (BDR-066):** every subagent dispatched under SDD — per-task -implementers AND its reviewers — MUST carry `model: "sonnet"` in the Agent +implementers AND its reviewers — MUST carry `model: "sonnet"` and +`effort="medium"` (the `implement` level; a main route never reaches a child) in the Agent call. The plan is closed; execution and plan-conformity review are sonnet work. Reflection (task decomposition, review verdict arbitration) stays in this loop. ## STEP 4b — ERROR RECOVERY (if STEP 4 fails) If a subagent returns a build error, failing test, or type error: -1. `Skill(effort-max)` (effort-shift: error recovery; send it in the same message as the Read of the analyzer file below), then load +1. `mcp__model-router__route(phase="escalate")` (route: error recovery; send it with the Read of the analyzer file below), then load `$HOME/.claude/agents/analyzer.md` in DEBUG MODE on the exact error output. Produce: root cause hypotheses (ordered), affected files, what NOT to touch. 2. Present gate: @@ -210,10 +211,10 @@ OPTIONS : C) Abort feature — preserve work done so far ``` 3. Wait for user choice. Do NOT auto-fix. Do NOT proceed without explicit approval. -4. On resume the turn is at the session level (effort-shift: turn reset). - If A → `Skill(effort-medium)` sent with the re-dispatch, apply minimal fix, re-run STEP 4 for the failed task only. Max 2 retry attempts. +4. On resume: `mcp__model-router__route(phase="plan")` first (route: resumed turn). + If A → `mcp__model-router__route(phase="orchestrate")` sent with the re-dispatch, apply minimal fix, re-run STEP 4 for the failed task only. Max 2 retry attempts. If still failing after 2 → fall back to options B or C. - If B or C → `Skill(effort-xhigh)` first, sent with the next tool call. + If B or C → continue at the plan level set above. If B → before skipping: scan remaining task list for tasks that depend on the failed task (look for references to the same file or function in subsequent tasks). If dependents found → present: "Tasks [N, M] depend on the skipped task. @@ -243,9 +244,8 @@ conformity + security vs. craft/design) — both run, neither subsumes the other ([[LRN-095]]). ## STEP 6 — CODE REVIEW -`Skill(effort-xhigh)` first, sent with the review dispatch (effort-shift: judgment dispatch; the reviewer is a built-in and inherits the level in force). Invoke `requesting-code-review` (vendored superpowers skill). **Model routing (BDR-077):** the -review subagent it dispatches MUST carry `model: "opus"` in the Agent call — +review subagent it dispatches MUST carry `model: "opus"` and `effort="xhigh"` in the Agent call — craft review is dispatched judgment, never inherited from the session. Fix all CRITICAL before proceeding. @@ -277,7 +277,7 @@ Feature shipped implies at least one design decision worth capturing. Run this B If nothing substantive to log → print `CAPITALIZE: nothing substantive to log` and skip. -`Skill(effort-low)` first (effort-shift: bookkeeping tail; send it in the same message as the memory-commit command). +`mcp__model-router__route(phase="apply")` first (route: bookkeeping tail; send it with the memory-commit command). **Then commit the memory** — follow `$HOME/.claude/lib/capitalize-commit.md`: it surgically commits what capitalize just wrote (`.claude/memory` + `.claude/tasks` diff --git a/skills/tour/SKILL.md b/skills/tour/SKILL.md index a486a4d..f62fa78 100644 --- a/skills/tour/SKILL.md +++ b/skills/tour/SKILL.md @@ -30,7 +30,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). One pipeline per project: **security → clean → re-verify → reconcile → doc → convergence re-audit**, looping until a full pass applies zero new @@ -169,8 +169,8 @@ honestly in the summary. Never loop past 3. ### Phase B — CLEAN -1. Dispatch a read-only cleanup audit (analyzer — opus-pinned, BDR-076 — - or general-purpose with `model="opus"`; NOT the sonnet code-cleaner, +1. Dispatch a read-only cleanup audit (analyzer — opus row, BDR-076 — + or general-purpose with `model="opus"`, `effort="xhigh"`; NOT the sonnet code-cleaner, which is now a fix executor): dead code, unused imports/exports, commented-out blocks, stale flags, norm violations. Findings as `id | file:line | finding | proposed fix`. diff --git a/skills/web-validate/SKILL.md b/skills/web-validate/SKILL.md index 0901830..8b6405b 100644 --- a/skills/web-validate/SKILL.md +++ b/skills/web-validate/SKILL.md @@ -28,7 +28,7 @@ Run `$HOME/.claude/lib/model-gate.md`. Reflection here (planning, audit judgment, loop decisions) requires Fable/Opus. Verdict `small` → STOP: the gate prints the remedy; end the turn — no later step, no dispatch. Nominal (big) path is silent. -EFFORT SHIFTS: follow `$HOME/.claude/lib/effort-shift.md` (BDR-107): medium when a dispatch span starts, own level before challenge synthesis, low at the bookkeeping tail, max at escalation; every shift goes in the same message as the step's first tool call, a lone Skill call is a no-op. +ROUTING: follow $HOME/.claude/lib/effort-shift.md (phases via mcp__model-router__route). This skill orchestrates a narrow-scope standards audit : @@ -180,7 +180,7 @@ Spawn a single `validator-analyzer` subagent with explicit scope and collected context : ``` -Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message +mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent( subagent_type="validator-analyzer", description="validate — W3C HTML + CSS + WCAG audit", @@ -255,7 +255,7 @@ grep -c '^### \[Critique\]' .claude/audits/VALIDATE.md --- ## STEP 2b — CHALLENGE THE FIX BUNDLE (MODE=fix only, advisory) -`Skill(effort-high)` first (effort-shift: own level before the challenge; send it in the same message as the challenger dispatch). +`mcp__model-router__route(phase="reflect")` first (route: own level before the challenge; send it with the challenger dispatch). Skip if MODE=audit (no bundle exists). Else, before the STEP 3 gate, harden the bundle: extract the `## 5. Fix bundle` section from VALIDATE.md to `.claude/tasks/plans/--.md` (a clean, blind-judgeable artifact), then run @@ -313,7 +313,7 @@ Options : share files: ``` - Skill(effort-medium) # effort-shift: dispatch span starts; send with the Agent call below in ONE message + mcp__model-router__route(phase="orchestrate") # route: dispatch span starts; send with the Agent call below in ONE message Agent(subagent_type="hotfixer") prompt: ". diff --git a/update-all.sh b/update-all.sh index f83d907..ba76c77 100644 --- a/update-all.sh +++ b/update-all.sh @@ -468,8 +468,7 @@ fi # ── 7.3b. Update the Higgsfield CLI + skill pack ── # CLI: global npm bin. Skills: re-cloned by lib/higgsfield-skills.sh, which # replaces the SOURCE under skills-external/ only: a pack parked in -# skills-disabled/ (symlinks to those sources) stays parked. Runs before the -# effort-pins re-apply below (BDR-108). +# skills-disabled/ (symlinks to those sources) stays parked. echo "" echo "── Updating Higgsfield CLI + skill pack..." if ! command -v higgsfield &>/dev/null; then @@ -562,15 +561,6 @@ print(d.get('21st',{}).get('version','latest')) rm -rf "$TFD_STAGE" fi -# Effort pins (BDR-107, BDR-108): every refresh above rewrites SKILL.md and -# drops the `effort:` line; the 21st pack refresh is the last step that rewrites -# a SKILL.md, so the entry levels of lib/effort-pins.txt go back here. -echo "" -echo "── Re-applying effort pins on the vendored skills..." -# shellcheck source=lib/effort-pins.sh disable=SC1091 -source "$REPO/lib/effort-pins.sh" -apply_effort_pins "$REPO" || warn "effort pins: map lines rejected — fix lib/effort-pins.txt" - # ── 7.5. Update external skills (npx skills) ── echo "" echo "── Updating external skills (npx skills)..." From 6f0df37f5b1719210d9b1485583607a97b5c1891 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 10 Oct 2026 11:32:57 +0200 Subject: [PATCH 053/547] =?UTF-8?q?docs:=20README=20model/effort=20routing?= =?UTF-8?q?=20+=20mod=20bullets,=20USAGE=20niveau=20d'effort,=20ARCHITECTU?= =?UTF-8?q?RE,=20CHANGELOG=20Unreleased=20(Removed,=20Changed,=20breaking?= =?UTF-8?q?=203.0.0)=20=E2=80=94=20feat=20model-router=20wave=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ARCHITECTURE.md | 2 +- CHANGELOG.md | 6 +++++- README.md | 53 +++++++++++++++++++++++++++++-------------------- USAGE.md | 23 +++++++++++---------- 4 files changed, 49 insertions(+), 35 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c0d616a..3a323e4 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -29,7 +29,7 @@ claude-config/ ├── mods/ # Claude Code mods (function-hooks plugins), loaded through the skills/ symlink ├── skills-external/ # Vendored skill packs: gstack submodule, design skills, superpowers, agent-skills, MengTo scroll skills, 21st and Higgsfield packs (machine-owned copies gitignored) ├── templates/ # Per-project templates (CLAUDE.md, settings, memory registries, deploy runbook, gitignore) -└── lib/ # Shared libs: gitflow, profiles, vendoring, effort pins, gates, archetypes, tests +└── lib/ # Shared libs: gitflow, profiles, vendoring, route doctrine, gates, archetypes, tests ``` ## Architecture principles diff --git a/CHANGELOG.md b/CHANGELOG.md index 4dac3e8..3ec6fde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,11 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project ## [Unreleased] ### Added -- **model-router mod**: `mods/model-router/`, a Claude Code mod (function-hooks plugin), routes the effort of every main-loop request from a phase table, along with the model and effort of the built-in sub-agents (Explore on sonnet/medium, Plan on opus/xhigh). It answers `Skill(effort-*)` itself, so the five `effort-*` skills no longer load while it is on. `ultrathink` in a prompt and a typed `/effort-` set the main turn's default and minimum effort. The model gets a `route` tool and the user a `/route` command (`show|clear|off|on|reload||model= effort=|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: the main loop switches model only with `mainModelSwitch` on (default off, one cold-cache step per switch into another model), and 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`, `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 `), 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||model= effort=|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: the main loop switches model only with `mainModelSwitch` on (default off, one cold-cache step per switch into another model), and the hooks send full model ids, so the `models` table has to follow new versions. - **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
` 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. In manual mode it over-blocks any command where a `push` word follows a `git` token; 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/
..
` 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). ### Changed +- `lib/model-gate.md` calls the model-router `route` tool and takes its answer as the witness; with the mod off the gate stops and names `/route on`. The `model:` / `effort:` frontmatter of agents and skills is now the off-state floor, census-locked equal to the rows (`lib/tests/effort-routing.test.sh`). `analyzer` effort goes from high to xhigh. Built-in judgment dispatches carry an explicit `effort=`. - `settings.json` denies every write form of the human-only `gitflow.*` keys (18 entries): any `git … config` spelling, section remove/rename, `git -c`, the git config env overrides, and Edit/Write of `.git/config`, `.gitconfig` and `~/.config/git/config`. Side effect: Claude can no longer read `gitflow.autopush` through `git config` either; hooks and `lib/gitflow.sh` still read it. The `hard_deny` rule on routing around a guardrail now names PreToolUse hook refusals. - `gitflow start` and `finish` warn on stderr when a base is behind origin and cannot fast-forward, instead of a silent `git pull --ff-only || true` (T18l, T18n). - `/close` (`/capitalize` STEP 5C) no longer runs its own push of develop: `gitflow finish` already pushes develop in auto-push mode (BDR-095). The closing line reports the real state, read after the merge: pushed, manual push mode with the `! git push origin develop` to run, not on origin, push failed, or an invalid `gitflow.autopush` value named and treated as manual push mode. A finish whose merge landed but whose branch delete failed (rc 5/2/6) still reports the push state. @@ -18,6 +19,9 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project - `/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`. 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 "" push -u origin ` to run. The tour never pushes or retries. +### 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-` no longer exists: use `ultrathink` or `/route effort=max`. Breaking: the next release is 3.0.0. + ### Fixed - `gitflow delete` (and `finish`) land on the base that contains the branch and drop the branch's upstream before `git branch -d`, so a branch whose upstream lags (manual-push mode) is deleted instead of refused by git (T18k). - An invalid `gitflow.autopush` value (not a boolean, or a config read that fails) no longer pushes. The post-commit / post-merge hooks and every push site of `lib/gitflow.sh` (`start`, `finish`, the `origin/` cleanup of `delete`) read it as auto and pushed; they now push nothing and say why. Each hook run prints `gitflow post-commit: gitflow.autopush unreadable (git rc ) — NOT pushed, treated as manual push mode; fix the value by hand` (post-merge likewise), and the lib passes through the `push-mode` verb's line, `gitflow.sh push-mode: gitflow.autopush='' is not a boolean (git rc )`. A repo with its own committed `.githooks/` (onboarded projects) keeps running its old hooks, which still push on an invalid value, until a session start runs `reconcile-hooks` and rewrites them; commit that refresh so other clones get it. Tests: `lib/gitflow-test.sh` T18q block. diff --git a/README.md b/README.md index 801d907..33fa880 100644 --- a/README.md +++ b/README.md @@ -71,10 +71,14 @@ commands, settings, secrets, maintenance. Doctrine: the session model (Fable) does main-loop reflection ONLY — brainstorm, plan, contract, audit judgment, gates, loop decisions — enforced -by a blocking gate (`lib/model-gate.md` + `lib/model-check.sh`) at the entry -of the 15 reflection skills (the orchestrators plus `/analyze`). Nothing dispatched inherits silently: -typed agents carry a frontmatter pin, built-ins get an explicit `model=` at -every call site. +by a blocking gate (`lib/model-gate.md`) at the entry +of the 15 reflection skills (the orchestrators plus `/analyze`): the skill +calls the model-router `route` tool and its answer, which names the model +id the main loop runs on, is the witness. A non-Fable/Opus id or the mod +off stops the skill (`/route on` resumes the mod). Nothing dispatched +inherits silently: typed agents run on their model-router row, their +`model:` frontmatter being the off-state floor; built-ins get an explicit +`model=` at every call site. | Agent | Model | Tier | |---|---|---| @@ -100,31 +104,37 @@ children are dispatched `model:"fable"` (they carry reflection). ## Effort routing (BDR-107, BDR-108) Second axis of the same table: how hard each phase thinks. Session default -`high`. Every typed agent carries an `effort:` pin next to its `model:` (low -appliers, medium executors, high judgment, xhigh challengers and gates; none -on haiku, which rejects the parameter). Every user-invoked skill carries an -entry level (`/status` low … `/ship-feature` xhigh); the vendored externals -(design stack, superpowers, agent-skills, MengTo scroll skills, 21st) get theirs from -`lib/effort-pins.txt`, re-applied by `lib/effort-pins.sh` after every -vendoring step. Orchestrators shift per phase through the `effort-low` … -`effort-max` skills (`lib/effort-shift.md`, always sent with another tool -call: a lone Skill call applies nothing (mod off)). Model pins stay tier aliases +`high`. The model-router mod (below) holds the live source: one phase row +per repo skill and agent, each phase naming a tier and an effort level +(`plan` best/xhigh, `reflect` best/high, `orchestrate` best/medium, +`escalate` best/max, `judge` big/xhigh, `implement` work/medium, `write` +work/high, `verify` work/xhigh, `explore` work/medium, `apply` work/low, +`mechanical` cheap/low). The `model:` and `effort:` frontmatter of every +typed agent and user-invoked skill stays as the off-state floor, kept equal +to the rows by the census `lib/tests/effort-routing.test.sh`: low +appliers, medium executors, high writers, xhigh judgment and gates (none +on haiku, which rejects the parameter); `/status` low … `/ship-feature` +xhigh. The vendored externals (design stack, superpowers, agent-skills, +MengTo scroll skills, 21st) get their level from their row only. +Orchestrators declare each phase through the `mcp__model-router__route` +tool (`lib/effort-shift.md`): `orchestrate` at a dispatch span, `reflect` +or `plan` when reflection resumes, `apply` at the bookkeeping tail, +`escalate` at the verify-secure caps. Model pins stay tier aliases (`sonnet`, `opus`, `haiku`, `fable`): the latest version of a tier is also -the cheapest or same-priced, so the quality/price trade-off is tier × effort, -never version. Census `lib/tests/effort-routing.test.sh`; transcript audit -`python3 lib/effort-audit.py`. +the cheapest or same-priced, so the quality/price trade-off is tier × +effort, never version. Transcript audit `python3 lib/effort-audit.py`. ### model-router mod `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 effort of the phase in force. The mod answers `Skill(effort-*)` itself and applies the level from the next request on, so the five `effort-*` skills no longer load while it is on. -- Built-in sub-agents: Explore runs on sonnet/medium, Plan on opus/xhigh. An explicit `model` on the Agent call wins. -- User floor: `ultrathink` in a prompt, or a typed `/effort-`, sets the main turn's default and minimum effort. -- `/route` (user command) shows or sets the route: `show`, `clear`, `off`, `on`, `reload`, a phase name, `model= effort=`, `switch on|off`, `verbose on|off`. The model sets routes through a `route` tool. +- 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`) 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. +- 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. +- Levers inside a run: `ultrathink` in a prompt sets the turn's minimum effort; `/route effort=max` holds until `/route clear`. The built-in `/effort` is not a lever inside a run, rows and routes outrank it. +- `/route` (user command) shows or sets the route: `show`, `clear`, `off`, `on`, `reload`, a phase name, `model= effort=`, `switch on|off`, `verbose on|off`. `/route show` names the run slot when one holds (`main: run `). The model sets routes through a `route` tool. - The spinner suffix and the status line under the prompt show the route in force. -Optional per-machine config: `~/.claude/model-router.json`. Keys: `models` (alias → full id), `windows` (context window per full id), `phases`, `agents`, `skills`, `prompt` (rules), `mainModelSwitch` (default `false`), `verbose` (default `false`), `spinner` (default `true`), `enabled` (default `true`; `false` turns the mod off on that machine). `/route reload` re-reads it. +Optional per-machine config: `~/.claude/model-router.json`. Keys: `models` (alias → full id), `windows` (context window per full id), `phases`, `agents`, `skills`, `prompt` (rules), `mainModelSwitch` (default `false`), `verbose` (default `false`), `spinner` (default `true`), `enabled` (default `true`; `false` turns the mod off on that machine). A `null` value in `agents` or `skills` drops a default row. `/route reload` re-reads it. Limits: the main loop changes model only with `mainModelSwitch` on, and each switch into another model costs one cold-cache step. The hooks send full model ids, so the `models` table has to follow new model versions. @@ -218,7 +228,6 @@ a different package, ships its own conflicting `graphify` bin) — see | `/profile` | Activate a skill profile (web / seo / web-full / full / max / backend / design / dev / qa / audit / minimal) (default: full) | | `/tour` | Grouped all-axes sweep — cleanup + security + reconcile + doc, fix and loop until clean | | `/site-motion` | Site-level motion: scroll engine choice, page transitions, pin/scrub sequencing across a page or Astro route (design stack) | -| `/effort-low` … `/effort-max` | Effort shifters the orchestrators send per phase (answered by the model-router mod when on); typed by you, they set the main turn's default and minimum effort | | `/route` | model-router mod: show or set the main-loop route (show, clear, off, on, reload, , model=… effort=…, switch on\|off, verbose on\|off) | > This table lists personal skills. Gstack skills (investigate, review, retro, diff --git a/USAGE.md b/USAGE.md index 3a002d1..15869b9 100644 --- a/USAGE.md +++ b/USAGE.md @@ -174,19 +174,20 @@ Tu veux... ### Niveau d'effort -Chaque commande démarre à un niveau de réflexion fixé dans son frontmatter -(`effort:`) : low pour la tenue de registre (`/status`, `/close`, +Chaque commande a une ligne de phase dans le mod model-router +(`mods/model-router/`, actif dans chaque session), qui fixe son niveau de +réflexion : low pour la tenue de registre (`/status`, `/close`, `/commit-change`), medium pour le courant (`/gitflow`, `/prune-memory`), -high pour un fix ou un refactor (`/feat`, `/hotfix`, `/bugfix`, `/refactor`, -audits avec fix), xhigh pour l'architecture et l'audit avant validation -(`/ship-feature`, `/onboard`, `/analyze`). Les orchestrateurs décalent -ensuite le niveau par phase (`lib/effort-shift.md`), et `/effort-max` tapé à -la main relance un tour bloqué au maximum. Les skills externes vendorés -(pile design, superpowers, agent-skills, skills scroll MengTo, 21st) reçoivent leur niveau de -`lib/effort-pins.txt`. Un skill chargé seul par Claude n'applique pas son -niveau : il doit partir avec un autre appel d'outil dans le même message. +high pour un fix ou un refactor (`/feat`, `/hotfix`, `/bugfix`, +`/refactor`, audits avec fix), xhigh pour l'architecture et l'audit avant +validation (`/ship-feature`, `/onboard`, `/analyze`). Le frontmatter +(`model:`, `effort:`) garde les mêmes valeurs et sert de plancher quand le +mod est coupé. Les orchestrateurs déclarent ensuite chaque phase via +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. -Avec le mod model-router (`mods/model-router/`, actif dans chaque session), le niveau suit la phase à chaque requête. Le mod répond lui-même à `Skill(effort-*)` : le niveau s'applique dès la requête suivante et le texte des skills `effort-*` n'est plus chargé. Écrire `ultrathink` dans un prompt, ou taper `/effort-`, fixe le niveau par défaut et le minimum du tour principal. Les sous-agents intégrés suivent leur route : Explore en sonnet/medium, Plan en opus/xhigh. `/route` affiche ou fixe la route (`/route show`, `/route clear`, `/route off`). La config par machine, optionnelle, vit dans `~/.claude/model-router.json` ; `"enabled": false` y coupe le mod sur cette machine. +Taper un skill qui a une ligne route la boucle principale dessus. Une ligne du tier best (plan, reflect, orchestrate, escalate) tient d'un tour à l'autre pendant tout le run, jusqu'à `/route clear`, `/route off`, un `/model` tapé ou un skill d'un autre tier tapé. Pour relancer un tour bloqué : `ultrathink` dans le prompt (plancher du tour) ou `/route effort=max` (tient jusqu'à `/route clear`). Le `/effort` intégré n'a pas d'effet dans un run : les lignes et les routes passent devant. 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. `/route show` affiche la route en cours, slot de run compris (`main: run `). La config par machine, optionnelle, vit dans `~/.claude/model-router.json` ; `"enabled": false` y coupe le mod sur cette machine, et une ligne à `null` y retire une ligne par défaut. ## Les plugins — décision rapide From c1767a503291286ef10ff7292e29e91a79824948 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 10 Oct 2026 11:32:58 +0200 Subject: [PATCH 054/547] =?UTF-8?q?chore(memory):=20BDR-115=20amendment=20?= =?UTF-8?q?2=20+=20LRN-210/211=20+=20EVAL-042=20+=20journal/TODO/contract?= =?UTF-8?q?=20w2b=20=E2=80=94=20feat=20model-router=20wave=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 2 +- .claude/memory/evals.md | 7 +++ .claude/memory/journal.md | 3 + .claude/memory/learnings.md | 7 +++ .claude/tasks/TODO.md | 7 ++- .../2026-10-10-model-router-w2b-1045.md | 55 +++++++++++++++++++ 6 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-10-model-router-w2b-1045.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index e3ddd31..de2ecf2 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1402,4 +1402,4 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Gates**: plan r1 → r3 through 3 challengers + 1 confirmation (2 BLOCKER + 10 MAJOR closed, [[EVAL-040]]); feater DONE first pass; GATE 0 MET; verifier CONFORME 6/6; security PASS + hardening round (criteria 7-11). - **Refs**: plan `.claude/tasks/plans/2026-10-08-model-router-mod.md`, contract `.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md`, [[BDR-107]], [[BDR-108]], [[BLK-029]], [[LRN-205]], [[LRN-206]]. - **Amendment (2026-10-09, user decisions 2026-10-08 evening)**: (a) LOAD supersedes the "Load:" line: tracked relative symlink `skills/model-router` → `../mods/model-router`, loaded in place as `model-router@skills-dir` wherever link.sh links `~/.claude/skills`; `CLAUDE_CODE_PLUGIN_DIRS` dropped (absolute path, settings `env` has no `$HOME` expansion, settings.json tracked), local marketplace dropped (`add` writes an absolute path into settings.json). Proven by fresh-process `claude plugin list --json`. (b) PRECEDENCE amended: `ultrathink` and a typed `/effort-` are the main turn's DEFAULT and MINIMUM (floor slot `turnFloor`): sticky `/route` effort > turn route effort > floor > engine, then floored; per axis; mid-turn prompt floors the running turn and the next (`wait` ignored). Rationale: user "un choix explicite bat la phase déduite"; a pure floor made `/effort-low` a no-op (challenge finding). (c) Per-machine kill switch `"enabled": false` in the untracked `~/.claude/model-router.json` (survives `/clear`, a failed reload keeps the previous config); `enabledPlugins` would dirty the tracked settings.json on every machine. (d) Hardening: `/route` composer-only; agent loops effort-only (model fixed at spawn); config caps; typed slash attested at `prompt.submit`. Commits 346d6ae, 1ff608a, 6430ac6; contracts `2026-10-08-model-router-floor-1835`, `2026-10-08-model-router-wiring-1835`; residuals parked in TODO. - +- **Amendment 2 (2026-10-10, wave 2 closed, commits bb56f3e + 1f2d33b)**: (a) rule 4 closed: rows for every repo skill (56) + agent (21) + Explore/Plan, PHASES by role (plan/reflect/orchestrate/escalate best · judge big · implement/write/verify/explore/apply work · mechanical cheap; `write` work/high + `apply` work/low added). User: pins "deleted or reworked", not copied → rows are the live source, tracked `model:`/`effort:` frontmatter KEPT as off-state floor, census-locked equal to rows (`lib/tests/effort-routing.test.sh`). Robustness BLOCKER closed: mod off → agents would inherit parent model. (b) Rule 5 amended: unrowed skill load changes nothing; best-tier skill row lives in `runMain` slot surviving turn end (precedence userMain > turnMain > runMain > floor > engine), dropped by `/route clear`, `/route off`, user `/model`, typed non-best skill; turn writers (route tool, prompt rules) never touch it. (c) Agents: model written at spawn WITHIN tier, upward only (never below frontmatter alias); explicit Agent params win; project-defined agent (agent.offer source projectSettings|localSettings) skipped. (d) Typed slash: name-bound marker at prompt.submit (composer|sdk|bridge) + pending slot + idle fallback (no live/spawning loop). (e) Shifters `effort-*`, `effort-pins.*`, `model-check.sh` DELETED; orchestrators call `mcp__model-router__route` per phase; gate witness = route answer id, remedy `/route on`; builtin `/effort` not a lever inside a run (levers `ultrathink`, `/route effort=max`). (f) SemVer: typed `/effort-*` removal = breaking → next release 3.0.0. Plan `.claude/tasks/plans/2026-10-09-model-router-w2-1546.md` r4, contracts `2026-10-09-model-router-w2a-1546`, `2026-10-10-model-router-w2b-1045`. Links [[LRN-210]], [[LRN-211]], [[EVAL-042]]. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 951f19b..5fad2a1 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -62,6 +62,7 @@ rules: | EVAL-039 | 2026-09-30 | ship-feature run higgsfield-pack: plan dry-run in scratch → 0 executor failure on 7 tasks; challenge found 7 MAJOR I missed; floor-guard caught 2 shellcheck suppressions of mine; final review found README/code gap | keep | | EVAL-040 | 2026-10-08 | model-router w1a plan: 3 challengers + 1 confirmation found 2 BLOCKER + 14 MAJOR on a plan judged closed; executor then passed every gate first time | keep the round, never dispatch a mod plan without it | | EVAL-041 | 2026-10-09 | model-router W1-C plan: 3 lenses FATAL (4 BLOCKER + 20 MAJOR) then 2 confirmations each FATAL with a NEW BLOCKER in my own revision; executor DONE first pass, 3 short text/hardening rounds | one confirmation is not enough when a revision removes a whole mechanism; the plan carried the risk, the code almost none | +| EVAL-042 | 2026-10-10 | model-router W2 plan r1 → r4: 3 lenses (1 BLOCKER), 2 confirmations (1 BLOCKER then 0); W2-A verifier 3× ECARTS on coverage clauses only, W2-B ECARTS(7) → CONFORME; gate A→B read from engine records | second confirmation paid again (BLOCKER on my own r2 slot); compound coverage criterion = endless ECARTS; engine jsonl replaces the live log | --- @@ -387,3 +388,9 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Anomaly**: 6 BLOCKER + 29 MAJOR over four revisions, each confirmation found a flaw my own fix had introduced; the doctrine cap (one confirmation) would have shipped r2 with a 5-hour false outage. The executor never needed a re-dispatch for logic: all later rounds were text truthfulness and hardening. - **Action**: when a revision REMOVES or REPLACES a mechanism, re-challenge once more (state the deviation); keep plan sections additive with an explicit precedence line (r4 > r3 > r2) so executors and verifiers read one law; name superseded clauses of prior contracts in the Disposition. Links [[EVAL-040]], [[LRN-207]], [[BDR-115]]. +## EVAL-042 — model-router W2: challenge value held on the second confirmation; coverage-shaped criterion burned three verifiers +- **Date**: 2026-10-10 +- **Output checked**: plan `.claude/tasks/plans/2026-10-09-model-router-w2-1546.md` r1 → r4; W2-A diff (register.ts, 88 kit tests); W2-B diff (43 files, 140-check census). +- **Method**: 3 blind lenses (simplicity CONCERNS(5), correctness CONCERNS(10), robustness FATAL(8) → BLOCKER: mod off = agents inherit parent model); confirmation 1 robustness FATAL(8) → BLOCKER introduced by r2 (route calls wiped the sticky slot); confirmation 2 correctness CONCERNS(3), no BLOCKER → r4. W2-A: feater DONE + 4 rounds (1 internal decision, 3 coverage), GATE 0 MET, verifier ECARTS(3)/(1)/(1) all coverage, user accepted at cap; security PASS. W2-B: feater DONE first pass, verifier ECARTS(7) (5 FLOOR items = planned deletions needing a CLARIFICATIONS line, 2 prose, 1 scope add) → CONFORME 10/10; security PASS; full `make test` once (env red only). Gate A→B: 3/4 probes answered from engine jsonl, probe 4 (typed skill with a live agent) unobserved, recorded as a limit. +- **Anomaly**: the user's rework answer ("delete or rework, not copy") changed the design mid-plan; r2's own fix carried a BLOCKER again (as in EVAL-041). Coverage criterion: 3 verifiers, 0 defects. FLOOR guard needs the test deletions named in CLARIFICATIONS, not only in criteria. +- **Action**: keep the "second confirmation after a mechanism change" rule; write coverage criteria one clause each (LRN-210); when a plan deletes tests, write the authorizing CLARIFICATIONS line BEFORE the first verifier. Links [[EVAL-041]], [[LRN-210]], [[LRN-211]], [[BDR-115]]. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 05a4fb3..ac278f4 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -591,3 +591,6 @@ rules: - /hotfix make-test-names-red-suites (user: '9 min pour un merge?'): measured from transcript timestamps, the merge took <20 s; 454 s went to make test run TWICE (full + per-suite sweep to name the red suite, because the aggregate rc is silent). Fix: Makefile test prints FAIL + summary, rc unchanged (GNU make returns 2 on a failed recipe; my first oracle expected 1). hotfixer DONE, GATE 0 MET 2/2, security PASS. Branch bugfix/make-test-names-red-suites UNMERGED (human signal). Method note: a mods/-only diff needs only the mods suite + doctrine census, the full run once before merge. - User go 'all, merge le, et je clear': LRN-207/208/209 + EVAL-041 written (ca96458); gitflow finish bugfix/make-test-names-red-suites → develop 5e0e5c0, branch removed. develop 28 commits ahead of origin, NOT pushed (manual mode, user publishes). Only settings.json dirty (user's own /model change). Session closes; next: wave 2 of model-router (TODO W2 line). - model-router W2-A landed (bb56f3e, feature/model-router-w2). User go 'lance la vague 2' + 4 pass-B answers: shifters deleted, pins reworked into phase rows (not copied), phases declared, slim gate. Plan r1→r4: 3 lenses (1 BLOCKER: mod off → agents inherit parent model → frontmatter kept as off-state floor), confirmation 1 FATAL (BLOCKER: route calls wiped the sticky slot → separate runMain), confirmation 2 CONCERNS (deviation: 2 confirmations, stated). Feater DONE + 4 gap rounds (A5 in-agent decision, 6+3+3 coverage tests, every one mutation-proven). GATE 0 MET; verifier ECARTS(3)/(1)/(1) all on coverage of criterion 3 clauses, never code → diagnosis at max: compound criterion → user accepted at the cap. Security PASS (2 MEDIUM pre-existing). Kit 58→88. Next: user /reload-plugins + live probe, then W2-B. Lesson for the next contract: one coverage clause per criterion, not twelve. + +## 2026-10-10 +- model-router W2-B landed (1f2d33b) + gate A→B. User /reload-plugins + typed /status; I read the engine jsonl instead of the UI log: main low on typed /status, analyzer opus/xhigh at step 0 → ordering + row-over-frontmatter proven; probe 4 unobserved (user away), limit recorded. Route tool checked live (`mcp__model-router__route`, deferred → ToolSearch once; answer names the id); session itself routed through it (reflect → orchestrate). W2-B: contract 10 criteria, feater DONE first pass (43 files), verifier ECARTS(7): 5 FLOOR items (planned test deletions → CLARIFICATIONS line), `/route on` wording, false CLAUDE.global.md sentence, plan-challenger scope add → CONFORME 10/10; I folded 3 observations by hand (SDD sonnet implementers `effort="medium"`, run-slot droppers, 80-col). Security PASS (push-guard false positive on a grep pattern; it also bit my registry heredoc). Full make test green (env red only). Doc audit SIGNIFICANT → user: apply all P1-P8, SemVer BREAKING → 3.0.0, registries all → BDR-115 amendment 2, LRN-210/211, EVAL-042. Pending: doc commit, memory commit, user merge decision (gitflow finish, human signal), publish by hand. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 60a6a7f..34b18a7 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1777,3 +1777,10 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s - **Context**: 2026-10-09 the pre-merge check took 454 s = full `make test` (48 suites) + a per-suite re-run to NAME the red one (aggregate rc, permanent env red design-tool-gate). Three more full passes earlier that day for mods/-only diffs. Hotfix efdd491: the recipe prints `FAIL ` + `all suites green` / ` suite(s) red: …`. My oracle expected rc 1; GNU make returns 2 when a recipe line fails. - **Apply**: a diff confined to one component runs that component's suite + the doctrine census; the full suite runs ONCE before `gitflow finish`; read the FAIL lines, never re-run per suite. Oracles on `make` test `[ $rc -ne 0 ]`, not `-eq 1`. Links [[LRN-173]]. +## LRN-210 — One coverage clause per contract criterion; a compound "covered by kit tests" criterion yields ECARTS forever with zero defects +- **Context**: W2-A contract criterion 3 bundled ~12 clauses under one "Covered by kit tests". Three fresh verifiers: ECARTS(3), (1), (1), each a NEW untested guard, code judged correct 3×. Cap hit, diagnosis at max, user accepted. 4 feater rounds added 30 tests (58 → 88), every one mutation-proven. +- **Apply**: split coverage criteria: one clause = one criterion with its own test name; or make the oracle a mutation script (`CHECK:` flips the guard, expects a red test). Verifier reads clauses literally: write only what one test can prove. Links [[LRN-209]], [[EVAL-042]]. + +## LRN-211 — Typed-slash routing: name-bound marker + idle fallback; run slot separate from turn routes; engine records are the live oracle +- **Context**: mod needs "user typed /feat" from `skill.prompt`, which carries no origin. `prompt.submit` sees the raw `/name` first (composer|sdk|bridge): store the NAME (not a boolean; a bare flag leaked to the next preload), pending slot when mid-turn, consume only on the matching `skill.prompt`; fallback = no live/spawning loop AND allowed origin. Sticky run route in the SAME slot as turn routes was wiped by the first `route()` call (confirmation BLOCKER) → separate `runMain`, best-tier rows only (work/cheap rows leak low effort across turns). Live facts read from `~/.claude/projects//.jsonl` (+ `subagents/agent-*.jsonl`): `effort` + `message.model` per step. Typed `/status` → main low; analyzer step 0 opus/xhigh with frontmatter high (spawn bookkeeping precedes step 0; row beats frontmatter). +- **Apply**: hook-side user-intent markers: bind to a name, add a pending slot for mid-turn, keep an ordering-independent fallback. Two lifetimes = two slots, never one slot with a source tag. Verify engine behaviour in the transcript jsonl, not in `$.ui.log`. Links [[BDR-115]], [[LRN-206]]. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 9de2a5b..d7c3756 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -18,9 +18,12 @@ migration of shifters/pins/model-gate in wave 2 after proof; names model-router - [x] W1-C live verification part 1 (2026-10-09 after `/reload-plugins`, skills-dir copy loaded, 12 hooks): derived orchestrate on a real background Explore (main high → medium while it ran → high after its end); Explore on sonnet/medium; `route plan` → next request xhigh (engine record); `Skill(effort-low)` bridged → next request low (engine record); `/route show` resolves all 10 phases to full ids, `down: none`; steps arrive as bare `claude-fable-5-1` (no `[1m]`) so the suffix carry never fires on this session - [ ] W1-C live verification part 2 (needs a real incident): StopFailure vs turn.complete order; `PostModelSwitch` `auto` semantics and its `from_model` after a router upgrade; whether a router rewrite raises `auto`; `[1m]` carry validity on opus (only on a session whose steps carry it) - [x] W2-A mod (2026-10-09, bb56f3e on feature/model-router-w2, contract `2026-10-09-model-router-w2a-1546`, plan r4 `2026-10-09-model-router-w2-1546`): user decisions — effort-* skills deleted (W2-B), pins REWORKED not deleted (rows = phases by role; frontmatter `model:`/`effort:` kept as census-locked off-state floor after a robustness BLOCKER), orchestrators declare phases, slim model gate. Phases `write` work/high + `apply` work/low; 56 skill rows, 21 agent rows; agents' model at spawn within tier, upward only, project-defined agents skipped (agent.offer); typed slash → name-bound marker (composer|sdk|bridge) + pending slot + idle fallback; best-tier rows in a `runMain` slot surviving turn end; unrowed skill leaves the route; route answer always names the id; `null` override rows. 3 lenses + 2 confirmations (1 BLOCKER each round closed), feater + 4 gap rounds, GATE 0 MET, verifier 3× ECARTS on coverage clauses only → user accepted at the cap, security PASS (2 MEDIUM pre-existing: first-load kill switch fails open, ReDoS size-bounded). Kit 58 → 88 tests. Doc-sync skipped for A (mod-only, docs at B). -- [ ] W2 gate A→B (user): `/reload-plugins`, then the live probe of plan § Gate (4 points: typed `/status` marker vs fallback in the verbose log; a real rowed spawn line + `step 0 agent` effort = spawn/first-step ordering; sonnet session typed `/feat` self-check + route answer; probe 1 again with a background agent alive). `typed-marker` never seen → W2-B blocked, A4 re-planned. -- [ ] W2-B repo migration (plan § W2-B B0-B7 + STEP 6/7): bridge removal, `lib/effort-shift.md` rewrite, 15 citers → `route`, `effort=` on opus general-purpose dispatches, slim `lib/model-gate.md`, delete `model-check.sh` + `effort-pins.*` + their tests + install/update blocks, delete `skills/effort-*`, analyzer `effort: xhigh`, census rewrite (drift lock rows ↔ frontmatter), docs + registries (BDR-115 amendment, LRN typed-slash/run slot, EVAL) +- [x] W2 gate A→B (2026-10-10, engine records): typed `/status` → main low then medium during the dispatch; analyzer opus/xhigh from step 0 (frontmatter high) = spawn bookkeeping first, row beats frontmatter; status-reporter haiku step 0. Probe 3 dropped (gate always calls route). Probe 4 (typed skill while a background agent is live: marker vs fallback) NOT observed → limit in `lib/effort-shift.md`; re-check in the records whenever the user types a skill with an agent alive. +- [x] W2-B repo migration (2026-10-10, 1f2d33b, contract `2026-10-10-model-router-w2b-1045`): 15 citers → `mcp__model-router__route` per phase, `effort=` on built-in judgment dispatches + SDD sonnet implementers (`effort="medium"`), `lib/effort-shift.md` + `lib/model-gate.md` rewritten (witness = route answer, `/route on`), deletions (effort-*, effort-pins.*, model-check.sh, tests, installer blocks), bridge removed from the mod, census rewritten (140 checks, drift lock rows ↔ frontmatter), analyzer xhigh, CLAUDE.global.md Design-work line. Verifier ECARTS(7) → CONFORME 10/10, security PASS, full make test green (design-tool-gate env red). Docs P1-P8 user-approved; SemVer: breaking → next release 3.0.0 (MIGRATION section at release). +- [ ] (was) W2 gate A→B (user): `/reload-plugins`, then the live probe of plan § Gate (4 points: typed `/status` marker vs fallback in the verbose log; a real rowed spawn line + `step 0 agent` effort = spawn/first-step ordering; sonnet session typed `/feat` self-check + route answer; probe 1 again with a background agent alive). `typed-marker` never seen → W2-B blocked, A4 re-planned. +- [x] (was) W2-B repo migration (plan § W2-B B0-B7 + STEP 6/7): bridge removal, `lib/effort-shift.md` rewrite, 15 citers → `route`, `effort=` on opus general-purpose dispatches, slim `lib/model-gate.md`, delete `model-check.sh` + `effort-pins.*` + their tests + install/update blocks, delete `skills/effort-*`, analyzer `effort: xhigh`, census rewrite (drift lock rows ↔ frontmatter), docs + registries (BDR-115 amendment, LRN typed-slash/run slot, EVAL) - [ ] W2-A residuals (security, accepted): first-load failure of the override activates the router despite `enabled:false` (fix = treat a failed first load as off); ReDoS on a self-authored prompt pattern (size-bounded); error text in the local log; model alias keys unvalidated (PHASE_KEY would do); `offers` map uncapped; `__proto__`/`constructor` override keys untested. Known limits: `skillCalls`/`spawning` counters are global; offers keyed by name only; builtin `/effort` is not a lever inside a run. +- [ ] W2 residuals: probe 4 unobserved (above); the push-guard hook denies a read-only grep (or a heredoc) whose TEXT contains the push verb next to `git` (security-auditor + orchestrator 2026-10-10, false positives, reworded); ~27 loose "sonnet pin"/"opus pin" shorthand sites kept (true by census); README config key list omits `tiers`/`fallback`/`cooldownMinutes`/`mainUpgrade`/`upgradeMaxTokens` (doc audit item 6, pre-existing); MIGRATION.md "Upgrading to 3.0.0" at release time; `skillCalls`/`spawning` counters global; offers keyed by name. - [ ] W3 optional: step heuristics, haiku classifier, quota-aware downgrade, A/B ## 2026-09-30 — Higgsfield pack: CLI + skills in the install process, off by default (feature/higgsfield-pack) diff --git a/.claude/tasks/contracts/2026-10-10-model-router-w2b-1045.md b/.claude/tasks/contracts/2026-10-10-model-router-w2b-1045.md new file mode 100644 index 0000000..118f3e3 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-10-model-router-w2b-1045.md @@ -0,0 +1,55 @@ +# CONTRACT — model-router-w2b +- date: 2026-10-10 | flow: feat | branch: feature/model-router-w2 +- status: active +- wave: W2-B (repo migration), plan r4 `.claude/tasks/plans/2026-10-09-model-router-w2-1546.md` § D1-D4, § Row tables, § W2-B B0-B7. Follows W2-A (bb56f3e) and the A→B gate. + +## REQUEST (verbatim — IMMUTABLE) +tu peux lancer la vague 2 +(TODO W2 line: 15 skills `Skill(effort-*)` → `route` tool calls; remove `skills/effort-*`, `lib/effort-pins.txt/.sh`, install/update steps, `effort:` frontmatter on skills and agents; repo agents into the mod's `agents` table (verify the spawn/first-step ordering first); `lib/model-gate.md` + `lib/model-check.sh` → mod rule; census tests repointed; `lib/effort-shift.md` rewritten; docs) + +## CLARIFICATIONS +Q: pass B 2026-10-09 (see the W2-A contract) / A: effort-* deleted; pins reworked into phase rows with the tracked frontmatter kept as census-locked off-state floor; orchestrators declare phases; slim model gate [gated 2026-10-09] +Q: A→B gate evidence (engine records 2026-10-10) / A: typed `/status` → main effort low then medium during the dispatch (row applied to a typed slash); analyzer spawn → opus/xhigh from step 0 while its frontmatter still said high (spawn bookkeeping precedes the first step; the row beats the frontmatter); status-reporter haiku from step 0. Probe 4 (typed skill while a background agent is live: marker vs fallback) NOT observed → recorded as a limit in `lib/effort-shift.md`, re-checked later in the records; not blocking [gated 2026-10-10] +Q: slim gate design / A: the include ALWAYS calls the route tool at entry (`mcp__model-router__route` phase = the skill's row) and reads the id in the answer; no self-check wording dependency; the tool is deferred for the model → `ToolSearch("select:mcp__model-router__route")` once per session when it is not loaded [gated 2026-10-10] + +Q: FLOOR items (verifier 1): deletion of `lib/tests/effort-pins.test.sh` and `lib/tests/model-check.test.sh`, removal of the two `Skill(effort-low)` bridge kit tests, the from-scratch rewrite of `lib/tests/effort-routing.test.sh` (has/ok/ko helpers, its `# shellcheck disable=SC2015,SC2016` directive carried over from HEAD) / A: all authorized — they are the plan's B0 and B4 steps, accepted at pass B (shifters, pins and witness deleted with their tests) [gated 2026-10-10] +Q: scope addition (verifier 1, criterion 9a): `agents/plan-challenger.md:110-112` twins `lib/challenge-plan.md:46` ("`model: opus`-pinned in its frontmatter, session-independent") / A: added to FILE SCOPE, same rewording (row + off-state floor); the ~20 loose "sonnet pin"/"opus pin" shorthand sites stay (true: alias == row tier by census) [gated 2026-10-10, orchestrator — minor, user may veto] + +## ACCEPTANCE CRITERIA +1. No `Skill(effort-` call and no `EFFORT SHIFTS:` header line remains in tracked skills, agents and lib (the mod and CHANGELOG excepted). + CHECK: ! git grep -nE 'Skill\(effort-|EFFORT SHIFTS:' -- skills agents lib ':!mods' >/dev/null && echo W2B-NO-SHIFTER-CITER + EXPECT: W2B-NO-SHIFTER-CITER + EVIDENCE: MET exit=0 marker-found :: W2B-NO-SHIFTER-CITER +2. Deleted: `skills/effort-{low,medium,high,xhigh,max}`, `lib/effort-pins.txt`, `lib/effort-pins.sh`, `lib/model-check.sh`, `lib/tests/effort-pins.test.sh`, `lib/tests/model-check.test.sh`; no tracked reference to `effort-pins`, `apply_effort_pins` or `model-check.sh` outside CHANGELOG.md, `.claude/`, README.md and USAGE.md (the two docs are the STEP 6 doc-sync targets [gated 2026-10-10]). + CHECK: for p in skills/effort-low skills/effort-medium skills/effort-high skills/effort-xhigh skills/effort-max lib/effort-pins.txt lib/effort-pins.sh lib/model-check.sh lib/tests/effort-pins.test.sh lib/tests/model-check.test.sh; do [ ! -e "$p" ] || { echo "still here: $p"; exit 1; }; done && ! git grep -nE 'effort-pins|apply_effort_pins|model-check\.sh' -- . ':!CHANGELOG.md' ':!.claude' ':!README.md' ':!USAGE.md' >/dev/null && echo W2B-DELETIONS-DONE + EXPECT: W2B-DELETIONS-DONE + EVIDENCE: MET exit=0 marker-found :: W2B-DELETIONS-DONE +3. Mod: the `Skill(effort-*)` bridge is gone (`EFFORT_SKILL`, `effortBridge` absent), the kit suite and the mods suite are green. + CHECK: ! grep -qE 'EFFORT_SKILL|effortBridge' mods/model-router/hooks/register.ts && cd mods/model-router && out="$(claude plugin test . 2>&1)" && printf '%s\n' "$out" | grep -qE '[0-9]+ pass' && ! printf '%s\n' "$out" | grep -qE '[1-9][0-9]* fail' && cd ../.. && make test suite=lib/tests/mods.test.sh 2>&1 | grep -q 'all suites green' && echo W2B-MOD-GREEN + EXPECT: W2B-MOD-GREEN + EVIDENCE: MET exit=0 marker-found :: W2B-MOD-GREEN +4. `lib/tests/effort-routing.test.sh` is rewritten as the wave-2 census (drift lock rows ↔ frontmatter parsed from `register.ts`, no `effort:`-less routed skill, D3 wiring markers, no shifter citers) and is green; `lib/tests/model-routing.test.sh` and `lib/tests/higgsfield.test.sh` are green. + CHECK: grep -q 'register.ts' lib/tests/effort-routing.test.sh && bash lib/tests/effort-routing.test.sh >/dev/null 2>&1 && bash lib/tests/model-routing.test.sh >/dev/null 2>&1 && bash lib/tests/higgsfield.test.sh >/dev/null 2>&1 && echo W2B-CENSUS-GREEN + EXPECT: W2B-CENSUS-GREEN + EVIDENCE: MET exit=0 marker-found :: W2B-CENSUS-GREEN +5. Wiring follows plan D3 at every former shifter site: dispatch span → `mcp__model-router__route` phase orchestrate; own level high → reflect, xhigh → plan; bookkeeping tail → apply; escalation (verify-secure-loop ×3, ship-feature error recovery) → escalate; judgment dispatches of built-ins (`general-purpose` `model="opus"` in ship-feature, init-project, onboard, tour; `model: "fable"` skill-runners in client-handover-writer) carry an explicit `effort=` param instead of a shift; the "turn reset" re-assert sites become a route call at the first step of the resumed turn. Judged by reading each site against the plan. +6. `lib/model-gate.md` is the mod rule, ≤ 30 lines: always call `mcp__model-router__route` at entry with the skill's row phase, STOP unless the answer names a fable or opus id (tool missing → ToolSearch once; "is off" → STOP with the remedy); keeps the dispatch-tier table with `model: "fable"` for skill-runners; no `model-check` reference. + CHECK: [ "$(wc -l < lib/model-gate.md)" -le 30 ] && grep -q 'mcp__model-router__route' lib/model-gate.md && grep -q 'model: "fable"' lib/model-gate.md && ! grep -q 'model-check' lib/model-gate.md && echo W2B-GATE-SLIM + EXPECT: W2B-GATE-SLIM + EVIDENCE: MET exit=0 marker-found :: W2B-GATE-SLIM +7. `lib/effort-shift.md` is rewritten (≤ 60 lines) as the route doctrine: the tool name and the ToolSearch note, the D3 wiring points, explicit `effort=` for built-in judgment dispatches, the run slot and `/route clear`, levers (`ultrathink`, `/route effort=max`; builtin `/effort` is not a lever inside a run), last rowed skill wins and an unrowed one changes nothing, the probe-4 limit, headless OK, `effort-audit.py`. + CHECK: [ "$(wc -l < lib/effort-shift.md)" -le 60 ] && grep -q 'mcp__model-router__route' lib/effort-shift.md && grep -q 'ToolSearch' lib/effort-shift.md && grep -q 'effort-audit.py' lib/effort-shift.md && ! grep -q 'Skill(effort' lib/effort-shift.md && echo W2B-DOCTRINE + EXPECT: W2B-DOCTRINE + EVIDENCE: MET exit=0 marker-found :: W2B-DOCTRINE +8. Frontmatter aligned to the rows: `agents/analyzer.md` carries `effort: xhigh`; every other tracked `effort:`/`model:` value equals its row (criterion 4 census proves it); `CLAUDE.global.md` Design-work lines no longer cite `lib/effort-pins.txt` or the lone-Skill-call rule. + CHECK: grep -q '^effort: xhigh' agents/analyzer.md && ! grep -q 'effort-pins' CLAUDE.global.md && ! grep -q 'lone Skill call' CLAUDE.global.md && echo W2B-FRONTMATTER + EXPECT: W2B-FRONTMATTER + EVIDENCE: MET exit=0 marker-found :: W2B-FRONTMATTER +9. Prose sites that stated pin semantics ("sonnet by frontmatter pin", "`model: opus`-pinned in their frontmatter, session-independent", STOP texts naming `/effort-max`) are reworded to the row/off-state-floor semantics and the D4 levers. Judged by reading. +10. The suites the diff touches are green (doctrine-citers, loops-light, plan-challenger, skill-routing-census, profile-census, portability-census, gitflow-test if present) and `shellcheck *.sh hooks/*.sh lib/*.sh` is clean; the full `make test` runs once before the merge (LRN-209), the orchestrator reports it. + CHECK: for t in doctrine-citers loops-light plan-challenger skill-routing-census profile-census portability-census; do [ -f "lib/tests/$t.test.sh" ] || continue; bash "lib/tests/$t.test.sh" >/dev/null 2>&1 || { echo "red: $t"; exit 1; }; done; shellcheck ./*.sh hooks/*.sh lib/*.sh && echo W2B-SUITE-GREEN + EXPECT: W2B-SUITE-GREEN + EVIDENCE: MET exit=0 marker-found :: W2B-SUITE-GREEN + +## FILE SCOPE +mods/model-router/hooks/register.ts, mods/model-router/hooks/register.test.ts; lib/effort-shift.md, lib/model-gate.md, lib/verify-secure-loop.md, lib/challenge-plan.md; skills/{ship-feature,init-project,feat,bugfix,web-validate,seo,hotfix,geo,harden,code-clean,audit-delta,onboard,tour,client-handover,analyze,commit-change}/SKILL.md; agents/client-handover-writer.md, agents/analyzer.md, agents/plan-challenger.md (prose only), agents/{commit-changer,handover-doc-writer,geo-analyzer,doc-syncer,seo-analyzer}.md (prose only); deletions listed in criterion 2; install-plugins.sh, update-all.sh; lib/tests/{effort-routing,model-routing,higgsfield}.test.sh; CLAUDE.global.md (Design-work lines only). From 22455c051f1df3ac4aad564630abbc270071c82f Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 11 Oct 2026 11:48:25 +0200 Subject: [PATCH 055/547] =?UTF-8?q?feat(model-router):=20wave=203-A=20?= =?UTF-8?q?=E2=80=94=20first-use=20route=20confirmation,=20decision=20memo?= =?UTF-8?q?ry,=20project=20exceptions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit routing.json (tracked, reached through the plugin directory) is now the single source of the phase table and of every skill/agent row, plus the decisions: confirmed rows/phases, changed rows (from/to) and projects exceptions keyed by a normalized git remote (credentials never stored, no machine paths). First use of a rowed typed skill, a rowed agent spawn or a main-loop phase opens the engine's dialog (Later / Keep / two alternative phases; Other = a phase name); a change asks Everywhere or This project only. One dialog at a time, never in headless, never inside an agent, never written by the model: only a dialog answer or /route ask writes, serialized, size-capped, never creating the file. Layers: routing.json < ~/.claude/model-router.json; the project tree is never read. /route pending, /route ask on|off. Census reads rows and phases from the file and tolerates a user-changed row (WARN). Kit suite 86 → 190 tests. Contract .claude/tasks/contracts/2026-10-10-model-router-w3a-confirm-1201.md, plan r4: 3 lenses + 1 confirmation, feater + 4 rounds, GATE 0 MET, verifier CONFORME then re-verify after security, security BLOCK(1) fixed then PASS. Live: T2 dialogs answered by the user from the hot-loaded mod. --- lib/effort-shift.md | 4 + lib/tests/effort-routing.test.sh | 169 ++- mods/model-router/hooks/register.test.ts | 1347 +++++++++++++++++++++- mods/model-router/hooks/register.ts | 809 +++++++++++-- mods/model-router/routing.json | 144 +++ 5 files changed, 2299 insertions(+), 174 deletions(-) create mode 100644 mods/model-router/routing.json diff --git a/lib/effort-shift.md b/lib/effort-shift.md index dc487d0..52f685c 100644 --- a/lib/effort-shift.md +++ b/lib/effort-shift.md @@ -48,6 +48,10 @@ Builtin `/effort` is NOT a lever inside a run: rows and routes outrank it. typed marker (unverified live 2026-10-10). - Headless (`-p`, SDK) runs the hooks, so routing works there too. - Mod off: typed agents fall back to their `model:`/`effort:` frontmatter. +- First use of a row asks once (Keep, Later or another phase, then + Everywhere or this project only); the answer is kept in + `mods/model-router/routing.json`. `/route pending` lists what is still + unconfirmed, `/route ask off|on` toggles the dialog. Measure the split any time: `python3 ~/.claude/lib/effort-audit.py` (thinking/output/cache tokens per scope, model and effort). diff --git a/lib/tests/effort-routing.test.sh b/lib/tests/effort-routing.test.sh index e2b9214..3d7f855 100755 --- a/lib/tests/effort-routing.test.sh +++ b/lib/tests/effort-routing.test.sh @@ -1,12 +1,16 @@ #!/usr/bin/env bash # lib/tests/effort-routing.test.sh — wave-2 census of the model-router rows. -# Drift lock: every tracked skill/agent row in mods/model-router/hooks/ -# register.ts equals its frontmatter (the off-state floor), the D3 wiring -# markers sit in the orchestrators, no shifter citer survives. +# Drift lock: every tracked skill/agent row of mods/model-router/routing.json +# equals its frontmatter (the off-state floor), except a row the user changed +# through the first-use dialog (WARN floor drift: the floor may lag a +# confirmed decision); the D3 wiring markers sit in the orchestrators, no +# shifter citer survives. # shellcheck disable=SC2015,SC2016 # A && ok || ko is deliberate (ok/ko never fail) set -u R="$(cd "$(dirname "$0")/../.." && pwd)" -REG="$R/mods/model-router/hooks/register.ts" +MOD="$R/mods/model-router" +RJ="$MOD/routing.json" +REG="$MOD/hooks/register.ts" pass=0; fail=0 ok() { pass=$((pass+1)); } ko() { fail=$((fail+1)); printf 'FAIL %s\n' "$1"; } @@ -16,84 +20,145 @@ lacks() { if grep -qF "$2" "$R/$1"; then ko "$1 must NOT contain: $2"; else ok; fm() { awk 'NR==1&&/^---$/{p=1;next} p&&/^---$/{exit} p' "$1"; } fm_val() { fm "$1" | grep -E "^$2: [a-z]+$" | head -1 | cut -d' ' -f2; } -# ── register.ts parsers (awk/sed on the DEFAULT_CONFIG literal) ────────── -# rows -> "name phase" per row -rows() { - awk -v s="$2" '$0 ~ "^ "s": \\{"{f=1;next} f&&/^ \},?$/{f=0} f' "$1" \ - | grep -v '^ *//' | grep -oE "('[^']+'|[A-Za-z0-9_-]+): '[a-z]+'" \ - | sed -E "s/'//g; s/: / /" -} -# phase_effort -> " " -phase_effort() { - awk '/^ phases: \{/{f=1;next} f&&/^ \},?$/{f=0} f' "$1" \ - | sed -nE "s/^ *$2: \{ tier: '([a-z]+)', effort: '([a-z]+)' \},?$/\1 \2/p" +# ── routing.json (rows, phases, decisions) and the tier heads ──────────── +# dump -> "skills|agents ", "phases

+# ", "changed " lines +dump() { + python3 -I - "$1" <<'PY' +import json, sys +d = json.load(open(sys.argv[1])) +for kind in ("skills", "agents"): + for k, v in d.get(kind, {}).items(): + print(kind, k, v) +for k, v in d.get("phases", {}).items(): + print("phases", k, v.get("tier", ""), v.get("effort", "")) +for kind in ("skills", "agents"): + for k, v in d.get("changed", {}).get(kind, {}).items(): + print("changed", kind, k, v["from"], v["to"]) +PY } +# lookups on a dump text: row_of D kind name · phase_effort D phase · +# changed_of D kind name -> "from to" +row_of() { printf '%s\n' "$1" | awk -v k="$2" -v n="$3" '$1==k&&$2==n{print $3}'; } +phase_effort() { printf '%s\n' "$1" | awk -v p="$2" '$1=="phases"&&$2==p{print $3, $4}'; } +changed_of() { printf '%s\n' "$1" | awk -v k="$2" -v n="$3" '$1=="changed"&&$2==k&&$3==n{print $4, $5}'; } # tier_head -> first alias of the tier list tier_head() { awk '/^ tiers: \{/{f=1;next} f&&/^ \},?$/{f=0} f' "$1" \ | sed -nE "s/^ *$2: \['([a-z]+)'.*$/\1/p" } -row_of() { rows "$REG" "$1" | awk -v n="$2" '$1==n{print $2}'; } +# the fallback copy of the phases inside the mod's code: " " +code_phase() { + awk '/^ phases: \{/{f=1;next} f&&/^ \},?$/{f=0} f' "$REG" \ + | sed -nE "s/^ *$1: \{ tier: '([a-z]+)', effort: '([a-z]+)' \},?$/\1 \2/p" +} +# field_of -> that phase's frontmatter value +field_of() { + local pe tier + pe="$(phase_effort "$1" "$2")" + if [ "$3" = effort ]; then printf '%s\n' "${pe#* }"; return; fi + tier="${pe% *}"; tier_head "$REG" "$tier" +} +# verdict : ok when the +# frontmatter equals the row's phase; warn when the row was changed through +# the dialog (changed.from is the shipped phase, changed.to the row) and the +# frontmatter still holds the shipped value; fail otherwise (a Keep alone, +# an empty or unknown value, a hand edit after a change) +verdict() { + local D="$1" kind="$2" name="$3" field="$4" got="$5" phase="$6" ch from fromval + [ -n "$got" ] || { echo fail; return; } + [ "$got" = "$(field_of "$D" "$phase" "$field")" ] && { echo ok; return; } + ch="$(changed_of "$D" "$kind" "$name")"; from="${ch% *}" + [ -n "$ch" ] && [ "${ch#* }" = "$phase" ] || { echo fail; return; } + fromval="$(field_of "$D" "$from" "$field")" + [ -n "$fromval" ] && [ "$got" = "$fromval" ] && echo warn || echo fail +} +# floor_check

` blocks, HTML-escaped (`<` as `<`, `>` as `>`,
+   `&` as `&`). An unescaped `` generic or JSX tag silently swallows
+   the code that follows it.
+4. The quiz lives in the `quiz-data` JSON block and the template's script
+   renders it. Keep the page self-contained: no CDN, no web font, no remote
+   image. It has to open offline from disk a year from now.
+
+## STEP 5 — Save, check, hand over
+
+1. Save to `~/Documents/explanations//YYYY-MM-DD-.html`.
+   Today's date comes first so the folder sorts by time, `` is the
+   basename of the repo and `` a few kebab-case words naming the
+   change. Never inside the project tree. A taken name gets `-2`.
+2. Run the checker and fix every FAIL until it exits 0:
+   ```bash
+   python3 "$HOME/.claude/skills/explain-diff/scripts/check_explanation.py" 
+   ```
+3. Reread the prose against the writing rules and fix what slipped.
+4. Reply with the absolute path and its `file://` URL, the one-line summary
+   of the change, the inferences the page marks as such, and the secret
+   warning if one was redacted. Do not paste the explanation into the chat:
+   the page is the deliverable.
+
+## When things go wrong
+
+| Situation | Action |
+|---|---|
+| Not a git repository | Ask for the project path |
+| Target resolves to an empty diff | Stop and name the target |
+| PR number without `gh`, or a non-GitHub remote | Ask for the branch name |
+| Binary files in the diff | List them in Code, do not walk them |
+| Over about 5000 changed lines | Explain the top level, offer one page per commit or folder |
+| Checker FAIL | Fix and rerun; never hand over a failing page |
diff --git a/skills/explain-diff/assets/template.html b/skills/explain-diff/assets/template.html
new file mode 100644
index 0000000..574056d
--- /dev/null
+++ b/skills/explain-diff/assets/template.html
@@ -0,0 +1,549 @@
+
+
+
+
+
+
+{{TITLE}}
+
+
+
+
+ +
+

{{TITLE}}

+

{{PROJECT}} · {{RANGE}} · {{DATE}} · {{STATS}}

+

{{LEAD}}

+
+ +
+ +
+
+

{{BACKGROUND_TITLE}}

+ {{BACKGROUND_BODY}} +
+ +
+

{{INTUITION_TITLE}}

+ {{INTUITION_BODY}} +
+ +
+

{{CODE_TITLE}}

+ {{CODE_BODY}} +
+ +
+

{{QUIZ_TITLE}}

+ {{QUIZ_INTRO}} +
+

+
+
+ +
{{COLOPHON}}
+
+ + + + + diff --git a/skills/explain-diff/references/components.md b/skills/explain-diff/references/components.md new file mode 100644 index 0000000..03424c1 --- /dev/null +++ b/skills/explain-diff/references/components.md @@ -0,0 +1,187 @@ +# Components for an explain-diff page + +Every snippet below is styled by `assets/template.html`. Copy, then replace +the sample content. Keep the class names: the stylesheet and the checker +know them. Sample text is in English; write yours in the page language. + +## Skippable deep background + +The newcomer's tour of the system goes in a collapsible block, so a reader +who knows it can jump straight to the narrow background. + +```html +
+ How the hint service works (skip if you + know it) +

…

+
+``` + +## Callouts + +Three kinds: `concept` (a definition or key idea), `edge` (an edge case +worth remembering), `risk` (what can still go wrong, or a follow-up). + +```html + + + +``` + +## Flow of components + +Nodes left to right, an edge between each pair. The edge label carries the +example data that travels (a call, a payload, a return value). `hl` marks +the component the change touches. On a phone the flow turns vertical. + +```html +
+
+
Browser + guest g-42, no session
+
ensureGuest()
+
fetchHint + new: session first
+
rpc hint(day=12)
+
Database + auth-gated RPC
+
+
After the fix: the session exists before the hint call. +
+
+``` + +A return value travels back through the label of the same edge +(`hint(day=12) → "starts with B"`) or through a second flow below. + +## Row of states + +Same markup with `state` nodes; `hl` marks the state the change adds. + +```html +
+
running
+
crash ×3
+
stopped + new: final
+
+``` + +## Before and after + +```html +
+
+

Before

+

…

+
+
+

After

+

…

+
+
+``` + +## Simplified UI mock + +For UI changes: draw only what the user sees that matters, as boxes. +`mark` outlines the element the change affects. Put two mocks inside the +panes of a `compare` block for a before and after view. + +```html +
+
Daily puzzle · day 12
+
+

Find the word in 6 tries.

+
B _ _ _ _
+
Hint
+
Hint unavailable
+
+
+``` + +`mock-alert ok` gives the success colour. + +## Toy data + +```html +
+
+ + + + +
VisitorSessionHint
g-42nonerefused
+ +``` + +## Code excerpt and diff + +Show only the lines that matter, with the `path:line` above. Escape `<`, +`>` and `&` in every code block. + +```html +
+ apps/web/src/game/daily.ts:31 +
export async function fetchDailyHint(day: number) {
+  const ok = await ensureGuestSession();
+  if (!ok) return null;
+}
+
The session comes first; a failure ends in null.
+
+``` + +A diff block holds raw unified-diff lines; the template's script colours +the `+`, `-` and `@@` lines. Keep the leading `+` / `-` / space. + +```html +
+ apps/web/src/game/daily.ts +
@@ -28,6 +28,9 @@ export async function fetchDailyHint
+ export async function fetchDailyHint(day: number) {
++  const ok = await ensureGuestSession();
++  if (!ok) return null;
+   return rpc("hint", { day });
+
+``` + +## Quiz data + +The template renders the quiz from the JSON block `quiz-data`. Five +questions, three or four options each, exactly one `"correct": true`, and a +`why` on every option. Backticks in any string render as inline code. Plain +text only, no HTML; write `<\/` for any ` +Prints one PASS / WARN / FAIL line per check. Exit 1 when any check fails, +2 on a usage or read error. +""" +import json +import re +import subprocess +import sys +from html.parser import HTMLParser +from pathlib import Path + +SECTIONS = ("background", "intuition", "code", "quiz") +PRE_INLINE_TAGS = {"code", "span", "b", "strong", "em", "i", "mark", "a", "br"} +BOX_DRAWING = re.compile("[─-╿]") +ASCII_BOX = re.compile(r"\+-{3,}\+|\|\s{2,}\S.*\s{2,}\|") +NAME = re.compile(r"^\d{4}-\d{2}-\d{2}-[a-z0-9]+(-[a-z0-9]+)*\.html$") +REMOTE_TAG = re.compile( + r"<(script|link|img|iframe|source|video|audio)\b[^>]*" + r"\b(src|href)\s*=\s*[\"']?(https?:)?//", re.I) +REMOTE_CSS = re.compile(r"@import|url\(\s*[\"']?(https?:)?//", re.I) +EM_DASH = "—" + + +class Page(HTMLParser): + """Collects, in one pass, what the checks below need.""" + + def __init__(self): + super().__init__(convert_charrefs=True) + self.ids, self.toc_links, self.pre_bad_tags = set(), set(), set() + self.lang, self.viewport, self.quiz_text = "", False, None + self.pre_text, self.prose = [], [] + self._pre = self._code = self._skip = 0 + self._nav = self._quiz = False + + def handle_starttag(self, tag, attrs): + attr = {k: v or "" for k, v in attrs} + if attr.get("id"): + self.ids.add(attr["id"]) + if self._pre and tag not in PRE_INLINE_TAGS: + self.pre_bad_tags.add(tag) + handler = getattr(self, "_open_" + tag, None) + if handler: + handler(attr) + + def handle_endtag(self, tag): + if tag == "pre": + self._pre = max(0, self._pre - 1) + elif tag == "code": + self._code = max(0, self._code - 1) + elif tag in ("script", "style"): + self._skip, self._quiz = max(0, self._skip - 1), False + elif tag == "nav": + self._nav = False + + def handle_data(self, data): + if self._quiz: + self.quiz_text = (self.quiz_text or "") + data + elif self._skip: + return + elif self._pre: + self.pre_text.append(data) + elif not self._code: + self.prose.append(data) + + def _open_html(self, attr): + self.lang = attr.get("lang", "").strip() + + def _open_meta(self, attr): + if attr.get("name", "").lower() == "viewport": + self.viewport = True + + def _open_nav(self, _attr): + self._nav = True + + def _open_a(self, attr): + href = attr.get("href", "") + if self._nav and href.startswith("#"): + self.toc_links.add(href[1:]) + + def _open_pre(self, _attr): + self._pre += 1 + + def _open_code(self, _attr): + self._code += 1 + + def _open_style(self, _attr): + self._skip += 1 + + def _open_script(self, attr): + self._skip += 1 + self._quiz = attr.get("id") == "quiz-data" + + +def check_name(path): + if NAME.match(path.name): + return [("PASS", "name", path.name)] + return [("FAIL", "name", f"{path.name} must be YYYY-MM-DD-.html")] + + +def check_location(path): + try: + out = subprocess.run( + ["git", "-C", str(path.parent), "rev-parse", + "--is-inside-work-tree"], + capture_output=True, text=True, check=False).stdout.strip() + except OSError: + return [("WARN", "location", "git not found, location unchecked")] + if out == "true": + return [("FAIL", "location", "file sits inside a git work tree")] + return [("PASS", "location", "outside any git work tree")] + + +def check_self_contained(src): + hits = REMOTE_TAG.findall(src) + REMOTE_CSS.findall(src) + if hits: + return [("FAIL", "self-contained", f"{len(hits)} remote resource(s)")] + return [("PASS", "self-contained", "no remote script, style or media")] + + +def check_head(page): + out = [] + if not page.lang: + out.append(("FAIL", "lang", " has no lang attribute")) + if not page.viewport: + out.append(("FAIL", "viewport", "no viewport meta")) + return out or [("PASS", "head", f"lang={page.lang}, viewport set")] + + +def check_sections(page): + missing = [s for s in SECTIONS if s not in page.ids] + if missing: + return [("FAIL", "sections", "missing id(s): " + ", ".join(missing))] + unlinked = [s for s in SECTIONS if s not in page.toc_links] + if unlinked: + return [("FAIL", "toc", "