From 2c8e4a20c07be1b616d1adc88d2192b4267ab916 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 01:02:02 +0100 Subject: [PATCH 01/17] docs(spec): phase 0 claude-md split design --- .../2026-10-26-claude-md-split-design.md | 191 ++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-26-claude-md-split-design.md diff --git a/docs/superpowers/specs/2026-10-26-claude-md-split-design.md b/docs/superpowers/specs/2026-10-26-claude-md-split-design.md new file mode 100644 index 0000000..39e9fd1 --- /dev/null +++ b/docs/superpowers/specs/2026-10-26-claude-md-split-design.md @@ -0,0 +1,191 @@ +# Phase 0 — split project CLAUDE.md into `.claude/rules/` (design) + +Date: 2026-10-26 · flow: /ship-feature · branch: feature/claude-md-split +Contract: `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md` +Parent: BDR-125 (context mod queue), TODO.md "Phase 0, no mod". + +## Intent + +The project CLAUDE.md of this repo (5,285 chars) loads in every session of +this repo; four of its five sections only matter when a matching file is +being read. Move those four into project-scope path rules +(`.claude/rules/.md` with `paths:` frontmatter), prove they load, and +give the other projects the same lever through a `/onboard split` mode and +generators that emit path rules from day one. No mod, subtract-only. + +Decided with the user (2026-10-26): this run covers this repo, the mode and +the generators; the per-repo pass over the six other repos runs after the +merge through the shipped `/onboard split`, one `chore/claude-md-split` +branch per repo, user approval per repo, never an automatic merge. The +InstructionsLoaded proof hook is permanent. The transient-artifacts rule +carries a `# static-check: skip` marker. The gitignore socle gains +`!.claude/rules/`. Generator skeleton set: docker, testing, ci. + +## 1. This repo's rules + +| Rule file | `paths:` | Source section (CLAUDE.md, verbatim) | +|---|---|---| +| `.claude/rules/rules-maintenance.md` | `rules/**`, `CLAUDE.global.md` | `## rules/ maintenance` | +| `.claude/rules/graphify-vendored.md` | `skills/graphify/**`, `install-plugins.sh`, `.graphify_version` | `## Machine-owned: the vendored graphify skill` | +| `.claude/rules/mods.md` | `mods/**`, `skills/model-router/**`, `lib/tests/mods.test.sh` | `## mods/ — function-hooks plugins (Claude Code mods)` | +| `.claude/rules/transient-artifacts.md` | `docs/superpowers/**`, `.audit/**` (+ `# static-check: skip`) | `## Transient planning artifacts` | + +Frontmatter shape = `rules/a11y.md`: `paths: ["glob", ...]` on one line. +The skip marker is a YAML comment line inside the frontmatter, invisible to +the engine. Body text moves verbatim; the title line becomes `#
`. CLAUDE.md keeps its header, `## Health Stack`, and a two-line +pointer: path-scoped rules live in `.claude/rules/` and load on Read of a +matching file; the four names listed. + +`.gitignore`: `!.claude/rules/` right after `.claude/*` (line 122). +`templates/gitignore/standard.gitignore`: same line after `.claude/*` +(order matters: a negation must follow the ignore it carves; reconcile +appends missing lines at the end, which is after any existing `.claude/*`). +`lib/gitflow-test.sh`: one `chk "socle: !.claude/rules/"` beside the +`!.claude/deploy/` assertion. + +## 2. Static check and proof hook + +`lib/project-rules.sh` (our code, strict limits, shellcheck): +- `check [dir]` (default `.claude/rules`): for each `*.md`: frontmatter + delimited by `---` present; a `paths:` line whose value is a JSON-style + array of double-quoted globs; each glob matches ≥1 path in the working + tree (`shopt -s globstar dotglob nullglob`, so the symlinked + `skills/model-router/**` and the gitignored `skills/graphify/SKILL.md` + count, and a typo matches nothing). A frontmatter line + `# static-check: skip` exempts that file's globs (printed as SKIP). Exit 0 + and `project-rules: N rule(s) ok` on success; exit 2 and one + `: ` line per failure. An empty or absent dir is exit 0 + with `0 rule(s)` (a project without rules is not an error). +- `sections `: prints `\t\t## ` per + top-level section, for the split-mode classification table. +- `extract "" `: writes + `` with the frontmatter and the section body (title demoted to + `#`), removes the section from CLAUDE.md. Deterministic, idempotent + failure (heading absent → exit 2, nothing written). Used by the onboarder + in MODE: split and by the per-repo pass. + +`lib/tests/project-rules.test.sh` (picked up by `make test` via the +`lib/tests/*.test.sh` glob): fixtures in `mktemp -d`: a good rule passes; +an unmatched glob fails with the culprit; a missing frontmatter fails; the +skip marker passes an unmatched glob; `sections` lists sizes; `extract` +round-trips (rule written, section gone, second call exit 2); then the real +check on this repo's `.claude/rules` (exit 0). PASS/FAIL tally like +`doctrine-citers.test.sh`. + +`hooks/instructions-loaded.sh`: reads the hook JSON on stdin, appends one +`jq -c` line `{ts, cwd, file_path, memory_type, load_reason, +trigger_file_path}` to `~/.claude/logs/instructions-loaded.jsonl` +(`mkdir -p`), always exits 0, never prints to stdout (a stdout line would +reach the model). Registered in `settings.json` under `"InstructionsLoaded"` +beside the other classic hooks. No hooks suite exists: the hook test lives +in `lib/tests/project-rules.test.sh` (fixture JSON on stdin, `HOME` pointed +at a temp dir, the appended line asserted, stdout asserted empty). + +Proof for this repo (recorded in the journal): `claude -p "/context"` on +develop BEFORE any edit (baseline, same measure as 2026-10-23), the same on +the branch after the split, one fresh interactive session that Reads one +matching file per rule, then `grep path_glob_match +~/.claude/logs/instructions-loaded.jsonl | tail -4` pasted. + +## 3. `/onboard split` + +`skills/onboard/SKILL.md`: right after the MODEL GATE, a MODE DISPATCH +paragraph: `$ARGUMENTS` starting with the token `split` → § SPLIT MODE; +anything else → the existing flow unchanged. The description gains the +trigger ("split CLAUDE.md", "découpe le CLAUDE.md"), the argument-hint gains +`split`, RULES line "NO skipping STEP 0, 1, 2" gains "(split mode runs its +own steps, § SPLIT MODE)". Routing rows, test locks (`model-routing`, +`effort-routing`, `loops-heavy`, `plan-challenger`, `security-auditor`) and +`routing.json:67` keep their anchors. + +§ SPLIT MODE (steps): +1. Precondition: `CLAUDE.md` at the project root, else print "nothing to + split, run /onboard" and stop. `git status --porcelain` clean on the + CLAUDE.md path, else stop (an in-flight edit would be lost). +2. Baseline: `claude -p "/context"` at the root; refused → the user runs + `! claude -p "/context"`; the always-on total is noted. +3. `bash ~/.claude/lib/project-rules.sh sections CLAUDE.md`; classify each + `##` section: always-on (overview, stack, build/test/lint commands, + conventions, workflow expectations, exceptions) or path-scoped (one + module, one folder, Docker, migrations, CI, a tool's gotchas); propose a + file name and globs from `git ls-files` for each path-scoped one, and + verify every proposed glob matches ≥1 tracked path before showing it. +4. Gate (prose table, per project): section · chars · keep / move → + `.md` · globs. The user edits or approves; "keep everything" is a + valid answer that ends the mode. +5. `bash ~/.claude/lib/gitflow.sh start chore claude-md-split` (a project + without gitflow: a plain branch, said so). +6. Dispatch `Agent(subagent_type="onboarder")` with `MODE: split`, the + project root, and the approved table verbatim (LRN-126: every field + crosses the prompt). It runs `extract` per row, writes the pointer lines + into CLAUDE.md, adds `!.claude/rules/` after `.claude/*` when that line + is present and the negation absent, runs `check`, commits + `chore(claude-md): split N sections into .claude/rules/`, reports. +7. After: `claude -p "/context"` again, the delta and the rule list go to + that project's `.claude/memory/journal.md`; the InstructionsLoaded proof + is the user's next session there (one Read per rule, grep the log). + Never `finish`: merge on the user's signal. + +Skill edit through /writing-skills: RED first (a sonnet subagent given the +CURRENT skill and a scratch repo holding a copy of this repo's pre-split +CLAUDE.md, asked to "/onboard split": it has no mode and runs or asks for +the full onboard), then the edit, then GREEN on the same scratch (the +subagent produces the classification table and stops at the gate). + +`agents/onboarder.md`: a `MODE:` header: absent → today's PHASES 1-5 +(generate config); `MODE: split` → the split executor above (PHASES +S1-S4: extract rows, pointer lines, gitignore negation, check + commit). +Stays sonnet, effort medium (BDR-077). + +## 4. Generators born split + +`templates/project-rules/` skeletons, each with `paths:` and 3-6 lines of +section stubs (HTML comments like the CLAUDE.md template): +- `docker.md`: `["Dockerfile*", "docker-compose*", "compose*.y*ml", ".dockerignore"]` +- `testing.md`: `["tests/**", "test/**", "**/*.test.*", "**/*.spec.*", "**/conftest.py"]` +- `ci.md`: `[".github/workflows/**", ".gitlab-ci.yml", ".circleci/**"]` + +onboarder (default mode) PHASE 1b and scaffolder PHASE 1b: for each +skeleton, emit `.claude/rules/.md` when ≥1 of its globs matches a +path in the project tree (onboarder: the real tree; scaffolder: the tree it +just scaffolded, so a Docker-relevant project gets `docker.md`), filled from +the BRIEF where known, else the template stubs. Then run `project-rules.sh +check` and report the emitted list. The onboarder's PHASE 4 gitignore check +also appends `!.claude/rules/` after an existing `.claude/*` line +(the socle covers gitflow-init projects; this covers the rest). The +scaffolder's `.gitignore` is reconciled by STEP 5f `gitflow init` before +the root commit, so the socle line lands first (LRN-066, BLK-010). +`templates/project-CLAUDE.md` keeps every section (commands stay always-on); +its header comment gains one line naming `.claude/rules/`. + +## 5. Cleanup and citers + +- `rules/README.md:9` → "see `.claude/rules/rules-maintenance.md` in the + claude-config repo". +- `doctor.sh:76` comment: "the project CLAUDE.md" (drop "29-line"). +- `ARCHITECTURE.md` tree gains `.claude/rules/` (doc pipeline, STEP 8). +- `install-plugins.sh` GUARDED_CONFIGS unchanged: `graphify claude install` + still rewrites CLAUDE.md and the trap still reverts it. +- `.claude/tasks/TODO.md`: phase 0 item updated (done parts, per-repo pass + queued as its own item with the repo order). +- Registries append-only: BDR-065 and LRN-154 keep their old location text. +- Manual step (user): `claude mcp remove -s user higgsfield`; journal line. + +## 6. Testing and proof + +- `make test` green (new suite + gitflow-test socle assertion + hook test). +- `shellcheck *.sh hooks/*.sh lib/*.sh` clean. +- `project-rules.sh check` exit 0 on this repo. +- `/context` before/after at the repo root; the four `path_glob_match` + log lines from one real session. +- RED → GREEN pressure test transcript summary for `/onboard split`. + +## 7. Out of scope, risks kept + +- The per-repo pass (six repos) and whether path rules load inside + sub-agents: measured on faunosteo first, during that pass. +- A `paths:` rule loads on Read, not on Write of a new file: generator + rules load once the scaffolded file is edited (Edit needs a Read). +- The pre-commit `.claude/**` exemption lets a rules-only commit land on + develop; split mode always branches first. From 420448a93b40a9f1cf71976d17c017fcb9970767 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 01:16:50 +0100 Subject: [PATCH 02/17] docs(plan): phase 0 claude-md split implementation plan --- .../plans/2026-10-26-claude-md-split.md | 1067 +++++++++++++++++ 1 file changed, 1067 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-26-claude-md-split.md diff --git a/docs/superpowers/plans/2026-10-26-claude-md-split.md b/docs/superpowers/plans/2026-10-26-claude-md-split.md new file mode 100644 index 0000000..ea8b280 --- /dev/null +++ b/docs/superpowers/plans/2026-10-26-claude-md-split.md @@ -0,0 +1,1067 @@ +# Phase 0 — split project CLAUDE.md into `.claude/rules/` — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Move the four path-bound sections of this repo's project CLAUDE.md into `.claude/rules/.md` path rules, prove they load, and give every project the same lever (`/onboard split`, generators born split). + +**Architecture:** One bash lib (`lib/project-rules.sh`: `check`, `sections`, `extract`, `emit`) is the deterministic oracle for every consumer: the `make test` suite, this repo's own split, the onboarder in `MODE: split`, and the two generators. Judgment (which section is path-scoped, which globs) stays in the `/onboard split` main loop; writes are executed by the sonnet onboarder. A permanent `InstructionsLoaded` hook logs every loaded instruction file so a path-rule load is a grep, not a guess. + +**Tech Stack:** bash 5 (globstar), awk, jq, shellcheck; markdown skills/agents; Claude Code path-scoped rules (`paths:` frontmatter) and the `InstructionsLoaded` classic hook. + +**Spec:** `docs/superpowers/specs/2026-10-26-claude-md-split-design.md` +**Contract:** `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md` +**Branch:** `feature/claude-md-split` (already started off develop, spec committed 2c8e4a2). + +Spec delta, decided while planning: a fourth subcommand `emit ` (the spec's "emit only skeletons whose globs match" needs a per-glob prune the sonnet generators cannot do by hand; `emit` writes the rule with the matching globs only, so the strict "each glob matches" check still holds). + +## Global Constraints + +- Our code (strict): max 25 logic lines per function, 80 chars per line, 5 params, 5 locals; `shellcheck *.sh hooks/*.sh lib/*.sh` clean. +- Subtract-only: section text moves verbatim; nothing deleted from CLAUDE.global.md / rules/; registries (`.claude/memory/*`) are never edited by a task (STEP 7 capitalize owns them). +- Never write into `rules/` (user scope, every project) except the one pointer fix in `rules/README.md`. +- `.gitignore` negations only work with the `.claude/*` file form (BDR-003); the negation line must come AFTER `.claude/*`. +- Hooks never print to stdout (stdout reaches the model) and never block. +- Commit on the feature branch only, one commit per task, message under 50 words, no attribution lines. +- Frontmatter shape is exactly `paths: ["glob", "glob"]` on one line (as `rules/a11y.md`). +- Commands with a shell variable in the path are denied by the permission rules in this repo: write literal paths in every Bash step. + +## Review Focus + +1. A heading inside a fenced code block in CLAUDE.md (` ```\n## x\n``` `) must not be read as a section by `sections`/`extract` (test T6 in Task 1). +2. `extract` on a heading that is absent, or onto a rule file that already exists, must write nothing and exit 2 (test T8 in Task 1). +3. A glob with a typo (`skils/**`) must fail `check` with the culprit named, and the skip marker must only silence globs of its own file (tests T2, T4 in Task 1). +4. `emit` on a project where only some globs of a skeleton match must keep exactly the matching ones; none matching → nothing written, rc 1 (test T12 in Task 7). +5. The hook must exit 0 and print nothing when `jq` is absent or the log dir is unwritable, so a broken log never reaches the model (test T10f in Task 2). + +--- + +### Task 1: `lib/project-rules.sh` + its suite (check / sections / extract) + +**Files:** +- Create: `lib/project-rules.sh` +- Create: `lib/tests/project-rules.test.sh` + +**Interfaces:** +- Produces: `bash lib/project-rules.sh check [dir]` (rc 0 + `project-rules: N rule(s) ok`; rc 2 + `: ` lines; `: SKIP ` lines for a skip-marked file); `sections ` (`\t\t## ` per top-level section); `extract "" ''` (rc 0 moved; rc 2 heading absent / target exists / malformed globs, nothing written). Functions are sourceable (`source lib/project-rules.sh`; main guarded by `BASH_SOURCE`). + +- [ ] **Step 1: Write the failing suite (T1-T9)** + +Create `lib/tests/project-rules.test.sh`: + +```bash +#!/usr/bin/env bash +# lib/tests/project-rules.test.sh — lib/project-rules.sh (check / sections / +# extract / emit) and hooks/instructions-loaded.sh. Flip-tests on fixtures +# first (LRN-096), then the real check on this repo's .claude/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 +echo x > src/app.ts + +# 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 +rm .claude/rules/bad.md + +# T3 missing frontmatter fails +printf '# No front\nbody\n' > .claude/rules/nofm.md +out=$(bash "$PR" check); rc=$? +check T3-missing-frontmatter-fails "$rc" 2 +check T3b-named "$(printf '%s\n' "$out" | grep -c 'nofm.md: no frontmatter')" 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 +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 + +# T6 sections lists headings with sizes, fence-aware +cat > CLAUDE.md <<'EOF' +# Proj + +## Alpha +aaa + +--- + +## Beta +``` +## not a heading +``` +bbb +EOF +out=$(bash "$PR" sections CLAUDE.md) +check T6-two-sections "$(printf '%s\n' "$out" | wc -l | tr -d ' ')" 2 +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 + +# 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 + +# T8 extract refuses a missing heading and an existing target, writes nothing +bash "$PR" extract CLAUDE.md "Alpha" .claude/rules/alpha2.md '["src/**"]' 2>/dev/null +check T8-missing-heading-rc "$?" 2 +check T8b-nothing-written "$(ls .claude/rules | wc -l | tr -d ' ')" 1 +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 + +# T9 extract refuses a malformed globs argument +bash "$PR" extract CLAUDE.md "Beta" .claude/rules/beta.md 'src/**' 2>/dev/null +check T9-bad-globs-rc "$?" 2 +check T9b-nothing-written "$(ls .claude/rules/beta.md 2>/dev/null | wc -l | tr -d ' ')" 0 + +echo "PASS=$pass FAIL=$fail" +[ "$fail" -eq 0 ] +``` + +(T6c: the Alpha section spans `## Alpha`, `aaa`, blank, `---`, blank; each line counts its length plus one newline: 9+4+1+4+1 = 19.) + +- [ ] **Step 2: Run the suite, verify it fails** + +Run: `bash lib/tests/project-rules.test.sh` +Expected: many `FAIL …` lines (the lib does not exist), last line `PASS=0 FAIL=…`, exit 1. + +- [ ] **Step 3: Write the lib** + +Create `lib/project-rules.sh`: + +```bash +#!/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: +# check [dir] frontmatter parses, every glob matches ≥1 path (rc 2) +# sections "\t\t## " per top-level section +# extract move one section to a rule +# emit write the rule with the globs that match (rc 1 +# when none matches, nothing written) +# Globs match the WORKING TREE (globstar, dotglob, through symlinks): 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 (docs/superpowers/**). +set -uo pipefail + +_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" +} + +_rules_globs() { # → one glob per line, rc 1 if no paths: + local line + line=$(printf '%s\n' "$1" | grep -E '^paths: *\[.*\] *$') || return 1 + printf '%s\n' "$line" | grep -oE '"[^"]+"' | tr -d '"' +} + +_rules_glob_matches() { # → rc 0 when ≥1 path exists in the tree + local -a hits + shopt -s globstar dotglob nullglob + # shellcheck disable=SC2206 # the glob MUST expand: that is the test + hits=( $1 ) + shopt -u globstar dotglob nullglob + [ "${#hits[@]}" -gt 0 ] +} + +_rules_matching() { # → JSON array of the matching ones + local g out="" + while IFS= read -r g; do + [ -n "$g" ] && _rules_glob_matches "$g" && out="$out, \"$g\"" + done <<< "$1" + [ -n "$out" ] || return 1 + printf '[%s]\n' "${out#, }" +} + +_rules_check_file() { # → rc 0 ok, rc 1 with the culprit lines + local fm globs skip=0 g bad=0 + fm=$(_rules_frontmatter "$1") || { echo "$1: no frontmatter"; return 1; } + globs=$(_rules_globs "$fm") || { echo "$1: no paths: array"; return 1; } + printf '%s\n' "$fm" | grep -qx '# static-check: skip' && skip=1 + while IFS= read -r g; do + [ -n "$g" ] || continue + if [ "$skip" = 1 ]; then echo "$1: SKIP $g"; continue; fi + _rules_glob_matches "$g" || { echo "$1: glob matches nothing: $g"; bad=1; } + done <<< "$globs" + [ "$bad" = 0 ] +} + +project_rules_check() { # [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_sections() { # → "\t\t## " + [ -f "$1" ] || { echo "project-rules: $1 not found" >&2; return 2; } + awk ' + /^```/ { fence = !fence } + /^## / && !fence { if (h != "") printf "%d\t%d\t%s\n", c, l, h + h = $0; l = NR; c = 0 } + h != "" { c += length($0) + 1 } + END { if (h != "") printf "%d\t%d\t%s\n", c, l, h }' "$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" +} + +project_rules_extract() { # + local src="$1" heading="$2" out="$3" globs="$4" tmp + grep -qxF -- "## $heading" "$src" \ + || { echo "project-rules: heading not found: ## $heading" >&2; return 2; } + [ -e "$out" ] && { echo "project-rules: $out exists" >&2; return 2; } + _rules_globs "paths: $globs" >/dev/null \ + || { echo "project-rules: globs must be a JSON array: $globs" >&2; return 2; } + mkdir -p "$(dirname "$out")" + { printf -- '---\npaths: %s\n---\n\n# %s\n' "$globs" "$heading" + _rules_section_body "$src" "$heading"; } > "$out" + tmp=$(mktemp) + _rules_without_section "$src" "$heading" > "$tmp" && cat "$tmp" > "$src" + 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 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() { + case "${1:-}" in + check) project_rules_check "${2:-.claude/rules}" ;; + sections) project_rules_sections "${2:?CLAUDE.md path}" ;; + 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 check [dir] | sections " \ + "| extract " \ + "| emit " >&2; return 2 ;; + esac +} + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then _project_rules_main "$@"; fi +``` + +- [ ] **Step 4: Run the suite, verify T1-T9 pass** + +Run: `bash lib/tests/project-rules.test.sh` +Expected: `PASS=33 FAIL=0`, exit 0 (count may differ by one or two; the invariant is `FAIL=0`). + +- [ ] **Step 5: shellcheck + make test on the new suite** + +Run: `shellcheck lib/project-rules.sh lib/tests/project-rules.test.sh && make test suite=lib/tests/project-rules.test.sh` +Expected: no shellcheck output; `all suites green`. + +- [ ] **Step 6: Commit** + +```bash +git add lib/project-rules.sh lib/tests/project-rules.test.sh +git commit -m "feat(rules): lib/project-rules.sh check/sections/extract/emit + suite" +``` + +--- + +### Task 2: InstructionsLoaded proof hook + +**Files:** +- Create: `hooks/instructions-loaded.sh` +- Modify: `settings.json` (hooks block, after `"SessionStart": [...]`, line ~374) +- Modify: `lib/tests/project-rules.test.sh` (append T10 before the tally) + +**Interfaces:** +- Produces: one JSON line per loaded instruction file in `~/.claude/logs/instructions-loaded.jsonl` (`ts, cwd, file_path, memory_type, load_reason, trigger_file_path`); `CLAUDE_INSTRUCTIONS_LOG=` overrides the log path (tests). + +- [ ] **Step 1: Append the failing hook tests (T10) to the suite** + +Insert before the `echo "PASS=$pass FAIL=$fail"` line of `lib/tests/project-rules.test.sh`: + +```bash +# 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","cwd":"/p","file_path":"/p/.claude/rules/x.md","memory_type":"Project","load_reason":"path_glob_match","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-trigger-kept "$(jq -r '.trigger_file_path' "$LOG")" /p/src/a.ts +out=$(printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG=/proc/nowhere/il.jsonl bash "$HOOK"); rc=$? +check T10f-unwritable-log-still-rc0 "$rc" 0 +check T10g-unwritable-log-stdout-empty "$out" "" +``` + +- [ ] **Step 2: Run the suite, verify T10 fails** + +Run: `bash lib/tests/project-rules.test.sh` +Expected: `FAIL T10-hook-rc` (hook missing), exit 1. + +- [ ] **Step 3: Write the hook** + +Create `hooks/instructions-loaded.sh`: + +```bash +#!/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` with the file that triggered it. +# Never blocks, never prints to stdout (stdout reaches the model), exits 0 +# whatever happens. 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 +jq -c --arg ts "$(date -u +%FT%TZ)" \ + '{ts: $ts, cwd, file_path, memory_type, load_reason, trigger_file_path}' \ + >> "$log" 2>/dev/null +exit 0 +``` + +- [ ] **Step 4: Register it in `settings.json`** + +In `settings.json`, after the `"SessionStart": [ ... ],` block (the `],` that closes it, just before `"PreToolUse": [`), insert: + +```json + "InstructionsLoaded": [ + { + "hooks": [ + { + "type": "command", + "command": "bash ~/.claude/hooks/instructions-loaded.sh", + "timeout": 5 + } + ] + } + ], +``` + +Verify: `jq '.hooks.InstructionsLoaded[0].hooks[0].command' settings.json` prints `"bash ~/.claude/hooks/instructions-loaded.sh"`. + +- [ ] **Step 5: Run the suite, verify T10 passes** + +Run: `bash lib/tests/project-rules.test.sh && shellcheck hooks/instructions-loaded.sh` +Expected: `FAIL=0`, no shellcheck output. + +- [ ] **Step 6: Commit** + +```bash +git add hooks/instructions-loaded.sh settings.json lib/tests/project-rules.test.sh +git commit -m "feat(hooks): InstructionsLoaded logger, the proof channel for path rules" +``` + +--- + +### Task 3: gitignore negation, here and in the socle + +**Files:** +- Modify: `.gitignore:122-126` +- Modify: `templates/gitignore/standard.gitignore` (the `.claude/*` block) +- Modify: `lib/gitflow-test.sh:47` (one more socle assertion) + +- [ ] **Step 1: Add the failing socle assertion** + +In `lib/gitflow-test.sh`, after line 47 (`chk "socle: !.claude/deploy/" …`), add: + +```bash +chk "socle: !.claude/rules/" 'grep -qxF "!.claude/rules/" .gitignore' +``` + +- [ ] **Step 2: Run gitflow-test, verify the new assertion fails** + +Run: `make test suite=lib/gitflow-test.sh 2>&1 | grep -E 'rules|suite'` +Expected: `FAIL socle: !.claude/rules/ …` and `1 suite(s) red`. + +- [ ] **Step 3: Patch the socle and this repo's `.gitignore`** + +`templates/gitignore/standard.gitignore`: after the line `!.claude/deploy/` add the line `!.claude/rules/` (it must stay after `.claude/*`; reconcile appends missing lines at the end of a project's file, which is after any existing `.claude/*`). + +`.gitignore`: after line 122 `.claude/*` and its negations, add `!.claude/rules/` directly after `!.claude/settings.json` (line 126): + +``` +.claude/* +!.claude/tasks/ +!.claude/memory/ +!.claude/audits/ +!.claude/settings.json +!.claude/rules/ +``` + +- [ ] **Step 4: Verify** + +Run: `make test suite=lib/gitflow-test.sh 2>&1 | tail -2 && mkdir -p .claude/rules && touch .claude/rules/.probe && git check-ignore -v .claude/rules/.probe; echo "rc=$?"; rm .claude/rules/.probe` +Expected: `all suites green`; `git check-ignore` prints nothing and `rc=1` (not ignored). + +- [ ] **Step 5: Commit** + +```bash +git add .gitignore templates/gitignore/standard.gitignore lib/gitflow-test.sh +git commit -m "chore(gitignore): un-ignore .claude/rules/ here and in the gitflow socle" +``` + +--- + +### Task 4: split this repo's CLAUDE.md (dogfood `extract`) + +**Files:** +- Modify: `CLAUDE.md` (four sections leave, a pointer section arrives) +- Create: `.claude/rules/rules-maintenance.md`, `.claude/rules/graphify-vendored.md`, `.claude/rules/mods.md`, `.claude/rules/transient-artifacts.md` +- Modify: `lib/tests/project-rules.test.sh` (append T11 before the tally) + +**Interfaces:** +- Consumes: `lib/project-rules.sh extract` / `check` (Task 1). + +- [ ] **Step 1: Append the failing real-repo test (T11)** + +Insert before the `echo "PASS=$pass FAIL=$fail"` line of `lib/tests/project-rules.test.sh`: + +```bash +# T11 the real rules of this repo pass the check (4 rules, 1 skip-marked) +out=$(cd "$ROOT" && bash "$PR" 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 +``` + +Run: `bash lib/tests/project-rules.test.sh | tail -4` +Expected: `FAIL T11b-four-rules: got[0] want[1]` (0 rules yet). + +- [ ] **Step 2: Move the four sections with `extract`** + +From the repo root, in this order (headings are exact, copied from CLAUDE.md): + +```bash +bash lib/project-rules.sh extract CLAUDE.md "rules/ maintenance" .claude/rules/rules-maintenance.md '["rules/**", "CLAUDE.global.md"]' +bash lib/project-rules.sh extract CLAUDE.md "Machine-owned: the vendored graphify skill" .claude/rules/graphify-vendored.md '["skills/graphify/**", "install-plugins.sh", ".graphify_version"]' +bash lib/project-rules.sh extract CLAUDE.md "mods/ — function-hooks plugins (Claude Code mods)" .claude/rules/mods.md '["mods/**", "skills/model-router/**", "lib/tests/mods.test.sh"]' +bash lib/project-rules.sh extract CLAUDE.md "Transient planning artifacts" .claude/rules/transient-artifacts.md '["docs/superpowers/**", ".audit/**"]' +``` + +Expected: four `project-rules: moved "## …" to .claude/rules/….md` lines. `git diff --stat CLAUDE.md` shows about 90 deletions and no insertion. + +- [ ] **Step 3: Skip marker on the transient rule** + +Edit `.claude/rules/transient-artifacts.md`: between the `paths:` line and the closing `---`, insert the line `# static-check: skip`. The file starts: + +``` +--- +paths: ["docs/superpowers/**", ".audit/**"] +# static-check: skip +--- + +# Transient planning artifacts +``` + +- [ ] **Step 4: The pointer section in CLAUDE.md** + +CLAUDE.md now holds only the title and `## Health Stack`. 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): rules-maintenance, +graphify-vendored, mods, transient-artifacts. Check: `bash +lib/project-rules.sh check` (runs in `make test`). +``` + +The whole file must then read: + +```markdown +# claude-config — project instructions + +## Health Stack +- shell: `shellcheck *.sh hooks/*.sh lib/*.sh` + +## 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`). +``` + +(Remove any run of more than one blank line left by the extraction.) + +- [ ] **Step 5: Verify verbatim move and the check** + +Run: +```bash +git show HEAD:CLAUDE.md | sed -n '/^## rules\/ maintenance$/,/^## Machine-owned/p' | sed '1d;$d' | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/old-rules.txt +sed -n '6,$p' .claude/rules/rules-maintenance.md | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/new-rules.txt +diff /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/old-rules.txt /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/new-rules.txt && echo VERBATIM +bash lib/project-rules.sh check +bash lib/tests/project-rules.test.sh | tail -1 +git status --short .claude/rules +``` +Expected: `VERBATIM`; `transient-artifacts.md: SKIP docs/superpowers/**`, `… SKIP .audit/**`, `project-rules: 4 rule(s) ok`; `PASS=… FAIL=0`; four `??`/`A` entries under `.claude/rules/` (tracked thanks to Task 3). + +- [ ] **Step 6: Commit** + +```bash +git add CLAUDE.md .claude/rules lib/tests/project-rules.test.sh +git commit -m "refactor(claude-md): four sections become .claude/rules path rules (phase 0)" +``` + +--- + +### Task 5: citers of the moved sections + +**Files:** +- Modify: `rules/README.md:7-9` +- Modify: `doctor.sh:76` + +- [ ] **Step 1: Repoint `rules/README.md`** + +Replace lines 7-9: + +``` +Maintenance doctrine (what belongs here, lazy-load `paths:` semantics, +machine-owned files): see `CLAUDE.md` (project scope) at the repo root. +``` + +with: + +``` +Maintenance doctrine (what belongs here, lazy-load `paths:` semantics, +machine-owned files): see `.claude/rules/rules-maintenance.md` in the +claude-config repo (project scope, loads on Read under `rules/`). +``` + +- [ ] **Step 2: Fix the stale doctor comment** + +`doctor.sh:76`: replace `(the 29-line project CLAUDE.md instead of` with `(the project CLAUDE.md instead of`. + +- [ ] **Step 3: Census grep** + +Run: +```bash +grep -rnE 'CLAUDE\.md \(project scope\)|29-line project CLAUDE\.md|Machine-owned: the vendored|§ ?Transient planning|"rules/ maintenance"|"mods/ — function-hooks"' rules/ doctor.sh skills/ agents/ lib/ hooks/ README.md ARCHITECTURE.md --include='*.md' --include='*.sh' | grep -v 'skills-external\|skills/graphify/\|lib/tests/project-rules' +``` +Expected: no output. (`lib/gitflow.sh:21` says "transient planning artifacts" in a comment about the purge, not as a citation: leave it. `install-plugins.sh` GUARDED_CONFIGS keeps `CLAUDE.md`: leave it. `ARCHITECTURE.md` is the doc pipeline's, STEP 8.) + +- [ ] **Step 4: make test + commit** + +Run: `make test suite=lib/tests/doctrine-citers.test.sh | tail -2` +Expected: `all suites green`. + +```bash +git add rules/README.md doctor.sh +git commit -m "chore(citers): rules/README and doctor point at .claude/rules after the split" +``` + +--- + +### Task 6: `/onboard split` RED pressure test (orchestrator dispatch, no code) + +**Files:** none modified. Scratch: `/tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/` (a git repo holding `CLAUDE.md` = `git show develop:CLAUDE.md`, plus `rules/x.md`, `mods/m/plugin.json`, `.gitignore` with `.claude/*`). + +- [ ] **Step 1: Build the scratch repo** + +```bash +S=/tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red +mkdir -p "$S/rules" "$S/mods/m" "$S/.claude" && git show develop:CLAUDE.md > "$S/CLAUDE.md" && echo r > "$S/rules/x.md" && echo '{}' > "$S/mods/m/plugin.json" && printf '.claude/*\n!.claude/memory/\n' > "$S/.gitignore" && git -C "$S" init -q && git -C "$S" add -A && git -C "$S" commit -qm init +``` + +(The denied-variable rule: run it as ONE line with the literal path substituted for `$S`.) + +- [ ] **Step 2: Dispatch the RED probe (sonnet)** + +`Agent(subagent_type="general-purpose", model="sonnet", effort="medium")` with: "You are executing the skill at `/home/bchanot/.claude/skills/onboard/SKILL.md` with `$ARGUMENTS` = `split`, working directory ``. Read the skill, then do exactly what it tells you for its first three steps, in the scratch directory only; do not dispatch agents, do not run `claude`, do not write outside the scratch. Stop after the third step and report: which steps you ran, whether any step asked you to classify CLAUDE.md sections into path-scoped rules, and what you would have produced." + +Expected (RED): the report names MODEL GATE / plugin check / archetype detection; no classification table, no `.claude/rules/` written. Record one line in the plan's commit message of Task 7 ("RED: current skill runs archetype detection on `split`"). + +If the probe DOES produce a split with the current skill: stop, the mode is unnecessary as designed; re-plan. + +--- + +### Task 7: `/onboard split` mode + onboarder `MODE: split` + +**Files:** +- Modify: `skills/onboard/SKILL.md` (frontmatter lines 4-5, after `## REQUEST` ~line 20, RULES line ~1037, append § SPLIT MODE after FINAL OUTPUT) +- Modify: `agents/onboarder.md` (after `## INPUTS`, before `## PHASE 1`; and a new section after PHASE 6) + +**Interfaces:** +- Consumes: `project-rules.sh sections|extract|check` (Task 1). +- Produces: the onboarder `MODE: split` contract: INPUTS `PROJECT_ROOT`, `TABLE` rows ` | | `; OUTPUT rules written, check result, commit hash. + +- [ ] **Step 1: Skill frontmatter** + +Line 4 `description:` — append inside the quoted string, before the closing `'`: ` `split` mode: "split CLAUDE.md", "découpe le CLAUDE.md", "path-scoped rules", "move sections to .claude/rules".` +Line 5: `argument-hint: '[split | optional hints: "Python FastAPI" | "Next.js monorepo" | "force-archetype:wordpress"]'` + +- [ ] **Step 2: MODE DISPATCH after `## REQUEST`** + +After the `$ARGUMENTS` line of `## REQUEST` and its `---`, insert: + +```markdown +## 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 3: RULES line** + +Replace `- NO skipping STEP 0, 1, 2 — ils sont obligatoires.` with `- NO skipping STEP 0, 1, 2 — ils sont obligatoires (split mode runs its own steps, § SPLIT MODE).` + +- [ ] **Step 4: § SPLIT MODE appended at the end of the skill** + +```markdown + +--- + +## 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 oracle. The MODEL GATE above +has run. `mcp__model-router__route(phase="plan")` first. + +S1 — PRECONDITIONS. `CLAUDE.md` at the project root, else print +`nothing to split — run /onboard` and stop. `git status --porcelain +CLAUDE.md` empty, else stop (an in-flight edit would be lost). `.claude/rules/` +already holding rules → list them, continue (new rules add to them). + +S2 — BASELINE. Run `claude -p "/context"` at the root (refused → ask the +user to run `! claude -p "/context"`); note the `Memory files` total and the +project CLAUDE.md row. + +S3 — CLASSIFY. `bash ~/.claude/lib/project-rules.sh 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; +- 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 from `git ls-files` (a folder → `dir/**`, + a tool → its config files), and verify every proposed glob with + `git ls-files ''` (≥1 line) before showing it. + Sections that are needed before any file is read (how to run the project) + stay always-on even when they name a folder. + +S4 — GATE (mandatory stop). Print the table, then end the turn: + +``` +SPLIT — CLAUDE.md ( chars, sections) +| # | 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. The approved rows are the +TABLE handed to the onboarder, verbatim. + +S5 — BRANCH. `bash ~/.claude/lib/gitflow.sh start chore claude-md-split`. +A project without gitflow (no `develop`): `git switch -c chore/claude-md-split` +and say so. + +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 extracts each row, writes the pointer section, adds the +gitignore negation, runs `check`, commits. A STOP report (heading absent, +target exists, check red) comes back here: fix the row, re-dispatch; rows +already moved stay moved. + +S7 — AFTER. `claude -p "/context"` again; 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 `grep path_glob_match ~/.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 + grep path_glob_match +``` +``` + +- [ ] **Step 5: Onboarder: mode header + `MODE: split` section** + +In `agents/onboarder.md`, insert right after `## ROLE`'s paragraph (before the `---` that precedes `## INPUTS`): + +```markdown +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. +``` + +Append at the end of the file: + +```markdown + +--- + +## MODE: split (dispatched by `/onboard split`) + +INPUTS: `PROJECT_ROOT` (absolute), `TABLE` = the approved rows, one per +line, ` | | ` (heading without `## `). No +BRIEF; PHASES 1-6 do not run. + +S1 — EXTRACT. From `${PROJECT_ROOT}`, per row: +```bash +bash ~/.claude/lib/project-rules.sh extract CLAUDE.md "" .claude/rules/.md '' +``` +rc 2 (heading absent, target exists, malformed globs) → STOP and report +the row; rows already moved stay (the orchestrator re-dispatches the rest). + +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. Collapse runs of blank lines left by +the extraction (never more than one). + +S3 — GITIGNORE. When `.gitignore` has the exact line `.claude/*` and no +`!.claude/rules/` line: +```bash +sed -i '\|^\.claude/\*$|a !.claude/rules/' .gitignore +``` +(No `.claude/*` line → the rules are not ignored, nothing to add.) + +S4 — CHECK + COMMIT. +```bash +bash ~/.claude/lib/project-rules.sh check +``` +rc ≠ 0 → STOP, report the culprit lines, do not commit. rc 0 → +```bash +git add CLAUDE.md .claude/rules .gitignore +git commit -m "chore(claude-md): split section(s) into .claude/rules/" +``` + +OUTPUT: +``` +SPLIT DONE: rule(s) — .md (), … +CLAUDE.md: → lines +CHECK : project-rules: rule(s) ok +COMMIT : +``` +or `STOP: — `. +``` + +- [ ] **Step 6: Locks still hold** + +Run: `make test suite=lib/tests/model-routing.test.sh && make test suite=lib/tests/effort-routing.test.sh && make test suite=lib/tests/loops-heavy.test.sh && make test suite=lib/tests/plan-challenger.test.sh && make test suite=lib/tests/security-auditor.test.sh && make test suite=lib/tests/doctrine-citers.test.sh` +Expected: `all suites green` six times. + +- [ ] **Step 7: Commit** + +```bash +git add skills/onboard/SKILL.md agents/onboarder.md +git commit -m "feat(onboard): split mode — classify CLAUDE.md sections, onboarder MODE: split executes (RED: current skill ran archetype detection on 'split')" +``` + +--- + +### Task 8: `/onboard split` GREEN pressure test (orchestrator dispatch, no code) + +- [ ] **Step 1: Reset the scratch repo** + +`git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red checkout -- . && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red clean -fdq` + +- [ ] **Step 2: Dispatch the GREEN probe (sonnet, same prompt as Task 6 Step 2)** + +Expected (GREEN): the report says it jumped to § SPLIT MODE, ran S1-S3, and produced the classification table (at least `rules/ maintenance` → move with `rules/**`, `Health Stack` → keep), then stopped at the S4 gate without writing. A probe that writes files or skips the gate = not green: fix the skill text, re-run. + +- [ ] **Step 3: Executor dry run (sonnet onboarder, MODE: split) on the scratch** + +Dispatch `Agent(subagent_type="onboarder")` with `MODE: split`, `PROJECT_ROOT: `, `TABLE:` two rows: `rules/ maintenance | rules-maintenance | ["rules/**"]` and `mods/ — function-hooks plugins (Claude Code mods) | mods | ["mods/**"]`. +Expected: `SPLIT DONE: 2 rule(s)`, a commit in the scratch repo, `.gitignore` there gained `!.claude/rules/`, and `bash lib/project-rules.sh check` run from the scratch root prints `2 rule(s) ok`. + +- [ ] **Step 4: Record** + +No commit. The orchestrator notes RED/GREEN outcomes for STEP 7 capitalize (EVAL entry). + +--- + +### Task 9: generators born split (skeletons, `emit`, onboarder PHASE 1b + PHASE 4, scaffolder PHASE 1b) + +**Files:** +- Create: `templates/project-rules/docker.md`, `templates/project-rules/testing.md`, `templates/project-rules/ci.md` +- Modify: `templates/project-CLAUDE.md:3-4` (header comment) +- Modify: `agents/onboarder.md` (new PHASE 1b after PHASE 1; PHASE 4 gains the negation) +- Modify: `agents/scaffolder.md` (new PHASE 1b after PHASE 1) +- Modify: `lib/tests/project-rules.test.sh` (append T12 before the tally) + +**Interfaces:** +- Consumes: `project-rules.sh emit ` (Task 1): rc 0 written with matching globs only, rc 1 none matched (nothing written), rc 2 malformed / target exists. + +- [ ] **Step 1: Append the failing skeleton tests (T12)** + +Insert before the tally line of the suite: + +```bash +# 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 "$(ls .claude/rules/ci.md 2>/dev/null | wc -l | tr -d ' ')" 0 +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 +``` + +Run: `bash lib/tests/project-rules.test.sh | tail -3` +Expected: `FAIL T12-docker-emitted` (skeleton missing). + +- [ ] **Step 2: The three skeletons** + +`templates/project-rules/docker.md`: +```markdown +--- +paths: ["Dockerfile*", "docker-compose*", "compose*.y*ml", ".dockerignore"] +--- + +# Docker + + + + + +``` + +`templates/project-rules/testing.md`: +```markdown +--- +paths: ["tests/**", "test/**", "**/*.test.*", "**/*.spec.*", "**/conftest.py"] +--- + +# Testing conventions + + + + + +``` + +`templates/project-rules/ci.md`: +```markdown +--- +paths: [".github/workflows/**", ".gitlab-ci.yml", ".circleci/**"] +--- + +# CI + + + + + +``` + +`templates/project-CLAUDE.md` line 4: after `# Global rules: ~/.claude/CLAUDE.md — this file extends or overrides them.` add the line `# Path-scoped rules: .claude/rules/.md (paths: frontmatter), loaded on Read of a matching file.` + +- [ ] **Step 3: Onboarder PHASE 1b + PHASE 4 negation** + +In `agents/onboarder.md`, after the PHASE 1 block (after `For Option C (monorepo sequential): path = ${package_root}/CLAUDE.md.` and before its `---`), add: + +```markdown + +## PHASE 1b — PATH-SCOPED RULES (born split) + +From `${PROJECT_ROOT}`, for each of `docker`, `testing`, `ci`: +```bash +bash ~/.claude/lib/project-rules.sh emit ~/.claude/templates/project-rules/.md .claude/rules/.md +``` +- rc 0 → written with the globs that match this tree. Fill its stub comments + from the BRIEF where known (`docker` from `build_cmd`, `testing` from + `test_cmd` and `conventions`); unknown → keep the stubs. +- rc 1 → no match, nothing written, skip silently. +- rc 2 → the file exists: keep it, never overwrite. +Then `bash ~/.claude/lib/project-rules.sh check` must print `N rule(s) ok`; +list the emitted rules in OUTPUT. +``` + +In PHASE 4, replace the three bullets with: + +```markdown +- **`.gitignore` exists AND contains `settings.local.json`** → nothing to do for it. +- **`.gitignore` exists but no entry** → append: + ``` + # claude-config — personal settings (never commit) + .claude/settings.local.json + ``` +- **`.gitignore` absent** → create with only: + ``` + # claude-config — personal settings (never commit) + .claude/settings.local.json + ``` +- Then, whatever the case: when `.gitignore` has the exact line `.claude/*` + and no `!.claude/rules/` line, add the negation right after it (PHASE 1b + rules would be ignored otherwise, LRN-066): + ```bash + sed -i '\|^\.claude/\*$|a !.claude/rules/' .gitignore + ``` +``` + +- [ ] **Step 4: Scaffolder PHASE 1b** + +In `agents/scaffolder.md`, after PHASE 1 (`Write to CLAUDE.md at project root.`), before its `---`, add: + +```markdown + +## PHASE 1b — PATH-SCOPED RULES (born split) + +Runs AFTER PHASE 3 has written the files (the globs match the scaffolded +tree). For each of `docker` (only when DOCKER_RELEVANT), `testing`, `ci`: +```bash +bash ~/.claude/lib/project-rules.sh emit ~/.claude/templates/project-rules/.md .claude/rules/.md +``` +rc 0 → fill its stubs from the DESIGN (image, compose services, test +layout, pipeline jobs); rc 1 → nothing matched, skipped. Then +`bash ~/.claude/lib/project-rules.sh 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. +``` + +- [ ] **Step 5: Verify** + +Run: `bash lib/tests/project-rules.test.sh | tail -1 && cd /tmp && mkdir -p /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/.github/workflows && cd /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all && touch Dockerfile docker-compose.yml compose.yaml .dockerignore .gitlab-ci.yml && mkdir -p tests test .circleci && touch tests/a test/b a.test.ts b.spec.ts conftest.py .github/workflows/ci.yml .circleci/config.yml && bash /home/bchanot/Documents/claude/lib/project-rules.sh check /home/bchanot/Documents/claude/templates/project-rules` +Expected: `PASS=… FAIL=0`; `project-rules: 3 rule(s) ok` (every skeleton glob is syntactically sound). + +- [ ] **Step 6: Commit** + +```bash +git add templates/project-rules templates/project-CLAUDE.md agents/onboarder.md agents/scaffolder.md lib/tests/project-rules.test.sh +git commit -m "feat(generators): onboarder and scaffolder emit docker/testing/ci path rules from templates/project-rules" +``` + +--- + +### Task 10: TODO.md phase 0 bookkeeping + full suite + +**Files:** +- Modify: `.claude/tasks/TODO.md:20-30` (the phase 0 item) + +- [ ] **Step 1: Update the phase 0 item** + +Replace the `- [ ] **Phase 0, no mod: split project CLAUDE.md**` block (lines 20-30) with: + +```markdown +- [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/sections/extract/emit + suite, `hooks/instructions-loaded.sh` (log `~/.claude/logs/instructions-loaded.jsonl`), `!.claude/rules/` here + socle, `/onboard split` + onboarder `MODE: split`, generators emit docker/testing/ci from `templates/project-rules/`. Baseline `/context` 32.2k (project CLAUDE.md 2.1k). + - [ ] Proof, this repo: `/context` after the merge; one fresh session Reading one file per rule → 4 `path_glob_match` lines in the log, pasted 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 0b, per-repo pass** (after phase 0 merges; via `/onboard split`, one `chore/claude-md-split` per repo, approval per repo, never an automatic merge; `/context` before/after in that repo's journal; faunosteo first and measure whether path rules load inside sub-agents before moving anything a sub-agent needs). Order by size: faunosteo 52,322 chars (on feature/v1-1-clients-animals: wait for it or branch off develop and rebase), 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). +``` + +- [ ] **Step 2: Full suite + shellcheck** + +Run: `make test 2>&1 | tail -3 && shellcheck ./*.sh hooks/*.sh lib/*.sh && echo SHELLCHECK-OK` +Expected: `all suites green`, `SHELLCHECK-OK`. + +- [ ] **Step 3: Commit** + +```bash +git add .claude/tasks/TODO.md +git commit -m "chore(todo): phase 0 done in-repo, per-repo pass queued as phase 0b" +``` + +--- + +### Task 11: proof on this branch (orchestrator, no code) + +- [ ] **Step 1: `/context` after** + +Run from the repo root: `claude -p "/context" 2>/dev/null | grep -E 'Memory files|Documents/claude/CLAUDE.md'` +Expected: the project CLAUDE.md row well under 2.1k (about 150 tokens); Memory files total about 1.9k lower than the 11.6k baseline. Record both numbers for the journal. + +- [ ] **Step 2: Logged loads** + +The hook needs a session started AFTER Task 2 landed in `settings.json`. Run a headless session that reads one file per rule: `claude -p "Read rules/a11y.md, install-plugins.sh, mods/model-router/.claude-plugin/plugin.json and docs/superpowers/specs/2026-10-26-claude-md-split-design.md, then answer with the single word done." 2>/dev/null | tail -1`, then `grep path_glob_match ~/.claude/logs/instructions-loaded.jsonl | tail -4 | jq -c '{file_path, trigger_file_path}'`. +Expected: four lines, one per `.claude/rules/*.md`. Zero lines → the event does not fire as a classic hook on this CLI: report it, the proof falls back to a transcript check (`/context` in the same session listing the rule under Memory files), and the finding goes to STEP 7 as a BLK. + +--- + +## Self-review + +- Spec coverage: §1 rules → Task 4; `.gitignore` + socle → Task 3; §2 check/sections/extract + suite → Task 1, hook + settings → Task 2, proof → Task 11; §3 skill + onboarder split + RED/GREEN → Tasks 6-8; §4 skeletons + generators + template header → Task 9; §5 citers → Task 5 (ARCHITECTURE.md is STEP 8's), TODO → Task 10, higgsfield user step → Task 10 TODO line + STEP 7 journal; §6 testing → every task's verify step + Task 10 Step 2. +- Placeholder scan: none. Every code step carries its content. +- Type consistency: `extract` arg order ` ` is the same in the lib, the suite, Task 4 and the onboarder S1; `emit ` the same in the lib, T12, PHASE 1b (both agents); the skip marker string `# static-check: skip` is identical in the lib grep, T4 and Task 4 Step 3; the `check` success line `project-rules: N rule(s) ok` is what T5b, T11b and the agents quote. +- Review Focus: 1 → T6/T7h, 2 → T8, 3 → T2/T4c, 4 → T12, 5 → T10f/T10g. All pinned. From 11119d8d6dd49e1cac3cd551b49dafc022b2cfa8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 08:49:47 +0100 Subject: [PATCH 03/17] =?UTF-8?q?docs(plan):=20r2=20after=203-lens=20chall?= =?UTF-8?q?enge=20=E2=80=94=20compgen=20matcher,=20-C=20root,=20matches,?= =?UTF-8?q?=20preflight+rollback,=20hook=20ids?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plans/2026-10-26-claude-md-split.md | 682 +++++++++++------- 1 file changed, 404 insertions(+), 278 deletions(-) diff --git a/docs/superpowers/plans/2026-10-26-claude-md-split.md b/docs/superpowers/plans/2026-10-26-claude-md-split.md index ea8b280..10d7d4d 100644 --- a/docs/superpowers/plans/2026-10-26-claude-md-split.md +++ b/docs/superpowers/plans/2026-10-26-claude-md-split.md @@ -4,45 +4,49 @@ **Goal:** Move the four path-bound sections of this repo's project CLAUDE.md into `.claude/rules/.md` path rules, prove they load, and give every project the same lever (`/onboard split`, generators born split). -**Architecture:** One bash lib (`lib/project-rules.sh`: `check`, `sections`, `extract`, `emit`) is the deterministic oracle for every consumer: the `make test` suite, this repo's own split, the onboarder in `MODE: split`, and the two generators. Judgment (which section is path-scoped, which globs) stays in the `/onboard split` main loop; writes are executed by the sonnet onboarder. A permanent `InstructionsLoaded` hook logs every loaded instruction file so a path-rule load is a grep, not a guess. +**Architecture:** One bash lib (`lib/project-rules.sh`: `check`, `matches`, `sections`, `extract`, `emit`, all behind an optional `-C

`) is the deterministic oracle for every consumer: the `make test` suite, this repo's own split, the onboarder in `MODE: split`, and the two generators. Judgment (which section is path-scoped, which globs) stays in the `/onboard split` main loop; writes are executed by the sonnet onboarder against an explicit project root. A permanent `InstructionsLoaded` hook logs every loaded instruction file (with session and agent ids) so a path-rule load is a grep, not a guess. -**Tech Stack:** bash 5 (globstar), awk, jq, shellcheck; markdown skills/agents; Claude Code path-scoped rules (`paths:` frontmatter) and the `InstructionsLoaded` classic hook. +**Tech Stack:** bash 5 (`compgen -G` with globstar/dotglob), awk, jq, shellcheck; markdown skills/agents; Claude Code path-scoped rules (`paths:` frontmatter) and the `InstructionsLoaded` classic hook. **Spec:** `docs/superpowers/specs/2026-10-26-claude-md-split-design.md` **Contract:** `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md` -**Branch:** `feature/claude-md-split` (already started off develop, spec committed 2c8e4a2). +**Branch:** `feature/claude-md-split`, already started off develop (spec 2c8e4a2, plan r1 420448a). **Implement in place on this checkout, no worktree**: `~/.claude/{lib,agents,skills,hooks,settings.json}` are symlinks into this repo, and Tasks 6, 8 and 11 exercise the live links. -Spec delta, decided while planning: a fourth subcommand `emit ` (the spec's "emit only skeletons whose globs match" needs a per-glob prune the sonnet generators cannot do by hand; `emit` writes the rule with the matching globs only, so the strict "each glob matches" check still holds). +Spec deltas, decided while planning (r2, after the three-lens challenge): a `matches ` subcommand (the split mode's only glob oracle, so the skill never consults `git ls-files`); `emit ` (writes a skeleton with the matching globs only); `-C ` on every subcommand (a dispatched agent's cwd is the session's, never the project's); `extract` refuses a glob that matches nothing and a heading that does not occur exactly once; the hook also logs `session_id`, `agent_id`, `agent_type`, `globs` and rotates above 5 MB; the graphify rule drops `.graphify_version` (it lives under `skills/graphify/`, already covered); the onboarder's default-mode PHASE 4 is untouched (the gitignore socle reaches onboarded projects through STEP 2.6 `gitflow init`). + +Baseline, taken 2026-10-26 before any edit (`claude -p "/context"` at the repo root, CLAUDE.md unchanged): total 32.2k; Memory files 11.6k, of which project CLAUDE.md 2.1k; Skills 10k; Custom agents 2.6k; System prompt 4.4k; MCP instructions 2.2k. ## Global Constraints -- Our code (strict): max 25 logic lines per function, 80 chars per line, 5 params, 5 locals; `shellcheck *.sh hooks/*.sh lib/*.sh` clean. -- Subtract-only: section text moves verbatim; nothing deleted from CLAUDE.global.md / rules/; registries (`.claude/memory/*`) are never edited by a task (STEP 7 capitalize owns them). -- Never write into `rules/` (user scope, every project) except the one pointer fix in `rules/README.md`. +- Our code (strict): max 25 logic lines per function, 80 chars per line, 5 params, 5 locals; `shellcheck *.sh hooks/*.sh lib/*.sh` clean; no `sed -i '` in any file (portability census scans `*.sh`; agent text follows the same rule). +- Subtract-only: section text moves verbatim; nothing deleted from CLAUDE.global.md / rules/; registries (`.claude/memory/*`) are never edited by a task (STEP 7 capitalize owns them). CLAUDE.md keeps its lines 1-3 HTML comment. +- Never write into `rules/` (user scope, every project) except the pointer fix in `rules/README.md`. - `.gitignore` negations only work with the `.claude/*` file form (BDR-003); the negation line must come AFTER `.claude/*`. - Hooks never print to stdout (stdout reaches the model) and never block. +- The doctrine-citers census (`lib/tests/doctrine-citers.test.sh`) flags any `CLAUDE.md` followed within 12 chars by a double quote in skills/agents/lib/rules/hooks: new text never writes `CLAUDE.md "…"`; headings in command templates are single-quoted. - Commit on the feature branch only, one commit per task, message under 50 words, no attribution lines. - Frontmatter shape is exactly `paths: ["glob", "glob"]` on one line (as `rules/a11y.md`). -- Commands with a shell variable in the path are denied by the permission rules in this repo: write literal paths in every Bash step. +- Commands with a shell variable in a path are denied by the permission rules in this repo: write literal paths in every Bash step; agent templates say `` and the executor substitutes the literal. +- Deferred, for the human gate: the pre-commit `.claude/**` exemption lets a rules-only commit land directly on develop/main `[deferred 2026-10-26]` (phase 2, guards, narrows it; split mode always branches first). ## Review Focus -1. A heading inside a fenced code block in CLAUDE.md (` ```\n## x\n``` `) must not be read as a section by `sections`/`extract` (test T6 in Task 1). -2. `extract` on a heading that is absent, or onto a rule file that already exists, must write nothing and exit 2 (test T8 in Task 1). -3. A glob with a typo (`skils/**`) must fail `check` with the culprit named, and the skip marker must only silence globs of its own file (tests T2, T4 in Task 1). -4. `emit` on a project where only some globs of a skeleton match must keep exactly the matching ones; none matching → nothing written, rc 1 (test T12 in Task 7). -5. The hook must exit 0 and print nothing when `jq` is absent or the log dir is unwritable, so a broken log never reaches the model (test T10f in Task 2). +1. A heading inside a fenced code block, or a duplicated heading, must never be moved: `sections` ignores fenced lines, `extract` refuses unless the fence-aware count is exactly 1 (T6, T8e, T8f in Task 1). +2. A literal glob (no `*?[`) that names a missing file must fail `check` and be pruned by `emit`: bash never expands a plain word, so the matcher uses `compgen -G` (T2c, T12b, T12f in Tasks 1 and 9). +3. A glob that matches only under `node_modules/`, `.venv/`, `vendor/`, `target/`, `dist/`, `build/` or `.git/` counts as no match (T2d in Task 1). +4. A dispatched onboarder must act on the project root it was given, never on the session cwd: every lib call carries `-C `, every git call `-C` (Task 8 asserts the scratch repo got the commit and this repo stayed clean). +5. The hook must exit 0 and print nothing when `jq` is absent or the log dir is unwritable (T10f-T10h in Task 2). --- -### Task 1: `lib/project-rules.sh` + its suite (check / sections / extract) +### Task 1: `lib/project-rules.sh` + its suite (check / matches / sections / extract) **Files:** - Create: `lib/project-rules.sh` - Create: `lib/tests/project-rules.test.sh` **Interfaces:** -- Produces: `bash lib/project-rules.sh check [dir]` (rc 0 + `project-rules: N rule(s) ok`; rc 2 + `: ` lines; `: SKIP ` lines for a skip-marked file); `sections ` (`\t\t## ` per top-level section); `extract "" ''` (rc 0 moved; rc 2 heading absent / target exists / malformed globs, nothing written). Functions are sourceable (`source lib/project-rules.sh`; main guarded by `BASH_SOURCE`). +- Produces: `bash lib/project-rules.sh [-C ] check [rules-dir]` (rc 0 + `project-rules: N rule(s) ok`; rc 2 + `: ` lines; `: SKIP ` for a skip-marked file; `: always-on (no frontmatter)` / `(no paths:)` as info); `matches ` (rc 0 + up to 3 hits, rc 1 + `no match: ` on stderr); `sections ` (`\t\t## ` per top-level section, fence-aware); `extract '' ''` (rc 0 moved; rc 2 heading count ≠ 1 / target exists / malformed globs / a glob matches nothing, nothing written). Task 9 adds `emit`. - [ ] **Step 1: Write the failing suite (T1-T9)** @@ -50,9 +54,9 @@ Create `lib/tests/project-rules.test.sh`: ```bash #!/usr/bin/env bash -# lib/tests/project-rules.test.sh — lib/project-rules.sh (check / sections / -# extract / emit) and hooks/instructions-loaded.sh. Flip-tests on fixtures -# first (LRN-096), then the real check on this repo's .claude/rules. +# 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 @@ -61,8 +65,9 @@ check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); else fail=$((fail+1)); PR="$ROOT/lib/project-rules.sh" FIX=$(mktemp -d); trap 'rm -rf "$FIX"' EXIT cd "$FIX" || exit 1 -mkdir -p .claude/rules src +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 @@ -74,13 +79,30 @@ 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 missing frontmatter fails +# 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-missing-frontmatter-fails "$rc" 2 -check T3b-named "$(printf '%s\n' "$out" | grep -c 'nofm.md: no frontmatter')" 1 +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: is not a JSON array of strings')" 1 rm .claude/rules/nofm.md # T4 the skip marker passes an unmatched glob, and only in its own file @@ -93,11 +115,25 @@ 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 +# 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 # T6 sections lists headings with sizes, fence-aware cat > CLAUDE.md <<'EOF' @@ -113,14 +149,21 @@ aaa ## not a heading ``` bbb + +## Gamma +g1 + +## Gamma +g2 EOF out=$(bash "$PR" sections CLAUDE.md) -check T6-two-sections "$(printf '%s\n' "$out" | wc -l | tr -d ' ')" 2 +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 # T7 extract moves the section, writes the frontmatter, demotes the title -bash "$PR" extract CLAUDE.md "Alpha" .claude/rules/alpha.md '["src/**"]' >/dev/null +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' @@ -131,18 +174,27 @@ 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 -# T8 extract refuses a missing heading and an existing target, writes nothing -bash "$PR" extract CLAUDE.md "Alpha" .claude/rules/alpha2.md '["src/**"]' 2>/dev/null +# 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 "$(ls .claude/rules | wc -l | tr -d ' ')" 1 -bash "$PR" extract CLAUDE.md "Beta" .claude/rules/alpha.md '["src/**"]' 2>/dev/null +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 "$(ls .claude/rules | tr '\n' ' ')" 'alpha.md good.md ' -# T9 extract refuses a malformed globs argument -bash "$PR" extract CLAUDE.md "Beta" .claude/rules/beta.md 'src/**' 2>/dev/null +# 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 -check T9b-nothing-written "$(ls .claude/rules/beta.md 2>/dev/null | wc -l | tr -d ' ')" 0 +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 echo "PASS=$pass FAIL=$fail" [ "$fail" -eq 0 ] @@ -163,17 +215,24 @@ Create `lib/project-rules.sh`: #!/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: -# check [dir] frontmatter parses, every glob matches ≥1 path (rc 2) -# sections "\t\t## " per top-level section +# /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 # extract move one section to a rule -# emit write the rule with the globs that match (rc 1 +# emit the rule with the matching globs only (rc 1 # when none matches, nothing written) -# Globs match the WORKING TREE (globstar, dotglob, through symlinks): 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 (docs/superpowers/**). -set -uo pipefail +# Globs match the WORKING TREE (compgen -G with globstar and dotglob, +# through symlinks), dependency dirs excluded: 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. + +_RULES_DEP_DIRS='(^|/)(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 } @@ -182,44 +241,50 @@ _rules_frontmatter() { # → frontmatter body on stdout, rc 1 if none END { exit found ? 0 : 1 }' "$1" } -_rules_globs() { # → one glob per line, rc 1 if no paths: - local line - line=$(printf '%s\n' "$1" | grep -E '^paths: *\[.*\] *$') || return 1 - printf '%s\n' "$line" | grep -oE '"[^"]+"' | tr -d '"' +# → 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_glob_matches() { # → rc 0 when ≥1 path exists in the tree - local -a hits - shopt -s globstar dotglob nullglob - # shellcheck disable=SC2206 # the glob MUST expand: that is the test - hits=( $1 ) - shopt -u globstar dotglob nullglob - [ "${#hits[@]}" -gt 0 ] +_rules_hits() { # → matching paths outside dependency dirs, rc 1 none + ( shopt -s globstar dotglob; compgen -G "$1" ) 2>/dev/null \ + | grep -Ev "$_RULES_DEP_DIRS" } _rules_matching() { # → JSON array of the matching ones local g out="" while IFS= read -r g; do - [ -n "$g" ] && _rules_glob_matches "$g" && out="$out, \"$g\"" + [ -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, rc 1 with the culprit lines +_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: no frontmatter"; return 1; } - globs=$(_rules_globs "$fm") || { echo "$1: no paths: array"; return 1; } + 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: is not a JSON array of strings"; return 1 ;; + esac printf '%s\n' "$fm" | grep -qx '# static-check: skip' && skip=1 while IFS= read -r g; do - [ -n "$g" ] || continue if [ "$skip" = 1 ]; then echo "$1: SKIP $g"; continue; fi - _rules_glob_matches "$g" || { echo "$1: glob matches nothing: $g"; bad=1; } + _rules_hits "$g" >/dev/null || { echo "$1: glob matches nothing: $g"; bad=1; } done <<< "$globs" [ "$bad" = 0 ] } -project_rules_check() { # [dir] → rc 0 all ok, rc 2 with culprits named +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 @@ -231,7 +296,12 @@ project_rules_check() { # [dir] → rc 0 all ok, rc 2 with culprits named echo "project-rules: $n rule(s) ok" } -project_rules_sections() { # → "\t\t## " +project_rules_matches() { # → rc 0 + the first 3 hits, rc 1 none + _rules_hits "$1" | head -3 + [ "${PIPESTATUS[0]}" -eq 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 ' /^```/ { fence = !fence } @@ -241,6 +311,12 @@ project_rules_sections() { # → "\t\t## " END { if (h != "") printf "%d\t%d\t%s\n", c, l, h }' "$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 } @@ -259,20 +335,31 @@ _rules_without_section() { # → the file minus that section !skip { print }' "$1" } -project_rules_extract() { # +_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 - grep -qxF -- "## $heading" "$src" \ - || { echo "project-rules: heading not found: ## $heading" >&2; return 2; } + [ "$(_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 "paths: $globs" >/dev/null \ - || { echo "project-rules: globs must be a JSON array: $globs" >&2; return 2; } + _rules_globs_all_match "$globs" || return 2 mkdir -p "$(dirname "$out")" { printf -- '---\npaths: %s\n---\n\n# %s\n' "$globs" "$heading" _rules_section_body "$src" "$heading"; } > "$out" tmp=$(mktemp) _rules_without_section "$src" "$heading" > "$tmp" && cat "$tmp" > "$src" rm -f "$tmp" - echo "project-rules: moved \"## $heading\" to $out" + echo "project-rules: moved '## $heading' to $out" } project_rules_emit() { # → the rule, matching globs only @@ -280,7 +367,7 @@ project_rules_emit() { # → the rule, matching globs on fm=$(_rules_frontmatter "$1") \ || { echo "project-rules: $1: no frontmatter" >&2; return 2; } globs=$(_rules_globs "$fm") \ - || { echo "project-rules: $1: no paths: array" >&2; return 2; } + || { 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; } @@ -291,15 +378,21 @@ project_rules_emit() { # → the rule, matching globs on } _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}" ;; - sections) project_rules_sections "${2:?CLAUDE.md path}" ;; + 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 check [dir] | sections " \ - "| extract " \ - "| emit " >&2; return 2 ;; + *) echo "usage: project-rules.sh [-C dir] check [rules-dir] | matches" \ + " | sections | extract " \ + " | emit " >&2; return 2 ;; esac } @@ -309,18 +402,18 @@ if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then _project_rules_main "$@"; fi - [ ] **Step 4: Run the suite, verify T1-T9 pass** Run: `bash lib/tests/project-rules.test.sh` -Expected: `PASS=33 FAIL=0`, exit 0 (count may differ by one or two; the invariant is `FAIL=0`). +Expected: `PASS=… FAIL=0`, exit 0. -- [ ] **Step 5: shellcheck + make test on the new suite** +- [ ] **Step 5: shellcheck, 80 columns, census, make test on the new suite** -Run: `shellcheck lib/project-rules.sh lib/tests/project-rules.test.sh && make test suite=lib/tests/project-rules.test.sh` -Expected: no shellcheck output; `all suites green`. +Run: `shellcheck lib/project-rules.sh lib/tests/project-rules.test.sh; awk 'length > 80 {print FILENAME": "FNR": "length}' lib/project-rules.sh; make test suite=lib/tests/project-rules.test.sh | tail -1; make test suite=lib/tests/doctrine-citers.test.sh | tail -1; make test suite=lib/tests/portability-census.test.sh | tail -1` +Expected: no shellcheck output, no awk output, `all suites green` three times. - [ ] **Step 6: Commit** ```bash git add lib/project-rules.sh lib/tests/project-rules.test.sh -git commit -m "feat(rules): lib/project-rules.sh check/sections/extract/emit + suite" +git commit -m "feat(rules): lib/project-rules.sh check/matches/sections/extract + suite" ``` --- @@ -329,11 +422,11 @@ git commit -m "feat(rules): lib/project-rules.sh check/sections/extract/emit + s **Files:** - Create: `hooks/instructions-loaded.sh` -- Modify: `settings.json` (hooks block, after `"SessionStart": [...]`, line ~374) +- Modify: `settings.json` (hooks block, after the `"SessionStart": [ … ],` block, before `"PreToolUse": [`) - Modify: `lib/tests/project-rules.test.sh` (append T10 before the tally) **Interfaces:** -- Produces: one JSON line per loaded instruction file in `~/.claude/logs/instructions-loaded.jsonl` (`ts, cwd, file_path, memory_type, load_reason, trigger_file_path`); `CLAUDE_INSTRUCTIONS_LOG=` overrides the log path (tests). +- Produces: one JSON line per loaded instruction file in `~/.claude/logs/instructions-loaded.jsonl` (`ts, session_id, agent_id, agent_type, cwd, file_path, memory_type, load_reason, globs, trigger_file_path`); `CLAUDE_INSTRUCTIONS_LOG=` overrides the log path (tests); the log rotates to `.1` above 5 MB. - [ ] **Step 1: Append the failing hook tests (T10) to the suite** @@ -343,21 +436,29 @@ Insert before the `echo "PASS=$pass FAIL=$fail"` line of `lib/tests/project-rule # 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","cwd":"/p","file_path":"/p/.claude/rules/x.md","memory_type":"Project","load_reason":"path_glob_match","trigger_file_path":"/p/src/a.ts"}' +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-trigger-kept "$(jq -r '.trigger_file_path' "$LOG")" /p/src/a.ts +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-still-rc0 "$rc" 0 +check T10f-unwritable-log-rc0 "$rc" 0 check T10g-unwritable-log-stdout-empty "$out" "" +out=$(printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent bash "$HOOK"); rc=$? +check T10h-no-jq-rc0 "$rc" 0 +check T10i-no-jq-stdout-empty "$out" "" +check T10j-no-jq-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 ``` - [ ] **Step 2: Run the suite, verify T10 fails** -Run: `bash lib/tests/project-rules.test.sh` +Run: `bash lib/tests/project-rules.test.sh | tail -3` Expected: `FAIL T10-hook-rc` (hook missing), exit 1. - [ ] **Step 3: Write the hook** @@ -370,21 +471,25 @@ Create `hooks/instructions-loaded.sh`: # 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` with the file that triggered it. -# Never blocks, never prints to stdout (stdout reaches the model), exits 0 -# whatever happens. CLAUDE_INSTRUCTIONS_LOG overrides the path (tests). +# `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 -jq -c --arg ts "$(date -u +%FT%TZ)" \ - '{ts: $ts, cwd, file_path, memory_type, load_reason, trigger_file_path}' \ - >> "$log" 2>/dev/null +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 ``` - [ ] **Step 4: Register it in `settings.json`** -In `settings.json`, after the `"SessionStart": [ ... ],` block (the `],` that closes it, just before `"PreToolUse": [`), insert: +In `settings.json`, after the `"SessionStart": [ … ],` block (the `],` that closes it, just before `"PreToolUse": [`), insert: ```json "InstructionsLoaded": [ @@ -400,12 +505,12 @@ In `settings.json`, after the `"SessionStart": [ ... ],` block (the `],` that cl ], ``` -Verify: `jq '.hooks.InstructionsLoaded[0].hooks[0].command' settings.json` prints `"bash ~/.claude/hooks/instructions-loaded.sh"`. +Verify: `jq -r '.hooks.InstructionsLoaded[0].hooks[0].command' settings.json` prints `bash ~/.claude/hooks/instructions-loaded.sh`. - [ ] **Step 5: Run the suite, verify T10 passes** -Run: `bash lib/tests/project-rules.test.sh && shellcheck hooks/instructions-loaded.sh` -Expected: `FAIL=0`, no shellcheck output. +Run: `bash lib/tests/project-rules.test.sh | tail -1 && shellcheck hooks/instructions-loaded.sh && make test suite=lib/tests/curated-config-guard.test.sh | tail -1` +Expected: `FAIL=0`, no shellcheck output, `all suites green`. - [ ] **Step 6: Commit** @@ -438,9 +543,9 @@ Expected: `FAIL socle: !.claude/rules/ …` and `1 suite(s) red`. - [ ] **Step 3: Patch the socle and this repo's `.gitignore`** -`templates/gitignore/standard.gitignore`: after the line `!.claude/deploy/` add the line `!.claude/rules/` (it must stay after `.claude/*`; reconcile appends missing lines at the end of a project's file, which is after any existing `.claude/*`). +`templates/gitignore/standard.gitignore`: after the line `!.claude/deploy/` add the line `!.claude/rules/` (it stays after `.claude/*`; reconcile appends missing lines at the end of a project's file, which is after any existing `.claude/*`). -`.gitignore`: after line 122 `.claude/*` and its negations, add `!.claude/rules/` directly after `!.claude/settings.json` (line 126): +`.gitignore`: add `!.claude/rules/` directly after `!.claude/settings.json` (line 126), so the block reads: ``` .claude/* @@ -453,8 +558,8 @@ Expected: `FAIL socle: !.claude/rules/ …` and `1 suite(s) red`. - [ ] **Step 4: Verify** -Run: `make test suite=lib/gitflow-test.sh 2>&1 | tail -2 && mkdir -p .claude/rules && touch .claude/rules/.probe && git check-ignore -v .claude/rules/.probe; echo "rc=$?"; rm .claude/rules/.probe` -Expected: `all suites green`; `git check-ignore` prints nothing and `rc=1` (not ignored). +Run: `make test suite=lib/gitflow-test.sh 2>&1 | tail -1; git check-ignore -q .claude/rules/probe.md; echo "ignored-rc=$?"` +Expected: `all suites green`; `ignored-rc=1` (not ignored; `git check-ignore` needs no existing file). - [ ] **Step 5: Commit** @@ -468,7 +573,7 @@ git commit -m "chore(gitignore): un-ignore .claude/rules/ here and in the gitflo ### Task 4: split this repo's CLAUDE.md (dogfood `extract`) **Files:** -- Modify: `CLAUDE.md` (four sections leave, a pointer section arrives) +- Modify: `CLAUDE.md` (four sections leave, a pointer section arrives; lines 1-3 comment stays) - Create: `.claude/rules/rules-maintenance.md`, `.claude/rules/graphify-vendored.md`, `.claude/rules/mods.md`, `.claude/rules/transient-artifacts.md` - Modify: `lib/tests/project-rules.test.sh` (append T11 before the tally) @@ -481,7 +586,7 @@ Insert before the `echo "PASS=$pass FAIL=$fail"` line of `lib/tests/project-rule ```bash # T11 the real rules of this repo pass the check (4 rules, 1 skip-marked) -out=$(cd "$ROOT" && bash "$PR" check); rc=$? +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 @@ -494,33 +599,31 @@ Expected: `FAIL T11b-four-rules: got[0] want[1]` (0 rules yet). - [ ] **Step 2: Move the four sections with `extract`** -From the repo root, in this order (headings are exact, copied from CLAUDE.md): +From the repo root, in this order (headings are exact, copied from CLAUDE.md; the transient rule is extracted with the one glob that matches mid-run, `docs/superpowers/**`, since `.audit/` does not exist at rest): ```bash -bash lib/project-rules.sh extract CLAUDE.md "rules/ maintenance" .claude/rules/rules-maintenance.md '["rules/**", "CLAUDE.global.md"]' -bash lib/project-rules.sh extract CLAUDE.md "Machine-owned: the vendored graphify skill" .claude/rules/graphify-vendored.md '["skills/graphify/**", "install-plugins.sh", ".graphify_version"]' -bash lib/project-rules.sh extract CLAUDE.md "mods/ — function-hooks plugins (Claude Code mods)" .claude/rules/mods.md '["mods/**", "skills/model-router/**", "lib/tests/mods.test.sh"]' -bash lib/project-rules.sh extract CLAUDE.md "Transient planning artifacts" .claude/rules/transient-artifacts.md '["docs/superpowers/**", ".audit/**"]' +bash lib/project-rules.sh extract CLAUDE.md 'rules/ maintenance' .claude/rules/rules-maintenance.md '["rules/**", "CLAUDE.global.md"]' +bash lib/project-rules.sh extract CLAUDE.md 'Machine-owned: the vendored graphify skill' .claude/rules/graphify-vendored.md '["skills/graphify/**", "install-plugins.sh"]' +bash lib/project-rules.sh extract CLAUDE.md 'mods/ — function-hooks plugins (Claude Code mods)' .claude/rules/mods.md '["mods/**", "skills/model-router/**", "lib/tests/mods.test.sh"]' +bash lib/project-rules.sh extract CLAUDE.md 'Transient planning artifacts' .claude/rules/transient-artifacts.md '["docs/superpowers/**"]' ``` -Expected: four `project-rules: moved "## …" to .claude/rules/….md` lines. `git diff --stat CLAUDE.md` shows about 90 deletions and no insertion. +Expected: four `project-rules: moved '## …' to .claude/rules/….md` lines. `git diff --stat CLAUDE.md` shows about 90 deletions and no insertion. -- [ ] **Step 3: Skip marker on the transient rule** +- [ ] **Step 3: Transient rule: second glob + skip marker** -Edit `.claude/rules/transient-artifacts.md`: between the `paths:` line and the closing `---`, insert the line `# static-check: skip`. The file starts: +Edit `.claude/rules/transient-artifacts.md` so its frontmatter reads exactly: ``` --- paths: ["docs/superpowers/**", ".audit/**"] # static-check: skip --- - -# Transient planning artifacts ``` - [ ] **Step 4: The pointer section in CLAUDE.md** -CLAUDE.md now holds only the title and `## Health Stack`. Append: +Append to CLAUDE.md: ```markdown @@ -531,9 +634,13 @@ graphify-vendored, mods, transient-artifacts. Check: `bash lib/project-rules.sh check` (runs in `make test`). ``` -The whole file must then read: +The whole file must then read (lines 1-3 are the existing comment, untouched): ```markdown + + # claude-config — project instructions ## Health Stack @@ -548,18 +655,10 @@ lib/project-rules.sh check` (runs in `make test`). (Remove any run of more than one blank line left by the extraction.) -- [ ] **Step 5: Verify verbatim move and the check** +- [ ] **Step 5: Verify** -Run: -```bash -git show HEAD:CLAUDE.md | sed -n '/^## rules\/ maintenance$/,/^## Machine-owned/p' | sed '1d;$d' | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/old-rules.txt -sed -n '6,$p' .claude/rules/rules-maintenance.md | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/new-rules.txt -diff /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/old-rules.txt /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/new-rules.txt && echo VERBATIM -bash lib/project-rules.sh check -bash lib/tests/project-rules.test.sh | tail -1 -git status --short .claude/rules -``` -Expected: `VERBATIM`; `transient-artifacts.md: SKIP docs/superpowers/**`, `… SKIP .audit/**`, `project-rules: 4 rule(s) ok`; `PASS=… FAIL=0`; four `??`/`A` entries under `.claude/rules/` (tracked thanks to Task 3). +Run: `bash lib/project-rules.sh check; bash lib/tests/project-rules.test.sh | tail -1; git status --short .claude/rules CLAUDE.md; git diff HEAD --stat -- CLAUDE.md; wc -c .claude/rules/*.md` +Expected: `transient-artifacts.md: SKIP docs/superpowers/**`, `… SKIP .audit/**`, `project-rules: 4 rule(s) ok`; `FAIL=0`; four `??` entries under `.claude/rules/` plus ` M CLAUDE.md`; the four rule files sum to roughly the 4,960 chars the sections held (T7 proves `extract` is verbatim; the sizes are the sanity check). - [ ] **Step 6: Commit** @@ -573,12 +672,12 @@ git commit -m "refactor(claude-md): four sections become .claude/rules path rule ### Task 5: citers of the moved sections **Files:** -- Modify: `rules/README.md:7-9` +- Modify: `rules/README.md:8-9` - Modify: `doctor.sh:76` - [ ] **Step 1: Repoint `rules/README.md`** -Replace lines 7-9: +Replace lines 8-9: ``` Maintenance doctrine (what belongs here, lazy-load `paths:` semantics, @@ -593,6 +692,8 @@ machine-owned files): see `.claude/rules/rules-maintenance.md` in the claude-config repo (project scope, loads on Read under `rules/`). ``` +Line 7 (`User-scope rules, deployed to …`) stays. + - [ ] **Step 2: Fix the stale doctor comment** `doctor.sh:76`: replace `(the 29-line project CLAUDE.md instead of` with `(the project CLAUDE.md instead of`. @@ -603,11 +704,11 @@ Run: ```bash grep -rnE 'CLAUDE\.md \(project scope\)|29-line project CLAUDE\.md|Machine-owned: the vendored|§ ?Transient planning|"rules/ maintenance"|"mods/ — function-hooks"' rules/ doctor.sh skills/ agents/ lib/ hooks/ README.md ARCHITECTURE.md --include='*.md' --include='*.sh' | grep -v 'skills-external\|skills/graphify/\|lib/tests/project-rules' ``` -Expected: no output. (`lib/gitflow.sh:21` says "transient planning artifacts" in a comment about the purge, not as a citation: leave it. `install-plugins.sh` GUARDED_CONFIGS keeps `CLAUDE.md`: leave it. `ARCHITECTURE.md` is the doc pipeline's, STEP 8.) +Expected: no output. (`lib/gitflow.sh:21` mentions transient planning artifacts in a comment about the purge, not as a citation: leave it. `install-plugins.sh` GUARDED_CONFIGS keeps `CLAUDE.md`: leave it. `ARCHITECTURE.md` is the doc pipeline's, STEP 8.) - [ ] **Step 4: make test + commit** -Run: `make test suite=lib/tests/doctrine-citers.test.sh | tail -2` +Run: `make test suite=lib/tests/doctrine-citers.test.sh | tail -1` Expected: `all suites green`. ```bash @@ -619,22 +720,21 @@ git commit -m "chore(citers): rules/README and doctor point at .claude/rules aft ### Task 6: `/onboard split` RED pressure test (orchestrator dispatch, no code) -**Files:** none modified. Scratch: `/tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/` (a git repo holding `CLAUDE.md` = `git show develop:CLAUDE.md`, plus `rules/x.md`, `mods/m/plugin.json`, `.gitignore` with `.claude/*`). +**Files:** none modified. Scratch: `/tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/` (a git repo on branch `develop` holding `CLAUDE.md` = `git show develop:CLAUDE.md`, plus `rules/x.md`, `mods/m/plugin.json`, `.gitignore` with `.claude/*`). -- [ ] **Step 1: Build the scratch repo** +- [ ] **Step 1: Assert in-place links, build the scratch repo** + +Run (one line, literal paths): `readlink -f ~/.claude/lib ~/.claude/skills ~/.claude/agents ~/.claude/hooks ~/.claude/settings.json` → every line under `/home/bchanot/Documents/claude/`. ```bash -S=/tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red -mkdir -p "$S/rules" "$S/mods/m" "$S/.claude" && git show develop:CLAUDE.md > "$S/CLAUDE.md" && echo r > "$S/rules/x.md" && echo '{}' > "$S/mods/m/plugin.json" && printf '.claude/*\n!.claude/memory/\n' > "$S/.gitignore" && git -C "$S" init -q && git -C "$S" add -A && git -C "$S" commit -qm init +mkdir -p /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/rules /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/mods/m && git show develop:CLAUDE.md > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/CLAUDE.md && echo r > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/rules/x.md && echo '{}' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/mods/m/plugin.json && printf '.claude/*\n!.claude/memory/\n' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/.gitignore && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red init -q -b develop && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red add -A && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red commit -qm init ``` -(The denied-variable rule: run it as ONE line with the literal path substituted for `$S`.) - - [ ] **Step 2: Dispatch the RED probe (sonnet)** -`Agent(subagent_type="general-purpose", model="sonnet", effort="medium")` with: "You are executing the skill at `/home/bchanot/.claude/skills/onboard/SKILL.md` with `$ARGUMENTS` = `split`, working directory ``. Read the skill, then do exactly what it tells you for its first three steps, in the scratch directory only; do not dispatch agents, do not run `claude`, do not write outside the scratch. Stop after the third step and report: which steps you ran, whether any step asked you to classify CLAUDE.md sections into path-scoped rules, and what you would have produced." +`Agent(subagent_type="general-purpose", model="sonnet", effort="medium")` with: "Probe of a skill's text, not a real run. Read `/home/bchanot/.claude/skills/onboard/SKILL.md` as if you had been invoked as `/onboard split` in the project ``. Treat the MODEL GATE as passed and never call `mcp__model-router__route`; do not dispatch agents, do not run `claude`, do not write outside the scratch. Follow the skill's text for what it tells you to do first, up to the first point where it would stop for the user or dispatch an agent, then stop. Report: the steps you ran in order, whether any step had you classify the CLAUDE.md sections into path-scoped rules, and what you would have shown the user." -Expected (RED): the report names MODEL GATE / plugin check / archetype detection; no classification table, no `.claude/rules/` written. Record one line in the plan's commit message of Task 7 ("RED: current skill runs archetype detection on `split`"). +Expected (RED): the report names the plugin check / archetype detection; no classification table, no `.claude/rules/` written. Record one line for the Task 7 commit message ("RED: current skill runs archetype detection on `split`"). If the probe DOES produce a split with the current skill: stop, the mode is unnecessary as designed; re-plan. @@ -643,16 +743,16 @@ If the probe DOES produce a split with the current skill: stop, the mode is unne ### Task 7: `/onboard split` mode + onboarder `MODE: split` **Files:** -- Modify: `skills/onboard/SKILL.md` (frontmatter lines 4-5, after `## REQUEST` ~line 20, RULES line ~1037, append § SPLIT MODE after FINAL OUTPUT) -- Modify: `agents/onboarder.md` (after `## INPUTS`, before `## PHASE 1`; and a new section after PHASE 6) +- Modify: `skills/onboard/SKILL.md` (frontmatter lines 4-5, after `## REQUEST` ~line 20, STEP 3 draft-update line ~201, RULES lines ~1037 and ~1041, append § SPLIT MODE after FINAL OUTPUT) +- Modify: `agents/onboarder.md` (after `## ROLE`; RULES line 170; a new section at the end) **Interfaces:** -- Consumes: `project-rules.sh sections|extract|check` (Task 1). -- Produces: the onboarder `MODE: split` contract: INPUTS `PROJECT_ROOT`, `TABLE` rows ` | | `; OUTPUT rules written, check result, commit hash. +- Consumes: `project-rules.sh -C sections|matches|extract|check` (Task 1). +- Produces: the onboarder `MODE: split` contract: INPUTS `PROJECT_ROOT`, `TABLE` rows ` | | `; OUTPUT rules written, check result, commit hash, or `STOP: — ` with the rollback done. - [ ] **Step 1: Skill frontmatter** -Line 4 `description:` — append inside the quoted string, before the closing `'`: ` `split` mode: "split CLAUDE.md", "découpe le CLAUDE.md", "path-scoped rules", "move sections to .claude/rules".` +Line 4 `description:` — replace `Do NOT use for repos created via /init-project.` with `Default flow: do NOT use it for repos created via /init-project.` and append inside the quoted string, before the closing `'`: ` `split` mode (any repo): "onboard split", "split the project instructions", "découpe le fichier CLAUDE", "path-scoped rules".` Line 5: `argument-hint: '[split | optional hints: "Python FastAPI" | "Next.js monorepo" | "force-archetype:wordpress"]'` - [ ] **Step 2: MODE DISPATCH after `## REQUEST`** @@ -668,9 +768,11 @@ below, unchanged. --- ``` -- [ ] **Step 3: RULES line** +- [ ] **Step 3: STEP 3 draft update and the RULES lines** -Replace `- NO skipping STEP 0, 1, 2 — ils sont obligatoires.` with `- NO skipping STEP 0, 1, 2 — ils sont obligatoires (split mode runs its own steps, § SPLIT MODE).` +STEP 3 (~line 201): replace `Après réponses : **mettre à jour le brouillon CLAUDE.md** avec les infos obtenues.` with `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).` + +RULES: replace `- NO skipping STEP 0, 1, 2 — ils sont obligatoires.` with `- NO skipping STEP 0, 1, 2 — ils sont obligatoires (split mode runs its own steps, § SPLIT MODE).` and replace `- Si `CLAUDE.md` existe : le lire, ne pas l'écraser sans fusion après STEP 3.` with `- 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 4: § SPLIT MODE appended at the end of the skill** @@ -683,63 +785,75 @@ Replace `- NO skipping STEP 0, 1, 2 — ils sont obligatoires.` with `- NO skipp 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 oracle. The MODEL GATE above -has run. `mcp__model-router__route(phase="plan")` first. +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 the project root, else print -`nothing to split — run /onboard` and stop. `git status --porcelain -CLAUDE.md` empty, else stop (an in-flight edit would be lost). `.claude/rules/` -already holding rules → list them, continue (new rules add to them). +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 → list +them, continue (new rules add to them). -S2 — BASELINE. Run `claude -p "/context"` at the root (refused → ask the -user to run `! claude -p "/context"`); note the `Memory files` total and the +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 — CLASSIFY. `bash ~/.claude/lib/project-rules.sh sections CLAUDE.md` -lists every `##` section with its size. For each one decide: +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; + 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 from `git ls-files` (a folder → `dir/**`, - a tool → its config files), and verify every proposed glob with - `git ls-files ''` (≥1 line) before showing it. - Sections that are needed before any file is read (how to run the project) - stay always-on even when they name a folder. + section's subject) and globs (a folder → `dir/**`, a tool → its config + files) and verify EVERY proposed glob with `bash + ~/.claude/lib/project-rules.sh -C matches ''` (rc 0) before + showing it. A heading containing `'` or `|` is not split by this mode + (say so; the user renames it first). -S4 — GATE (mandatory stop). Print the table, then end the turn: +S5 — GATE (mandatory stop). Print the table, then end the turn: ``` -SPLIT — CLAUDE.md ( chars, sections) +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. The approved rows are the -TABLE handed to the onboarder, verbatim. - -S5 — BRANCH. `bash ~/.claude/lib/gitflow.sh start chore claude-md-split`. -A project without gitflow (no `develop`): `git switch -c chore/claude-md-split` -and say so. +"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 +`PROJECT_ROOT: `, `TABLE:` the approved rows, one per line as ` | | ` (LRN-126: every field crosses the -prompt). It extracts each row, writes the pointer section, adds the -gitignore negation, runs `check`, commits. A STOP report (heading absent, -target exists, check red) comes back here: fix the row, re-dispatch; rows -already moved stay moved. +prompt). It pre-flights every row, then extracts, writes the pointer +section, secures the gitignore negation, runs `check`, commits, and +verifies the rules are tracked. A `STOP:` report comes back here with the +rollback already done (nothing committed): fix the row, re-dispatch the +WHOLE table (nothing was moved). A `STOP:` after a commit cannot happen +(the commit is the last step). -S7 — AFTER. `claude -p "/context"` again; 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 `grep path_glob_match ~/.claude/logs/instructions-loaded.jsonl | -tail`. Never `finish`: the merge is the user's signal. +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: ``` @@ -748,19 +862,21 @@ RULES : files under .claude/rules/ () CLAUDE.md: → CONTEXT : → (Memory files) BRANCH : chore/claude-md-split () — merge on your signal -PROOF : pending — fresh session + grep path_glob_match +PROOF : pending — fresh session + the jq filter above ``` ``` -- [ ] **Step 5: Onboarder: mode header + `MODE: split` section** +- [ ] **Step 5: Onboarder: mode header, RULES exemption, `MODE: split` section** -In `agents/onboarder.md`, insert right after `## ROLE`'s paragraph (before the `---` that precedes `## INPUTS`): +In `agents/onboarder.md`, insert right after the `## ROLE` paragraph (before the `---` that precedes `## INPUTS`): ```markdown 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. ``` +RULES line 170: replace `- NO destructive writes: never overwrite CLAUDE.md if it exists without asking (print path + STOP, let orchestrator decide).` with `- 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.` + Append at the end of the file: ```markdown @@ -769,16 +885,34 @@ Append at the end of the file: ## MODE: split (dispatched by `/onboard split`) -INPUTS: `PROJECT_ROOT` (absolute), `TABLE` = the approved rows, one per -line, ` | | ` (heading without `## `). No -BRIEF; PHASES 1-6 do not run. +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 `. -S1 — EXTRACT. From `${PROJECT_ROOT}`, per row: +S0 — PREFLIGHT (no write before every row passes): +- `git -C status --porcelain` is empty, else STOP. +- gitignore: `git -C check-ignore -q .claude/rules/probe.md` + rc 0 means the rules would be ignored → append the negation (portable, + lands after any `.claude/*` line): + `printf '!.claude/rules/\n' >> /.gitignore` + then re-run `check-ignore`; still rc 0 → STOP: "ignore form cannot be + negated (BDR-003: use the `.claude/*` file form)", and `git -C + checkout -- .gitignore`. +- 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 (nothing written yet besides the gitignore + line, which the STOP reverts). + +S1 — EXTRACT, per row (single quotes around the heading): ```bash -bash ~/.claude/lib/project-rules.sh extract CLAUDE.md "" .claude/rules/.md '' +bash ~/.claude/lib/project-rules.sh -C extract CLAUDE.md '' .claude/rules/.md '' ``` -rc 2 (heading absent, target exists, malformed globs) → STOP and report -the row; rows already moved stay (the orchestrator re-dispatches the rest). +rc ≠ 0 (should not happen after S0) → ROLLBACK: `git -C +checkout -- CLAUDE.md .gitignore`, delete every `.claude/rules/.md` +this run wrote, then STOP with the row and the lib's message. S2 — POINTER. If CLAUDE.md has no `## Path-scoped rules` section, append: ```markdown @@ -790,61 +924,60 @@ matching their `paths:` (never at session start): , . Else add the new names to its list. Collapse runs of blank lines left by the extraction (never more than one). -S3 — GITIGNORE. When `.gitignore` has the exact line `.claude/*` and no -`!.claude/rules/` line: +S3 — CHECK, COMMIT, VERIFY TRACKED. ```bash -sed -i '\|^\.claude/\*$|a !.claude/rules/' .gitignore +bash ~/.claude/lib/project-rules.sh -C check ``` -(No `.claude/*` line → the rules are not ignored, nothing to add.) - -S4 — CHECK + COMMIT. +rc ≠ 0 → ROLLBACK as in S1, STOP with the culprit lines. rc 0 → ```bash -bash ~/.claude/lib/project-rules.sh check -``` -rc ≠ 0 → STOP, report the culprit lines, do not commit. rc 0 → -```bash -git add CLAUDE.md .claude/rules .gitignore -git commit -m "chore(claude-md): split section(s) into .claude/rules/" +git -C add CLAUDE.md .claude/rules .gitignore +git -C commit -m "chore(claude-md): split section(s) into .claude/rules/" +git -C ls-files --error-unmatch .claude/rules/.md # per row ``` +A rule `ls-files` cannot find → report it as `STOP: not tracked +after commit` (the commit stays; the orchestrator decides). OUTPUT: ``` SPLIT DONE: rule(s) — .md (), … CLAUDE.md: → lines CHECK : project-rules: rule(s) ok -COMMIT : +COMMIT : — all rules tracked ``` -or `STOP: — `. +or `STOP: — (rollback done, nothing committed)`. ``` - [ ] **Step 6: Locks still hold** -Run: `make test suite=lib/tests/model-routing.test.sh && make test suite=lib/tests/effort-routing.test.sh && make test suite=lib/tests/loops-heavy.test.sh && make test suite=lib/tests/plan-challenger.test.sh && make test suite=lib/tests/security-auditor.test.sh && make test suite=lib/tests/doctrine-citers.test.sh` -Expected: `all suites green` six times. +Run: `for s in model-routing effort-routing loops-heavy plan-challenger security-auditor doctrine-citers portability-census; do make test suite=lib/tests/$s.test.sh | tail -1; done` +(If the loop form is refused by the permission rules, run the seven `make test suite=…` commands one by one.) +Expected: `all suites green` seven times. - [ ] **Step 7: Commit** ```bash git add skills/onboard/SKILL.md agents/onboarder.md -git commit -m "feat(onboard): split mode — classify CLAUDE.md sections, onboarder MODE: split executes (RED: current skill ran archetype detection on 'split')" +git commit -m "feat(onboard): split mode classifies CLAUDE.md sections, onboarder MODE: split executes (RED: current skill ran archetype detection on split)" ``` --- ### Task 8: `/onboard split` GREEN pressure test (orchestrator dispatch, no code) -- [ ] **Step 1: Reset the scratch repo** +- [ ] **Step 1: Fresh scratch repo `split-green/`** -`git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red checkout -- . && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red clean -fdq` +Same one-liner as Task 6 Step 1 with `split-red` replaced by `split-green` everywhere (no `git clean`: a fresh directory). -- [ ] **Step 2: Dispatch the GREEN probe (sonnet, same prompt as Task 6 Step 2)** +- [ ] **Step 2: Dispatch the GREEN probe (sonnet, its own prompt)** -Expected (GREEN): the report says it jumped to § SPLIT MODE, ran S1-S3, and produced the classification table (at least `rules/ maintenance` → move with `rules/**`, `Health Stack` → keep), then stopped at the S4 gate without writing. A probe that writes files or skips the gate = not green: fix the skill text, re-run. +`Agent(subagent_type="general-purpose", model="sonnet", effort="medium")` with: "Probe of a skill's text, not a real run. Read `/home/bchanot/.claude/skills/onboard/SKILL.md` as if you had been invoked as `/onboard split` in the project `` (a git repo on `develop`, clean). Treat the MODEL GATE as passed and never call `mcp__model-router__route`; treat S2 (the `claude -p` baseline) as done with the value 2.1k; do not dispatch agents; do not write anything, not even the branch (report the command you would run instead). Follow the skill's text up to the mandatory stop, then stop. Report: the steps you ran in order, the classification table you would print, and the exact `matches` commands you ran." -- [ ] **Step 3: Executor dry run (sonnet onboarder, MODE: split) on the scratch** +Expected (GREEN): the report says it took MODE DISPATCH → § SPLIT MODE, ran S1, S3 (reported, not run), S4 with `matches` calls, and printed the S5 table (at least `rules/ maintenance` → move with `rules/**` and `Health Stack` → keep), then stopped. A probe that writes files, skips the gate, or runs archetype detection = not green: fix the skill text, re-run. -Dispatch `Agent(subagent_type="onboarder")` with `MODE: split`, `PROJECT_ROOT: `, `TABLE:` two rows: `rules/ maintenance | rules-maintenance | ["rules/**"]` and `mods/ — function-hooks plugins (Claude Code mods) | mods | ["mods/**"]`. -Expected: `SPLIT DONE: 2 rule(s)`, a commit in the scratch repo, `.gitignore` there gained `!.claude/rules/`, and `bash lib/project-rules.sh check` run from the scratch root prints `2 rule(s) ok`. +- [ ] **Step 3: Executor dry run (onboarder, MODE: split) on the scratch** + +Dispatch `Agent(subagent_type="onboarder")` with `MODE: split`, `PROJECT_ROOT: `, `TABLE:` two rows: `rules/ maintenance | rules-maintenance | ["rules/**"]` and `mods/ — function-hooks plugins (Claude Code mods) | mods | ["mods/**"]`. +Expected: `SPLIT DONE: 2 rule(s)` with `all rules tracked`; `git -C log --oneline -1` shows the split commit; `.gitignore` there ends with `!.claude/rules/`; `bash lib/project-rules.sh -C check` prints `2 rule(s) ok`; and THIS repo is untouched: `git status --porcelain` empty here and `git log --oneline -1` unchanged. - [ ] **Step 4: Record** @@ -852,13 +985,13 @@ No commit. The orchestrator notes RED/GREEN outcomes for STEP 7 capitalize (EVAL --- -### Task 9: generators born split (skeletons, `emit`, onboarder PHASE 1b + PHASE 4, scaffolder PHASE 1b) +### Task 9: generators born split (skeletons, `emit`, onboarder PHASE 5b, scaffolder PHASE 3b) **Files:** - Create: `templates/project-rules/docker.md`, `templates/project-rules/testing.md`, `templates/project-rules/ci.md` -- Modify: `templates/project-CLAUDE.md:3-4` (header comment) -- Modify: `agents/onboarder.md` (new PHASE 1b after PHASE 1; PHASE 4 gains the negation) -- Modify: `agents/scaffolder.md` (new PHASE 1b after PHASE 1) +- Modify: `templates/project-CLAUDE.md:4` (header comment) +- Modify: `agents/onboarder.md` (new PHASE 5b after PHASE 5) +- Modify: `agents/scaffolder.md` (new PHASE 3b between PHASE 3 and PHASE 4) - Modify: `lib/tests/project-rules.test.sh` (append T12 before the tally) **Interfaces:** @@ -881,7 +1014,7 @@ 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 "$(ls .claude/rules/ci.md 2>/dev/null | wc -l | tr -d ' ')" 0 +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 @@ -902,9 +1035,9 @@ paths: ["Dockerfile*", "docker-compose*", "compose*.y*ml", ".dockerignore"] # Docker - - - + + + ``` `templates/project-rules/testing.md`: @@ -916,9 +1049,9 @@ paths: ["tests/**", "test/**", "**/*.test.*", "**/*.spec.*", "**/conftest.py"] # Testing conventions - - - + + + ``` `templates/project-rules/ci.md`: @@ -930,81 +1063,66 @@ paths: [".github/workflows/**", ".gitlab-ci.yml", ".circleci/**"] # CI - - - + + + ``` `templates/project-CLAUDE.md` line 4: after `# Global rules: ~/.claude/CLAUDE.md — this file extends or overrides them.` add the line `# Path-scoped rules: .claude/rules/.md (paths: frontmatter), loaded on Read of a matching file.` -- [ ] **Step 3: Onboarder PHASE 1b + PHASE 4 negation** +- [ ] **Step 3: Onboarder PHASE 5b** -In `agents/onboarder.md`, after the PHASE 1 block (after `For Option C (monorepo sequential): path = ${package_root}/CLAUDE.md.` and before its `---`), add: +In `agents/onboarder.md`, after the PHASE 5 block (after `**Do NOT overwrite existing content.**` and before the `---` that precedes PHASE 6), add: ```markdown -## PHASE 1b — PATH-SCOPED RULES (born split) +## PHASE 5b — PATH-SCOPED RULES (born split) -From `${PROJECT_ROOT}`, for each of `docker`, `testing`, `ci`: +For each of `docker`, `testing`, `ci`: ```bash -bash ~/.claude/lib/project-rules.sh emit ~/.claude/templates/project-rules/.md .claude/rules/.md +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. Fill its stub comments - from the BRIEF where known (`docker` from `build_cmd`, `testing` from - `test_cmd` and `conventions`); unknown → keep the stubs. +- 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 check` must print `N rule(s) ok`; -list the emitted rules in OUTPUT. +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. ``` -In PHASE 4, replace the three bullets with: +- [ ] **Step 4: Scaffolder PHASE 3b** -```markdown -- **`.gitignore` exists AND contains `settings.local.json`** → nothing to do for it. -- **`.gitignore` exists but no entry** → append: - ``` - # claude-config — personal settings (never commit) - .claude/settings.local.json - ``` -- **`.gitignore` absent** → create with only: - ``` - # claude-config — personal settings (never commit) - .claude/settings.local.json - ``` -- Then, whatever the case: when `.gitignore` has the exact line `.claude/*` - and no `!.claude/rules/` line, add the negation right after it (PHASE 1b - rules would be ignored otherwise, LRN-066): - ```bash - sed -i '\|^\.claude/\*$|a !.claude/rules/' .gitignore - ``` -``` - -- [ ] **Step 4: Scaffolder PHASE 1b** - -In `agents/scaffolder.md`, after PHASE 1 (`Write to CLAUDE.md at project root.`), before its `---`, add: +In `agents/scaffolder.md`, after the PHASE 3 block (its last stack line, before the `---` that precedes `## PHASE 4`), add: ```markdown -## PHASE 1b — PATH-SCOPED RULES (born split) +## PHASE 3b — PATH-SCOPED RULES (born split) -Runs AFTER PHASE 3 has written the files (the globs match the scaffolded -tree). For each of `docker` (only when DOCKER_RELEVANT), `testing`, `ci`: +After PHASE 3 wrote the files and BEFORE PHASE 4 installs dependencies +(installed packages must not match the globs). For each of `docker`, +`testing`, `ci`, one uniform loop: ```bash -bash ~/.claude/lib/project-rules.sh emit ~/.claude/templates/project-rules/.md .claude/rules/.md +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); rc 1 → nothing matched, skipped. Then -`bash ~/.claude/lib/project-rules.sh 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. +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. ``` - [ ] **Step 5: Verify** -Run: `bash lib/tests/project-rules.test.sh | tail -1 && cd /tmp && mkdir -p /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/.github/workflows && cd /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all && touch Dockerfile docker-compose.yml compose.yaml .dockerignore .gitlab-ci.yml && mkdir -p tests test .circleci && touch tests/a test/b a.test.ts b.spec.ts conftest.py .github/workflows/ci.yml .circleci/config.yml && bash /home/bchanot/Documents/claude/lib/project-rules.sh check /home/bchanot/Documents/claude/templates/project-rules` -Expected: `PASS=… FAIL=0`; `project-rules: 3 rule(s) ok` (every skeleton glob is syntactically sound). +Run: `bash lib/tests/project-rules.test.sh | tail -1; mkdir -p /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/.github/workflows /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/tests /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/test /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/.circleci && cd /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all && touch Dockerfile docker-compose.yml compose.yaml .dockerignore .gitlab-ci.yml tests/a test/b a.test.ts b.spec.ts conftest.py .github/workflows/ci.yml .circleci/config.yml && bash /home/bchanot/Documents/claude/lib/project-rules.sh check /home/bchanot/Documents/claude/templates/project-rules; make -C /home/bchanot/Documents/claude test suite=lib/tests/doctrine-citers.test.sh | tail -1` +Expected: `FAIL=0`; `project-rules: 3 rule(s) ok` (every skeleton glob is syntactically sound); `all suites green`. - [ ] **Step 6: Commit** @@ -1025,10 +1143,11 @@ git commit -m "feat(generators): onboarder and scaffolder emit docker/testing/ci Replace the `- [ ] **Phase 0, no mod: split project CLAUDE.md**` block (lines 20-30) with: ```markdown -- [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/sections/extract/emit + suite, `hooks/instructions-loaded.sh` (log `~/.claude/logs/instructions-loaded.jsonl`), `!.claude/rules/` here + socle, `/onboard split` + onboarder `MODE: split`, generators emit docker/testing/ci from `templates/project-rules/`. Baseline `/context` 32.2k (project CLAUDE.md 2.1k). - - [ ] Proof, this repo: `/context` after the merge; one fresh session Reading one file per rule → 4 `path_glob_match` lines in the log, pasted in the journal. +- [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 0b, per-repo pass** (after phase 0 merges; via `/onboard split`, one `chore/claude-md-split` per repo, approval per repo, never an automatic merge; `/context` before/after in that repo's journal; faunosteo first and measure whether path rules load inside sub-agents before moving anything a sub-agent needs). Order by size: faunosteo 52,322 chars (on feature/v1-1-clients-animals: wait for it or branch off develop and rebase), 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). + - [ ] 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. ``` - [ ] **Step 2: Full suite + shellcheck** @@ -1050,18 +1169,25 @@ git commit -m "chore(todo): phase 0 done in-repo, per-repo pass queued as phase - [ ] **Step 1: `/context` after** Run from the repo root: `claude -p "/context" 2>/dev/null | grep -E 'Memory files|Documents/claude/CLAUDE.md'` -Expected: the project CLAUDE.md row well under 2.1k (about 150 tokens); Memory files total about 1.9k lower than the 11.6k baseline. Record both numbers for the journal. +Expected: the project CLAUDE.md row well under the 2.1k baseline (about 200 tokens); Memory files total about 1.9k lower than 11.6k. Record both for the journal. -- [ ] **Step 2: Logged loads** +- [ ] **Step 2: Main-session loads** -The hook needs a session started AFTER Task 2 landed in `settings.json`. Run a headless session that reads one file per rule: `claude -p "Read rules/a11y.md, install-plugins.sh, mods/model-router/.claude-plugin/plugin.json and docs/superpowers/specs/2026-10-26-claude-md-split-design.md, then answer with the single word done." 2>/dev/null | tail -1`, then `grep path_glob_match ~/.claude/logs/instructions-loaded.jsonl | tail -4 | jq -c '{file_path, trigger_file_path}'`. -Expected: four lines, one per `.claude/rules/*.md`. Zero lines → the event does not fire as a classic hook on this CLI: report it, the proof falls back to a transcript check (`/context` in the same session listing the rule under Memory files), and the finding goes to STEP 7 as a BLK. +The hook needs a session started AFTER Task 2 landed in `settings.json`. Note the start time, then run a headless session that reads one file per rule: `date -u +%FT%TZ; claude -p "Read rules/a11y.md, install-plugins.sh, mods/model-router/.claude-plugin/plugin.json and docs/superpowers/specs/2026-10-26-claude-md-split-design.md, then answer with the single word done." 2>/dev/null | tail -1`, then +`jq -c 'select(.memory_type=="Project" and (.file_path|contains("/.claude/rules/")) and .ts >= "") | {file_path, trigger_file_path, load_reason}' ~/.claude/logs/instructions-loaded.jsonl`. +Expected: exactly four lines with `load_reason: path_glob_match`, one per `.claude/rules/*.md`. Zero lines → the event does not fire as a classic hook on this CLI: report it, the proof falls back to `/context` inside the same `-p` session listing the rule under Memory files, and the finding goes to STEP 7 as a BLK. + +- [ ] **Step 3: Sub-agent loads** + +Dispatch `Agent(subagent_type="general-purpose", model="sonnet", effort="low")`: "Read `rules/a11y.md` and `install-plugins.sh` in /home/bchanot/Documents/claude, then reply with the single word done." Then +`jq -c 'select(.agent_id != null and (.file_path|contains("/.claude/rules/")) and .ts >= "") | {agent_type, file_path, load_reason}' ~/.claude/logs/instructions-loaded.jsonl`. +Expected: two lines (rules-maintenance, graphify-vendored) with an `agent_id` → path rules load inside sub-agents. Zero lines → they do not: record it (journal + STEP 7 LRN), and the per-repo pass keeps sub-agent-needed sections always-on; whether this repo's two hazards (graphify untrack-then-merge, mods `[ -L ]` guard) return as always-on one-liners is the user's call at the next gate. --- ## Self-review -- Spec coverage: §1 rules → Task 4; `.gitignore` + socle → Task 3; §2 check/sections/extract + suite → Task 1, hook + settings → Task 2, proof → Task 11; §3 skill + onboarder split + RED/GREEN → Tasks 6-8; §4 skeletons + generators + template header → Task 9; §5 citers → Task 5 (ARCHITECTURE.md is STEP 8's), TODO → Task 10, higgsfield user step → Task 10 TODO line + STEP 7 journal; §6 testing → every task's verify step + Task 10 Step 2. +- Spec coverage: §1 rules → Task 4; `.gitignore` + socle → Task 3; §2 check/sections/extract (+ matches, emit, -C) + suite → Task 1 (emit Task 9), hook + settings → Task 2, proof → Task 11; §3 skill + onboarder split + RED/GREEN → Tasks 6-8; §4 skeletons + generators + template header → Task 9; §5 citers → Task 5 (ARCHITECTURE.md is STEP 8's), TODO → Task 10, higgsfield user step → Task 10 TODO line + STEP 7 journal; §6 testing → every task's verify step + Task 10 Step 2; §7 pre-commit exemption → deferred, Task 10 TODO line. - Placeholder scan: none. Every code step carries its content. -- Type consistency: `extract` arg order ` ` is the same in the lib, the suite, Task 4 and the onboarder S1; `emit ` the same in the lib, T12, PHASE 1b (both agents); the skip marker string `# static-check: skip` is identical in the lib grep, T4 and Task 4 Step 3; the `check` success line `project-rules: N rule(s) ok` is what T5b, T11b and the agents quote. -- Review Focus: 1 → T6/T7h, 2 → T8, 3 → T2/T4c, 4 → T12, 5 → T10f/T10g. All pinned. +- Type consistency: `extract` arg order ` ` is the same in the lib, the suite, Task 4 and the onboarder S1; `emit ` the same in the lib, T12, PHASE 5b and PHASE 3b; `-C ` precedes the subcommand everywhere; the skip marker string `# static-check: skip` is identical in the lib grep, T4 and Task 4 Step 3; the `check` success line `project-rules: N rule(s) ok` is what T3c, T5b, T5d, T11b and the agents quote; the `matches` stderr line `no match: ` is what T5i expects. +- Review Focus: 1 → T6d/T8e/T8f, 2 → T2c/T12b/T12f, 3 → T2d/T5j, 4 → Task 8 Step 3 assertions, 5 → T10f-T10j. All pinned. From 36dfee0b2661e3f25daf19ada9da0d0141dabf74 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:27:47 +0100 Subject: [PATCH 04/17] =?UTF-8?q?docs(plan):=20r3=20after=20correctness=20?= =?UTF-8?q?confirmation=20=E2=80=94=20awk=20matches=20(SIGPIPE),=20$BASH?= =?UTF-8?q?=20no-jq=20test,=20dry=20run=20branches=20first,=20commit=20rc?= =?UTF-8?q?=20+=20cat-file=20HEAD,=2080=20cols,=204-backtick=20fences?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plans/2026-10-26-claude-md-split.md | 173 +++++++++++------- 1 file changed, 109 insertions(+), 64 deletions(-) diff --git a/docs/superpowers/plans/2026-10-26-claude-md-split.md b/docs/superpowers/plans/2026-10-26-claude-md-split.md index 10d7d4d..8a13c93 100644 --- a/docs/superpowers/plans/2026-10-26-claude-md-split.md +++ b/docs/superpowers/plans/2026-10-26-claude-md-split.md @@ -12,7 +12,7 @@ **Contract:** `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md` **Branch:** `feature/claude-md-split`, already started off develop (spec 2c8e4a2, plan r1 420448a). **Implement in place on this checkout, no worktree**: `~/.claude/{lib,agents,skills,hooks,settings.json}` are symlinks into this repo, and Tasks 6, 8 and 11 exercise the live links. -Spec deltas, decided while planning (r2, after the three-lens challenge): a `matches ` subcommand (the split mode's only glob oracle, so the skill never consults `git ls-files`); `emit ` (writes a skeleton with the matching globs only); `-C ` on every subcommand (a dispatched agent's cwd is the session's, never the project's); `extract` refuses a glob that matches nothing and a heading that does not occur exactly once; the hook also logs `session_id`, `agent_id`, `agent_type`, `globs` and rotates above 5 MB; the graphify rule drops `.graphify_version` (it lives under `skills/graphify/`, already covered); the onboarder's default-mode PHASE 4 is untouched (the gitignore socle reaches onboarded projects through STEP 2.6 `gitflow init`). +Spec deltas, decided while planning (r2 after the three-lens challenge, r3 after the correctness confirmation): a `matches ` subcommand (the split mode's only glob oracle, so the skill never consults `git ls-files`); `emit ` (writes a skeleton with the matching globs only); `-C ` on every subcommand (a dispatched agent's cwd is the session's, never the project's); `extract` refuses a glob that matches nothing and a heading that does not occur exactly once; the hook also logs `session_id`, `agent_id`, `agent_type`, `globs` and rotates above 5 MB; the graphify rule drops `.graphify_version` (it lives under `skills/graphify/`, already covered); the onboarder's default-mode PHASE 4 is untouched (the gitignore socle reaches onboarded projects through STEP 2.6 `gitflow init`). r3: `matches` reads its whole pipe through awk (a `head` reader gives the writer SIGPIPE, rc 141 under `pipefail`, so any glob with more than a pipe buffer of hits read as "no match"); the no-jq hook test runs `"$BASH"` (a temporary `PATH=/nonexistent` makes `bash` itself unfindable, rc 127); the Task 8 dry run branches the scratch first (the global pre-commit hook blocks a CLAUDE.md commit on `develop`); the onboarder checks the commit rc, rolls back on failure and verifies `HEAD:` with `cat-file`; globs carry no braces (`compgen -G` does not expand them). Baseline, taken 2026-10-26 before any edit (`claude -p "/context"` at the repo root, CLAUDE.md unchanged): total 32.2k; Memory files 11.6k, of which project CLAUDE.md 2.1k; Skills 10k; Custom agents 2.6k; System prompt 4.4k; MCP instructions 2.2k. @@ -25,7 +25,9 @@ Baseline, taken 2026-10-26 before any edit (`claude -p "/context"` at the repo r - Hooks never print to stdout (stdout reaches the model) and never block. - The doctrine-citers census (`lib/tests/doctrine-citers.test.sh`) flags any `CLAUDE.md` followed within 12 chars by a double quote in skills/agents/lib/rules/hooks: new text never writes `CLAUDE.md "…"`; headings in command templates are single-quoted. - Commit on the feature branch only, one commit per task, message under 50 words, no attribution lines. -- Frontmatter shape is exactly `paths: ["glob", "glob"]` on one line (as `rules/a11y.md`). +- Frontmatter shape is exactly `paths: ["glob", "glob"]` on one line (as `rules/a11y.md`). No brace glob (`*.{ts,tsx}`): `compgen -G` does no brace expansion, so one glob per extension. +- A pipeline whose reader may stop early (`head`, `grep -q`) gives the writer SIGPIPE; under `set -o pipefail` that is rc 141 on the whole pipeline. The lib never puts `head` after a producer: awk reads the pipe to its end. +- A temporary assignment `PATH=/nonexistent cmd` applies to the lookup of `cmd` itself: write `"$BASH"`, never `bash`, when the test blanks PATH. - Commands with a shell variable in a path are denied by the permission rules in this repo: write literal paths in every Bash step; agent templates say `` and the executor substitutes the literal. - Deferred, for the human gate: the pre-commit `.claude/**` exemption lets a rules-only commit land directly on develop/main `[deferred 2026-10-26]` (phase 2, guards, narrows it; split mode always branches first). @@ -34,7 +36,8 @@ Baseline, taken 2026-10-26 before any edit (`claude -p "/context"` at the repo r 1. A heading inside a fenced code block, or a duplicated heading, must never be moved: `sections` ignores fenced lines, `extract` refuses unless the fence-aware count is exactly 1 (T6, T8e, T8f in Task 1). 2. A literal glob (no `*?[`) that names a missing file must fail `check` and be pruned by `emit`: bash never expands a plain word, so the matcher uses `compgen -G` (T2c, T12b, T12f in Tasks 1 and 9). 3. A glob that matches only under `node_modules/`, `.venv/`, `vendor/`, `target/`, `dist/`, `build/` or `.git/` counts as no match (T2d in Task 1). -4. A dispatched onboarder must act on the project root it was given, never on the session cwd: every lib call carries `-C `, every git call `-C` (Task 8 asserts the scratch repo got the commit and this repo stayed clean). +4. A dispatched onboarder must act on the project root it was given, never on the session cwd: every lib call carries `-C `, every git call `-C` (Task 8 asserts the scratch repo got the commit on its chore branch and this repo's status is unchanged). +6. A glob with thousands of hits (a real repo's `src/**`) must still be a match: `matches` reads the whole pipe (T5k, T5l in Task 1). 5. The hook must exit 0 and print nothing when `jq` is absent or the log dir is unwritable (T10f-T10h in Task 2). --- @@ -50,9 +53,9 @@ Baseline, taken 2026-10-26 before any edit (`claude -p "/context"` at the repo r - [ ] **Step 1: Write the failing suite (T1-T9)** -Create `lib/tests/project-rules.test.sh`: +Create `lib/tests/project-rules.test.sh` (4-backtick fence: the heredoc inside holds a ``` line): -```bash +````bash #!/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 @@ -134,6 +137,15 @@ 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 # T6 sections lists headings with sizes, fence-aware cat > CLAUDE.md <<'EOF' @@ -186,7 +198,7 @@ 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 "$(ls .claude/rules | tr '\n' ' ')" 'alpha.md good.md ' +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 @@ -198,14 +210,14 @@ check T9d-beta-still-there "$(grep -c '^## Beta' CLAUDE.md)" 1 echo "PASS=$pass FAIL=$fail" [ "$fail" -eq 0 ] -``` +```` (T6c: the Alpha section spans `## Alpha`, `aaa`, blank, `---`, blank; each line counts its length plus one newline: 9+4+1+4+1 = 19.) - [ ] **Step 2: Run the suite, verify it fails** Run: `bash lib/tests/project-rules.test.sh` -Expected: many `FAIL …` lines (the lib does not exist), last line `PASS=0 FAIL=…`, exit 1. +Expected: many `FAIL …` lines (the lib does not exist), last line `PASS=… FAIL=…` with FAIL above 40 (a few negative checks such as T6d, T8b, T9c pass with no lib), exit 1. - [ ] **Step 3: Write the lib** @@ -226,13 +238,15 @@ Create `lib/project-rules.sh`: # 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, -# through symlinks), dependency dirs excluded: 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. +# through symlinks, no brace expansion: one glob per extension), +# dependency dirs excluded: 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_DEP_DIRS='(^|/)(node_modules|\.venv|venv|vendor|target|dist|build|\.git)/' +_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 } @@ -255,7 +269,7 @@ _rules_globs() { _rules_hits() { # → matching paths outside dependency dirs, rc 1 none ( shopt -s globstar dotglob; compgen -G "$1" ) 2>/dev/null \ - | grep -Ev "$_RULES_DEP_DIRS" + | grep -Ev "$_RULES_DEPS" } _rules_matching() { # → JSON array of the matching ones @@ -279,14 +293,16 @@ _rules_check_file() { # → rc 0 ok or always-on, rc 1 with culprits 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; } + _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; } + [ -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)) @@ -297,8 +313,10 @@ project_rules_check() { # [rules-dir] → rc 0 all ok, rc 2 with culprits named } project_rules_matches() { # → rc 0 + the first 3 hits, rc 1 none - _rules_hits "$1" | head -3 - [ "${PIPESTATUS[0]}" -eq 0 ] || { echo "no match: $1" >&2; return 1; } + # 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 @@ -380,7 +398,8 @@ project_rules_emit() { # → the rule, matching globs on _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; } + cd "${2:?dir}" 2>/dev/null \ + || { echo "project-rules: no dir $2" >&2; return 2; } shift 2 fi case "${1:-}" in @@ -446,7 +465,9 @@ check T10e-ids-kept "$(jq -r '[.session_id, .agent_id, .globs[0]] | join(",")' " 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" "" -out=$(printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent bash "$HOOK"); rc=$? +# "$BASH", not bash: the blank PATH applies to the command lookup too (rc 127) +out=$(printf '%s' "$IN" \ + | CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent "$BASH" "$HOOK"); rc=$? check T10h-no-jq-rc0 "$rc" 0 check T10i-no-jq-stdout-empty "$out" "" check T10j-no-jq-nothing-appended "$(wc -l < "$LOG" | tr -d ' ')" 1 @@ -657,8 +678,8 @@ lib/project-rules.sh check` (runs in `make test`). - [ ] **Step 5: Verify** -Run: `bash lib/project-rules.sh check; bash lib/tests/project-rules.test.sh | tail -1; git status --short .claude/rules CLAUDE.md; git diff HEAD --stat -- CLAUDE.md; wc -c .claude/rules/*.md` -Expected: `transient-artifacts.md: SKIP docs/superpowers/**`, `… SKIP .audit/**`, `project-rules: 4 rule(s) ok`; `FAIL=0`; four `??` entries under `.claude/rules/` plus ` M CLAUDE.md`; the four rule files sum to roughly the 4,960 chars the sections held (T7 proves `extract` is verbatim; the sizes are the sanity check). +Run: `bash lib/project-rules.sh check; bash lib/tests/project-rules.test.sh | tail -1; git status --short --untracked-files=all .claude/rules CLAUDE.md; git diff HEAD --stat -- CLAUDE.md; wc -c .claude/rules/*.md` +Expected: `transient-artifacts.md: SKIP docs/superpowers/**`, `… SKIP .audit/**`, `project-rules: 4 rule(s) ok`; `FAIL=0`; four `??` entries under `.claude/rules/` (`--untracked-files=all`, else git collapses the new dir into one line) plus ` M CLAUDE.md`; the four rule files sum to roughly the 4,960 chars the sections held (T7 proves `extract` is verbatim; the sizes are the sanity check). - [ ] **Step 6: Commit** @@ -702,9 +723,9 @@ Line 7 (`User-scope rules, deployed to …`) stays. Run: ```bash -grep -rnE 'CLAUDE\.md \(project scope\)|29-line project CLAUDE\.md|Machine-owned: the vendored|§ ?Transient planning|"rules/ maintenance"|"mods/ — function-hooks"' rules/ doctor.sh skills/ agents/ lib/ hooks/ README.md ARCHITECTURE.md --include='*.md' --include='*.sh' | grep -v 'skills-external\|skills/graphify/\|lib/tests/project-rules' +grep -rnE 'CLAUDE\.md`? \(project scope\)|29-line project CLAUDE\.md|Machine-owned: the vendored|§ ?Transient planning|"rules/ maintenance"|"mods/ — function-hooks"' rules/ doctor.sh skills/ agents/ lib/ hooks/ README.md ARCHITECTURE.md --include='*.md' --include='*.sh' | grep -v 'skills-external\|skills/graphify/\|lib/tests/project-rules' ``` -Expected: no output. (`lib/gitflow.sh:21` mentions transient planning artifacts in a comment about the purge, not as a citation: leave it. `install-plugins.sh` GUARDED_CONFIGS keeps `CLAUDE.md`: leave it. `ARCHITECTURE.md` is the doc pipeline's, STEP 8.) +Expected: no output. (The optional backtick matches the README's `` `CLAUDE.md` (project scope) `` form: on today's tree, before Step 1, this grep returns rules/README.md:9 and doctor.sh:76; after Steps 1-2 nothing.) (`lib/gitflow.sh:21` mentions transient planning artifacts in a comment about the purge, not as a citation: leave it. `install-plugins.sh` GUARDED_CONFIGS keeps `CLAUDE.md`: leave it. `ARCHITECTURE.md` is the doc pipeline's, STEP 8.) - [ ] **Step 4: make test + commit** @@ -774,9 +795,9 @@ STEP 3 (~line 201): replace `Après réponses : **mettre à jour le brouillon CL RULES: replace `- NO skipping STEP 0, 1, 2 — ils sont obligatoires.` with `- NO skipping STEP 0, 1, 2 — ils sont obligatoires (split mode runs its own steps, § SPLIT MODE).` and replace `- Si `CLAUDE.md` existe : le lire, ne pas l'écraser sans fusion après STEP 3.` with `- 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 4: § SPLIT MODE appended at the end of the skill** +- [ ] **Step 4: § SPLIT MODE appended at the end of the skill** (4-backtick fence, inner ``` blocks are part of the text) -```markdown +````markdown --- @@ -815,10 +836,11 @@ CLAUDE.md` lists every `##` section with its size. For each one decide: - 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) and verify EVERY proposed glob with `bash - ~/.claude/lib/project-rules.sh -C matches ''` (rc 0) before - showing it. A heading containing `'` or `|` is not split by this mode - (say so; the user renames it first). + 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. A heading containing `'` or `|` is not split by this + mode (say so; the user renames it first). S5 — GATE (mandatory stop). Print the table, then end the turn: @@ -840,11 +862,14 @@ 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, and -verifies the rules are tracked. A `STOP:` report comes back here with the -rollback already done (nothing committed): fix the row, re-dispatch the -WHOLE table (nothing was moved). A `STOP:` after a commit cannot happen -(the commit is the last step). +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 @@ -864,7 +889,7 @@ CONTEXT : → (Memory files) BRANCH : chore/claude-md-split () — merge on your signal PROOF : pending — fresh session + the jq filter above ``` -``` +```` - [ ] **Step 5: Onboarder: mode header, RULES exemption, `MODE: split` section** @@ -877,9 +902,9 @@ Two modes. No `MODE:` line in the brief → the generator below (PHASES 1-6). RULES line 170: replace `- NO destructive writes: never overwrite CLAUDE.md if it exists without asking (print path + STOP, let orchestrator decide).` with `- 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.` -Append at the end of the file: +Append at the end of the file (4-backtick fence, inner ``` blocks are part of the text): -```markdown +````markdown --- @@ -899,7 +924,10 @@ S0 — PREFLIGHT (no write before every row passes): `printf '!.claude/rules/\n' >> /.gitignore` then re-run `check-ignore`; still rc 0 → STOP: "ignore form cannot be negated (BDR-003: use the `.claude/*` file form)", and `git -C - checkout -- .gitignore`. + checkout -- .gitignore`. Remember whether this step + appended (`GITIGNORE_TOUCHED`): `.gitignore` enters the later `add`, + `checkout` and `commit` only then (a repo with no `.gitignore` is rc 1 + here and never names it: a missing pathspec is a fatal git error). - 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 @@ -911,8 +939,10 @@ S1 — EXTRACT, per row (single quotes around the heading): bash ~/.claude/lib/project-rules.sh -C extract CLAUDE.md '' .claude/rules/.md '' ``` rc ≠ 0 (should not happen after S0) → ROLLBACK: `git -C -checkout -- CLAUDE.md .gitignore`, delete every `.claude/rules/.md` -this run wrote, then STOP with the row and the lib's message. +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 @@ -930,22 +960,31 @@ 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 .gitignore -git -C commit -m "chore(claude-md): split section(s) into .claude/rules/" -git -C ls-files --error-unmatch .claude/rules/.md # per row +git -C add CLAUDE.md .claude/rules # + .gitignore when S0 appended +git -C commit -m "" ``` -A rule `ls-files` cannot find → report it as `STOP: not tracked -after commit` (the commit stays; the orchestrator decides). +`` 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 tracked -``` -or `STOP: — (rollback done, nothing committed)`. +COMMIT : — all rules in HEAD ``` +or `STOP: — (rollback done, nothing committed)`, or +`STOP: not in HEAD after commit (commit kept)`. +```` - [ ] **Step 6: Locks still hold** @@ -976,8 +1015,10 @@ Expected (GREEN): the report says it took MODE DISPATCH → § SPLIT MODE, ran S - [ ] **Step 3: Executor dry run (onboarder, MODE: split) on the scratch** +Before the dispatch, mirror the skill's S3 (the scratch is on `develop`, and the global `core.hooksPath` pre-commit blocks any commit there that stages a path outside `.claude/`): `git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-green switch -c chore/claude-md-split`, and snapshot this repo: `git status --porcelain > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/status-before.txt; git rev-parse HEAD`. + Dispatch `Agent(subagent_type="onboarder")` with `MODE: split`, `PROJECT_ROOT: `, `TABLE:` two rows: `rules/ maintenance | rules-maintenance | ["rules/**"]` and `mods/ — function-hooks plugins (Claude Code mods) | mods | ["mods/**"]`. -Expected: `SPLIT DONE: 2 rule(s)` with `all rules tracked`; `git -C log --oneline -1` shows the split commit; `.gitignore` there ends with `!.claude/rules/`; `bash lib/project-rules.sh -C check` prints `2 rule(s) ok`; and THIS repo is untouched: `git status --porcelain` empty here and `git log --oneline -1` unchanged. +Expected: `SPLIT DONE: 2 rule(s)` with `all rules in HEAD`; `git -C log --oneline -1 --decorate` shows the split commit on `chore/claude-md-split` (the post-commit push hook warns about the missing origin, never blocks); `.gitignore` there ends with `!.claude/rules/`; `bash lib/project-rules.sh -C check` prints `2 rule(s) ok`; and THIS repo is untouched: `git status --porcelain | diff - /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/status-before.txt` empty (the untracked contract file is in both) and `git rev-parse HEAD` unchanged. - [ ] **Step 4: Record** @@ -1072,9 +1113,9 @@ paths: [".github/workflows/**", ".gitlab-ci.yml", ".circleci/**"] - [ ] **Step 3: Onboarder PHASE 5b** -In `agents/onboarder.md`, after the PHASE 5 block (after `**Do NOT overwrite existing content.**` and before the `---` that precedes PHASE 6), add: +In `agents/onboarder.md`, after the PHASE 5 block (after `**Do NOT overwrite existing content.**` and before the `---` that precedes PHASE 6), add (4-backtick fence, the inner ```bash block is part of the text): -```markdown +````markdown ## PHASE 5b — PATH-SCOPED RULES (born split) @@ -1093,19 +1134,21 @@ bash ~/.claude/lib/project-rules.sh -C emit ~/.claude/templates/p 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. -``` +```` - [ ] **Step 4: Scaffolder PHASE 3b** -In `agents/scaffolder.md`, after the PHASE 3 block (its last stack line, before the `---` that precedes `## PHASE 4`), add: +In `agents/scaffolder.md`, after the PHASE 3 block (its last stack line, before the `---` that precedes `## PHASE 4`), add (4-backtick fence, the inner ```bash block is part of the text): -```markdown +````markdown ## 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). For each of `docker`, -`testing`, `ci`, one uniform loop: +(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 ``` @@ -1117,7 +1160,7 @@ skipped (a plain scaffold yields `docker.md` when Docker is relevant, and `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. -``` +```` - [ ] **Step 5: Verify** @@ -1179,9 +1222,10 @@ Expected: exactly four lines with `load_reason: path_glob_match`, one per `.clau - [ ] **Step 3: Sub-agent loads** -Dispatch `Agent(subagent_type="general-purpose", model="sonnet", effort="low")`: "Read `rules/a11y.md` and `install-plugins.sh` in /home/bchanot/Documents/claude, then reply with the single word done." Then -`jq -c 'select(.agent_id != null and (.file_path|contains("/.claude/rules/")) and .ts >= "") | {agent_type, file_path, load_reason}' ~/.claude/logs/instructions-loaded.jsonl`. -Expected: two lines (rules-maintenance, graphify-vendored) with an `agent_id` → path rules load inside sub-agents. Zero lines → they do not: record it (journal + STEP 7 LRN), and the per-repo pass keeps sub-agent-needed sections always-on; whether this repo's two hazards (graphify untrack-then-merge, mods `[ -L ]` guard) return as always-on one-liners is the user's call at the next gate. +Note the time, then dispatch `Agent(subagent_type="general-purpose", model="sonnet", effort="low")`: "Read `rules/a11y.md` and `install-plugins.sh` in /home/bchanot/Documents/claude, then reply with the single word done." Then two filters: +1. Control, does the hook see sub-agent loads at all: `jq -c 'select(.agent_id != null and .ts >= "") | {agent_type, memory_type, file_path}' ~/.claude/logs/instructions-loaded.jsonl` (`agent_id` is optional in the hook input, "present only when the hook fires from within a subagent"). Zero lines → the event does not fire, or carries no `agent_id`, inside sub-agents: the sub-agent question is UNANSWERED (not "no"), record that, and the per-repo pass keeps sub-agent-needed sections always-on until a later probe answers it. +2. With at least one control line: `jq -c 'select(.agent_id != null and (.file_path|contains("/.claude/rules/")) and .ts >= "") | {agent_type, file_path, load_reason}' ~/.claude/logs/instructions-loaded.jsonl`. +Expected: two lines (rules-maintenance, graphify-vendored) with an `agent_id` → path rules load inside sub-agents. Zero lines with a non-empty control → they do not: record it (journal + STEP 7 LRN), and the per-repo pass keeps sub-agent-needed sections always-on; whether this repo's two hazards (graphify untrack-then-merge, mods `[ -L ]` guard) return as always-on one-liners is the user's call at the next gate. --- @@ -1189,5 +1233,6 @@ Expected: two lines (rules-maintenance, graphify-vendored) with an `agent_id` - Spec coverage: §1 rules → Task 4; `.gitignore` + socle → Task 3; §2 check/sections/extract (+ matches, emit, -C) + suite → Task 1 (emit Task 9), hook + settings → Task 2, proof → Task 11; §3 skill + onboarder split + RED/GREEN → Tasks 6-8; §4 skeletons + generators + template header → Task 9; §5 citers → Task 5 (ARCHITECTURE.md is STEP 8's), TODO → Task 10, higgsfield user step → Task 10 TODO line + STEP 7 journal; §6 testing → every task's verify step + Task 10 Step 2; §7 pre-commit exemption → deferred, Task 10 TODO line. - Placeholder scan: none. Every code step carries its content. -- Type consistency: `extract` arg order ` ` is the same in the lib, the suite, Task 4 and the onboarder S1; `emit ` the same in the lib, T12, PHASE 5b and PHASE 3b; `-C ` precedes the subcommand everywhere; the skip marker string `# static-check: skip` is identical in the lib grep, T4 and Task 4 Step 3; the `check` success line `project-rules: N rule(s) ok` is what T3c, T5b, T5d, T11b and the agents quote; the `matches` stderr line `no match: ` is what T5i expects. -- Review Focus: 1 → T6d/T8e/T8f, 2 → T2c/T12b/T12f, 3 → T2d/T5j, 4 → Task 8 Step 3 assertions, 5 → T10f-T10j. All pinned. +- Type consistency: `extract` arg order ` ` is the same in the lib, the suite, Task 4 and the onboarder S1; `emit ` the same in the lib, T12, PHASE 5b and PHASE 3b; `-C ` precedes the subcommand everywhere; the skip marker string `# static-check: skip` is identical in the lib grep, T4 and Task 4 Step 3; the `check` success line `project-rules: N rule(s) ok` is what T3c, T5b, T5d, T11b and the agents quote; the `matches` stderr line `no match: ` is what T5i expects; the onboarder's success line `all rules in HEAD` is what Task 8 Step 3 expects; the two STOP shapes in onboarder S3 are the two the skill's S6 handles. +- Review Focus: 1 → T6d/T8e/T8f, 2 → T2c/T12b/T12f, 3 → T2d/T5j, 4 → Task 8 Step 3 assertions, 5 → T10f-T10j, 6 → T5k/T5l. All pinned. +- r3 lint pass on the plan's own code: every line of the lib block is 80 columns or fewer (the four over-long r2 lines are wrapped, `_RULES_DEPS` renamed); the suite has no `ls` pipe (T8g uses `printf '%s ' *`); the lib has no `head` after a producer. From abfa4167ea23a80f136f363d22543ec5f6c657ba Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:41:07 +0100 Subject: [PATCH 05/17] feat(rules): lib/project-rules.sh check/matches/sections/extract + suite --- lib/project-rules.sh | 192 ++++++++++++++++++++++++++++++++ lib/tests/project-rules.test.sh | 154 +++++++++++++++++++++++++ 2 files changed, 346 insertions(+) create mode 100644 lib/project-rules.sh create mode 100644 lib/tests/project-rules.test.sh diff --git a/lib/project-rules.sh b/lib/project-rules.sh new file mode 100644 index 0000000..a592583 --- /dev/null +++ b/lib/project-rules.sh @@ -0,0 +1,192 @@ +#!/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 +# 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, +# through symlinks, no brace expansion: one glob per extension), +# dependency dirs excluded: 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 + ( 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: is not a JSON array of strings"; 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 ' + /^```/ { fence = !fence } + /^## / && !fence { if (h != "") printf "%d\t%d\t%s\n", c, l, h + h = $0; l = NR; c = 0 } + h != "" { c += length($0) + 1 } + END { if (h != "") printf "%d\t%d\t%s\n", c, l, h }' "$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")" + { printf -- '---\npaths: %s\n---\n\n# %s\n' "$globs" "$heading" + _rules_section_body "$src" "$heading"; } > "$out" + tmp=$(mktemp) + _rules_without_section "$src" "$heading" > "$tmp" && cat "$tmp" > "$src" + 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..a94d5dd --- /dev/null +++ b/lib/tests/project-rules.test.sh @@ -0,0 +1,154 @@ +#!/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: is not a JSON array of strings')" 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 + +# 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 + +# 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 + +# 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 + +echo "PASS=$pass FAIL=$fail" +[ "$fail" -eq 0 ] From e7d800f053048bd5a4c86e0092e90a1ad5f84c47 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:44:17 +0100 Subject: [PATCH 06/17] feat(hooks): InstructionsLoaded logger, the proof channel for path rules --- hooks/instructions-loaded.sh | 19 +++++++++++++++++++ lib/tests/project-rules.test.sh | 24 ++++++++++++++++++++++++ settings.json | 11 +++++++++++ 3 files changed, 54 insertions(+) create mode 100755 hooks/instructions-loaded.sh 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/tests/project-rules.test.sh b/lib/tests/project-rules.test.sh index a94d5dd..2b636b9 100644 --- a/lib/tests/project-rules.test.sh +++ b/lib/tests/project-rules.test.sh @@ -150,5 +150,29 @@ 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 +# 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: the blank PATH applies to the command lookup too (rc 127) +out=$(printf '%s' "$IN" \ + | CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent "$BASH" "$HOOK"); rc=$? +check T10h-no-jq-rc0 "$rc" 0 +check T10i-no-jq-stdout-empty "$out" "" +check T10j-no-jq-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 + echo "PASS=$pass FAIL=$fail" [ "$fail" -eq 0 ] 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", From ce8e60ee7ca54ced482e1c931c2c37115727f679 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:46:24 +0100 Subject: [PATCH 07/17] chore(gitignore): un-ignore .claude/rules/ here and in the gitflow socle --- .gitignore | 1 + lib/gitflow-test.sh | 1 + templates/gitignore/standard.gitignore | 1 + 3 files changed, 3 insertions(+) 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/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/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/ From 433c10d78fa86a06d42ef3947d901b319b14628a Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:47:53 +0100 Subject: [PATCH 08/17] refactor(claude-md): four sections become .claude/rules path rules (phase 0) --- .claude/rules/graphify-vendored.md | 32 ++++++++++ .claude/rules/mods.md | 25 ++++++++ .claude/rules/rules-maintenance.md | 27 ++++++++ .claude/rules/transient-artifacts.md | 19 ++++++ CLAUDE.md | 94 ++-------------------------- lib/tests/project-rules.test.sh | 8 +++ 6 files changed, 116 insertions(+), 89 deletions(-) create mode 100644 .claude/rules/graphify-vendored.md create mode 100644 .claude/rules/mods.md create mode 100644 .claude/rules/rules-maintenance.md create mode 100644 .claude/rules/transient-artifacts.md 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.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/lib/tests/project-rules.test.sh b/lib/tests/project-rules.test.sh index 2b636b9..91d2eb1 100644 --- a/lib/tests/project-rules.test.sh +++ b/lib/tests/project-rules.test.sh @@ -174,5 +174,13 @@ 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 + echo "PASS=$pass FAIL=$fail" [ "$fail" -eq 0 ] From b4131666afee1895a98dd467ebbb2c826ea1eabf Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:49:07 +0100 Subject: [PATCH 09/17] chore(citers): rules/README and doctor point at .claude/rules after the split --- doctor.sh | 2 +- rules/README.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) 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/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/`). From 041e04b1d615a9cf45d93fd96e6b1fe874b82746 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:51:20 +0100 Subject: [PATCH 10/17] feat(onboard): split mode classifies CLAUDE.md sections, onboarder MODE: split executes (RED: current skill ran archetype detection on split) --- agents/onboarder.md | 84 ++++++++++++++++++++++++++++++- skills/onboard/SKILL.md | 108 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 186 insertions(+), 6 deletions(-) diff --git a/agents/onboarder.md b/agents/onboarder.md index 209d1d7..f9d2b63 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) @@ -167,6 +170,85 @@ 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 row passes): +- `git -C status --porcelain` is empty, else STOP. +- gitignore: `git -C check-ignore -q .claude/rules/probe.md` + rc 0 means the rules would be ignored → append the negation (portable, + lands after any `.claude/*` line): + `printf '!.claude/rules/\n' >> /.gitignore` + then re-run `check-ignore`; still rc 0 → STOP: "ignore form cannot be + negated (BDR-003: use the `.claude/*` file form)", and `git -C + checkout -- .gitignore`. Remember whether this step + appended (`GITIGNORE_TOUCHED`): `.gitignore` enters the later `add`, + `checkout` and `commit` only then (a repo with no `.gitignore` is rc 1 + here and never names it: a missing pathspec is a fatal git error). +- 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 (nothing written yet besides the gitignore + line, which the STOP reverts). + +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. Collapse runs of blank lines left by +the extraction (never more than one). + +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 # + .gitignore when S0 appended +git -C commit -m "" +``` +`` 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/skills/onboard/SKILL.md b/skills/onboard/SKILL.md index a4f10b8..a0e3fd4 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). @@ -198,7 +205,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 +1041,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 +1086,94 @@ 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 → 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. A heading containing `'` or `|` is not split by this + mode (say so; the user renames it 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 +``` From dbd20dd5756ae556f5abb0a252d132aa14e3cfa8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:55:01 +0100 Subject: [PATCH 11/17] feat(generators): onboarder and scaffolder emit docker/testing/ci path rules from templates/project-rules --- agents/onboarder.md | 18 ++++++++++++++++++ agents/scaffolder.md | 19 +++++++++++++++++++ lib/tests/project-rules.test.sh | 18 ++++++++++++++++++ templates/project-CLAUDE.md | 1 + templates/project-rules/ci.md | 10 ++++++++++ templates/project-rules/docker.md | 10 ++++++++++ templates/project-rules/testing.md | 10 ++++++++++ 7 files changed, 86 insertions(+) create mode 100644 templates/project-rules/ci.md create mode 100644 templates/project-rules/docker.md create mode 100644 templates/project-rules/testing.md diff --git a/agents/onboarder.md b/agents/onboarder.md index f9d2b63..23a4915 100644 --- a/agents/onboarder.md +++ b/agents/onboarder.md @@ -128,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) 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/lib/tests/project-rules.test.sh b/lib/tests/project-rules.test.sh index 91d2eb1..b6ab70b 100644 --- a/lib/tests/project-rules.test.sh +++ b/lib/tests/project-rules.test.sh @@ -182,5 +182,23 @@ 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/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 + + + + + From 7b878b5dc30311cfe5c57f431729f35f83ff66ac Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:58:23 +0100 Subject: [PATCH 12/17] chore(todo): phase 0 done in-repo, per-repo pass queued as phase 0b --- .claude/tasks/TODO.md | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 3a139e5..bb43b71 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -17,17 +17,11 @@ 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. - [ ] **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. From 89334f29014dd1c8a85fc7aa65a544920ce89cbc Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 18:04:15 +0100 Subject: [PATCH 13/17] fix(rules): named dep-dir globs match, inline-paths error names the form, gitignore newline guard, no | in globs --- agents/onboarder.md | 7 ++++++- lib/project-rules.sh | 14 +++++++++++--- lib/tests/project-rules.test.sh | 7 ++++++- skills/onboard/SKILL.md | 6 ++++-- 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/agents/onboarder.md b/agents/onboarder.md index 23a4915..d50d331 100644 --- a/agents/onboarder.md +++ b/agents/onboarder.md @@ -206,7 +206,12 @@ S0 — PREFLIGHT (no write before every row passes): - `git -C status --porcelain` is empty, else STOP. - gitignore: `git -C check-ignore -q .claude/rules/probe.md` rc 0 means the rules would be ignored → append the negation (portable, - lands after any `.claude/*` line): + lands after any `.claude/*` line). If `/.gitignore` does + not exist, STOP: the ignore comes from outside the repo (global excludes + or `.git/info/exclude`); the user decides. Guard the trailing newline + first: `[ -n "$(tail -c1 /.gitignore)" ] && echo >> + /.gitignore` so the negation never glues onto the last + line. Then: `printf '!.claude/rules/\n' >> /.gitignore` then re-run `check-ignore`; still rc 0 → STOP: "ignore form cannot be negated (BDR-003: use the `.claude/*` file form)", and `git -C diff --git a/lib/project-rules.sh b/lib/project-rules.sh index a592583..6b50ad6 100644 --- a/lib/project-rules.sh +++ b/lib/project-rules.sh @@ -12,8 +12,11 @@ # 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, -# through symlinks, no brace expansion: one glob per extension), -# dependency dirs excluded: the engine matches the path the model reads, +# through symlinks, no brace expansion: one glob per extension; +# 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: @@ -42,6 +45,10 @@ _rules_globs() { } _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" } @@ -62,7 +69,8 @@ _rules_check_file() { # → rc 0 ok or always-on, rc 1 with culprits globs=$(_rules_globs "$fm") case $? in 1) echo "$1: always-on (no paths:)"; return 0 ;; - 2) echo "$1: paths: is not a JSON array of strings"; return 1 ;; + 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 diff --git a/lib/tests/project-rules.test.sh b/lib/tests/project-rules.test.sh index b6ab70b..a827ce3 100644 --- a/lib/tests/project-rules.test.sh +++ b/lib/tests/project-rules.test.sh @@ -47,7 +47,7 @@ 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: is not a JSON array of strings')" 1 + "$(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 @@ -88,6 +88,11 @@ 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' diff --git a/skills/onboard/SKILL.md b/skills/onboard/SKILL.md index a0e3fd4..f12ce69 100644 --- a/skills/onboard/SKILL.md +++ b/skills/onboard/SKILL.md @@ -1127,8 +1127,10 @@ CLAUDE.md` lists every `##` section with its size. For each one decide: 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. A heading containing `'` or `|` is not split by this - mode (say so; the user renames it first). + before showing it. A heading containing + `'` or `|`, or a glob containing `|`, is not split by this mode (the + TABLE rows are `|`-separated; say so, the user renames or re-globs + first). S5 — GATE (mandatory stop). Print the table, then end the turn: From 0b59687e1e0a32f73e6a05fcaa27b755f0e10ee7 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 21:53:49 +0100 Subject: [PATCH 14/17] fix(rules): extract rc 2 on a failed rewrite, H1 ends a section, split S0 ordered with row allowlist, stage per row --- agents/onboarder.md | 68 +++++++++++++++++++++------------ lib/project-rules.sh | 26 +++++++++---- lib/tests/project-rules.test.sh | 36 +++++++++++++++-- skills/onboard/SKILL.md | 17 ++++++--- 4 files changed, 104 insertions(+), 43 deletions(-) diff --git a/agents/onboarder.md b/agents/onboarder.md index d50d331..a01ece0 100644 --- a/agents/onboarder.md +++ b/agents/onboarder.md @@ -177,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 : ``` @@ -202,28 +203,38 @@ 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 row passes): -- `git -C status --porcelain` is empty, else STOP. -- gitignore: `git -C check-ignore -q .claude/rules/probe.md` - rc 0 means the rules would be ignored → append the negation (portable, - lands after any `.claude/*` line). If `/.gitignore` does - not exist, STOP: the ignore comes from outside the repo (global excludes - or `.git/info/exclude`); the user decides. Guard the trailing newline - first: `[ -n "$(tail -c1 /.gitignore)" ] && echo >> - /.gitignore` so the negation never glues onto the last - line. Then: - `printf '!.claude/rules/\n' >> /.gitignore` - then re-run `check-ignore`; still rc 0 → STOP: "ignore form cannot be - negated (BDR-003: use the `.claude/*` file form)", and `git -C - checkout -- .gitignore`. Remember whether this step - appended (`GITIGNORE_TOUCHED`): `.gitignore` enters the later `add`, - `checkout` and `commit` only then (a repo with no `.gitignore` is rc 1 - here and never names it: a missing pathspec is a fatal git error). -- 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 (nothing written yet besides the gitignore - line, which the STOP reverts). +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 @@ -242,8 +253,12 @@ S2 — POINTER. If CLAUDE.md has no `## Path-scoped rules` section, append: 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. Collapse runs of blank lines left by -the extraction (never more than one). +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 @@ -251,9 +266,12 @@ 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 # + .gitignore when S0 appended +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. diff --git a/lib/project-rules.sh b/lib/project-rules.sh index 6b50ad6..62e84fd 100644 --- a/lib/project-rules.sh +++ b/lib/project-rules.sh @@ -8,11 +8,15 @@ # 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, -# through symlinks, no brace expansion: one glob per extension; +# 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 @@ -104,11 +108,12 @@ project_rules_matches() { # → rc 0 + the first 3 hits, rc 1 none 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 { if (h != "") printf "%d\t%d\t%s\n", c, l, h - h = $0; l = NR; c = 0 } + /^# / && !fence { flush() } + /^## / && !fence { flush(); h = $0; l = NR; c = 0 } h != "" { c += length($0) + 1 } - END { if (h != "") printf "%d\t%d\t%s\n", c, l, h }' "$1" + END { flush() }' "$1" } _rules_heading_count() { # → fence-aware count of "## h" @@ -121,7 +126,7 @@ _rules_section_body() { # → body, trailing ---/blank trimmed awk -v h="## $2" ' /^```/ { fence = !fence } !fence && $0 == h { on = 1; next } - !fence && on && /^## / { exit } + !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" @@ -131,7 +136,7 @@ _rules_without_section() { # → the file minus that section awk -v h="## $2" ' /^```/ { fence = !fence } !fence && $0 == h { skip = 1; next } - !fence && skip && /^## / { skip = 0 } + !fence && skip && (/^## / || /^# /) { skip = 0 } !skip { print }' "$1" } @@ -154,10 +159,15 @@ project_rules_extract() { # [ -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" - tmp=$(mktemp) - _rules_without_section "$src" "$heading" > "$tmp" && cat "$tmp" > "$src" + 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" } diff --git a/lib/tests/project-rules.test.sh b/lib/tests/project-rules.test.sh index a827ce3..54bf3a0 100644 --- a/lib/tests/project-rules.test.sh +++ b/lib/tests/project-rules.test.sh @@ -121,6 +121,7 @@ check T6b-beta-line "$(printf '%s\n' "$out" | awk -F'\t' '$3=="## Beta"{print $2 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 @@ -132,6 +133,10 @@ 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 @@ -155,6 +160,29 @@ 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" @@ -168,12 +196,12 @@ check T10e-ids-kept "$(jq -r '[.session_id, .agent_id, .globs[0]] | join(",")' " 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: the blank PATH applies to the command lookup too (rc 127) +# "$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-no-jq-rc0 "$rc" 0 -check T10i-no-jq-stdout-empty "$out" "" -check T10j-no-jq-nothing-appended "$(wc -l < "$LOG" | tr -d ' ')" 1 +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 diff --git a/skills/onboard/SKILL.md b/skills/onboard/SKILL.md index f12ce69..da14e89 100644 --- a/skills/onboard/SKILL.md +++ b/skills/onboard/SKILL.md @@ -117,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. @@ -1103,8 +1104,11 @@ 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 → list -them, continue (new rules add to them). +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 @@ -1127,10 +1131,11 @@ CLAUDE.md` lists every `##` section with its size. For each one decide: 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. A heading containing - `'` or `|`, or a glob containing `|`, is not split by this mode (the - TABLE rows are `|`-separated; say so, the user renames or re-globs - first). + 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: From 336e7a7e4e219641464b2a80198f0a33e94ee36d Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 27 Oct 2026 11:36:37 +0100 Subject: [PATCH 15/17] =?UTF-8?q?chore(memory):=20BDR-128=20+=20LRN-232/23?= =?UTF-8?q?3=20+=20EVAL-051=20=E2=80=94=20ship-feature=20claude-md=20split?= =?UTF-8?q?,=20contract=20+=20TODO=200b=20note?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/decisions.md | 8 ++ .claude/memory/evals.md | 6 ++ .claude/memory/journal.md | 6 ++ .claude/memory/learnings.md | 10 ++ .claude/tasks/TODO.md | 3 +- .../2026-10-26-claude-md-split-0042.md | 93 +++++++++++++++++++ 6 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 .claude/tasks/contracts/2026-10-26-claude-md-split-0042.md 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/tasks/TODO.md b/.claude/tasks/TODO.md index bb43b71..2f3eff3 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -21,7 +21,8 @@ Shared rules for every phase: - [ ] 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. +- [ ] **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). From dc6580a6e57ad70cca183c09dddae99b8a57723b Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 27 Oct 2026 12:05:38 +0100 Subject: [PATCH 16/17] =?UTF-8?q?docs:=20ARCHITECTURE=20tree,=20README/USA?= =?UTF-8?q?GE=20/onboard=20split,=20CHANGELOG=20path=20rules=20+=20Instruc?= =?UTF-8?q?tionsLoaded=20logger=20=E2=80=94=20ship-feature=20claude-md=20s?= =?UTF-8?q?plit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ARCHITECTURE.md | 7 ++++--- CHANGELOG.md | 3 +++ README.md | 2 +- USAGE.md | 5 +++-- 4 files changed, 11 insertions(+), 6 deletions(-) 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/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 :** From 9e116a48d7220335947b15dc553e00f6c84106c1 Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 27 Oct 2026 13:24:19 +0100 Subject: [PATCH 17/17] chore: purge transient planning artifacts (BDR-065) --- .../plans/2026-10-26-claude-md-split.md | 1238 ----------------- .../2026-10-26-claude-md-split-design.md | 191 --- 2 files changed, 1429 deletions(-) delete mode 100644 docs/superpowers/plans/2026-10-26-claude-md-split.md delete mode 100644 docs/superpowers/specs/2026-10-26-claude-md-split-design.md diff --git a/docs/superpowers/plans/2026-10-26-claude-md-split.md b/docs/superpowers/plans/2026-10-26-claude-md-split.md deleted file mode 100644 index 8a13c93..0000000 --- a/docs/superpowers/plans/2026-10-26-claude-md-split.md +++ /dev/null @@ -1,1238 +0,0 @@ -# Phase 0 — split project CLAUDE.md into `.claude/rules/` — Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Move the four path-bound sections of this repo's project CLAUDE.md into `.claude/rules/.md` path rules, prove they load, and give every project the same lever (`/onboard split`, generators born split). - -**Architecture:** One bash lib (`lib/project-rules.sh`: `check`, `matches`, `sections`, `extract`, `emit`, all behind an optional `-C `) is the deterministic oracle for every consumer: the `make test` suite, this repo's own split, the onboarder in `MODE: split`, and the two generators. Judgment (which section is path-scoped, which globs) stays in the `/onboard split` main loop; writes are executed by the sonnet onboarder against an explicit project root. A permanent `InstructionsLoaded` hook logs every loaded instruction file (with session and agent ids) so a path-rule load is a grep, not a guess. - -**Tech Stack:** bash 5 (`compgen -G` with globstar/dotglob), awk, jq, shellcheck; markdown skills/agents; Claude Code path-scoped rules (`paths:` frontmatter) and the `InstructionsLoaded` classic hook. - -**Spec:** `docs/superpowers/specs/2026-10-26-claude-md-split-design.md` -**Contract:** `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md` -**Branch:** `feature/claude-md-split`, already started off develop (spec 2c8e4a2, plan r1 420448a). **Implement in place on this checkout, no worktree**: `~/.claude/{lib,agents,skills,hooks,settings.json}` are symlinks into this repo, and Tasks 6, 8 and 11 exercise the live links. - -Spec deltas, decided while planning (r2 after the three-lens challenge, r3 after the correctness confirmation): a `matches ` subcommand (the split mode's only glob oracle, so the skill never consults `git ls-files`); `emit ` (writes a skeleton with the matching globs only); `-C ` on every subcommand (a dispatched agent's cwd is the session's, never the project's); `extract` refuses a glob that matches nothing and a heading that does not occur exactly once; the hook also logs `session_id`, `agent_id`, `agent_type`, `globs` and rotates above 5 MB; the graphify rule drops `.graphify_version` (it lives under `skills/graphify/`, already covered); the onboarder's default-mode PHASE 4 is untouched (the gitignore socle reaches onboarded projects through STEP 2.6 `gitflow init`). r3: `matches` reads its whole pipe through awk (a `head` reader gives the writer SIGPIPE, rc 141 under `pipefail`, so any glob with more than a pipe buffer of hits read as "no match"); the no-jq hook test runs `"$BASH"` (a temporary `PATH=/nonexistent` makes `bash` itself unfindable, rc 127); the Task 8 dry run branches the scratch first (the global pre-commit hook blocks a CLAUDE.md commit on `develop`); the onboarder checks the commit rc, rolls back on failure and verifies `HEAD:` with `cat-file`; globs carry no braces (`compgen -G` does not expand them). - -Baseline, taken 2026-10-26 before any edit (`claude -p "/context"` at the repo root, CLAUDE.md unchanged): total 32.2k; Memory files 11.6k, of which project CLAUDE.md 2.1k; Skills 10k; Custom agents 2.6k; System prompt 4.4k; MCP instructions 2.2k. - -## Global Constraints - -- Our code (strict): max 25 logic lines per function, 80 chars per line, 5 params, 5 locals; `shellcheck *.sh hooks/*.sh lib/*.sh` clean; no `sed -i '` in any file (portability census scans `*.sh`; agent text follows the same rule). -- Subtract-only: section text moves verbatim; nothing deleted from CLAUDE.global.md / rules/; registries (`.claude/memory/*`) are never edited by a task (STEP 7 capitalize owns them). CLAUDE.md keeps its lines 1-3 HTML comment. -- Never write into `rules/` (user scope, every project) except the pointer fix in `rules/README.md`. -- `.gitignore` negations only work with the `.claude/*` file form (BDR-003); the negation line must come AFTER `.claude/*`. -- Hooks never print to stdout (stdout reaches the model) and never block. -- The doctrine-citers census (`lib/tests/doctrine-citers.test.sh`) flags any `CLAUDE.md` followed within 12 chars by a double quote in skills/agents/lib/rules/hooks: new text never writes `CLAUDE.md "…"`; headings in command templates are single-quoted. -- Commit on the feature branch only, one commit per task, message under 50 words, no attribution lines. -- Frontmatter shape is exactly `paths: ["glob", "glob"]` on one line (as `rules/a11y.md`). No brace glob (`*.{ts,tsx}`): `compgen -G` does no brace expansion, so one glob per extension. -- A pipeline whose reader may stop early (`head`, `grep -q`) gives the writer SIGPIPE; under `set -o pipefail` that is rc 141 on the whole pipeline. The lib never puts `head` after a producer: awk reads the pipe to its end. -- A temporary assignment `PATH=/nonexistent cmd` applies to the lookup of `cmd` itself: write `"$BASH"`, never `bash`, when the test blanks PATH. -- Commands with a shell variable in a path are denied by the permission rules in this repo: write literal paths in every Bash step; agent templates say `` and the executor substitutes the literal. -- Deferred, for the human gate: the pre-commit `.claude/**` exemption lets a rules-only commit land directly on develop/main `[deferred 2026-10-26]` (phase 2, guards, narrows it; split mode always branches first). - -## Review Focus - -1. A heading inside a fenced code block, or a duplicated heading, must never be moved: `sections` ignores fenced lines, `extract` refuses unless the fence-aware count is exactly 1 (T6, T8e, T8f in Task 1). -2. A literal glob (no `*?[`) that names a missing file must fail `check` and be pruned by `emit`: bash never expands a plain word, so the matcher uses `compgen -G` (T2c, T12b, T12f in Tasks 1 and 9). -3. A glob that matches only under `node_modules/`, `.venv/`, `vendor/`, `target/`, `dist/`, `build/` or `.git/` counts as no match (T2d in Task 1). -4. A dispatched onboarder must act on the project root it was given, never on the session cwd: every lib call carries `-C `, every git call `-C` (Task 8 asserts the scratch repo got the commit on its chore branch and this repo's status is unchanged). -6. A glob with thousands of hits (a real repo's `src/**`) must still be a match: `matches` reads the whole pipe (T5k, T5l in Task 1). -5. The hook must exit 0 and print nothing when `jq` is absent or the log dir is unwritable (T10f-T10h in Task 2). - ---- - -### Task 1: `lib/project-rules.sh` + its suite (check / matches / sections / extract) - -**Files:** -- Create: `lib/project-rules.sh` -- Create: `lib/tests/project-rules.test.sh` - -**Interfaces:** -- Produces: `bash lib/project-rules.sh [-C ] check [rules-dir]` (rc 0 + `project-rules: N rule(s) ok`; rc 2 + `: ` lines; `: SKIP ` for a skip-marked file; `: always-on (no frontmatter)` / `(no paths:)` as info); `matches ` (rc 0 + up to 3 hits, rc 1 + `no match: ` on stderr); `sections ` (`\t\t## ` per top-level section, fence-aware); `extract '' ''` (rc 0 moved; rc 2 heading count ≠ 1 / target exists / malformed globs / a glob matches nothing, nothing written). Task 9 adds `emit`. - -- [ ] **Step 1: Write the failing suite (T1-T9)** - -Create `lib/tests/project-rules.test.sh` (4-backtick fence: the heredoc inside holds a ``` line): - -````bash -#!/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: is not a JSON array of strings')" 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 - -# 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 - -# 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 - -# 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 - -echo "PASS=$pass FAIL=$fail" -[ "$fail" -eq 0 ] -```` - -(T6c: the Alpha section spans `## Alpha`, `aaa`, blank, `---`, blank; each line counts its length plus one newline: 9+4+1+4+1 = 19.) - -- [ ] **Step 2: Run the suite, verify it fails** - -Run: `bash lib/tests/project-rules.test.sh` -Expected: many `FAIL …` lines (the lib does not exist), last line `PASS=… FAIL=…` with FAIL above 40 (a few negative checks such as T6d, T8b, T9c pass with no lib), exit 1. - -- [ ] **Step 3: Write the lib** - -Create `lib/project-rules.sh`: - -```bash -#!/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 -# 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, -# through symlinks, no brace expansion: one glob per extension), -# dependency dirs excluded: 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 - ( 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: is not a JSON array of strings"; 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 ' - /^```/ { fence = !fence } - /^## / && !fence { if (h != "") printf "%d\t%d\t%s\n", c, l, h - h = $0; l = NR; c = 0 } - h != "" { c += length($0) + 1 } - END { if (h != "") printf "%d\t%d\t%s\n", c, l, h }' "$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")" - { printf -- '---\npaths: %s\n---\n\n# %s\n' "$globs" "$heading" - _rules_section_body "$src" "$heading"; } > "$out" - tmp=$(mktemp) - _rules_without_section "$src" "$heading" > "$tmp" && cat "$tmp" > "$src" - 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 -``` - -- [ ] **Step 4: Run the suite, verify T1-T9 pass** - -Run: `bash lib/tests/project-rules.test.sh` -Expected: `PASS=… FAIL=0`, exit 0. - -- [ ] **Step 5: shellcheck, 80 columns, census, make test on the new suite** - -Run: `shellcheck lib/project-rules.sh lib/tests/project-rules.test.sh; awk 'length > 80 {print FILENAME": "FNR": "length}' lib/project-rules.sh; make test suite=lib/tests/project-rules.test.sh | tail -1; make test suite=lib/tests/doctrine-citers.test.sh | tail -1; make test suite=lib/tests/portability-census.test.sh | tail -1` -Expected: no shellcheck output, no awk output, `all suites green` three times. - -- [ ] **Step 6: Commit** - -```bash -git add lib/project-rules.sh lib/tests/project-rules.test.sh -git commit -m "feat(rules): lib/project-rules.sh check/matches/sections/extract + suite" -``` - ---- - -### Task 2: InstructionsLoaded proof hook - -**Files:** -- Create: `hooks/instructions-loaded.sh` -- Modify: `settings.json` (hooks block, after the `"SessionStart": [ … ],` block, before `"PreToolUse": [`) -- Modify: `lib/tests/project-rules.test.sh` (append T10 before the tally) - -**Interfaces:** -- Produces: one JSON line per loaded instruction file in `~/.claude/logs/instructions-loaded.jsonl` (`ts, session_id, agent_id, agent_type, cwd, file_path, memory_type, load_reason, globs, trigger_file_path`); `CLAUDE_INSTRUCTIONS_LOG=` overrides the log path (tests); the log rotates to `.1` above 5 MB. - -- [ ] **Step 1: Append the failing hook tests (T10) to the suite** - -Insert before the `echo "PASS=$pass FAIL=$fail"` line of `lib/tests/project-rules.test.sh`: - -```bash -# 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: the blank PATH applies to the command lookup too (rc 127) -out=$(printf '%s' "$IN" \ - | CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent "$BASH" "$HOOK"); rc=$? -check T10h-no-jq-rc0 "$rc" 0 -check T10i-no-jq-stdout-empty "$out" "" -check T10j-no-jq-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 -``` - -- [ ] **Step 2: Run the suite, verify T10 fails** - -Run: `bash lib/tests/project-rules.test.sh | tail -3` -Expected: `FAIL T10-hook-rc` (hook missing), exit 1. - -- [ ] **Step 3: Write the hook** - -Create `hooks/instructions-loaded.sh`: - -```bash -#!/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 -``` - -- [ ] **Step 4: Register it in `settings.json`** - -In `settings.json`, after the `"SessionStart": [ … ],` block (the `],` that closes it, just before `"PreToolUse": [`), insert: - -```json - "InstructionsLoaded": [ - { - "hooks": [ - { - "type": "command", - "command": "bash ~/.claude/hooks/instructions-loaded.sh", - "timeout": 5 - } - ] - } - ], -``` - -Verify: `jq -r '.hooks.InstructionsLoaded[0].hooks[0].command' settings.json` prints `bash ~/.claude/hooks/instructions-loaded.sh`. - -- [ ] **Step 5: Run the suite, verify T10 passes** - -Run: `bash lib/tests/project-rules.test.sh | tail -1 && shellcheck hooks/instructions-loaded.sh && make test suite=lib/tests/curated-config-guard.test.sh | tail -1` -Expected: `FAIL=0`, no shellcheck output, `all suites green`. - -- [ ] **Step 6: Commit** - -```bash -git add hooks/instructions-loaded.sh settings.json lib/tests/project-rules.test.sh -git commit -m "feat(hooks): InstructionsLoaded logger, the proof channel for path rules" -``` - ---- - -### Task 3: gitignore negation, here and in the socle - -**Files:** -- Modify: `.gitignore:122-126` -- Modify: `templates/gitignore/standard.gitignore` (the `.claude/*` block) -- Modify: `lib/gitflow-test.sh:47` (one more socle assertion) - -- [ ] **Step 1: Add the failing socle assertion** - -In `lib/gitflow-test.sh`, after line 47 (`chk "socle: !.claude/deploy/" …`), add: - -```bash -chk "socle: !.claude/rules/" 'grep -qxF "!.claude/rules/" .gitignore' -``` - -- [ ] **Step 2: Run gitflow-test, verify the new assertion fails** - -Run: `make test suite=lib/gitflow-test.sh 2>&1 | grep -E 'rules|suite'` -Expected: `FAIL socle: !.claude/rules/ …` and `1 suite(s) red`. - -- [ ] **Step 3: Patch the socle and this repo's `.gitignore`** - -`templates/gitignore/standard.gitignore`: after the line `!.claude/deploy/` add the line `!.claude/rules/` (it stays after `.claude/*`; reconcile appends missing lines at the end of a project's file, which is after any existing `.claude/*`). - -`.gitignore`: add `!.claude/rules/` directly after `!.claude/settings.json` (line 126), so the block reads: - -``` -.claude/* -!.claude/tasks/ -!.claude/memory/ -!.claude/audits/ -!.claude/settings.json -!.claude/rules/ -``` - -- [ ] **Step 4: Verify** - -Run: `make test suite=lib/gitflow-test.sh 2>&1 | tail -1; git check-ignore -q .claude/rules/probe.md; echo "ignored-rc=$?"` -Expected: `all suites green`; `ignored-rc=1` (not ignored; `git check-ignore` needs no existing file). - -- [ ] **Step 5: Commit** - -```bash -git add .gitignore templates/gitignore/standard.gitignore lib/gitflow-test.sh -git commit -m "chore(gitignore): un-ignore .claude/rules/ here and in the gitflow socle" -``` - ---- - -### Task 4: split this repo's CLAUDE.md (dogfood `extract`) - -**Files:** -- Modify: `CLAUDE.md` (four sections leave, a pointer section arrives; lines 1-3 comment stays) -- Create: `.claude/rules/rules-maintenance.md`, `.claude/rules/graphify-vendored.md`, `.claude/rules/mods.md`, `.claude/rules/transient-artifacts.md` -- Modify: `lib/tests/project-rules.test.sh` (append T11 before the tally) - -**Interfaces:** -- Consumes: `lib/project-rules.sh extract` / `check` (Task 1). - -- [ ] **Step 1: Append the failing real-repo test (T11)** - -Insert before the `echo "PASS=$pass FAIL=$fail"` line of `lib/tests/project-rules.test.sh`: - -```bash -# 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 -``` - -Run: `bash lib/tests/project-rules.test.sh | tail -4` -Expected: `FAIL T11b-four-rules: got[0] want[1]` (0 rules yet). - -- [ ] **Step 2: Move the four sections with `extract`** - -From the repo root, in this order (headings are exact, copied from CLAUDE.md; the transient rule is extracted with the one glob that matches mid-run, `docs/superpowers/**`, since `.audit/` does not exist at rest): - -```bash -bash lib/project-rules.sh extract CLAUDE.md 'rules/ maintenance' .claude/rules/rules-maintenance.md '["rules/**", "CLAUDE.global.md"]' -bash lib/project-rules.sh extract CLAUDE.md 'Machine-owned: the vendored graphify skill' .claude/rules/graphify-vendored.md '["skills/graphify/**", "install-plugins.sh"]' -bash lib/project-rules.sh extract CLAUDE.md 'mods/ — function-hooks plugins (Claude Code mods)' .claude/rules/mods.md '["mods/**", "skills/model-router/**", "lib/tests/mods.test.sh"]' -bash lib/project-rules.sh extract CLAUDE.md 'Transient planning artifacts' .claude/rules/transient-artifacts.md '["docs/superpowers/**"]' -``` - -Expected: four `project-rules: moved '## …' to .claude/rules/….md` lines. `git diff --stat CLAUDE.md` shows about 90 deletions and no insertion. - -- [ ] **Step 3: Transient rule: second glob + skip marker** - -Edit `.claude/rules/transient-artifacts.md` so its frontmatter reads exactly: - -``` ---- -paths: ["docs/superpowers/**", ".audit/**"] -# static-check: skip ---- -``` - -- [ ] **Step 4: The pointer section in CLAUDE.md** - -Append to CLAUDE.md: - -```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): rules-maintenance, -graphify-vendored, mods, transient-artifacts. Check: `bash -lib/project-rules.sh check` (runs in `make test`). -``` - -The whole file must then read (lines 1-3 are the existing comment, untouched): - -```markdown - - -# claude-config — project instructions - -## Health Stack -- shell: `shellcheck *.sh hooks/*.sh lib/*.sh` - -## 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`). -``` - -(Remove any run of more than one blank line left by the extraction.) - -- [ ] **Step 5: Verify** - -Run: `bash lib/project-rules.sh check; bash lib/tests/project-rules.test.sh | tail -1; git status --short --untracked-files=all .claude/rules CLAUDE.md; git diff HEAD --stat -- CLAUDE.md; wc -c .claude/rules/*.md` -Expected: `transient-artifacts.md: SKIP docs/superpowers/**`, `… SKIP .audit/**`, `project-rules: 4 rule(s) ok`; `FAIL=0`; four `??` entries under `.claude/rules/` (`--untracked-files=all`, else git collapses the new dir into one line) plus ` M CLAUDE.md`; the four rule files sum to roughly the 4,960 chars the sections held (T7 proves `extract` is verbatim; the sizes are the sanity check). - -- [ ] **Step 6: Commit** - -```bash -git add CLAUDE.md .claude/rules lib/tests/project-rules.test.sh -git commit -m "refactor(claude-md): four sections become .claude/rules path rules (phase 0)" -``` - ---- - -### Task 5: citers of the moved sections - -**Files:** -- Modify: `rules/README.md:8-9` -- Modify: `doctor.sh:76` - -- [ ] **Step 1: Repoint `rules/README.md`** - -Replace lines 8-9: - -``` -Maintenance doctrine (what belongs here, lazy-load `paths:` semantics, -machine-owned files): see `CLAUDE.md` (project scope) at the repo root. -``` - -with: - -``` -Maintenance doctrine (what belongs here, lazy-load `paths:` semantics, -machine-owned files): see `.claude/rules/rules-maintenance.md` in the -claude-config repo (project scope, loads on Read under `rules/`). -``` - -Line 7 (`User-scope rules, deployed to …`) stays. - -- [ ] **Step 2: Fix the stale doctor comment** - -`doctor.sh:76`: replace `(the 29-line project CLAUDE.md instead of` with `(the project CLAUDE.md instead of`. - -- [ ] **Step 3: Census grep** - -Run: -```bash -grep -rnE 'CLAUDE\.md`? \(project scope\)|29-line project CLAUDE\.md|Machine-owned: the vendored|§ ?Transient planning|"rules/ maintenance"|"mods/ — function-hooks"' rules/ doctor.sh skills/ agents/ lib/ hooks/ README.md ARCHITECTURE.md --include='*.md' --include='*.sh' | grep -v 'skills-external\|skills/graphify/\|lib/tests/project-rules' -``` -Expected: no output. (The optional backtick matches the README's `` `CLAUDE.md` (project scope) `` form: on today's tree, before Step 1, this grep returns rules/README.md:9 and doctor.sh:76; after Steps 1-2 nothing.) (`lib/gitflow.sh:21` mentions transient planning artifacts in a comment about the purge, not as a citation: leave it. `install-plugins.sh` GUARDED_CONFIGS keeps `CLAUDE.md`: leave it. `ARCHITECTURE.md` is the doc pipeline's, STEP 8.) - -- [ ] **Step 4: make test + commit** - -Run: `make test suite=lib/tests/doctrine-citers.test.sh | tail -1` -Expected: `all suites green`. - -```bash -git add rules/README.md doctor.sh -git commit -m "chore(citers): rules/README and doctor point at .claude/rules after the split" -``` - ---- - -### Task 6: `/onboard split` RED pressure test (orchestrator dispatch, no code) - -**Files:** none modified. Scratch: `/tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/` (a git repo on branch `develop` holding `CLAUDE.md` = `git show develop:CLAUDE.md`, plus `rules/x.md`, `mods/m/plugin.json`, `.gitignore` with `.claude/*`). - -- [ ] **Step 1: Assert in-place links, build the scratch repo** - -Run (one line, literal paths): `readlink -f ~/.claude/lib ~/.claude/skills ~/.claude/agents ~/.claude/hooks ~/.claude/settings.json` → every line under `/home/bchanot/Documents/claude/`. - -```bash -mkdir -p /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/rules /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/mods/m && git show develop:CLAUDE.md > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/CLAUDE.md && echo r > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/rules/x.md && echo '{}' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/mods/m/plugin.json && printf '.claude/*\n!.claude/memory/\n' > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red/.gitignore && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red init -q -b develop && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red add -A && git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-red commit -qm init -``` - -- [ ] **Step 2: Dispatch the RED probe (sonnet)** - -`Agent(subagent_type="general-purpose", model="sonnet", effort="medium")` with: "Probe of a skill's text, not a real run. Read `/home/bchanot/.claude/skills/onboard/SKILL.md` as if you had been invoked as `/onboard split` in the project ``. Treat the MODEL GATE as passed and never call `mcp__model-router__route`; do not dispatch agents, do not run `claude`, do not write outside the scratch. Follow the skill's text for what it tells you to do first, up to the first point where it would stop for the user or dispatch an agent, then stop. Report: the steps you ran in order, whether any step had you classify the CLAUDE.md sections into path-scoped rules, and what you would have shown the user." - -Expected (RED): the report names the plugin check / archetype detection; no classification table, no `.claude/rules/` written. Record one line for the Task 7 commit message ("RED: current skill runs archetype detection on `split`"). - -If the probe DOES produce a split with the current skill: stop, the mode is unnecessary as designed; re-plan. - ---- - -### Task 7: `/onboard split` mode + onboarder `MODE: split` - -**Files:** -- Modify: `skills/onboard/SKILL.md` (frontmatter lines 4-5, after `## REQUEST` ~line 20, STEP 3 draft-update line ~201, RULES lines ~1037 and ~1041, append § SPLIT MODE after FINAL OUTPUT) -- Modify: `agents/onboarder.md` (after `## ROLE`; RULES line 170; a new section at the end) - -**Interfaces:** -- Consumes: `project-rules.sh -C sections|matches|extract|check` (Task 1). -- Produces: the onboarder `MODE: split` contract: INPUTS `PROJECT_ROOT`, `TABLE` rows ` | | `; OUTPUT rules written, check result, commit hash, or `STOP: — ` with the rollback done. - -- [ ] **Step 1: Skill frontmatter** - -Line 4 `description:` — replace `Do NOT use for repos created via /init-project.` with `Default flow: do NOT use it for repos created via /init-project.` and append inside the quoted string, before the closing `'`: ` `split` mode (any repo): "onboard split", "split the project instructions", "découpe le fichier CLAUDE", "path-scoped rules".` -Line 5: `argument-hint: '[split | optional hints: "Python FastAPI" | "Next.js monorepo" | "force-archetype:wordpress"]'` - -- [ ] **Step 2: MODE DISPATCH after `## REQUEST`** - -After the `$ARGUMENTS` line of `## REQUEST` and its `---`, insert: - -```markdown -## 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 3: STEP 3 draft update and the RULES lines** - -STEP 3 (~line 201): replace `Après réponses : **mettre à jour le brouillon CLAUDE.md** avec les infos obtenues.` with `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).` - -RULES: replace `- NO skipping STEP 0, 1, 2 — ils sont obligatoires.` with `- NO skipping STEP 0, 1, 2 — ils sont obligatoires (split mode runs its own steps, § SPLIT MODE).` and replace `- Si `CLAUDE.md` existe : le lire, ne pas l'écraser sans fusion après STEP 3.` with `- 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 4: § SPLIT MODE appended at the end of the skill** (4-backtick fence, inner ``` blocks are part of the text) - -````markdown - ---- - -## 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 → 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. A heading containing `'` or `|` is not split by this - mode (say so; the user renames it 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 -``` -```` - -- [ ] **Step 5: Onboarder: mode header, RULES exemption, `MODE: split` section** - -In `agents/onboarder.md`, insert right after the `## ROLE` paragraph (before the `---` that precedes `## INPUTS`): - -```markdown -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. -``` - -RULES line 170: replace `- NO destructive writes: never overwrite CLAUDE.md if it exists without asking (print path + STOP, let orchestrator decide).` with `- 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.` - -Append at the end of the file (4-backtick fence, inner ``` blocks are part of the text): - -````markdown - ---- - -## 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 row passes): -- `git -C status --porcelain` is empty, else STOP. -- gitignore: `git -C check-ignore -q .claude/rules/probe.md` - rc 0 means the rules would be ignored → append the negation (portable, - lands after any `.claude/*` line): - `printf '!.claude/rules/\n' >> /.gitignore` - then re-run `check-ignore`; still rc 0 → STOP: "ignore form cannot be - negated (BDR-003: use the `.claude/*` file form)", and `git -C - checkout -- .gitignore`. Remember whether this step - appended (`GITIGNORE_TOUCHED`): `.gitignore` enters the later `add`, - `checkout` and `commit` only then (a repo with no `.gitignore` is rc 1 - here and never names it: a missing pathspec is a fatal git error). -- 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 (nothing written yet besides the gitignore - line, which the STOP reverts). - -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. Collapse runs of blank lines left by -the extraction (never more than one). - -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 # + .gitignore when S0 appended -git -C commit -m "" -``` -`` 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)`. -```` - -- [ ] **Step 6: Locks still hold** - -Run: `for s in model-routing effort-routing loops-heavy plan-challenger security-auditor doctrine-citers portability-census; do make test suite=lib/tests/$s.test.sh | tail -1; done` -(If the loop form is refused by the permission rules, run the seven `make test suite=…` commands one by one.) -Expected: `all suites green` seven times. - -- [ ] **Step 7: Commit** - -```bash -git add skills/onboard/SKILL.md agents/onboarder.md -git commit -m "feat(onboard): split mode classifies CLAUDE.md sections, onboarder MODE: split executes (RED: current skill ran archetype detection on split)" -``` - ---- - -### Task 8: `/onboard split` GREEN pressure test (orchestrator dispatch, no code) - -- [ ] **Step 1: Fresh scratch repo `split-green/`** - -Same one-liner as Task 6 Step 1 with `split-red` replaced by `split-green` everywhere (no `git clean`: a fresh directory). - -- [ ] **Step 2: Dispatch the GREEN probe (sonnet, its own prompt)** - -`Agent(subagent_type="general-purpose", model="sonnet", effort="medium")` with: "Probe of a skill's text, not a real run. Read `/home/bchanot/.claude/skills/onboard/SKILL.md` as if you had been invoked as `/onboard split` in the project `` (a git repo on `develop`, clean). Treat the MODEL GATE as passed and never call `mcp__model-router__route`; treat S2 (the `claude -p` baseline) as done with the value 2.1k; do not dispatch agents; do not write anything, not even the branch (report the command you would run instead). Follow the skill's text up to the mandatory stop, then stop. Report: the steps you ran in order, the classification table you would print, and the exact `matches` commands you ran." - -Expected (GREEN): the report says it took MODE DISPATCH → § SPLIT MODE, ran S1, S3 (reported, not run), S4 with `matches` calls, and printed the S5 table (at least `rules/ maintenance` → move with `rules/**` and `Health Stack` → keep), then stopped. A probe that writes files, skips the gate, or runs archetype detection = not green: fix the skill text, re-run. - -- [ ] **Step 3: Executor dry run (onboarder, MODE: split) on the scratch** - -Before the dispatch, mirror the skill's S3 (the scratch is on `develop`, and the global `core.hooksPath` pre-commit blocks any commit there that stages a path outside `.claude/`): `git -C /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/split-green switch -c chore/claude-md-split`, and snapshot this repo: `git status --porcelain > /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/status-before.txt; git rev-parse HEAD`. - -Dispatch `Agent(subagent_type="onboarder")` with `MODE: split`, `PROJECT_ROOT: `, `TABLE:` two rows: `rules/ maintenance | rules-maintenance | ["rules/**"]` and `mods/ — function-hooks plugins (Claude Code mods) | mods | ["mods/**"]`. -Expected: `SPLIT DONE: 2 rule(s)` with `all rules in HEAD`; `git -C log --oneline -1 --decorate` shows the split commit on `chore/claude-md-split` (the post-commit push hook warns about the missing origin, never blocks); `.gitignore` there ends with `!.claude/rules/`; `bash lib/project-rules.sh -C check` prints `2 rule(s) ok`; and THIS repo is untouched: `git status --porcelain | diff - /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/status-before.txt` empty (the untracked contract file is in both) and `git rev-parse HEAD` unchanged. - -- [ ] **Step 4: Record** - -No commit. The orchestrator notes RED/GREEN outcomes for STEP 7 capitalize (EVAL entry). - ---- - -### Task 9: generators born split (skeletons, `emit`, onboarder PHASE 5b, scaffolder PHASE 3b) - -**Files:** -- Create: `templates/project-rules/docker.md`, `templates/project-rules/testing.md`, `templates/project-rules/ci.md` -- Modify: `templates/project-CLAUDE.md:4` (header comment) -- Modify: `agents/onboarder.md` (new PHASE 5b after PHASE 5) -- Modify: `agents/scaffolder.md` (new PHASE 3b between PHASE 3 and PHASE 4) -- Modify: `lib/tests/project-rules.test.sh` (append T12 before the tally) - -**Interfaces:** -- Consumes: `project-rules.sh emit ` (Task 1): rc 0 written with matching globs only, rc 1 none matched (nothing written), rc 2 malformed / target exists. - -- [ ] **Step 1: Append the failing skeleton tests (T12)** - -Insert before the tally line of the suite: - -```bash -# 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 -``` - -Run: `bash lib/tests/project-rules.test.sh | tail -3` -Expected: `FAIL T12-docker-emitted` (skeleton missing). - -- [ ] **Step 2: The three skeletons** - -`templates/project-rules/docker.md`: -```markdown ---- -paths: ["Dockerfile*", "docker-compose*", "compose*.y*ml", ".dockerignore"] ---- - -# Docker - - - - - -``` - -`templates/project-rules/testing.md`: -```markdown ---- -paths: ["tests/**", "test/**", "**/*.test.*", "**/*.spec.*", "**/conftest.py"] ---- - -# Testing conventions - - - - - -``` - -`templates/project-rules/ci.md`: -```markdown ---- -paths: [".github/workflows/**", ".gitlab-ci.yml", ".circleci/**"] ---- - -# CI - - - - - -``` - -`templates/project-CLAUDE.md` line 4: after `# Global rules: ~/.claude/CLAUDE.md — this file extends or overrides them.` add the line `# Path-scoped rules: .claude/rules/.md (paths: frontmatter), loaded on Read of a matching file.` - -- [ ] **Step 3: Onboarder PHASE 5b** - -In `agents/onboarder.md`, after the PHASE 5 block (after `**Do NOT overwrite existing content.**` and before the `---` that precedes PHASE 6), add (4-backtick fence, the inner ```bash block is part of the text): - -````markdown - -## 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. -```` - -- [ ] **Step 4: Scaffolder PHASE 3b** - -In `agents/scaffolder.md`, after the PHASE 3 block (its last stack line, before the `---` that precedes `## PHASE 4`), add (4-backtick fence, the inner ```bash block is part of the text): - -````markdown - -## 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. -```` - -- [ ] **Step 5: Verify** - -Run: `bash lib/tests/project-rules.test.sh | tail -1; mkdir -p /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/.github/workflows /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/tests /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/test /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all/.circleci && cd /tmp/claude-1000/-home-bchanot-Documents-claude/ea0efe5f-67aa-4f89-9e2a-ba0ac8695999/scratchpad/gen-all && touch Dockerfile docker-compose.yml compose.yaml .dockerignore .gitlab-ci.yml tests/a test/b a.test.ts b.spec.ts conftest.py .github/workflows/ci.yml .circleci/config.yml && bash /home/bchanot/Documents/claude/lib/project-rules.sh check /home/bchanot/Documents/claude/templates/project-rules; make -C /home/bchanot/Documents/claude test suite=lib/tests/doctrine-citers.test.sh | tail -1` -Expected: `FAIL=0`; `project-rules: 3 rule(s) ok` (every skeleton glob is syntactically sound); `all suites green`. - -- [ ] **Step 6: Commit** - -```bash -git add templates/project-rules templates/project-CLAUDE.md agents/onboarder.md agents/scaffolder.md lib/tests/project-rules.test.sh -git commit -m "feat(generators): onboarder and scaffolder emit docker/testing/ci path rules from templates/project-rules" -``` - ---- - -### Task 10: TODO.md phase 0 bookkeeping + full suite - -**Files:** -- Modify: `.claude/tasks/TODO.md:20-30` (the phase 0 item) - -- [ ] **Step 1: Update the phase 0 item** - -Replace the `- [ ] **Phase 0, no mod: split project CLAUDE.md**` block (lines 20-30) with: - -```markdown -- [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. -``` - -- [ ] **Step 2: Full suite + shellcheck** - -Run: `make test 2>&1 | tail -3 && shellcheck ./*.sh hooks/*.sh lib/*.sh && echo SHELLCHECK-OK` -Expected: `all suites green`, `SHELLCHECK-OK`. - -- [ ] **Step 3: Commit** - -```bash -git add .claude/tasks/TODO.md -git commit -m "chore(todo): phase 0 done in-repo, per-repo pass queued as phase 0b" -``` - ---- - -### Task 11: proof on this branch (orchestrator, no code) - -- [ ] **Step 1: `/context` after** - -Run from the repo root: `claude -p "/context" 2>/dev/null | grep -E 'Memory files|Documents/claude/CLAUDE.md'` -Expected: the project CLAUDE.md row well under the 2.1k baseline (about 200 tokens); Memory files total about 1.9k lower than 11.6k. Record both for the journal. - -- [ ] **Step 2: Main-session loads** - -The hook needs a session started AFTER Task 2 landed in `settings.json`. Note the start time, then run a headless session that reads one file per rule: `date -u +%FT%TZ; claude -p "Read rules/a11y.md, install-plugins.sh, mods/model-router/.claude-plugin/plugin.json and docs/superpowers/specs/2026-10-26-claude-md-split-design.md, then answer with the single word done." 2>/dev/null | tail -1`, then -`jq -c 'select(.memory_type=="Project" and (.file_path|contains("/.claude/rules/")) and .ts >= "") | {file_path, trigger_file_path, load_reason}' ~/.claude/logs/instructions-loaded.jsonl`. -Expected: exactly four lines with `load_reason: path_glob_match`, one per `.claude/rules/*.md`. Zero lines → the event does not fire as a classic hook on this CLI: report it, the proof falls back to `/context` inside the same `-p` session listing the rule under Memory files, and the finding goes to STEP 7 as a BLK. - -- [ ] **Step 3: Sub-agent loads** - -Note the time, then dispatch `Agent(subagent_type="general-purpose", model="sonnet", effort="low")`: "Read `rules/a11y.md` and `install-plugins.sh` in /home/bchanot/Documents/claude, then reply with the single word done." Then two filters: -1. Control, does the hook see sub-agent loads at all: `jq -c 'select(.agent_id != null and .ts >= "") | {agent_type, memory_type, file_path}' ~/.claude/logs/instructions-loaded.jsonl` (`agent_id` is optional in the hook input, "present only when the hook fires from within a subagent"). Zero lines → the event does not fire, or carries no `agent_id`, inside sub-agents: the sub-agent question is UNANSWERED (not "no"), record that, and the per-repo pass keeps sub-agent-needed sections always-on until a later probe answers it. -2. With at least one control line: `jq -c 'select(.agent_id != null and (.file_path|contains("/.claude/rules/")) and .ts >= "") | {agent_type, file_path, load_reason}' ~/.claude/logs/instructions-loaded.jsonl`. -Expected: two lines (rules-maintenance, graphify-vendored) with an `agent_id` → path rules load inside sub-agents. Zero lines with a non-empty control → they do not: record it (journal + STEP 7 LRN), and the per-repo pass keeps sub-agent-needed sections always-on; whether this repo's two hazards (graphify untrack-then-merge, mods `[ -L ]` guard) return as always-on one-liners is the user's call at the next gate. - ---- - -## Self-review - -- Spec coverage: §1 rules → Task 4; `.gitignore` + socle → Task 3; §2 check/sections/extract (+ matches, emit, -C) + suite → Task 1 (emit Task 9), hook + settings → Task 2, proof → Task 11; §3 skill + onboarder split + RED/GREEN → Tasks 6-8; §4 skeletons + generators + template header → Task 9; §5 citers → Task 5 (ARCHITECTURE.md is STEP 8's), TODO → Task 10, higgsfield user step → Task 10 TODO line + STEP 7 journal; §6 testing → every task's verify step + Task 10 Step 2; §7 pre-commit exemption → deferred, Task 10 TODO line. -- Placeholder scan: none. Every code step carries its content. -- Type consistency: `extract` arg order ` ` is the same in the lib, the suite, Task 4 and the onboarder S1; `emit ` the same in the lib, T12, PHASE 5b and PHASE 3b; `-C ` precedes the subcommand everywhere; the skip marker string `# static-check: skip` is identical in the lib grep, T4 and Task 4 Step 3; the `check` success line `project-rules: N rule(s) ok` is what T3c, T5b, T5d, T11b and the agents quote; the `matches` stderr line `no match: ` is what T5i expects; the onboarder's success line `all rules in HEAD` is what Task 8 Step 3 expects; the two STOP shapes in onboarder S3 are the two the skill's S6 handles. -- Review Focus: 1 → T6d/T8e/T8f, 2 → T2c/T12b/T12f, 3 → T2d/T5j, 4 → Task 8 Step 3 assertions, 5 → T10f-T10j, 6 → T5k/T5l. All pinned. -- r3 lint pass on the plan's own code: every line of the lib block is 80 columns or fewer (the four over-long r2 lines are wrapped, `_RULES_DEPS` renamed); the suite has no `ls` pipe (T8g uses `printf '%s ' *`); the lib has no `head` after a producer. diff --git a/docs/superpowers/specs/2026-10-26-claude-md-split-design.md b/docs/superpowers/specs/2026-10-26-claude-md-split-design.md deleted file mode 100644 index 39e9fd1..0000000 --- a/docs/superpowers/specs/2026-10-26-claude-md-split-design.md +++ /dev/null @@ -1,191 +0,0 @@ -# Phase 0 — split project CLAUDE.md into `.claude/rules/` (design) - -Date: 2026-10-26 · flow: /ship-feature · branch: feature/claude-md-split -Contract: `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md` -Parent: BDR-125 (context mod queue), TODO.md "Phase 0, no mod". - -## Intent - -The project CLAUDE.md of this repo (5,285 chars) loads in every session of -this repo; four of its five sections only matter when a matching file is -being read. Move those four into project-scope path rules -(`.claude/rules/.md` with `paths:` frontmatter), prove they load, and -give the other projects the same lever through a `/onboard split` mode and -generators that emit path rules from day one. No mod, subtract-only. - -Decided with the user (2026-10-26): this run covers this repo, the mode and -the generators; the per-repo pass over the six other repos runs after the -merge through the shipped `/onboard split`, one `chore/claude-md-split` -branch per repo, user approval per repo, never an automatic merge. The -InstructionsLoaded proof hook is permanent. The transient-artifacts rule -carries a `# static-check: skip` marker. The gitignore socle gains -`!.claude/rules/`. Generator skeleton set: docker, testing, ci. - -## 1. This repo's rules - -| Rule file | `paths:` | Source section (CLAUDE.md, verbatim) | -|---|---|---| -| `.claude/rules/rules-maintenance.md` | `rules/**`, `CLAUDE.global.md` | `## rules/ maintenance` | -| `.claude/rules/graphify-vendored.md` | `skills/graphify/**`, `install-plugins.sh`, `.graphify_version` | `## Machine-owned: the vendored graphify skill` | -| `.claude/rules/mods.md` | `mods/**`, `skills/model-router/**`, `lib/tests/mods.test.sh` | `## mods/ — function-hooks plugins (Claude Code mods)` | -| `.claude/rules/transient-artifacts.md` | `docs/superpowers/**`, `.audit/**` (+ `# static-check: skip`) | `## Transient planning artifacts` | - -Frontmatter shape = `rules/a11y.md`: `paths: ["glob", ...]` on one line. -The skip marker is a YAML comment line inside the frontmatter, invisible to -the engine. Body text moves verbatim; the title line becomes `#
`. CLAUDE.md keeps its header, `## Health Stack`, and a two-line -pointer: path-scoped rules live in `.claude/rules/` and load on Read of a -matching file; the four names listed. - -`.gitignore`: `!.claude/rules/` right after `.claude/*` (line 122). -`templates/gitignore/standard.gitignore`: same line after `.claude/*` -(order matters: a negation must follow the ignore it carves; reconcile -appends missing lines at the end, which is after any existing `.claude/*`). -`lib/gitflow-test.sh`: one `chk "socle: !.claude/rules/"` beside the -`!.claude/deploy/` assertion. - -## 2. Static check and proof hook - -`lib/project-rules.sh` (our code, strict limits, shellcheck): -- `check [dir]` (default `.claude/rules`): for each `*.md`: frontmatter - delimited by `---` present; a `paths:` line whose value is a JSON-style - array of double-quoted globs; each glob matches ≥1 path in the working - tree (`shopt -s globstar dotglob nullglob`, so the symlinked - `skills/model-router/**` and the gitignored `skills/graphify/SKILL.md` - count, and a typo matches nothing). A frontmatter line - `# static-check: skip` exempts that file's globs (printed as SKIP). Exit 0 - and `project-rules: N rule(s) ok` on success; exit 2 and one - `: ` line per failure. An empty or absent dir is exit 0 - with `0 rule(s)` (a project without rules is not an error). -- `sections `: prints `\t\t## ` per - top-level section, for the split-mode classification table. -- `extract "" `: writes - `` with the frontmatter and the section body (title demoted to - `#`), removes the section from CLAUDE.md. Deterministic, idempotent - failure (heading absent → exit 2, nothing written). Used by the onboarder - in MODE: split and by the per-repo pass. - -`lib/tests/project-rules.test.sh` (picked up by `make test` via the -`lib/tests/*.test.sh` glob): fixtures in `mktemp -d`: a good rule passes; -an unmatched glob fails with the culprit; a missing frontmatter fails; the -skip marker passes an unmatched glob; `sections` lists sizes; `extract` -round-trips (rule written, section gone, second call exit 2); then the real -check on this repo's `.claude/rules` (exit 0). PASS/FAIL tally like -`doctrine-citers.test.sh`. - -`hooks/instructions-loaded.sh`: reads the hook JSON on stdin, appends one -`jq -c` line `{ts, cwd, file_path, memory_type, load_reason, -trigger_file_path}` to `~/.claude/logs/instructions-loaded.jsonl` -(`mkdir -p`), always exits 0, never prints to stdout (a stdout line would -reach the model). Registered in `settings.json` under `"InstructionsLoaded"` -beside the other classic hooks. No hooks suite exists: the hook test lives -in `lib/tests/project-rules.test.sh` (fixture JSON on stdin, `HOME` pointed -at a temp dir, the appended line asserted, stdout asserted empty). - -Proof for this repo (recorded in the journal): `claude -p "/context"` on -develop BEFORE any edit (baseline, same measure as 2026-10-23), the same on -the branch after the split, one fresh interactive session that Reads one -matching file per rule, then `grep path_glob_match -~/.claude/logs/instructions-loaded.jsonl | tail -4` pasted. - -## 3. `/onboard split` - -`skills/onboard/SKILL.md`: right after the MODEL GATE, a MODE DISPATCH -paragraph: `$ARGUMENTS` starting with the token `split` → § SPLIT MODE; -anything else → the existing flow unchanged. The description gains the -trigger ("split CLAUDE.md", "découpe le CLAUDE.md"), the argument-hint gains -`split`, RULES line "NO skipping STEP 0, 1, 2" gains "(split mode runs its -own steps, § SPLIT MODE)". Routing rows, test locks (`model-routing`, -`effort-routing`, `loops-heavy`, `plan-challenger`, `security-auditor`) and -`routing.json:67` keep their anchors. - -§ SPLIT MODE (steps): -1. Precondition: `CLAUDE.md` at the project root, else print "nothing to - split, run /onboard" and stop. `git status --porcelain` clean on the - CLAUDE.md path, else stop (an in-flight edit would be lost). -2. Baseline: `claude -p "/context"` at the root; refused → the user runs - `! claude -p "/context"`; the always-on total is noted. -3. `bash ~/.claude/lib/project-rules.sh sections CLAUDE.md`; classify each - `##` section: always-on (overview, stack, build/test/lint commands, - conventions, workflow expectations, exceptions) or path-scoped (one - module, one folder, Docker, migrations, CI, a tool's gotchas); propose a - file name and globs from `git ls-files` for each path-scoped one, and - verify every proposed glob matches ≥1 tracked path before showing it. -4. Gate (prose table, per project): section · chars · keep / move → - `.md` · globs. The user edits or approves; "keep everything" is a - valid answer that ends the mode. -5. `bash ~/.claude/lib/gitflow.sh start chore claude-md-split` (a project - without gitflow: a plain branch, said so). -6. Dispatch `Agent(subagent_type="onboarder")` with `MODE: split`, the - project root, and the approved table verbatim (LRN-126: every field - crosses the prompt). It runs `extract` per row, writes the pointer lines - into CLAUDE.md, adds `!.claude/rules/` after `.claude/*` when that line - is present and the negation absent, runs `check`, commits - `chore(claude-md): split N sections into .claude/rules/`, reports. -7. After: `claude -p "/context"` again, the delta and the rule list go to - that project's `.claude/memory/journal.md`; the InstructionsLoaded proof - is the user's next session there (one Read per rule, grep the log). - Never `finish`: merge on the user's signal. - -Skill edit through /writing-skills: RED first (a sonnet subagent given the -CURRENT skill and a scratch repo holding a copy of this repo's pre-split -CLAUDE.md, asked to "/onboard split": it has no mode and runs or asks for -the full onboard), then the edit, then GREEN on the same scratch (the -subagent produces the classification table and stops at the gate). - -`agents/onboarder.md`: a `MODE:` header: absent → today's PHASES 1-5 -(generate config); `MODE: split` → the split executor above (PHASES -S1-S4: extract rows, pointer lines, gitignore negation, check + commit). -Stays sonnet, effort medium (BDR-077). - -## 4. Generators born split - -`templates/project-rules/` skeletons, each with `paths:` and 3-6 lines of -section stubs (HTML comments like the CLAUDE.md template): -- `docker.md`: `["Dockerfile*", "docker-compose*", "compose*.y*ml", ".dockerignore"]` -- `testing.md`: `["tests/**", "test/**", "**/*.test.*", "**/*.spec.*", "**/conftest.py"]` -- `ci.md`: `[".github/workflows/**", ".gitlab-ci.yml", ".circleci/**"]` - -onboarder (default mode) PHASE 1b and scaffolder PHASE 1b: for each -skeleton, emit `.claude/rules/.md` when ≥1 of its globs matches a -path in the project tree (onboarder: the real tree; scaffolder: the tree it -just scaffolded, so a Docker-relevant project gets `docker.md`), filled from -the BRIEF where known, else the template stubs. Then run `project-rules.sh -check` and report the emitted list. The onboarder's PHASE 4 gitignore check -also appends `!.claude/rules/` after an existing `.claude/*` line -(the socle covers gitflow-init projects; this covers the rest). The -scaffolder's `.gitignore` is reconciled by STEP 5f `gitflow init` before -the root commit, so the socle line lands first (LRN-066, BLK-010). -`templates/project-CLAUDE.md` keeps every section (commands stay always-on); -its header comment gains one line naming `.claude/rules/`. - -## 5. Cleanup and citers - -- `rules/README.md:9` → "see `.claude/rules/rules-maintenance.md` in the - claude-config repo". -- `doctor.sh:76` comment: "the project CLAUDE.md" (drop "29-line"). -- `ARCHITECTURE.md` tree gains `.claude/rules/` (doc pipeline, STEP 8). -- `install-plugins.sh` GUARDED_CONFIGS unchanged: `graphify claude install` - still rewrites CLAUDE.md and the trap still reverts it. -- `.claude/tasks/TODO.md`: phase 0 item updated (done parts, per-repo pass - queued as its own item with the repo order). -- Registries append-only: BDR-065 and LRN-154 keep their old location text. -- Manual step (user): `claude mcp remove -s user higgsfield`; journal line. - -## 6. Testing and proof - -- `make test` green (new suite + gitflow-test socle assertion + hook test). -- `shellcheck *.sh hooks/*.sh lib/*.sh` clean. -- `project-rules.sh check` exit 0 on this repo. -- `/context` before/after at the repo root; the four `path_glob_match` - log lines from one real session. -- RED → GREEN pressure test transcript summary for `/onboard split`. - -## 7. Out of scope, risks kept - -- The per-repo pass (six repos) and whether path rules load inside - sub-agents: measured on faunosteo first, during that pass. -- A `paths:` rule loads on Read, not on Write of a new file: generator - rules load once the scaffolded file is edited (Edit needs a Read). -- The pre-commit `.claude/**` exemption lets a rules-only commit land on - develop; split mode always branches first.