diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 695716e..7bffcd9 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -143,6 +143,7 @@ rules: | BDR-123 | 2026-10-21 | Routing policy: opus session model, Fable via best-tier rows for orchestrator reflection + merge gates, sonnet writes, doctrine ceiling on Fable main; supersedes parts of BDR-066 / BDR-115 | accepted | | BDR-124 | 2026-10-23 | Foreign code keeps its own style (lib/code-origin.sh, `git config claude.origin`), limits strict in our code only | accepted | | BDR-125 | 2026-10-23 | Context mod: subtract-only JIT injection + deterministic guards; supersedes BDR-031 (conditional load proven reliable) | accepted · phases 0-5 planned | +| BDR-128 | 2026-10-27 | Project path rules: one bash oracle (lib/project-rules.sh), /onboard split subtract-only, generators born split, InstructionsLoaded proof hook | accepted · 0b pending | --- @@ -1523,3 +1524,10 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: `$.ui.ask` inside hook (never renders, spike); bypass inside `upgradeCall`/`downgradeCall` (breaker never checked on target: 2 BLOCKERs r1); handCall `keep(cur)` when unusable (pins down model when hand pick == cur: BLOCKER r2); mod restoring user settings.json after native write (BDR-116); alias pins (user kept full id). - **Residuals**: `/config` Model row still native (PreModelSwitch source `command`, same as Everywhere's own run); hand pick dropped at `/clear`; no timeout on never-answered dialog (slot held → picks denied, no leak); window guard needs a `windows` entry (none shipped); PostModelSwitch on denied pick unverified live (guarded). - **Refs**: contract `.claude/tasks/contracts/2026-10-25-picker-scope-1952.md`, plan r3 same name in `plans/`, commits 2202964, 5d262d3. [[BDR-126]], [[BDR-116]], [[BLK-036]], [[LRN-231]], [[EVAL-050]]. + +## BDR-128 — Project path rules: one bash oracle, `/onboard split` subtract-only, generators born split [accepted] (2026-10-27) +- **Decision**: `.claude/rules/.md`, frontmatter `paths: ["a", "b"]` one line (block list refused by the oracle, named in the error). One oracle `lib/project-rules.sh [-C dir] check | matches | sections | extract | emit`: globs on the WORKING TREE (`compgen -G` globstar dotglob, dep dirs filtered unless the glob names one: `vendor/**` valid), `# static-check: skip` marker exempts a rule whose files exist mid-run, a section ends at next `#`/`##` outside a fence, `extract` refuses (heading count ≠ 1, target exists, glob no match, failed rewrite rc 2 + rule removed). This repo: 4 rules (rules-maintenance, graphify-vendored, mods, transient-artifacts + skip), CLAUDE.md keeps header + Health Stack + `## Path-scoped rules` pointer. `/onboard split`: main loop classifies (`sections`), verifies every glob (`matches`), row shape `[a-z0-9][a-z0-9-]*` / no `'` `|` `/` `..`, gate, onboarder `MODE: split` executes (S0 preflight incl. `check` + gitignore negation ordered a-f, S1 extract per row, S2 pointer + `cat -s`, S3 check + commit + `cat-file -e HEAD:` per rule, two STOP shapes, rollback `reset -q` + `checkout`). Generators: onboarder PHASE 5b + scaffolder 3b `emit` docker/testing/ci from `templates/project-rules/` when a glob matches. `hooks/instructions-loaded.sh` permanent (`InstructionsLoaded` → `~/.claude/logs/instructions-loaded.jsonl`, field allowlist, exit 0 always, rotate 5 MB). `!.claude/rules/` after `.claude/*` here + socle. +- **Why**: project CLAUDE.md 5,285 → 584 bytes, `/context` Memory files 11.6k → 9.6k, project row 2.1k → 166 tokens; rules load on Read only, proven in main + sub-agent ([[LRN-232]]). Phase 0 of [[BDR-125]]: no mod, subtract-only, deterministic oracle in `make test`. +- **Alternatives rejected**: block-list `paths:` parsing (spec shape inline; pre-flight `check` at S0/S1 moves the failure before any write); mod-based injection (BDR-125 says phase 0 no mod); dep-dir filter unconditional (vetoed `vendor/**`); `git add .claude/rules` dir (a pre-existing rule made visible by the negation would ride along); whole-file Write for the pointer (subtract-only). +- **Residuals**: `###` granularity before faunosteo (12.6 KB path-bound content under always-on `## Project conventions`; `##`-only moves 1.5%), user decides (TODO 0b); `game` heading with `'` refused until renamed or extract by index; `extract -n` dry run deferred; T11b + AC2 hardcode 4 rules; `InstructionsLoaded` key on older CLIs unverified (check `claude --version` on work machine before pull); pre-commit `.claude/**` exemption lets a rules-only commit land on develop → phase 2. +- **Refs**: spec `docs/superpowers/specs/2026-10-26-claude-md-split-design.md`, plan r3 `docs/superpowers/plans/2026-10-26-claude-md-split.md`, contract `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md`, commits abfa416..0b59687. [[BDR-125]], [[BDR-003]], [[BDR-065]], [[LRN-154]], [[LRN-232]], [[LRN-233]], [[EVAL-051]]. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index e99d110..156c547 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -67,6 +67,7 @@ rules: | EVAL-044 | 2026-10-11 | model-router W3-B (dialog with context): 3 lenses converged on 2 BLOCKERs of my r1 (inline rows, phase edits) + 1 confirmation; feater DONE + 2 coverage rounds; verifier 3× to CONFORME; security PASS; user's first real decision through the new dialog | the lenses pay most when the plan adds a data shape; coverage criteria still cost rounds; live dialogs during the gates must be announced and their data reconciled before commit | | EVAL-045 | 2026-10-11 | model-router W4-B (prompt classifier): 3 lenses (BLOCKER: unbounded classify await) + 1 confirmation; feater DONE + 1 round; verifier ECARTS(2) → CONFORME; security PASS 0 findings; LRN-210 applied (one coverage clause per criterion) | first wave since W2 with no verifier cap: per-clause criteria + abort paths declared unverifiable up front cut the rounds to one | | EVAL-048 | 2026-10-23 | model-router feat C keyword cap: 3 lenses FATAL(4)/FATAL(5)/CONCERNS on r1 (3 BLOCKER: run-slot shadow, probe-test hang, reload fail-open), mechanism rewritten, confirmation SOLID; verifier CONFORME 1st pass; 1st verifier died 429 on Fable | +| EVAL-051 | 2026-10-27 | CLAUDE.md split: plan r1→r3 FATAL(5), 12 SDD tasks clean, RED/GREEN + dry run, sonnet final 3 Important, opus 2 Important 8 Minor; extract rc 0 on failed rewrite survived 5 reviews | failure-path test per rewriting function; review a cross-repo tool on real inputs | --- @@ -447,3 +448,8 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Method**: dev-mod spike, 2 live runs by user (ask-inside froze; deny + continuation worked) before any plan. Plan r1: correctness FATAL(5), robustness FATAL(2), simplicity SOLID. r2 confirm FATAL(1). r3 inline. feater DONE 29 tests (574 total); GATE 0 MET; verifier CONFORME 14/14 1st pass; auditor PASS 1st pass; doc-sync SIGNIFICANT 12 patches. - **Anomalies**: both FATAL rounds on breaker-vs-target: r1 bypass skipped target-down check across turns; r2 early branch pinned a down model when hand pick == cur (user's exact scenario). Main wrote "leaveDown untouched: down still wins" without tracing which model `decideMain` checks. - **Action**: a new routing branch gets a trace of every exit against `st.down` for cur AND target, across a turn boundary, before challenge. Spike-first paid: zero rework on the UI mechanism. Links [[BDR-127]], [[LRN-231]]. + +## EVAL-051 — CLAUDE.md split: 5 review layers, the I/O failure path survived 4 of them (2026-10-27) +- **Method**: 0d analyzer; brainstorm 4 user answers; plan r1 → r3 (correctness FATAL(5): SIGPIPE, rc 127, dry run on develop blocked, unchecked commit rc, 80 cols). SDD 12 tasks sonnet/medium, 12 task reviews clean (1 controller resolve avg, mostly attribution lines + oracle facts). RED (current skill stops at plugin-probe) → GREEN (S5 table, nothing written) → dry run on a branched scratch (2 rules in HEAD). Sonnet final review 3 Important → 89334f2. GATE 0 MET 14/20 runnable; verifier ECARTS(3) → ECARTS(1 = user MCP step); security PASS, 1 LOW. Opus/xhigh craft: 0 Critical, 2 Important, 8 Minor, ran the lib on the 6 real 0b targets (56 sections conserved) → 0b59687, re-review 0 open. `make test` all GREEN, suite PASS=93. +- **Anomalies**: `extract` rc 0 on a failed rewrite passed 3 challengers + 12 task reviews + 1 final review: nobody tested an I/O failure (only logic refusals). `##`-only granularity misses faunosteo's payload (12.6 KB under `###`): found only because the reviewer ran the tool on the real targets. Headless proof 0 lines (model skipped Read). T10h-j named a guard the test could not observe. Brief tally arithmetic wrong (96 vs 93). Final review found 3 Important the 12 task reviews missed (dep-dir veto of `vendor/**`, misleading error, gitignore newline glue): per-task scope hides cross-task consequences. +- **Action**: Review Focus lists a failure-path test per function that rewrites a file; a tool meant for other repos gets a reviewer run on their real inputs before merge; a load proof prompt names the tool call ([[LRN-232]]); test names state the observable. Links [[BDR-128]], [[LRN-233]]. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 761ed69..bb16c1f 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -655,3 +655,9 @@ rules: - BLK-036: bare /model picker wrote haiku into tracked user settings (integration_alphalink intent). Restored opus, haiku pinned in alphalink settings.local.json. /bugfix haiku table 2c39524 (BLK-035, LRN-230): verifier CONFORME 7/7, auditor PASS. Next: haiku effort bugfix, picker scope feat. Merge of feature/model-scope-dialog held. - /feat picker scope (BLK-036): spike (user ran 2 live picker tests: ask inside hook froze, deny + continuation works), plan r1 FATAL x2 / r2 FATAL(1) on breaker-vs-target, r3 inline; verifier CONFORME 14/14, auditor PASS. 2202964 + docs 5d262d3. BDR-127, LRN-231, EVAL-050. Spike mod neutralized. Next: haiku effort bugfix; live check picker in fresh session. - /bugfix haiku effort (bugfix/router-haiku-effort): 3 lenses no BLOCKER (2 caught delete-instead-of-scope), user pick Haiku 5.x like any model; guard = Haiku 4.x; verifier CONFORME 10/10, auditor PASS. 8e93507. BDR-123 + BDR-107 amended, BLK-035 closed, LRN-230 addendum. feature/model-scope-dialog merged a6b94a4. Next: merge bugfix on go, /clear, phase 0. + +## 2026-10-26 +- Phase 0 claude-md split (feature/claude-md-split, BDR-125): spec 2c8e4a2, plan r1→r3 (3 lenses FATAL, confirmation FATAL(5): `matches` SIGPIPE rc 141 under pipefail, `PATH=/nonexistent bash` rc 127, dry run on develop blocked by pre-commit), SDD 11 tasks sonnet, every task review clean, final review With fixes → 89334f2. Proof: `/context` 32.2k → 30.5k total, Memory files 11.6k → 9.6k, project CLAUDE.md 2.1k → 166 tokens; headless session 17:00:07Z: 4 Project `path_glob_match` (rules-maintenance ← rules/a11y.md, graphify-vendored ← install-plugins.sh, mods ← mods/model-router/.claude-plugin/plugin.json, transient-artifacts ← docs/superpowers/specs/…); sub-agent 17:00:33Z: rules-maintenance + graphify-vendored loaded with agent_id → path rules DO load in sub-agents. First probe answered without Read (0 lines): proof prompt must force the Read tool. RED (plugin-probe dispatch, no classify) → GREEN (S5 table) → dry run a092b88 on scratch chore branch, 2 rules in HEAD. User step pending: `claude mcp remove -s user higgsfield`. Merge on user go. + +## 2026-10-27 +- Phase 0 split STEP 6: opus/xhigh review 0 Critical 2 Important 8 Minor (extract rc 0 on failed rewrite; `###` granularity for faunosteo = 0b decision, TODO) → 0b59687, re-review 0 open, make test all GREEN. Capitalized BDR-128, LRN-232/233, EVAL-051. Next: doc-sync, merge on user go; user step still pending: `claude mcp remove -s user higgsfield`. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 3a7ec57..0a5c7b0 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -247,6 +247,8 @@ rules: | LRN-225 | 2026-10-22 | Gate on tool's exit-code contract, never its prose; positive control through gate's own helper on clean/dirty fixture pair; mktemp EXIT trap script-level | any test that wraps a CLI verdict | | LRN-226 | 2026-10-23 | Cap one axis of a layered route at the WRITER (effort-only route), never by filtering at the reader: reader cap shadows lower slots + depends on a baseline that can be unknown | any slot/precedence router, per-axis caps | | LRN-227 | 2026-10-23 | Root-commit author ≠ name the user remembers: check `git log --max-parents=0`; every root email the user ever used goes in `claude.identity` | code-origin claims, identity lists | +| LRN-232 | 2026-10-27 | Path rules load inside sub-agents (agent_id in hook log); a "does X load" proof prompt must name the Read tool call | per-repo split pass, any load proof | +| LRN-233 | 2026-10-27 | Bash under pipefail: head after producer = rc 141, blanked PATH hides bash (rc 127), unchecked mktemp+rewrite chain = rc 0 with source unchanged; compgen -G no braces, dotglob over-matches, globstar skips symlinks under ** | any bash lib with pipes, temp files, globs | --- @@ -1907,3 +1909,11 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s ## LRN-231 — PreModelSwitch hook: no dialog inside; deny at once, ask in a continuation - **Context**: picker spike 2026-10-25 (dev mod, user-run). `$.ui.ask` awaited inside `classic.PreModelSwitch` never renders: UI frozen on "Running PreModelSwitch hooks… (Esc to cancel)". Returning `{ permissionDecision: 'deny', permissionDecisionReason }` at once blocks switch AND user settings.json write; engine prints "Model switch to X was blocked by a PreModelSwitch hook: ". - **Apply**: launch `void (async () => { await $.clock.sleep(300); … $.ui.ask … })()` before returning the deny; hold any shared dialog slot synchronously before return, free it in the continuation's `finally`. `$.command.run({ command: 'model', args })` from the continuation re-enters as PreModelSwitch source `command` + command.run origin plugin: gate both. Links [[BDR-127]]. + +## LRN-232 — Path rules load inside sub-agents; a load proof prompt must name the Read tool call +- **Context**: phase 0 proof 2026-10-26. `InstructionsLoaded` hook fields: `session_id`, `agent_id` (sub-agents only), `agent_type`, `cwd`, `file_path`, `memory_type`, `load_reason`, `globs`, `trigger_file_path`. General-purpose sub-agent Reading `rules/a11y.md` → `.claude/rules/rules-maintenance.md` logged, `load_reason: path_glob_match`, `agent_id` set. First headless probe `claude -p "read these 4 files"` → 0 log lines: model answered from memory, never called Read. Re-run "Use the Read tool, one call per file" → 4 lines. +- **Apply**: per-repo split pass may move sub-agent-needed sections; verify per repo: `jq -c 'select(.memory_type=="Project" and (.file_path|contains("/.claude/rules/")))' ~/.claude/logs/instructions-loaded.jsonl | tail`. Any "does X load / fire" proof prompt names the tool and the call count; 0 lines first means "did the model act", not "the feature is off". A `paths:` rule loads on Read, not on Write of a new file. Links [[BDR-128]], [[BDR-125]]. + +## LRN-233 — Bash under pipefail: `head` after a producer, blanked PATH, unchecked temp-file rewrite +- **Context**: `lib/project-rules.sh` 2026-10-26, caught by plan challenger r2 + opus review after 2 sonnet reviews. (1) `compgen -G '**/*' | head -3` → producer SIGPIPE on > pipe buffer of hits, pipeline rc 141 under `pipefail`. (2) `PATH=/nonexistent bash hook.sh` → rc 127: blank PATH applies to the lookup of `bash` itself. (3) `tmp=$(mktemp); f > "$tmp" && cat "$tmp" > src` unchecked → `TMPDIR=/nonexistent` gives rc 0, "moved" printed, src unchanged (I/O failure path untested by 5 reviewers). (4) `compgen -G`: no brace expansion; dotglob matches dotfiles the engine skips; globstar never descends a symlink met under `**` (`top/link/**` finds, `top/**` misses). +- **Apply**: a bounded reader after a producer is awk, reads to the end: `awk 'NR <= 3 { print } END { exit NR == 0 }'`. `"$BASH"` when PATH is blanked in a test. `tmp=$(mktemp) || return 2`; rewrite as `if ! { f > "$tmp" && cat "$tmp" > src; }; then rm -f "$tmp" "$out"; return 2; fi` (SC2015 forbids `a && b || c`). Plan Review Focus: one failure-path test per file-rewriting function (`TMPDIR=/nonexistent`, `chmod a-w`; root ignores chmod). One glob per extension; test names say what they prove (a guard the final `exit 0` swallows is unobservable). Links [[BDR-128]], [[LRN-096]]. diff --git a/.claude/rules/graphify-vendored.md b/.claude/rules/graphify-vendored.md new file mode 100644 index 0000000..7a92cff --- /dev/null +++ b/.claude/rules/graphify-vendored.md @@ -0,0 +1,32 @@ +--- +paths: ["skills/graphify/**", "install-plugins.sh"] +--- + +# Machine-owned: the vendored graphify skill + +`skills/graphify/SKILL.md`, `skills/graphify/references/` and +`.graphify_version` are written by `graphify claude install` +(`install-plugins.sh` STEP graphify), which lands in the repo because +`~/.claude/skills` is a symlink to `skills/`. They are gitignored: a +`pipx upgrade graphifyy` used to dirty the tree and cost a +`chore(graphify): sync vendored skill X -> Y` commit each time. + +Two graphify commands, easy to confuse, and only one restores the skill: +- `graphify install --platform claude` copies SKILL.md + `references/` + + `.graphify_version` into `skills/graphify/`. Touches nothing else. + This is the recovery command. +- `graphify claude install` writes the CLAUDE.md graphify section and the + `.claude/settings.json` PreToolUse hooks. It **rewrites both guarded + configs** (EVAL-020, verified again 2026-09-15), so revert them after. It does NOT copy + the skill. + +`make plugin` runs both (`install-plugins.sh` STEP graphify) behind the +guarded-config EXIT trap, so a fresh clone is covered. + +Trade-off accepted: an upstream release can now change the skill's prompt +with no diff to review. `skills/graphify/test-prompts.json` is hand-written +for darwin and stays tracked. + +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. diff --git a/.claude/rules/mods.md b/.claude/rules/mods.md new file mode 100644 index 0000000..5b27c75 --- /dev/null +++ b/.claude/rules/mods.md @@ -0,0 +1,25 @@ +--- +paths: ["mods/**", "skills/model-router/**", "lib/tests/mods.test.sh"] +--- + +# 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. diff --git a/.claude/rules/rules-maintenance.md b/.claude/rules/rules-maintenance.md new file mode 100644 index 0000000..9089601 --- /dev/null +++ b/.claude/rules/rules-maintenance.md @@ -0,0 +1,27 @@ +--- +paths: ["rules/**", "CLAUDE.global.md"] +--- + +# rules/ maintenance + +Modular instruction files loaded by Claude Code alongside the global memory. +`rules/` is symlinked to `~/.claude/rules` by `link.sh` (user scope, ALL +projects). One rule = one file = one concern. + +A rule WITH `paths:` YAML frontmatter (glob list) loads lazily — only when +Claude reads a file matching a glob; a rule WITHOUT it loads at session +start, same cost as the global memory. Extract from CLAUDE.global.md only +what can be path-scoped (the token win) or what is generated; always-on +doctrine stays in CLAUDE.global.md. Exception: a standalone user-authored +rule set that would bust the 320-line density budget may live here WITHOUT +`paths:` (always-on load) — writing-style.md (BDR-085), default-language.md +(BDR-118), secure-by-default.md (BDR-120). `paths:` globs match against the +CURRENT project's tree — a broad glob (e.g. `rules/**`) can fire in foreign +projects; keep rule bodies tiny. +Docs: https://code.claude.com/docs/en/memory.md#path-specific-rules + +Machine-owned: `rules/context7.md` is DELETED BY DESIGN (BDR-053, +2026-07-06) — `ctx7 setup --claude --cli` still writes it, but +install-plugins.sh STEP ctx7 purges it right after; the find-docs skill is +the single ctx7 surface. If it reappears (manual `ctx7 setup`), delete it +or re-run `make plugin`. diff --git a/.claude/rules/transient-artifacts.md b/.claude/rules/transient-artifacts.md new file mode 100644 index 0000000..2fd1f26 --- /dev/null +++ b/.claude/rules/transient-artifacts.md @@ -0,0 +1,19 @@ +--- +paths: ["docs/superpowers/**", ".audit/**"] +# static-check: skip +--- + +# Transient planning artifacts + +`docs/superpowers/specs/**` and `docs/superpowers/plans/**` are run-time +artifacts of a feature pipeline (subagent briefs, reviewer references). +They are committed DURING the run (the SDD worktree + reviewers read them +from disk — NOT gitignored), then AUTO-PURGED by `gitflow finish` on a +`feature`/`bugfix` branch, before the merge, so develop's tip stays clean +(BDR-065, `lib/gitflow.sh` `_gitflow_purge_transient`). The feature commits +stay reachable from develop, so `git show :docs/…` is still the archive. +Opt out with `GITFLOW_PURGE_TRANSIENT=0`. NOT in scope: `.claude/tasks/{contracts,plans}` +(durable, versioned, referenced by decisions.md). Durable knowledge goes to +`.claude/memory/` registries, never to these files. Derived scan/audit +outputs (`.audit/**`) are gitignored and never committed, even redacted +(LRN-124). diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 3a139e5..2f3eff3 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -17,17 +17,12 @@ Shared rules for every phase: - [x] **/bugfix model-router haiku effort strip** (done 2026-10-25, 8e93507; merge on user signal) (BLK-035 residual, user pick 2026-10-25): Haiku 5.5 takes effort; drop 4.5-era "haiku takes no effort" (effortWord, step plan omission, isHaiku sites, census `lib/tests/effort-routing.test.sh:170`), so `mechanical` runs low. - [x] **/feat picker scope** (done 2026-10-25, 2202964 + docs 5d262d3, BDR-127; live check pending: picker in a fresh session, PostModelSwitch on a denied pick) (BLK-036, user ask 2026-10-25): bare `/model` → pick in native picker → ask project scope (`.claude/settings.local.json`) or user scope. First: engine types for a settings-write intercept; none → mod restores user settings.json = BDR-116 amendment, user decides before code. -- [ ] **Phase 0, no mod: split project CLAUDE.md** - - Move the 4 project CLAUDE.md sections (graphify vendored skill 1.4k chars, mods/ 1.3k, rules/ maintenance 1.3k, transient planning artifacts 0.9k) to `.claude/rules/.md` with `paths:` (`skills/graphify/**`; `mods/**`, `skills/model-router`; `rules/**`; `docs/superpowers/**`). Project scope only: no ~/.claude link points at `.claude/` (checked 2026-10-24); never into `rules/` (= ~/.claude/rules, every project). - - `.gitignore:122` ignores `.claude/*`: add `!.claude/rules/` (a directory-form ignore would untrack the rules). - - Higgsfield MCP: user-scope in ~/.claude.json while `toggle-external.sh` says disabled. The user runs `claude mcp remove -s user higgsfield` once; no toggle ownership, no doctor check: the phase 5 pack `.mcp.json` owns it (guide 2026-10-25: `disabledMcpjsonServers` never reaches a user-scope server, the `/mcp` toggle writes `~/.claude.json`). - - Proof: static check per moved rule + one InstructionsLoaded-logged session; `/context` delta (~1.9k memory files + higgsfield MCP share). - - Cleanup: CLAUDE.md keeps a 2-line pointer ("rules under .claude/rules load on path"); fix citers of the moved headings. - - Other projects (user ask 2026-10-24). Measured project CLAUDE.md, loaded every session of that project: faunosteo 50,228 chars (bigger than the global one), zenquality 23,378, game 14,918, robin_petier 12,895, config 4,990, integration_alphalink 4,249; none has `.claude/rules/`. Splitting is judgment (always-on: overview, stack, commands, conventions; path-scoped: one module, Docker, a folder), so no background automation and no new skill: - - `/onboard` gets a `split` mode (skill edit through /writing-skills: pressure test RED first): read the project CLAUDE.md, classify each section always-on vs path-scoped, propose globs from the real tree, user approves per project, write `.claude/rules/.md` + slim CLAUDE.md + `!.claude/rules/` in .gitignore when `.claude/*` is ignored. - - Generators fixed at the source: onboarder + scaffolder (init-project) emit path rules from day one, so new projects are born split. - - One pass over the git repos in ~/Documents/ (this repo first, then by size: faunosteo, zenquality, game, robin_petier, config, integration_alphalink): one `chore/claude-md-split` branch per repo, per-project approval, never an automatic merge (user signal per repo), `/context` before/after per project recorded in that project's journal. - - Proof: per project, the static glob check + one logged session; total always-on delta across the 7 projects. +- [x] **Phase 0, no mod: split project CLAUDE.md** (this repo + the lever, feature/claude-md-split, 2026-10-26; merge on user signal). Four rules under `.claude/rules/` (rules-maintenance, graphify-vendored, mods, transient-artifacts `# static-check: skip`), `lib/project-rules.sh` check/matches/sections/extract/emit (`-C `) + suite, `hooks/instructions-loaded.sh` (log `~/.claude/logs/instructions-loaded.jsonl`, session + agent ids), `!.claude/rules/` here + socle, `/onboard split` + onboarder `MODE: split`, generators emit docker/testing/ci from `templates/project-rules/`. Baseline 2026-10-26 `/context`: 32.2k total, Memory files 11.6k, project CLAUDE.md 2.1k. + - [ ] Proof, this repo: `/context` after the merge; one fresh session Reading one file per rule → 4 Project `path_glob_match` lines; one sub-agent Read → does a path rule load inside a sub-agent (decides what the per-repo pass may move). Results in the journal. + - [ ] User step: `claude mcp remove -s user higgsfield` (user-scope MCP, no toggle ownership, no doctor check; phase 5 `.mcp.json` owns it). + - [ ] Phase 2 folds: narrow the pre-commit `.claude/**` exemption so a rules-only commit cannot land on develop/main (deferred 2026-10-26). +- [ ] **Phase 0b, per-repo pass** (after phase 0 merges; via `/onboard split`, one `chore/claude-md-split` per repo off develop, approval per repo, never an automatic merge; `/context` before/after in that repo's journal). Order by size: faunosteo 52,322 chars (on feature/v1-1-clients-animals with 5 dirty files: finish or stash first, S1 refuses otherwise), zenquality 23,378, game 14,918 (on feature/replay-hint), robin_petier 12,895, config 4,990, integration_alphalink 4,249. None has `.claude/rules/` yet; all use the `.claude/*` file form (BDR-003). Sections a sub-agent needs stay always-on unless the phase 0 sub-agent proof says path rules load there (proof 2026-10-26: they do; verify per repo). + - [ ] Before faunosteo: decide `###` granularity (STEP 6 review 2026-10-26). Its path-bound content (i18n, Schemas, Stores, PDF, Supabase, Storage, 12.6 KB) sits in `###` subsections of the always-on `## Project conventions`; `##`-only extract moves ~1.5% of the file. Option: `extract` accepts a `###` heading (section ends at the next heading of the same or higher level), `sections --depth 3`. User decides; `game` also has a `'` in `## 4. POINTS D'ATTENTION…` (S4 refuses it until renamed, or extract by index). - [ ] **Phase 4a, memory v2 write side: shell, no mod** (shrunk 2026-10-25: the measured recall channels never read Meta; the measured status bug is a reconcile parser bug) - Facts 2026-10-24 (scratchpad memeval, 434 entries): registries ~1M chars, never in always-on context, read only by /feat /bugfix /ship-feature (analyze-before-plan); Index drift 6 rows; status in 3 places (title tag, body Status line, Index column) → reconcile false-open BLK-032..034; no single writer (Edit needs a Read of a 357k file, so real writes are ad hoc python/bash); 8 projects on this machine hold v1 registries. Verified 2026-10-25: `lib/reconcile.sh:60-67` drops the entry's OWN header while BLK-032..034 carry `[resolved]` there (the false-open); nothing machine-reads `## Index` (analyze-before-plan.md:42, reconcile.sh:9, test T1); 1 of 1,290 entries across the 8 projects above a 1% accent ratio. diff --git a/.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md b/.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md new file mode 100644 index 0000000..978631d --- /dev/null +++ b/.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md @@ -0,0 +1,93 @@ +# CONTRACT — claude-md-split +- date: 2026-10-26 | flow: ship-feature | branch: feature/claude-md-split (to be started off develop) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +Phase 0 of the context mod queue (BDR-125), TODO.md "Phase 0, no mod: split project CLAUDE.md": move the 4 project CLAUDE.md sections to .claude/rules/.md with paths: frontmatter, .gitignore !.claude/rules/, higgsfield MCP user step, /onboard split mode, onboarder + scaffolder emit path rules, then per-repo pass. Shared rules at TODO.md lines 8-13 (baseline /context first, static glob check + InstructionsLoaded session proof, cleanup + citers). + +(TODO.md lines 6-30 at commit aaeaac8 are the detailed spec this request points at.) + +## CLARIFICATIONS +Pass A (gaps found by the read-before analysis, asked in the STEP 1 brainstorm batch, answered 2026-10-26): +- Q: Scope of this run: the per-repo pass cannot live in this repo's feature branch. / A: this run = this repo's split + static check suite + gitignore socle + proof hook + `/onboard split` mode + onboarder/scaffolder path rules. The per-repo pass over the 6 other repos runs AFTER merge through the shipped `/onboard split`, one chore branch per repo, user approval per repo. [gated 2026-10-26] +- Q: No InstructionsLoaded hook exists anywhere. Throwaway bench or permanent? / A: permanent logging hook `hooks/instructions-loaded.sh` registered in settings.json, one JSON line per loaded instruction file into `~/.claude/logs/instructions-loaded.jsonl`; reused by phase 1 and the per-repo proofs. [gated 2026-10-26] +- Q: `docs/superpowers/**` matches 0 tracked files at rest and those files are Written, never Read: static check fails by construction. / A: path rule `.claude/rules/transient-artifacts.md` (paths `docs/superpowers/**`, `.audit/**`) with a YAML comment `# static-check: skip` in the frontmatter that the checker honors; its proof is the logged session. [gated 2026-10-26] +- Q: Patch `templates/gitignore/standard.gitignore` (the socle) too? / A: yes, socle + this repo's `.gitignore`, gitflow-test assertions updated. [gated 2026-10-26] +Brainstorm (design approved 2026-10-26): rule files `rules-maintenance.md`, `graphify-vendored.md`, `mods.md`, `transient-artifacts.md`; lib `lib/project-rules.sh` (check / sections / extract); generator skeleton set docker + testing + ci under `templates/project-rules/`; onboarder `MODE: split` executes the approved table; RED-then-GREEN pressure test on the skill edit. [gated 2026-10-26] +Pass B (plan, 2026-10-26): +- Q: name of the fourth lib subcommand that writes a skeleton with the matching globs only? / A: `emit `. [gated 2026-10-26] +- Q: heading of the pointer section left in a split CLAUDE.md? / A: `## Path-scoped rules`. [gated 2026-10-26] +- Q: language of the new onboard § SPLIT MODE and onboarder MODE: split inside a French skill? / A: English. [gated 2026-10-26] + +## ACCEPTANCE CRITERIA +1. Project `CLAUDE.md` no longer holds the 4 sections (rules/ maintenance, graphify vendored skill, mods/, transient planning artifacts); it keeps Health Stack plus a short pointer to `.claude/rules/`. + CHECK: cd /home/bchanot/Documents/claude && ! grep -qE '^## (rules/ maintenance|Machine-owned: the vendored graphify skill|mods/ — function-hooks|Transient planning artifacts)' CLAUDE.md && grep -q '.claude/rules' CLAUDE.md && echo SPLIT-OK + EXPECT: SPLIT-OK + EVIDENCE: MET exit=0 marker-found :: SPLIT-OK +2. Each moved section lives in `.claude/rules/.md` with a `paths:` frontmatter that parses (same shape as `rules/a11y.md`), is tracked by git (`!.claude/rules/` negation in `.gitignore`), and each glob matches at least one path in the working tree (the static check, `lib/project-rules.sh check`), unless the rule carries the `# static-check: skip` marker (transient-artifacts only). + CHECK: cd /home/bchanot/Documents/claude && test "$(git ls-files .claude/rules | wc -l)" -ge 4 && bash lib/project-rules.sh check | grep -q '4 rule(s) ok' && echo RULES-STATIC-OK + EXPECT: RULES-STATIC-OK + EVIDENCE: MET exit=0 marker-found :: RULES-STATIC-OK +3. The static glob check is a `make test` suite (`lib/tests/project-rules.test.sh`) with flip tests (an unmatched glob, a literal typo, a dep-dir-only match each fail it). + CHECK: cd /home/bchanot/Documents/claude && make test suite=lib/tests/project-rules.test.sh 2>&1 | grep -q 'all suites green' && grep -c 'T2c-literal-typo-fails\|T2d-dep-dir-only' lib/tests/project-rules.test.sh | grep -qx 2 && echo SUITE-OK + EXPECT: SUITE-OK + EVIDENCE: MET exit=0 marker-found :: SUITE-OK +4. One real session shows each moved rule loading on `load_reason: path_glob_match` (`~/.claude/logs/instructions-loaded.jsonl`, filtered on `memory_type == "Project"` and `/.claude/rules/`), plus one sub-agent probe recording whether a path rule loads inside a sub-agent; evidence pasted into the journal. +5. `/context` measured before and after at the repo root; the always-on delta recorded in the journal. +6. The higgsfield user-scope MCP is removed by the user (`claude mcp remove -s user higgsfield`), recorded as a manual step, no toggle ownership and no doctor check added. +7. Every citer of the moved headings or of "project CLAUDE.md" as their location is patched (rules/README.md:9, doctor.sh:76 comment, ARCHITECTURE.md tree, any skill/lib/agent grep hit); append-only registries untouched. + CHECK: cd /home/bchanot/Documents/claude && ! grep -rnE 'CLAUDE\.md`? \(project scope\)|29-line project CLAUDE.md' rules/ doctor.sh skills/ agents/ lib/ hooks/ --include='*.md' --include='*.sh' | grep -v skills-external && echo CITERS-OK + EXPECT: CITERS-OK + EVIDENCE: MET exit=0 marker-found :: CITERS-OK +8. `/onboard` gains a `split` mode (public name per pass B) that classifies an existing project CLAUDE.md's sections always-on vs path-scoped, proposes globs from the real tree, gets per-project approval, writes `.claude/rules/.md` + slimmed CLAUDE.md + the `!.claude/rules/` negation when `.claude/*` is ignored. Skill edit goes through /writing-skills with a RED pressure test first. +9. onboarder and scaffolder emit path rules from day one (the sections classified path-scoped per the brainstorm), with the gitignore negation reaching the project through the gitflow socle: before the root commit for a scaffold (init-project STEP 5f `gitflow init`), at /onboard STEP 2.6 `gitflow init` for an onboarded project (after the onboarder's write, before any commit); the onboarder's own PHASE 4 is unchanged. [amended 2026-10-26, plan r2/r3] +10. Full suite green: `make test`. + CHECK: cd /home/bchanot/Documents/claude && make test 2>&1 | tail -3 | grep -q 'all suites green' && echo MAKE-TEST-OK + EXPECT: MAKE-TEST-OK + EVIDENCE: MET exit=0 marker-found :: MAKE-TEST-OK +11. shellcheck clean on the Health Stack scope. + CHECK: cd /home/bchanot/Documents/claude && shellcheck ./*.sh hooks/*.sh lib/*.sh && echo SHELLCHECK-OK + EXPECT: SHELLCHECK-OK + EVIDENCE: MET exit=0 marker-found :: SHELLCHECK-OK +12. `lib/project-rules.sh matches `: rc 0 + up to 3 hits on stdout; rc 1 + `no match: ` on stderr; a glob with more than a pipe buffer of hits is still a match (no `head` after the producer; T5k/T5l). [gated 2026-10-26] + CHECK: cd /home/bchanot/Documents/claude && bash lib/project-rules.sh matches 'skills/**' >/dev/null && ! bash lib/project-rules.sh matches 'nowhere/**' 2>/dev/null && grep -c 'T5k-many-hits-rc\|T5l-three-lines' lib/tests/project-rules.test.sh | grep -qx 2 && echo MATCHES-OK + EXPECT: MATCHES-OK + EVIDENCE: MET exit=0 marker-found :: MATCHES-OK +13. Every subcommand takes a leading `-C ` (a dispatched agent's cwd is the session's); a missing dir is rc 2. [gated 2026-10-26] + CHECK: cd / && bash /home/bchanot/Documents/claude/lib/project-rules.sh -C /home/bchanot/Documents/claude check | grep -q '4 rule(s) ok' && ! bash /home/bchanot/Documents/claude/lib/project-rules.sh -C /nonexistent-dir check 2>/dev/null && echo DASH-C-OK + EXPECT: DASH-C-OK + EVIDENCE: MET exit=0 marker-found :: DASH-C-OK +14. `emit ` writes the skeleton with the matching globs only, rc 1 and nothing written when none matches, rc 2 when the target exists; the three skeletons `templates/project-rules/{docker,testing,ci}.md` exist with `paths:` frontmatter and `TODO(/onboard STEP 3)` stubs. [gated 2026-10-26] + CHECK: cd /home/bchanot/Documents/claude && test -f templates/project-rules/docker.md && test -f templates/project-rules/testing.md && test -f templates/project-rules/ci.md && grep -c 'T12b-docker-globs-pruned\|T12f-ci-not-emitted-rc\|T12h-existing-target-rc' lib/tests/project-rules.test.sh | grep -qx 3 && echo EMIT-OK + EXPECT: EMIT-OK + EVIDENCE: MET exit=0 marker-found :: EMIT-OK +15. The hook logs `ts, session_id, agent_id, agent_type, cwd, file_path, memory_type, load_reason, globs, trigger_file_path`, honors `CLAUDE_INSTRUCTIONS_LOG`, rotates above 5 MB, exits 0 with no stdout when jq is absent or the log is unwritable; registered in `settings.json` under `InstructionsLoaded`. [gated 2026-10-26] + CHECK: cd /home/bchanot/Documents/claude && jq -r '.hooks.InstructionsLoaded[0].hooks[0].command' settings.json | grep -q 'instructions-loaded.sh' && grep -c 'T10e-ids-kept\|T10h-no-jq-rc0\|T10k-rotated' lib/tests/project-rules.test.sh | grep -qx 3 && echo HOOK-OK + EXPECT: HOOK-OK + EVIDENCE: MET exit=0 marker-found :: HOOK-OK +16. `skills/onboard/SKILL.md` gains `## MODE DISPATCH` and `## SPLIT MODE` (S1 preconditions, S2 baseline, S3 branch, S4 classify with `matches`, S5 mandatory gate, S6 onboarder dispatch, S7 after, never `finish`); `agents/onboarder.md` gains `## MODE: split` (S0 preflight incl. gitignore negation, S1 extract with rollback, S2 pointer, S3 check + commit rc checked + `cat-file -e HEAD:` per rule, two STOP shapes); the routing locks stay green. [gated 2026-10-26] + CHECK: cd /home/bchanot/Documents/claude && grep -q '^## MODE DISPATCH' skills/onboard/SKILL.md && grep -q '^## SPLIT MODE' skills/onboard/SKILL.md && grep -q '^## MODE: split' agents/onboarder.md && grep -q 'cat-file -e HEAD:' agents/onboarder.md && grep -q 'not in HEAD after commit' agents/onboarder.md && echo SPLIT-MODE-OK + EXPECT: SPLIT-MODE-OK + EVIDENCE: MET exit=0 marker-found :: SPLIT-MODE-OK +17. onboarder `## PHASE 5b` and scaffolder `## PHASE 3b` emit `docker`/`testing`/`ci` through `emit`, then run `check`; `templates/project-CLAUDE.md` header names `.claude/rules/`. [gated 2026-10-26] + CHECK: cd /home/bchanot/Documents/claude && grep -q '^## PHASE 5b' agents/onboarder.md && grep -q '^## PHASE 3b' agents/scaffolder.md && grep -q 'Path-scoped rules: .claude/rules' templates/project-CLAUDE.md && echo GENERATORS-OK + EXPECT: GENERATORS-OK + EVIDENCE: MET exit=0 marker-found :: GENERATORS-OK +18. Socle: `templates/gitignore/standard.gitignore` carries `!.claude/rules/` after `.claude/*`, `lib/gitflow-test.sh` asserts it, and `.claude/rules/` is not ignored in this repo. [gated 2026-10-26] + CHECK: cd /home/bchanot/Documents/claude && grep -qxF '!.claude/rules/' templates/gitignore/standard.gitignore && grep -q 'socle: !.claude/rules/' lib/gitflow-test.sh && ! git check-ignore -q .claude/rules/probe.md && echo SOCLE-OK + EXPECT: SOCLE-OK + EVIDENCE: MET exit=0 marker-found :: SOCLE-OK +19. RED then GREEN pressure test on the `/onboard split` skill text (Tasks 6 and 8: RED = the current skill runs archetype detection on `split`; GREEN = the edited skill reaches the S5 table and stops; the onboarder dry run on a branched scratch commits 2 rules with `all rules in HEAD` and leaves this repo's status unchanged). Outcomes recorded for the STEP 7 EVAL entry. Manual. [gated 2026-10-26] +20. `.claude/tasks/TODO.md`: phase 0 item checked with what shipped, the proof / higgsfield / phase-2 sub-items open, phase 0b per-repo pass queued with the repo order. [gated 2026-10-26] + CHECK: cd /home/bchanot/Documents/claude && grep -q 'Phase 0b, per-repo pass' .claude/tasks/TODO.md && grep -q '\[x\] \*\*Phase 0, no mod' .claude/tasks/TODO.md && echo TODO-OK + EXPECT: TODO-OK + EVIDENCE: MET exit=0 marker-found :: TODO-OK + +## FILE SCOPE +- `CLAUDE.md`, `.claude/rules/*.md` (new), `.gitignore`, `templates/gitignore/standard.gitignore` (pending clarification), `rules/README.md` +- `skills/onboard/SKILL.md`, `agents/onboarder.md`, `agents/scaffolder.md`, `skills/init-project/SKILL.md`, `templates/project-CLAUDE.md`, `templates/` (new path-rule template) +- `lib/project-rules.sh` (new), `lib/tests/project-rules.test.sh` (new), `lib/gitflow-test.sh` (socle assertion), `templates/project-rules/` (new skeletons) +- `doctor.sh`, `ARCHITECTURE.md`, `README.md` (doc pipeline), `hooks/instructions-loaded.sh` (new) + `settings.json` (hook registration) +- `docs/superpowers/specs/`, `docs/superpowers/plans/` (run artifacts, purged at finish) +- `.claude/tasks/TODO.md`, `.claude/memory/*` (capitalize) +- Out of scope in this repo: the 6 other projects' trees (per-repo pass, pending clarification). diff --git a/.gitignore b/.gitignore index 42c29f2..aaf3d4e 100644 --- a/.gitignore +++ b/.gitignore @@ -124,6 +124,7 @@ skills-disabled/ !.claude/memory/ !.claude/audits/ !.claude/settings.json +!.claude/rules/ # But keep local stuff ignored within .claude/ .claude/settings.local.json .claude/agent-memory/ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e3a16d8..4551ebd 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -20,16 +20,17 @@ 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, manual-mode push guard +├── hooks/ # Claude Code hooks: session start, statusline, RTK rewrite, ctx7 + design-toolchain reminders, attention notify, unpushed-work guard, manual-mode push guard, instruction-load log ├── 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 +├── .claude/rules/ # This repo's project path rules (paths: frontmatter), loaded on Read of a matching file ├── 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, route doctrine, gates, archetypes, tests +├── templates/ # Per-project templates (CLAUDE.md, settings, memory registries, path-rule skeletons, deploy runbook, gitignore) +└── lib/ # Shared libs: gitflow, profiles, vendoring, route doctrine, gates, archetypes, project-rule oracle, tests ``` ## Architecture principles diff --git a/CHANGELOG.md b/CHANGELOG.md index a788389..32756dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project - **model-router prompt classifier**: a plain prompt typed in the composer (12 characters or more, not a slash command, not mid-turn, never under `-p` or in a sub-agent) that no keyword rule, skill, run slot, `/route` or floor covers is labelled by one call to the engine's small model (`design`, `analysis`, `coding`, `bookkeeping`, `chat`), bounded to 3 s. The label maps to plan, reflect, implement or apply and the turn takes that phase's route: its effort, and its model under the switch and the downgrade cap, never above the session model (an `ultrathink` floor raises the effort only, the guess's model holds); no dialog, no file write, gone at the end of the turn, replaced by any route call or typed skill, and dropped for that turn by a `/effort` typed between turns. Three failures in a row pause it for `cooldownMinutes` (one toast, `classifier: paused` in the status line). `"classify": false` in `~/.claude/model-router.json` and `/route classify on|off` turn it off; `/route show` prints `classify:`. The status line reads `route: classifier ` and `/route verbose on` adds `(: classifier)`. - **model-router cold-read caps**: both main-loop caps measure the cold read a switch costs, from a per-model record of main's last step, warm within the engine's prompt-cache TTL (`cache_ttl` 5m or 1h from main's model-switch events, 1 h before the first, kept across `/clear`; records cleared by `/clear` and `/route reload`), plus the submitted prompt the engine's usage may not count yet (code points / 3 of its text, context entries and a typed skill's body, added at the turn's first main step unless usage already grew by half of it; a `document` attachment blocks the switch for that step); `downgradeMaxTokens` (default 120000) joins `upgradeMaxTokens` (200000). A model-loaded helper skill inside a best-tier run moves effort only; main routed onto a model whose window the context outgrew returns to the session model. `/route show` prints `switch: on (downgrade, cap 120000 tokens cold, ttl 60 min)`, the status line shows ` · switch off` only when the switch is off, the skip line is logged once per cap crossing and the change toast names a cap hold. A built-in `general-purpose` agent that main spawns with no model while main sits below the session model starts on the session model instead of inheriting the lower one. - **/explain-diff skill**: turns a change (commit, range, branch, merge, PR, staged or uncommitted work) into one self-contained HTML page saved outside the repo, under `~/Documents/explanations//YYYY-MM-DD-.html`. The page has a background, an intuition built on toy data with HTML diagrams, a code walkthrough grouped by concern and a 5-question interactive quiz. Adapted from Geoffrey Litt's explain-diff gist. A bundled template (light and dark, works offline) and a checker (`scripts/check_explanation.py`: file name, location, sections, quiz, code escaping, no ASCII art, no em-dash) hold every page to the same floor. Routing row `reflect`; profiles full, max and dev. +- **Project path rules (CLAUDE.md split)**: `lib/project-rules.sh` (`check`, `matches`, `sections`, `extract`, `emit`, optional `-C `) is the glob oracle for `.claude/rules/.md` rules, one-line `paths:` frontmatter, loaded on Read of a matching file; suite `lib/tests/project-rules.test.sh`. `/onboard split` classifies an existing project CLAUDE.md section by section behind a gate and moves the path-bound ones into rules on a `chore/claude-md-split` branch. `/onboard` and `/init-project` emit `docker`, `testing` and `ci` rules from `templates/project-rules/` when their globs match. This repo's CLAUDE.md now keeps its header, Health Stack and a pointer; four sections load as path rules. +- **InstructionsLoaded logger**: `hooks/instructions-loaded.sh`, wired in `settings.json`, appends one JSON line per instruction file loaded to `~/.claude/logs/instructions-loaded.jsonl` (rotated above 5 MB), the proof that a path rule loaded. ### Changed - impeccable is the Build path for all UI: it replaces `frontend-design` on the design gate's `# GATE-BLOCK:` list and leads the Build line of the design doctrine. `frontend-design` stays installed as the light path for a one-off visual. Detector rule count corrected 45 to 61 (BDR-119). @@ -33,6 +35,7 @@ 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. - model-router keyword prompt rules (`plan|design|architecture…`, `why|review|audit…`), the `ultrathink` floor and the derived `orchestrate` route of a main Agent dispatch set the turn's effort only, never a model: they no longer lift main above the session model, and a held best-tier run keeps its model. Fable on main comes only from a skill row, the `route` tool, a typed `/route` or a `/model` hand pick (BDR-123). Tests: `mods/model-router/hooks/register.test.ts`. +- `.gitignore` and `templates/gitignore/standard.gitignore` un-ignore `.claude/rules/` (`!.claude/rules/` after `.claude/*`); `lib/gitflow-test.sh` asserts the socle line. ### 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. diff --git a/CLAUDE.md b/CLAUDE.md index 25adfcd..0637c63 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,92 +7,8 @@ ## Health Stack - shell: `shellcheck *.sh hooks/*.sh lib/*.sh` -## rules/ maintenance - -Modular instruction files loaded by Claude Code alongside the global memory. -`rules/` is symlinked to `~/.claude/rules` by `link.sh` (user scope, ALL -projects). One rule = one file = one concern. - -A rule WITH `paths:` YAML frontmatter (glob list) loads lazily — only when -Claude reads a file matching a glob; a rule WITHOUT it loads at session -start, same cost as the global memory. Extract from CLAUDE.global.md only -what can be path-scoped (the token win) or what is generated; always-on -doctrine stays in CLAUDE.global.md. Exception: a standalone user-authored -rule set that would bust the 320-line density budget may live here WITHOUT -`paths:` (always-on load) — writing-style.md (BDR-085), default-language.md -(BDR-118), secure-by-default.md (BDR-120). `paths:` globs match against the -CURRENT project's tree — a broad glob (e.g. `rules/**`) can fire in foreign -projects; keep rule bodies tiny. -Docs: https://code.claude.com/docs/en/memory.md#path-specific-rules - -Machine-owned: `rules/context7.md` is DELETED BY DESIGN (BDR-053, -2026-07-06) — `ctx7 setup --claude --cli` still writes it, but -install-plugins.sh STEP ctx7 purges it right after; the find-docs skill is -the single ctx7 surface. If it reappears (manual `ctx7 setup`), delete it -or re-run `make plugin`. - -## Machine-owned: the vendored graphify skill - -`skills/graphify/SKILL.md`, `skills/graphify/references/` and -`.graphify_version` are written by `graphify claude install` -(`install-plugins.sh` STEP graphify), which lands in the repo because -`~/.claude/skills` is a symlink to `skills/`. They are gitignored: a -`pipx upgrade graphifyy` used to dirty the tree and cost a -`chore(graphify): sync vendored skill X -> Y` commit each time. - -Two graphify commands, easy to confuse, and only one restores the skill: -- `graphify install --platform claude` copies SKILL.md + `references/` + - `.graphify_version` into `skills/graphify/`. Touches nothing else. - This is the recovery command. -- `graphify claude install` writes the CLAUDE.md graphify section and the - `.claude/settings.json` PreToolUse hooks. It **rewrites both guarded - configs** (EVAL-020, verified again 2026-09-15), so revert them after. It does NOT copy - the skill. - -`make plugin` runs both (`install-plugins.sh` STEP graphify) behind the -guarded-config EXIT trap, so a fresh clone is covered. - -Trade-off accepted: an upstream release can now change the skill's prompt -with no diff to review. `skills/graphify/test-prompts.json` is hand-written -for darwin and stays tracked. - -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 -artifacts of a feature pipeline (subagent briefs, reviewer references). -They are committed DURING the run (the SDD worktree + reviewers read them -from disk — NOT gitignored), then AUTO-PURGED by `gitflow finish` on a -`feature`/`bugfix` branch, before the merge, so develop's tip stays clean -(BDR-065, `lib/gitflow.sh` `_gitflow_purge_transient`). The feature commits -stay reachable from develop, so `git show :docs/…` is still the archive. -Opt out with `GITFLOW_PURGE_TRANSIENT=0`. NOT in scope: `.claude/tasks/{contracts,plans}` -(durable, versioned, referenced by decisions.md). Durable knowledge goes to -`.claude/memory/` registries, never to these files. Derived scan/audit -outputs (`.audit/**`) are gitignored and never committed, even redacted -(LRN-124). +## Path-scoped rules +Project rules live in `.claude/rules/.md` and load on Read of a file +matching their `paths:` (never at session start): rules-maintenance, +graphify-vendored, mods, transient-artifacts. Check: `bash +lib/project-rules.sh check` (runs in `make test`). diff --git a/README.md b/README.md index e3212f3..1f7a9bc 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,7 @@ a different package, ships its own conflicting `graphify` bin) — see |---|---| | `/init-project` | Initialize a complete project from scratch (full orchestrator, 12+ steps) | | `/ship-feature` | Ship a feature end-to-end with validation gates (full orchestrator) | -| `/onboard` | Onboard an existing project: CLAUDE.md, settings, .claudeignore, archetype audits, report and a sequenced TODO backlog | +| `/onboard` | Onboard an existing project: CLAUDE.md, settings, .claudeignore, path rules, archetype audits, report and a sequenced TODO backlog. `/onboard split` moves the path-bound sections of an existing CLAUDE.md into `.claude/rules/` (loaded on Read of a matching file) | | `/feat` | Small feature implementation (1-5 files, lightweight) | | `/bugfix` | Structured bug fix with root cause investigation | | `/hotfix` | Quick fix for superficial bugs (typos, CSS, config — max 2 files) | diff --git a/USAGE.md b/USAGE.md index d5f99c6..ed58ce2 100644 --- a/USAGE.md +++ b/USAGE.md @@ -139,7 +139,7 @@ Tu veux... | `/feat` | Petite feature (1-5 fichiers) | Léger, pas d'orchestration lourde | | `/bugfix` | Bug avec investigation root cause | Hypothèses, diagnostic, fix minimal | | `/hotfix` | Bug superficiel (typo, CSS, config) | Max 2 fichiers, cause évidente | -| `/onboard` | Projet existant non géré par ce config | Génère CLAUDE.md + settings | +| `/onboard` | Projet existant non géré par ce config | Génère CLAUDE.md + settings ; `/onboard split` découpe un CLAUDE.md existant en règles `.claude/rules/` | | `/plugin-check` | Avant de démarrer tout travail | Aussi embarqué en STEP 0 des orchestrateurs | | `/analyze` | Comprendre du code avant de le modifier | Read-only, aucune solution proposée | | `/analyze` + erreur | Diagnostiquer un test/build qui échoue | Mode DEBUG : hypothèses ordonnées | @@ -286,7 +286,7 @@ cd mon-projet-existant/ | 0 | plugin-advisor — détection signaux + activation plugins | recommandations plugins | | 1 | Archetype detection (scan ~/.claude/lib/project-archetypes/*.md) | archétype SELECTED + implications auto | | 1b | Gate monorepo (A/B/C si détecté) | mode choisi | -| 2 | Config baseline (onboarder agent) | CLAUDE.md, settings.json, .claudeignore, .claude/tasks/ + .claude/memory/ + .claude/audits/ | +| 2 | Config baseline (onboarder agent) | CLAUDE.md, settings.json, .claudeignore, .claude/tasks/ + .claude/memory/ + .claude/audits/ + .claude/rules/ (docker, testing, ci si un glob matche) | | 2.5| Lib d'animation (`motion`), proposée, opt-in | dépendance si acceptée | | 2.6| Gitflow init (main + develop, hooks) | branches + .githooks/ | | 3 | Interview deep = business minimum (users, deadlines, équipe, légal, perfs) + adaptative par archétype | brief enrichi | @@ -311,6 +311,7 @@ cd mon-projet-existant/ ``` /onboard "Python FastAPI" # hint stack /onboard force-archetype:wordpress # override detection +/onboard split # CLAUDE.md existant → règles .claude/rules/ (sections liées à un chemin) ``` **Après /onboard :** diff --git a/agents/onboarder.md b/agents/onboarder.md index 209d1d7..a01ece0 100644 --- a/agents/onboarder.md +++ b/agents/onboarder.md @@ -11,6 +11,9 @@ effort: medium ## ROLE Generate the baseline claude-config files in a project directory. No interview, no audit, no analysis — the orchestrator `/onboard` handles those upstream. This agent only writes config files given a prepared brief. +Two modes. No `MODE:` line in the brief → the generator below (PHASES 1-6). +`MODE: split` → only § MODE: split at the end of this file runs. + --- ## INPUTS (passed by orchestrator) @@ -125,6 +128,24 @@ ls ${PROJECT_ROOT}/.claude/tasks/TODO.md ${PROJECT_ROOT}/.claude/memory/ 2>/dev/ **Do NOT overwrite existing content.** +## PHASE 5b — PATH-SCOPED RULES (born split) + +For each of `docker`, `testing`, `ci`: +```bash +bash ~/.claude/lib/project-rules.sh -C emit ~/.claude/templates/project-rules/.md .claude/rules/.md +``` +- rc 0 → written with the globs that match this tree; its stub comments + are `` placeholders the orchestrator's + STEP 3 fills (list them in OUTPUT beside the CLAUDE.md placeholders). + Fill now only what the BRIEF already settles (`docker` commands from + `build_cmd`, `testing` layout from `test_cmd`); never duplicate the + always-on Build/Test sections. +- rc 1 → no match, nothing written, skip silently. +- rc 2 → the file exists: keep it, never overwrite. +Then `bash ~/.claude/lib/project-rules.sh -C check` must print +`N rule(s) ok`. The `!.claude/rules/` negation comes from the gitflow socle +at /onboard STEP 2.6 (`gitflow init` reconciles it); PHASE 4 stays as is. + --- ## PHASE 6 — GSD v2 ROADMAP (optional, per orchestrator flag) @@ -156,6 +177,7 @@ FILES WRITTEN: ✅ .claude/memory/journal.md (created | unchanged) ✅ .claude/memory/evals.md (created | unchanged) ✅ .claude/audits/ (created | unchanged) + [✅ .claude/rules/.md] (per skeleton that matched: docker | testing | ci) [✅ ROADMAP.md] (if generate_roadmap) PLACEHOLDERS : ``` @@ -167,6 +189,107 @@ PLACEHOLDERS : - A command the permission rules refuse is reported in your final message with the rule that stopped it, never rerun through a wrapper script, alias, env file, `make` target or another shell (a brief that orders the refused form is wrong: report it, do not comply). - NO interview (handled upstream). - NO audit (handled downstream by orchestrator). -- NO destructive writes: never overwrite CLAUDE.md if it exists without asking (print path + STOP, let orchestrator decide). +- NO destructive writes: never overwrite CLAUDE.md if it exists without asking (print path + STOP, let orchestrator decide). MODE: split edits it by design, row by row, on the approved TABLE. - Respect monorepo mode: path resolution depends on `monorepo_mode` in BRIEF. - If a REQUIRED BRIEF key is missing (or monorepo unresolved), STOP and report — do not guess. Null OPTIONAL keys are normal on first dispatch: placeholder, don't stop. + +--- + +## MODE: split (dispatched by `/onboard split`) + +INPUTS: `PROJECT_ROOT` (absolute; written as a literal path in every +command below, never through a variable), `TABLE` = the approved rows, one +per line, ` | | ` (heading without `## `). No +BRIEF; PHASES 1-6 do not run. `PR` below stands for +`bash ~/.claude/lib/project-rules.sh -C `. + +S0 — PREFLIGHT (no write before every step passes): +1. `git -C status --porcelain` is empty, else STOP. +2. `PR check` is rc 0, else STOP with its culprit lines: a pre-existing + rule the oracle cannot parse (the one-line `paths: ["a", "b"]` form + only) is fixed by the user before any split. +3. Per row, by reading the row (never a shell test that embeds it): + `` matches `[a-z0-9][a-z0-9-]*`; the heading has no `'`; every + glob is relative, with no `'`, no leading `/`, no `..`. A row that + fails → STOP with the row and the field. +4. Per row: `PR sections CLAUDE.md` lists `## ` exactly once; + `/.claude/rules/.md` does not exist; every glob of + `` passes `PR matches ''` (rc 0). Any failure → STOP + with the row and the reason. +5. gitignore, in this order: + a. `git -C check-ignore -q .claude/rules/probe.md`; + rc 1 → nothing to do, `GITIGNORE_TOUCHED` stays unset, go to S1. + b. rc 0 and `/.gitignore` does not exist → STOP: the + ignore comes from outside the repo (global excludes or + `.git/info/exclude`); the user decides. + c. Trailing-newline guard: `[ -n "$(tail -c1 /.gitignore)" ] + && echo >> /.gitignore` (rc 1 when already + newline-terminated is fine). + d. Append the negation (portable, lands after any `.claude/*` line): + `printf '!.claude/rules/\n' >> /.gitignore` + e. Re-run `check-ignore`; still rc 0 → `git -C checkout + -- .gitignore`, then STOP: "ignore form cannot be negated (BDR-003: + use the `.claude/*` file form)". + f. Set `GITIGNORE_TOUCHED`: `.gitignore` enters the later `add`, + `checkout` and `commit` only then (a missing pathspec is a fatal + git error). +A STOP after 5.d reverts the gitignore line (5.e); nothing else was +written. + +S1 — EXTRACT, per row (single quotes around the heading): +```bash +bash ~/.claude/lib/project-rules.sh -C extract CLAUDE.md '' .claude/rules/.md '' +``` +rc ≠ 0 (should not happen after S0) → ROLLBACK: `git -C +reset -q`, `git -C checkout -- CLAUDE.md` (plus +`.gitignore` when S0 appended to it), delete every +`.claude/rules/.md` this run wrote (literal paths, one `rm` per +row), then STOP with the row and the lib's message. + +S2 — POINTER. If CLAUDE.md has no `## Path-scoped rules` section, append: +```markdown + +## Path-scoped rules +Project rules live in `.claude/rules/.md` and load on Read of a file +matching their `paths:` (never at session start): , . +``` +Else add the new names to its list (Edit tool, or `cat >> /CLAUDE.md` +with a heredoc; never Write the whole file: subtract-only). Then squeeze +the blank runs the extraction left, through a literal temp path: +`cat -s /CLAUDE.md > /CLAUDE.md.tmp && cat +/CLAUDE.md.tmp > /CLAUDE.md && rm +/CLAUDE.md.tmp`. + +S3 — CHECK, COMMIT, VERIFY TRACKED. +```bash +bash ~/.claude/lib/project-rules.sh -C check +``` +rc ≠ 0 → ROLLBACK as in S1, STOP with the culprit lines. rc 0 → +```bash +git -C add -- CLAUDE.md .claude/rules/.md # one literal path per row, + .gitignore when GITIGNORE_TOUCHED +git -C commit -m "" +``` +Never `add` the directory: a +pre-existing rule that S0's negation made visible would ride along +unlisted. +`` follows the project's commit convention (its CLAUDE.md commit +rules: allowed types and scopes); with none, `chore: split CLAUDE.md +section(s) into .claude/rules/`. Commit rc ≠ 0 (a hook refused it, e.g. +the gitflow pre-commit on a protected branch, or gitleaks) → ROLLBACK as +in S1, STOP with the hook's output verbatim. rc 0 → verify each row in +the commit, not in the index: +```bash +git -C cat-file -e HEAD:.claude/rules/.md # per row +``` +A row `cat-file` cannot find → `STOP: not in HEAD after commit + (commit kept)`; the orchestrator never re-dispatches on it. + +OUTPUT: +``` +SPLIT DONE: rule(s) — .md (), … +CLAUDE.md: → lines +CHECK : project-rules: rule(s) ok +COMMIT : — all rules in HEAD +``` +or `STOP: — (rollback done, nothing committed)`, or +`STOP: not in HEAD after commit (commit kept)`. diff --git a/agents/scaffolder.md b/agents/scaffolder.md index 607bde3..9d24a93 100644 --- a/agents/scaffolder.md +++ b/agents/scaffolder.md @@ -73,6 +73,25 @@ Empty structure only: imports + empty main/init. No logic. `.dockerignore`: node_modules, .git, .env, dist/build/target, __pycache__. Add `COMPOSE_PROJECT_NAME=` to `.env.example`. +## PHASE 3b — PATH-SCOPED RULES (born split) + +After PHASE 3 wrote the files and BEFORE PHASE 4 installs dependencies +(installed packages must not match the globs). `` is the +project root PHASE 1 wrote `CLAUDE.md` into, as a literal absolute path +(`pwd` there; it is not an INPUT, the scaffold defines it). For each of +`docker`, `testing`, `ci`, one uniform loop: +```bash +bash ~/.claude/lib/project-rules.sh -C emit ~/.claude/templates/project-rules/.md .claude/rules/.md +``` +rc 0 → fill its stubs from the DESIGN (image, compose services, test +layout, pipeline jobs), no placeholders left; rc 1 → nothing matched, +skipped (a plain scaffold yields `docker.md` when Docker is relevant, and +`testing.md` only when the stack scaffolds a test file). Then +`bash ~/.claude/lib/project-rules.sh -C check` prints +`N rule(s) ok`. The `.gitignore` negation `!.claude/rules/` comes from the +gitflow socle at STEP 5f (`gitflow init` reconciles it before the root +commit); do not add `.claude` lines to the stack `.gitignore` yourself. + --- ## PHASE 4 — INSTALL DEPS diff --git a/doctor.sh b/doctor.sh index bd96fda..bd1c44b 100644 --- a/doctor.sh +++ b/doctor.sh @@ -73,7 +73,7 @@ check_symlink() { check_symlink "CLAUDE.md" # check_symlink only asserts the canonical path lands inside $REPO — after a # `git pull` without `link.sh`, ~/.claude/CLAUDE.md can still resolve inside -# $REPO but at the wrong file (the 29-line project CLAUDE.md instead of +# $REPO but at the wrong file (the project CLAUDE.md instead of # CLAUDE.global.md), passing green while the global doctrine is silently gone. _claude_md_target=$(readlink "$HOME/.claude/CLAUDE.md" 2>/dev/null || true) if [ "$_claude_md_target" != "$REPO/CLAUDE.global.md" ]; then diff --git a/hooks/instructions-loaded.sh b/hooks/instructions-loaded.sh new file mode 100755 index 0000000..30dd8d8 --- /dev/null +++ b/hooks/instructions-loaded.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# hooks/instructions-loaded.sh — InstructionsLoaded hook: one JSON line per +# instruction file the engine loads, into +# ~/.claude/logs/instructions-loaded.jsonl. The proof channel for +# path-scoped rules (BDR-125 phase 0): a rule that loaded shows +# `load_reason: path_glob_match`, the file that triggered it, and the +# session or sub-agent that loaded it. Never blocks, never prints to +# stdout (stdout reaches the model), exits 0 whatever happens. Rotates to +# .1 above 5 MB. CLAUDE_INSTRUCTIONS_LOG overrides the path (tests). +log="${CLAUDE_INSTRUCTIONS_LOG:-$HOME/.claude/logs/instructions-loaded.jsonl}" +command -v jq >/dev/null 2>&1 || exit 0 +mkdir -p "$(dirname "$log")" 2>/dev/null || exit 0 +if [ -f "$log" ] && [ "$(wc -c < "$log")" -gt 5242880 ]; then + mv -f "$log" "$log.1" 2>/dev/null +fi +jq -c --arg ts "$(date -u +%FT%TZ)" '{ts: $ts, session_id, agent_id, + agent_type, cwd, file_path, memory_type, load_reason, globs, + trigger_file_path}' >> "$log" 2>/dev/null +exit 0 diff --git a/lib/gitflow-test.sh b/lib/gitflow-test.sh index 7ba2cdf..ce0b9a5 100644 --- a/lib/gitflow-test.sh +++ b/lib/gitflow-test.sh @@ -45,6 +45,7 @@ chk "develop exists" 'git rev-parse --verify -q refs/heads/develop >/dev/nul chk "root commit on main" '[ -n "$(git rev-parse -q --verify main)" ]' chk "gitignore created" '[ -f .gitignore ]' chk "socle: !.claude/deploy/" 'grep -qxF "!.claude/deploy/" .gitignore' +chk "socle: !.claude/rules/" 'grep -qxF "!.claude/rules/" .gitignore' chk "socle: re-ignore PENDING" 'grep -qxF ".claude/deploy/PENDING.json" .gitignore' chk "hook installed" '[ -x .githooks/pre-commit ] && [ "$(git config core.hooksPath)" = .githooks ]' chk "tree CLEAN after init" '[ -z "$(git status --porcelain)" ]' diff --git a/lib/project-rules.sh b/lib/project-rules.sh new file mode 100644 index 0000000..62e84fd --- /dev/null +++ b/lib/project-rules.sh @@ -0,0 +1,210 @@ +#!/usr/bin/env bash +# lib/project-rules.sh — project-scope path rules (.claude/rules/.md), +# BDR-125 phase 0. One deterministic oracle for the make-test suite, the +# /onboard split mode, the onboarder and the scaffolder. Every subcommand +# takes an optional leading `-C ` (a dispatched agent's cwd is the +# session's, never the project's): +# check [rules-dir] every path rule parses and every glob matches ≥1 +# path; rc 2 with the culprit named +# matches rc 0 + the first hits, rc 1 none +# sections chars, line, heading per top-level ## section +# (a section ends at the next # or ## heading +# outside a fence) +# extract move one section to a rule +# emit the rule with the matching globs only (rc 1 +# when none matches, nothing written) +# Globs match the WORKING TREE (compgen -G with globstar and dotglob, +# no brace expansion: one glob per extension; a symlinked dir matches +# when the glob names it, globstar never descends into a symlink met +# under `**`; +# dotglob makes `*` match dotfiles, which the engine's matcher skips: a +# glob that only hits hidden paths passes here but never loads), +# dependency dirs excluded (unless the glob names one: `vendor/**` is a +# valid rule): the engine matches the path the model reads, +# tracked or not; a typo matches nothing either way. A frontmatter line +# `# static-check: skip` exempts a rule whose files only exist mid-run. A +# rule without frontmatter or without `paths:` is an always-on rule: +# reported, never failed. No `head` after a producer: an early reader +# gives the writer SIGPIPE (rc 141 under pipefail). + +_RULES_DEPS='(^|/)(node_modules|\.venv|venv|vendor|target|dist|build|\.git)/' + +_rules_frontmatter() { # → frontmatter body on stdout, rc 1 if none + awk 'NR == 1 && $0 != "---" { exit 1 } + NR > 1 && $0 == "---" { found = 1; exit } + NR > 1 { print } + END { exit found ? 0 : 1 }' "$1" +} + +# → one glob per line. rc 1: no paths: line (always-on); +# rc 2: a paths: value that is not a non-empty JSON array of strings. +_rules_globs() { + local line arr + line=$(printf '%s\n' "$1" | grep -E '^paths:') || return 1 + arr=${line#paths:} + printf '%s' "$arr" \ + | jq -e 'type == "array" and length > 0 and all(type == "string")' \ + >/dev/null 2>&1 || return 2 + printf '%s' "$arr" | jq -r '.[]' +} + +_rules_hits() { # → matching paths outside dependency dirs, rc 1 none + case "$1" in # a glob that names a dependency dir is not filtered + node_modules/*|.venv/*|venv/*|vendor/*|target/*|dist/*|build/*|.git/*) + ( shopt -s globstar dotglob; compgen -G "$1" ) 2>/dev/null; return ;; + esac + ( shopt -s globstar dotglob; compgen -G "$1" ) 2>/dev/null \ + | grep -Ev "$_RULES_DEPS" +} + +_rules_matching() { # → JSON array of the matching ones + local g out="" + while IFS= read -r g; do + [ -n "$g" ] && _rules_hits "$g" >/dev/null && out="$out, \"$g\"" + done <<< "$1" + [ -n "$out" ] || return 1 + printf '[%s]\n' "${out#, }" +} + +_rules_check_file() { # → rc 0 ok or always-on, rc 1 with culprits + local fm globs skip=0 g bad=0 + fm=$(_rules_frontmatter "$1") \ + || { echo "$1: always-on (no frontmatter)"; return 0; } + globs=$(_rules_globs "$fm") + case $? in + 1) echo "$1: always-on (no paths:)"; return 0 ;; + 2) echo "$1: paths: must be one line:" \ + "paths: [\"a\", \"b\"]"; return 1 ;; + esac + printf '%s\n' "$fm" | grep -qx '# static-check: skip' && skip=1 + while IFS= read -r g; do + if [ "$skip" = 1 ]; then echo "$1: SKIP $g"; continue; fi + _rules_hits "$g" >/dev/null \ + || { echo "$1: glob matches nothing: $g"; bad=1; } + done <<< "$globs" + [ "$bad" = 0 ] +} + +project_rules_check() { # [rules-dir] → rc 0 all ok, rc 2 with culprits named + local dir="${1:-.claude/rules}" f n=0 bad=0 + [ -d "$dir" ] \ + || { echo "project-rules: 0 rule(s) ok ($dir absent)"; return 0; } + for f in "$dir"/*.md; do + [ -e "$f" ] || continue + n=$((n + 1)) + _rules_check_file "$f" || bad=1 + done + [ "$bad" = 0 ] || return 2 + echo "project-rules: $n rule(s) ok" +} + +project_rules_matches() { # → rc 0 + the first 3 hits, rc 1 none + # awk reads the pipe to its end: a `head` reader would SIGPIPE the + # producer on any glob with more than a pipe buffer of hits (rc 141). + _rules_hits "$1" | awk 'NR <= 3 { print } END { exit NR == 0 }' \ + || { echo "no match: $1" >&2; return 1; } +} + +project_rules_sections() { # → chars, line, heading per ## section + [ -f "$1" ] || { echo "project-rules: $1 not found" >&2; return 2; } + awk ' + function flush() { if (h != "") printf "%d\t%d\t%s\n", c, l, h; h = "" } + /^```/ { fence = !fence } + /^# / && !fence { flush() } + /^## / && !fence { flush(); h = $0; l = NR; c = 0 } + h != "" { c += length($0) + 1 } + END { flush() }' "$1" +} + +_rules_heading_count() { # → fence-aware count of "## h" + awk -v h="## $2" '/^```/ { fence = !fence } + !fence && $0 == h { n++ } + END { print n + 0 }' "$1" +} + +_rules_section_body() { # → body, trailing ---/blank trimmed + awk -v h="## $2" ' + /^```/ { fence = !fence } + !fence && $0 == h { on = 1; next } + !fence && on && (/^## / || /^# /) { exit } + on { buf[++n] = $0 } + END { while (n > 0 && (buf[n] == "" || buf[n] == "---")) n-- + for (i = 1; i <= n; i++) print buf[i] }' "$1" +} + +_rules_without_section() { # → the file minus that section + awk -v h="## $2" ' + /^```/ { fence = !fence } + !fence && $0 == h { skip = 1; next } + !fence && skip && (/^## / || /^# /) { skip = 0 } + !skip { print }' "$1" +} + +_rules_globs_all_match() { # → rc 0 valid and every glob matches + local globs g + globs=$(_rules_globs "paths: $1") || { + echo "project-rules: globs must be a JSON array of strings: $1" >&2 + return 1; } + while IFS= read -r g; do + _rules_hits "$g" >/dev/null \ + || { echo "project-rules: glob matches nothing: $g" >&2; return 1; } + done <<< "$globs" +} + +project_rules_extract() { # + local src="$1" heading="$2" out="$3" globs="$4" tmp + [ "$(_rules_heading_count "$src" "$heading")" = 1 ] || { + echo "project-rules: heading must occur exactly once: ## $heading" >&2 + return 2; } + [ -e "$out" ] && { echo "project-rules: $out exists" >&2; return 2; } + _rules_globs_all_match "$globs" || return 2 + mkdir -p "$(dirname "$out")" + tmp=$(mktemp) || { echo "project-rules: no temp file" >&2; return 2; } + { printf -- '---\npaths: %s\n---\n\n# %s\n' "$globs" "$heading" + _rules_section_body "$src" "$heading"; } > "$out" + if ! { _rules_without_section "$src" "$heading" > "$tmp" \ + && cat "$tmp" > "$src"; }; then + rm -f "$tmp" "$out" + echo "project-rules: $src not rewritten, $out removed" >&2 + return 2 + fi + rm -f "$tmp" + echo "project-rules: moved '## $heading' to $out" +} + +project_rules_emit() { # → the rule, matching globs only + local fm globs kept + fm=$(_rules_frontmatter "$1") \ + || { echo "project-rules: $1: no frontmatter" >&2; return 2; } + globs=$(_rules_globs "$fm") \ + || { echo "project-rules: $1: no valid paths: array" >&2; return 2; } + kept=$(_rules_matching "$globs") \ + || { echo "project-rules: $1: no glob matches, not emitted" >&2; return 1; } + [ -e "$2" ] && { echo "project-rules: $2 exists" >&2; return 2; } + mkdir -p "$(dirname "$2")" + { printf -- '---\npaths: %s\n---\n' "$kept" + awk 'body { print } NR > 1 && $0 == "---" { body = 1 }' "$1"; } > "$2" + echo "project-rules: emitted $2 paths: $kept" +} + +_project_rules_main() { + set -uo pipefail + if [ "${1:-}" = "-C" ]; then + cd "${2:?dir}" 2>/dev/null \ + || { echo "project-rules: no dir $2" >&2; return 2; } + shift 2 + fi + case "${1:-}" in + check) project_rules_check "${2:-.claude/rules}" ;; + matches) project_rules_matches "${2:?glob}" ;; + sections) project_rules_sections "${2:?file}" ;; + extract) project_rules_extract "${2:?file}" "${3:?heading}" "${4:?out}" \ + "${5:?globs-json}" ;; + emit) project_rules_emit "${2:?skeleton}" "${3:?out}" ;; + *) echo "usage: project-rules.sh [-C dir] check [rules-dir] | matches" \ + " | sections | extract " \ + " | emit " >&2; return 2 ;; + esac +} + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then _project_rules_main "$@"; fi diff --git a/lib/tests/project-rules.test.sh b/lib/tests/project-rules.test.sh new file mode 100644 index 0000000..54bf3a0 --- /dev/null +++ b/lib/tests/project-rules.test.sh @@ -0,0 +1,237 @@ +#!/usr/bin/env bash +# lib/tests/project-rules.test.sh — lib/project-rules.sh (check / matches / +# sections / extract / emit) and hooks/instructions-loaded.sh. Flip-tests +# on fixtures first (LRN-096), then the real check on this repo's rules. +set -u +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +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; } +PR="$ROOT/lib/project-rules.sh" +FIX=$(mktemp -d); trap 'rm -rf "$FIX"' EXIT +cd "$FIX" || exit 1 +mkdir -p .claude/rules src node_modules/x +echo x > src/app.ts +echo n > node_modules/x/a.test.js + +# T1 a good rule passes +printf -- '---\npaths: ["src/**"]\n---\n\n# Src\nbody\n' > .claude/rules/good.md +bash "$PR" check >/dev/null; check T1-good-rule-passes "$?" 0 + +# T2 an unmatched glob fails, culprit named (flip test) +printf -- '---\npaths: ["src/**", "nowhere/**"]\n---\n\n# Bad\n' > .claude/rules/bad.md +out=$(bash "$PR" check); rc=$? +check T2-unmatched-glob-fails "$rc" 2 +check T2b-culprit-named \ + "$(printf '%s\n' "$out" | grep -c 'bad.md: glob matches nothing: nowhere/\*\*')" 1 +printf -- '---\npaths: ["src/app.tz"]\n---\n\n# Typo\n' > .claude/rules/bad.md +bash "$PR" check >/dev/null; check T2c-literal-typo-fails "$?" 2 +printf -- '---\npaths: ["**/*.test.*"]\n---\n\n# Deps\n' > .claude/rules/bad.md +out=$(bash "$PR" check); rc=$? +check T2d-dep-dir-only-is-no-match "$rc" 2 +check T2e-dep-dir-culprit \ + "$(printf '%s\n' "$out" | grep -c 'bad.md: glob matches nothing: \*\*/\*.test.\*')" 1 +rm .claude/rules/bad.md + +# T3 no frontmatter / no paths: = always-on info; a malformed paths: fails +printf '# No front\nbody\n' > .claude/rules/nofm.md +out=$(bash "$PR" check); rc=$? +check T3-no-frontmatter-is-always-on "$rc" 0 +check T3b-reported "$(printf '%s\n' "$out" | grep -c 'nofm.md: always-on (no frontmatter)')" 1 +check T3c-counted "$(printf '%s\n' "$out" | grep -c '2 rule(s) ok')" 1 +printf -- '---\ntitle: x\n---\n\n# No paths\n' > .claude/rules/nofm.md +out=$(bash "$PR" check); rc=$? +check T3d-no-paths-is-always-on "$rc" 0 +check T3e-reported "$(printf '%s\n' "$out" | grep -c 'nofm.md: always-on (no paths:)')" 1 +printf -- '---\npaths: src/**\n---\n\n# Malformed\n' > .claude/rules/nofm.md +out=$(bash "$PR" check); rc=$? +check T3f-malformed-paths-fails "$rc" 2 +check T3g-named \ + "$(printf '%s\n' "$out" | grep -c 'nofm.md: paths: must be one line')" 1 +rm .claude/rules/nofm.md + +# T4 the skip marker passes an unmatched glob, and only in its own file +printf -- '---\npaths: ["nowhere/**"]\n# static-check: skip\n---\n\n# T\n' \ + > .claude/rules/skip.md +out=$(bash "$PR" check); rc=$? +check T4-skip-marker-passes "$rc" 0 +check T4b-skip-printed "$(printf '%s\n' "$out" | grep -c 'skip.md: SKIP nowhere/\*\*')" 1 +printf -- '---\npaths: ["nowhere2/**"]\n---\n\n# U\n' > .claude/rules/other.md +bash "$PR" check >/dev/null; check T4c-skip-is-per-file "$?" 2 +rm .claude/rules/skip.md .claude/rules/other.md + +# T5 an absent dir is not an error; -C runs from elsewhere +rm -rf .claude/rules +out=$(bash "$PR" check); check T5-absent-dir-ok "$?" 0 +check T5b-zero-rules "$(printf '%s' "$out" | grep -c '0 rule(s) ok')" 1 +mkdir -p .claude/rules +printf -- '---\npaths: ["src/**"]\n---\n\n# Src\n' > .claude/rules/good.md +out=$(cd / && bash "$PR" -C "$FIX" check); rc=$? +check T5c-dash-C-rc "$rc" 0 +check T5d-dash-C-counted "$(printf '%s' "$out" | grep -c '1 rule(s) ok')" 1 +bash "$PR" -C /nonexistent-dir check 2>/dev/null; check T5e-dash-C-bad-dir "$?" 2 + +# T5f matches: hits on stdout, rc 1 and stderr line when none +out=$(bash "$PR" matches 'src/**'); rc=$? +check T5f-matches-rc "$rc" 0 +check T5g-matches-hit "$(printf '%s\n' "$out" | grep -c '^src/app.ts$')" 1 +err=$(bash "$PR" matches 'nope/**' 2>&1 >/dev/null); rc=$? +check T5h-no-match-rc "$rc" 1 +check T5i-no-match-stderr "$err" 'no match: nope/**' +bash "$PR" matches '**/*.test.*' >/dev/null 2>&1; check T5j-dep-only-no-match "$?" 1 +# T5k a glob with more than a pipe buffer of hits is still a match (no +# SIGPIPE from an early reader); T5m braces are not expanded by compgen +mkdir -p many +seq -f 'many/file-%04.0f-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 1 3000 \ + | xargs touch +bash "$PR" matches 'many/**' >/dev/null; check T5k-many-hits-rc "$?" 0 +check T5l-three-lines "$(bash "$PR" matches 'many/**' | wc -l | tr -d ' ')" 3 +bash "$PR" matches 'src/**/*.{ts,tz}' >/dev/null 2>&1 +check T5m-brace-glob-no-match "$?" 1 +# T5n a glob that names a dependency dir is a match (vendored area rule) +mkdir -p vendor/lib && echo v > vendor/lib/a.js +bash "$PR" matches 'vendor/**' >/dev/null; check T5n-named-dep-dir-rc "$?" 0 +bash "$PR" matches '**/a.js' >/dev/null 2>&1 +check T5o-unnamed-dep-dir-still-filtered "$?" 1 + +# T6 sections lists headings with sizes, fence-aware +cat > CLAUDE.md <<'EOF' +# Proj + +## Alpha +aaa + +--- + +## Beta +``` +## not a heading +``` +bbb + +## Gamma +g1 + +## Gamma +g2 +EOF +out=$(bash "$PR" sections CLAUDE.md) +check T6-four-sections "$(printf '%s\n' "$out" | wc -l | tr -d ' ')" 4 +check T6b-beta-line "$(printf '%s\n' "$out" | awk -F'\t' '$3=="## Beta"{print $2}')" 8 +check T6c-alpha-chars "$(printf '%s\n' "$out" | awk -F'\t' '$3=="## Alpha"{print $1}')" 19 +check T6d-fenced-not-listed "$(printf '%s\n' "$out" | grep -c 'not a heading')" 0 + +cp CLAUDE.md "$FIX/orig.md" +# T7 extract moves the section, writes the frontmatter, demotes the title +bash "$PR" extract CLAUDE.md 'Alpha' .claude/rules/alpha.md '["src/**"]' >/dev/null +check T7-extract-rc "$?" 0 +check T7b-rule-frontmatter "$(sed -n '2p' .claude/rules/alpha.md)" 'paths: ["src/**"]' +check T7c-rule-title "$(sed -n '5p' .claude/rules/alpha.md)" '# Alpha' +check T7d-rule-body "$(sed -n '6p' .claude/rules/alpha.md)" 'aaa' +check T7e-trailing-sep-trimmed "$(tail -1 .claude/rules/alpha.md)" 'aaa' +check T7f-section-gone "$(grep -c '^## Alpha' CLAUDE.md)" 0 +check T7g-beta-kept "$(grep -c '^## Beta' CLAUDE.md)" 1 +check T7h-fenced-line-kept "$(grep -c '^## not a heading' CLAUDE.md)" 1 +bash "$PR" check >/dev/null; check T7i-check-passes "$?" 0 +# T7j subtract-only: one deletion hunk, removed = heading + body + separators +check T7j-one-hunk "$(diff "$FIX/orig.md" CLAUDE.md | grep -c '^[0-9]')" 1 +check T7k-no-additions "$(diff "$FIX/orig.md" CLAUDE.md | grep -c '^> ')" 0 +check T7l-removed-lines "$(diff "$FIX/orig.md" CLAUDE.md | grep '^< ' | cut -c3- | grep -vE '^(---)?$' | tr '\n' '|')" '## Alpha|aaa|' + +# T8 extract refuses: missing heading, existing target, duplicate, fenced-only +bash "$PR" extract CLAUDE.md 'Alpha' .claude/rules/alpha2.md '["src/**"]' 2>/dev/null +check T8-missing-heading-rc "$?" 2 +check T8b-nothing-written "$([ -e .claude/rules/alpha2.md ] && echo yes || echo no)" no +bash "$PR" extract CLAUDE.md 'Beta' .claude/rules/alpha.md '["src/**"]' 2>/dev/null +check T8c-existing-target-rc "$?" 2 +check T8d-beta-still-there "$(grep -c '^## Beta' CLAUDE.md)" 1 +bash "$PR" extract CLAUDE.md 'Gamma' .claude/rules/gamma.md '["src/**"]' 2>/dev/null +check T8e-duplicate-heading-rc "$?" 2 +check T8e2-both-gammas-kept "$(grep -c '^## Gamma' CLAUDE.md)" 2 +bash "$PR" extract CLAUDE.md 'not a heading' .claude/rules/nah.md '["src/**"]' 2>/dev/null +check T8f-fenced-only-rc "$?" 2 +check T8g-nothing-written "$(cd .claude/rules && printf '%s ' *)" 'alpha.md good.md ' + +# T9 extract refuses malformed globs and a glob that matches nothing +bash "$PR" extract CLAUDE.md 'Beta' .claude/rules/beta.md 'src/**' 2>/dev/null +check T9-bad-globs-rc "$?" 2 +bash "$PR" extract CLAUDE.md 'Beta' .claude/rules/beta.md '["nowhere/**"]' 2>/dev/null +check T9b-unmatched-glob-rc "$?" 2 +check T9c-nothing-written "$([ -e .claude/rules/beta.md ] && echo yes || echo no)" no +check T9d-beta-still-there "$(grep -c '^## Beta' CLAUDE.md)" 1 + +# T9e a failed source rewrite is rc 2 and leaves no rule behind +TMPDIR=/nonexistent bash "$PR" extract CLAUDE.md 'Beta' .claude/rules/beta.md '["src/**"]' 2>/dev/null +check T9e-no-tmp-rc "$?" 2 +check T9f-no-tmp-nothing-written "$([ -e .claude/rules/beta.md ] && echo yes || echo no)" no +check T9g-no-tmp-beta-still-there "$(grep -c '^## Beta' CLAUDE.md)" 1 +chmod a-w CLAUDE.md +bash "$PR" extract CLAUDE.md 'Beta' .claude/rules/beta.md '["src/**"]' 2>/dev/null +check T9h-unwritable-src-rc "$?" 2 +check T9i-unwritable-src-rule-removed "$([ -e .claude/rules/beta.md ] && echo yes || echo no)" no +chmod u+w CLAUDE.md +check T9j-unwritable-src-beta-still-there "$(grep -c '^## Beta' CLAUDE.md)" 1 + +# T9k a mid-file H1 ends the section (foreign CLAUDE.md with several parts) +mkdir -p "$FIX/h1/src" && cd "$FIX/h1" || exit 1 +echo x > src/a.ts +printf '## A\naaa\n\n# Part Two\nintro\n\n## B\nbbb\n' > CLAUDE.md +check T9k-h1-ends-section "$(bash "$PR" sections CLAUDE.md | awk -F'\t' '$3=="## A"{print $1}')" 10 +bash "$PR" extract CLAUDE.md 'A' .claude/rules/a.md '["src/**"]' >/dev/null +check T9l-h1-kept "$(grep -c '^# Part Two' CLAUDE.md)" 1 +check T9m-h1-intro-kept "$(grep -c '^intro' CLAUDE.md)" 1 +check T9n-rule-body-stops-at-h1 "$(tail -1 .claude/rules/a.md)" aaa +cd "$FIX" || exit 1 + +# T10 the hook appends one jq line, prints nothing, never fails +HOOK="$ROOT/hooks/instructions-loaded.sh" +LOG="$FIX/il.jsonl" +IN='{"hook_event_name":"InstructionsLoaded","session_id":"s1","agent_id":"a1","agent_type":"general-purpose","cwd":"/p","file_path":"/p/.claude/rules/x.md","memory_type":"Project","load_reason":"path_glob_match","globs":["src/**"],"trigger_file_path":"/p/src/a.ts"}' +out=$(printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG="$LOG" bash "$HOOK"); rc=$? +check T10-hook-rc "$rc" 0 +check T10b-stdout-empty "$out" "" +check T10c-one-line "$(wc -l < "$LOG" | tr -d ' ')" 1 +check T10d-reason-kept "$(jq -r '.load_reason' "$LOG")" path_glob_match +check T10e-ids-kept "$(jq -r '[.session_id, .agent_id, .globs[0]] | join(",")' "$LOG")" 's1,a1,src/**' +out=$(printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG=/proc/nowhere/il.jsonl bash "$HOOK"); rc=$? +check T10f-unwritable-log-rc0 "$rc" 0 +check T10g-unwritable-log-stdout-empty "$out" "" +# "$BASH", not bash: a blank PATH applies to the command lookup too (rc 127); this proves the contract (rc 0, silent, nothing appended), not the jq guard +out=$(printf '%s' "$IN" \ + | CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent "$BASH" "$HOOK"); rc=$? +check T10h-empty-path-rc0 "$rc" 0 +check T10i-empty-path-stdout-empty "$out" "" +check T10j-empty-path-nothing-appended "$(wc -l < "$LOG" | tr -d ' ')" 1 +head -c 5300000 /dev/zero | tr '\0' 'x' > "$LOG" +printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG="$LOG" bash "$HOOK" +check T10k-rotated "$([ -e "$LOG.1" ] && echo yes || echo no)" yes +check T10l-fresh-log-one-line "$(wc -l < "$LOG" | tr -d ' ')" 1 + +# T11 the real rules of this repo pass the check (4 rules, 1 skip-marked) +out=$(bash "$PR" -C "$ROOT" check); rc=$? +[ "$rc" -eq 0 ] || printf '%s\n' "$out" +check T11-repo-rules-pass "$rc" 0 +check T11b-four-rules "$(printf '%s\n' "$out" | grep -c '4 rule(s) ok')" 1 +check T11c-transient-skipped \ + "$(printf '%s\n' "$out" | grep -c 'transient-artifacts.md: SKIP docs/superpowers/\*\*')" 1 + +# T12 skeletons: emit keeps the matching globs only, skips when none match +mkdir -p "$FIX/gen/tests" && cd "$FIX/gen" || exit 1 +echo x > Dockerfile; echo y > tests/test_a.py +bash "$PR" emit "$ROOT/templates/project-rules/docker.md" .claude/rules/docker.md >/dev/null +check T12-docker-emitted "$?" 0 +check T12b-docker-globs-pruned "$(sed -n '2p' .claude/rules/docker.md)" 'paths: ["Dockerfile*"]' +check T12c-docker-body-kept "$(grep -c '^# Docker' .claude/rules/docker.md)" 1 +bash "$PR" emit "$ROOT/templates/project-rules/testing.md" .claude/rules/testing.md >/dev/null +check T12d-testing-emitted "$?" 0 +check T12e-testing-globs-pruned "$(sed -n '2p' .claude/rules/testing.md)" 'paths: ["tests/**"]' +bash "$PR" emit "$ROOT/templates/project-rules/ci.md" .claude/rules/ci.md 2>/dev/null +check T12f-ci-not-emitted-rc "$?" 1 +check T12g-ci-not-written "$([ -e .claude/rules/ci.md ] && echo yes || echo no)" no +bash "$PR" emit "$ROOT/templates/project-rules/docker.md" .claude/rules/docker.md 2>/dev/null +check T12h-existing-target-rc "$?" 2 +bash "$PR" check >/dev/null; check T12i-emitted-rules-pass-check "$?" 0 +cd "$FIX" || exit 1 + +echo "PASS=$pass FAIL=$fail" +[ "$fail" -eq 0 ] diff --git a/rules/README.md b/rules/README.md index 4321cee..39f13a5 100644 --- a/rules/README.md +++ b/rules/README.md @@ -6,4 +6,5 @@ paths: ["rules/**"] User-scope rules, deployed to `~/.claude/rules` by `link.sh`. Maintenance doctrine (what belongs here, lazy-load `paths:` semantics, -machine-owned files): see `CLAUDE.md` (project scope) at the repo root. +machine-owned files): see `.claude/rules/rules-maintenance.md` in the +claude-config repo (project scope, loads on Read under `rules/`). diff --git a/settings.json b/settings.json index f619f5e..523e214 100644 --- a/settings.json +++ b/settings.json @@ -374,6 +374,17 @@ ] } ], + "InstructionsLoaded": [ + { + "hooks": [ + { + "type": "command", + "command": "bash ~/.claude/hooks/instructions-loaded.sh", + "timeout": 5 + } + ] + } + ], "PreToolUse": [ { "matcher": "Bash", diff --git a/skills/onboard/SKILL.md b/skills/onboard/SKILL.md index a4f10b8..da14e89 100644 --- a/skills/onboard/SKILL.md +++ b/skills/onboard/SKILL.md @@ -1,8 +1,8 @@ --- name: onboard effort: xhigh -description: 'Use when bringing an existing repo into the claude-config framework — needs archetype detection, config install, full multi-axis audit (debt/SEO/GEO/UI-UX/perf/security/a11y/docs), and prioritized backlog. Multi-agent orchestrator. Do NOT use for repos created via /init-project. Triggers: "onboard", "onboard project", "audit existing repo", "setup existing project".' -argument-hint: '[optional hints: "Python FastAPI" | "Next.js monorepo" | "force-archetype:wordpress"]' +description: 'Use when bringing an existing repo into the claude-config framework — needs archetype detection, config install, full multi-axis audit (debt/SEO/GEO/UI-UX/perf/security/a11y/docs), and prioritized backlog. Multi-agent orchestrator. Default flow: do NOT use it for repos created via /init-project. Triggers: "onboard", "onboard project", "audit existing repo", "setup existing project". `split` mode (any repo): "onboard split", "split the project instructions", "découpe le fichier CLAUDE", "path-scoped rules".' +argument-hint: '[split | optional hints: "Python FastAPI" | "Next.js monorepo" | "force-archetype:wordpress"]' allowed-tools: Read, Write, Edit, Bash, Glob, Grep, Agent, Skill --- @@ -21,6 +21,13 @@ $ARGUMENTS --- +## MODE DISPATCH +`$ARGUMENTS` whose first token is `split` → jump to § SPLIT MODE (end of +this file); STEP 0 to FINAL OUTPUT do not run. Anything else → the flow +below, unchanged. + +--- + ## STEP 0 — PLUGIN CHECK + AUTO-ACTIVATE Run `$HOME/.claude/lib/plugin-gate.md` with hint "onboarding existing project + $ARGUMENTS" (dispatch plugin-probe → checkpoint → dispatch plugin-advisor → gates in this loop, BDR-077). @@ -110,6 +117,7 @@ L'agent génère : - `.claudeignore` - `.gitignore` (safety check) - `.claude/tasks/TODO.md`, `.claude/memory/{decisions,learnings,blockers,journal,evals}.md` +- `.claude/rules/.md` pour chaque squelette dont un glob matche (docker, testing, ci) — placeholders listés avec ceux du CLAUDE.md - **Pas encore** `ROADMAP.md` (GSD multi-session : `gsd init` à la main, voir docs gsd-pi — cf. Next steps) Si `CLAUDE.md` existe déjà : lire son contenu, ne PAS écraser — fusionner après STEP 3. @@ -198,7 +206,7 @@ Ne pas redemander ce qui est déjà dans : Présenter toutes les questions en UN BLOC. Attendre les réponses. STOP. -Après réponses : **mettre à jour le brouillon CLAUDE.md** avec les infos obtenues. +Après réponses : **mettre à jour le brouillon CLAUDE.md** avec les infos obtenues, et les placeholders `` des `.claude/rules/*.md` émis en PHASE 5b (Docker, tests, CI : leurs réponses vont dans la règle, pas dans CLAUDE.md). --- @@ -1034,11 +1042,11 @@ Pour démarrer : lire .claude/tasks/TODO.md, choisir une tâche P0, lancer le /s --- ## RULES -- NO skipping STEP 0, 1, 2 — ils sont obligatoires. +- NO skipping STEP 0, 1, 2 — ils sont obligatoires (split mode runs its own steps, § SPLIT MODE). - NO audit agressif : chaque subagent doit recevoir "AUDIT-ONLY, no file modifications". - STEP 1 doit proposer un override `force-archetype:` si l'utilisateur sait déjà. - Monorepo : toujours demander le mode (A/B/C) avant STEP 2. -- Si `CLAUDE.md` existe : le lire, ne pas l'écraser sans fusion après STEP 3. +- Si `CLAUDE.md` existe : le lire, ne pas l'écraser sans fusion après STEP 3 (default flow; split mode edits it on the approved table). - STEP 3 : ne redemande jamais ce qui est déjà dans README ou manifests. - STEP 3.5 : si ctx7 absent + fast-libs, WARN mais ne bloque pas. - STEP 4 : graphify proposé seulement si `graphify-gate.sh` imprime une ligne (≥ 200 fichiers code, pas de graphe — BDR-097) ; l'utilisateur décide, jamais de build sans oui explicite. @@ -1079,3 +1087,100 @@ NEXT STEPS : 3. GSD (multi-session) : `gsd init` à la main, voir docs gsd-pi 4. .onboard-audit/ peut être supprimé (raw data consommée en synthèse) ``` + +--- + +## SPLIT MODE — `/onboard split` (BDR-125 phase 0) + +Move the path-bound sections of an existing project `CLAUDE.md` into +`.claude/rules/.md` path rules (loaded on Read of a matching file), +so the always-on context of that project shrinks. Judgment here, writes by +the onboarder, `lib/project-rules.sh` as the only glob oracle. The MODEL +GATE above has run. `mcp__model-router__route(phase="plan")` first. +`` below is the project root as a literal absolute path. + +S1 — PRECONDITIONS. `CLAUDE.md` at ``, else print `nothing to split — +run /onboard` and stop. `git -C status --porcelain` empty (whole +tree) and the current branch is `develop` (or `main` when no `develop` +exists), else stop and say why: the split branches off develop, and an +in-flight feature branch or dirty file would be classified on one version +and extracted on another. `.claude/rules/` already holding rules → `bash +~/.claude/lib/project-rules.sh -C check`; rc ≠ 0 → stop with the +culprit lines (the user fixes them first: the oracle reads the one-line +`paths: ["a", "b"]` form only); rc 0 → list them, continue (new rules add +to them). + +S2 — BASELINE. `claude -p "/context"` from `` (refused → ask the user +to run `! claude -p "/context"`); note the `Memory files` total and the +project CLAUDE.md row. + +S3 — BRANCH. `cd && bash ~/.claude/lib/gitflow.sh start chore +claude-md-split`. A project without gitflow (no `develop`): +`git -C switch -c chore/claude-md-split`, and say so. Everything +after this step reads the branched file. + +S4 — CLASSIFY. `bash ~/.claude/lib/project-rules.sh -C sections +CLAUDE.md` lists every `##` section with its size. For each one decide: +- always-on: project overview, stack, build/test/lint commands, folder + structure, conventions that apply everywhere, exceptions to global rules, + workflow expectations, key dependencies, anything needed before a file is + read (how to run the project), even when it names a folder; +- path-scoped: one module or folder, Docker, migrations, CI, a tool's + gotchas, a vendored or machine-owned area. Propose `` (kebab, the + section's subject) and globs (a folder → `dir/**`, a tool → its config + files; never a brace glob `*.{ts,tsx}`: one glob per extension, the + oracle does no brace expansion) and verify EVERY proposed glob with + `bash ~/.claude/lib/project-rules.sh -C matches ''` (rc 0) + before showing it. Row shape, checked before a row enters the TABLE: `` matches + `[a-z0-9][a-z0-9-]*`; globs are relative, no `'`, no leading `/`, no + `..`, no `|`; the heading has no `'` and no `|` (the rows are + `|`-separated and the executor single-quotes both). A section that fails + is not split by this mode: say so, the user renames or re-globs first. + +S5 — GATE (mandatory stop). Print the table, then end the turn: + +``` +SPLIT — CLAUDE.md ( chars, sections) on chore/claude-md-split +| # | section | chars | verdict | rule file | paths | +| 1 | Stack | 420 | keep | | | +| 2 | Docker | 1,340 | move | docker.md | ["Dockerfile*", "docker-compose*"] | +... +Moves sections, chars (

% of the file). Approve, edit a row, or "keep everything". +``` +"keep everything" ends the mode with no change (`bash +~/.claude/lib/gitflow.sh delete chore/claude-md-split`). An edited row's +globs are re-verified with `matches` before they enter the TABLE. The +approved rows are the TABLE handed to the onboarder, verbatim. + +S6 — EXECUTE. `mcp__model-router__route(phase="orchestrate")` with the +dispatch: `Agent(subagent_type="onboarder")`, prompt = `MODE: split`, +`PROJECT_ROOT: `, `TABLE:` the approved rows, one per line as +` | | ` (LRN-126: every field crosses the +prompt). It pre-flights every row, then extracts, writes the pointer +section, secures the gitignore negation, runs `check`, commits (message +per the project's commit convention), and verifies every rule is in +`HEAD`. Two STOP shapes come back: +- `STOP: — (rollback done, nothing committed)`: the tree is + back to the branch tip; fix the row, re-dispatch the WHOLE table. +- `STOP: not in HEAD after commit (commit kept)`: never + re-dispatch (the headings are gone from CLAUDE.md); show the user the + hash and `git -C show --stat `, the user decides. + +S7 — AFTER. `claude -p "/context"` again from ``; append to that +project's `.claude/memory/journal.md` under today's date: `CLAUDE.md +split: sections → .claude/rules/ (), always-on → +`. Tell the user the proof step: a fresh session in that project +that Reads one file per rule, then `jq -c 'select(.memory_type=="Project" +and (.file_path|contains("/.claude/rules/")))' +~/.claude/logs/instructions-loaded.jsonl | tail`. Never `finish`: the +merge is the user's signal. + +FINAL OUTPUT: +``` +SPLIT COMPLETE: +RULES : files under .claude/rules/ () +CLAUDE.md: → +CONTEXT : → (Memory files) +BRANCH : chore/claude-md-split () — merge on your signal +PROOF : pending — fresh session + the jq filter above +``` diff --git a/templates/gitignore/standard.gitignore b/templates/gitignore/standard.gitignore index 53fc2c3..e73aad1 100644 --- a/templates/gitignore/standard.gitignore +++ b/templates/gitignore/standard.gitignore @@ -18,6 +18,7 @@ Thumbs.db !.claude/audits/ !.claude/settings.json !.claude/deploy/ +!.claude/rules/ # re-ignore transients inside the versioned subtrees (the PENDING.json trap) .claude/settings.local.json .claude/agent-memory/ diff --git a/templates/project-CLAUDE.md b/templates/project-CLAUDE.md index e8b8417..401ffb7 100644 --- a/templates/project-CLAUDE.md +++ b/templates/project-CLAUDE.md @@ -2,6 +2,7 @@ # Generated by /init-project or /onboard. Single source of truth for Claude in this repo. # Global rules: ~/.claude/CLAUDE.md — this file extends or overrides them. +# Path-scoped rules: .claude/rules/.md (paths: frontmatter), loaded on Read of a matching file. --- diff --git a/templates/project-rules/ci.md b/templates/project-rules/ci.md new file mode 100644 index 0000000..fc5cbb0 --- /dev/null +++ b/templates/project-rules/ci.md @@ -0,0 +1,10 @@ +--- +paths: [".github/workflows/**", ".gitlab-ci.yml", ".circleci/**"] +--- + +# CI + + + + + diff --git a/templates/project-rules/docker.md b/templates/project-rules/docker.md new file mode 100644 index 0000000..d6e39c5 --- /dev/null +++ b/templates/project-rules/docker.md @@ -0,0 +1,10 @@ +--- +paths: ["Dockerfile*", "docker-compose*", "compose*.y*ml", ".dockerignore"] +--- + +# Docker + + + + + diff --git a/templates/project-rules/testing.md b/templates/project-rules/testing.md new file mode 100644 index 0000000..7e1611b --- /dev/null +++ b/templates/project-rules/testing.md @@ -0,0 +1,10 @@ +--- +paths: ["tests/**", "test/**", "**/*.test.*", "**/*.spec.*", "**/conftest.py"] +--- + +# Testing conventions + + + + +