fix(rules): extract rc 2 on a failed rewrite, H1 ends a section, split S0 ordered with row allowlist, stage per row

This commit is contained in:
bchanot committed 2026-10-26 21:53:49 +01:00
1 parent 89334f2901
commit 0b59687e1e
4 files changed
+104 -43

No files matched your search

+43 -25
View File
@@ -177,6 +177,7 @@ FILES WRITTEN:
✅ .claude/memory/journal.md (created | unchanged) ✅ .claude/memory/journal.md (created | unchanged)
✅ .claude/memory/evals.md (created | unchanged) ✅ .claude/memory/evals.md (created | unchanged)
✅ .claude/audits/ (created | unchanged) ✅ .claude/audits/ (created | unchanged)
[✅ .claude/rules/<name>.md] (per skeleton that matched: docker | testing | ci)
[✅ ROADMAP.md] (if generate_roadmap) [✅ ROADMAP.md] (if generate_roadmap)
PLACEHOLDERS : <null enrichment keys left as TODO(/onboard STEP 3), or none> PLACEHOLDERS : <null enrichment keys left as TODO(/onboard STEP 3), or none>
``` ```
@@ -202,28 +203,38 @@ per line, `<heading> | <name> | <globs-json>` (heading without `## `). No
BRIEF; PHASES 1-6 do not run. `PR` below stands for BRIEF; PHASES 1-6 do not run. `PR` below stands for
`bash ~/.claude/lib/project-rules.sh -C <PROJECT_ROOT>`. `bash ~/.claude/lib/project-rules.sh -C <PROJECT_ROOT>`.
S0 — PREFLIGHT (no write before every row passes): S0 — PREFLIGHT (no write before every step passes):
- `git -C <PROJECT_ROOT> status --porcelain` is empty, else STOP. 1. `git -C <PROJECT_ROOT> status --porcelain` is empty, else STOP.
- gitignore: `git -C <PROJECT_ROOT> check-ignore -q .claude/rules/probe.md` 2. `PR check` is rc 0, else STOP with its culprit lines: a pre-existing
rc 0 means the rules would be ignored → append the negation (portable, rule the oracle cannot parse (the one-line `paths: ["a", "b"]` form
lands after any `.claude/*` line). If `<PROJECT_ROOT>/.gitignore` does only) is fixed by the user before any split.
not exist, STOP: the ignore comes from outside the repo (global excludes 3. Per row, by reading the row (never a shell test that embeds it):
or `.git/info/exclude`); the user decides. Guard the trailing newline `<name>` matches `[a-z0-9][a-z0-9-]*`; the heading has no `'`; every
first: `[ -n "$(tail -c1 <PROJECT_ROOT>/.gitignore)" ] && echo >> glob is relative, with no `'`, no leading `/`, no `..`. A row that
<PROJECT_ROOT>/.gitignore` so the negation never glues onto the last fails → STOP with the row and the field.
line. Then: 4. Per row: `PR sections CLAUDE.md` lists `## <heading>` exactly once;
`printf '!.claude/rules/\n' >> <PROJECT_ROOT>/.gitignore` `<PROJECT_ROOT>/.claude/rules/<name>.md` does not exist; every glob of
then re-run `check-ignore`; still rc 0 → STOP: "ignore form cannot be `<globs-json>` passes `PR matches '<glob>'` (rc 0). Any failure → STOP
negated (BDR-003: use the `.claude/*` file form)", and `git -C with the row and the reason.
<PROJECT_ROOT> checkout -- .gitignore`. Remember whether this step 5. gitignore, in this order:
appended (`GITIGNORE_TOUCHED`): `.gitignore` enters the later `add`, a. `git -C <PROJECT_ROOT> check-ignore -q .claude/rules/probe.md`;
`checkout` and `commit` only then (a repo with no `.gitignore` is rc 1 rc 1 → nothing to do, `GITIGNORE_TOUCHED` stays unset, go to S1.
here and never names it: a missing pathspec is a fatal git error). b. rc 0 and `<PROJECT_ROOT>/.gitignore` does not exist → STOP: the
- per row: `PR sections CLAUDE.md` lists `## <heading>` exactly once; ignore comes from outside the repo (global excludes or
`<PROJECT_ROOT>/.claude/rules/<name>.md` does not exist; every glob of `.git/info/exclude`); the user decides.
`<globs-json>` passes `PR matches '<glob>'` (rc 0). Any failure → STOP c. Trailing-newline guard: `[ -n "$(tail -c1 <PROJECT_ROOT>/.gitignore)" ]
with the row and the reason (nothing written yet besides the gitignore && echo >> <PROJECT_ROOT>/.gitignore` (rc 1 when already
line, which the STOP reverts). newline-terminated is fine).
d. Append the negation (portable, lands after any `.claude/*` line):
`printf '!.claude/rules/\n' >> <PROJECT_ROOT>/.gitignore`
e. Re-run `check-ignore`; still rc 0 → `git -C <PROJECT_ROOT> 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): S1 — EXTRACT, per row (single quotes around the heading):
```bash ```bash
@@ -242,8 +253,12 @@ S2 — POINTER. If CLAUDE.md has no `## Path-scoped rules` section, append:
Project rules live in `.claude/rules/<name>.md` and load on Read of a file Project rules live in `.claude/rules/<name>.md` and load on Read of a file
matching their `paths:` (never at session start): <name>, <name>. matching their `paths:` (never at session start): <name>, <name>.
``` ```
Else add the new names to its list. Collapse runs of blank lines left by Else add the new names to its list (Edit tool, or `cat >> <PROJECT_ROOT>/CLAUDE.md`
the extraction (never more than one). 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 <PROJECT_ROOT>/CLAUDE.md > <PROJECT_ROOT>/CLAUDE.md.tmp && cat
<PROJECT_ROOT>/CLAUDE.md.tmp > <PROJECT_ROOT>/CLAUDE.md && rm
<PROJECT_ROOT>/CLAUDE.md.tmp`.
S3 — CHECK, COMMIT, VERIFY TRACKED. S3 — CHECK, COMMIT, VERIFY TRACKED.
```bash ```bash
@@ -251,9 +266,12 @@ bash ~/.claude/lib/project-rules.sh -C <PROJECT_ROOT> check
``` ```
rc ≠ 0 → ROLLBACK as in S1, STOP with the culprit lines. rc 0 → rc ≠ 0 → ROLLBACK as in S1, STOP with the culprit lines. rc 0 →
```bash ```bash
git -C <PROJECT_ROOT> add CLAUDE.md .claude/rules # + .gitignore when S0 appended git -C <PROJECT_ROOT> add -- CLAUDE.md .claude/rules/<name>.md # one literal path per row, + .gitignore when GITIGNORE_TOUCHED
git -C <PROJECT_ROOT> commit -m "<message>" git -C <PROJECT_ROOT> commit -m "<message>"
``` ```
Never `add` the directory: a
pre-existing rule that S0's negation made visible would ride along
unlisted.
`<message>` follows the project's commit convention (its CLAUDE.md commit `<message>` follows the project's commit convention (its CLAUDE.md commit
rules: allowed types and scopes); with none, `chore: split <k> CLAUDE.md rules: allowed types and scopes); with none, `chore: split <k> CLAUDE.md
section(s) into .claude/rules/`. Commit rc ≠ 0 (a hook refused it, e.g. section(s) into .claude/rules/`. Commit rc ≠ 0 (a hook refused it, e.g.
+18 -8
View File
@@ -8,11 +8,15 @@
# path; rc 2 with the culprit named # path; rc 2 with the culprit named
# matches <glob> rc 0 + the first hits, rc 1 none # matches <glob> rc 0 + the first hits, rc 1 none
# sections <file> chars, line, heading per top-level ## section # sections <file> chars, line, heading per top-level ## section
# (a section ends at the next # or ## heading
# outside a fence)
# extract <file> <heading> <out> <globs-json> move one section to a rule # extract <file> <heading> <out> <globs-json> move one section to a rule
# emit <skeleton> <out> the rule with the matching globs only (rc 1 # emit <skeleton> <out> the rule with the matching globs only (rc 1
# when none matches, nothing written) # when none matches, nothing written)
# Globs match the WORKING TREE (compgen -G with globstar and dotglob, # 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 # dotglob makes `*` match dotfiles, which the engine's matcher skips: a
# glob that only hits hidden paths passes here but never loads), # glob that only hits hidden paths passes here but never loads),
# dependency dirs excluded (unless the glob names one: `vendor/**` is a # dependency dirs excluded (unless the glob names one: `vendor/**` is a
@@ -104,11 +108,12 @@ project_rules_matches() { # <glob> → rc 0 + the first 3 hits, rc 1 none
project_rules_sections() { # <file> → chars, line, heading per ## section project_rules_sections() { # <file> → chars, line, heading per ## section
[ -f "$1" ] || { echo "project-rules: $1 not found" >&2; return 2; } [ -f "$1" ] || { echo "project-rules: $1 not found" >&2; return 2; }
awk ' awk '
function flush() { if (h != "") printf "%d\t%d\t%s\n", c, l, h; h = "" }
/^```/ { fence = !fence } /^```/ { fence = !fence }
/^## / && !fence { if (h != "") printf "%d\t%d\t%s\n", c, l, h /^# / && !fence { flush() }
h = $0; l = NR; c = 0 } /^## / && !fence { flush(); h = $0; l = NR; c = 0 }
h != "" { c += length($0) + 1 } 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() { # <file> <heading> → fence-aware count of "## h" _rules_heading_count() { # <file> <heading> → fence-aware count of "## h"
@@ -121,7 +126,7 @@ _rules_section_body() { # <file> <heading> → body, trailing ---/blank trimmed
awk -v h="## $2" ' awk -v h="## $2" '
/^```/ { fence = !fence } /^```/ { fence = !fence }
!fence && $0 == h { on = 1; next } !fence && $0 == h { on = 1; next }
!fence && on && /^## / { exit } !fence && on && (/^## / || /^# /) { exit }
on { buf[++n] = $0 } on { buf[++n] = $0 }
END { while (n > 0 && (buf[n] == "" || buf[n] == "---")) n-- END { while (n > 0 && (buf[n] == "" || buf[n] == "---")) n--
for (i = 1; i <= n; i++) print buf[i] }' "$1" for (i = 1; i <= n; i++) print buf[i] }' "$1"
@@ -131,7 +136,7 @@ _rules_without_section() { # <file> <heading> → the file minus that section
awk -v h="## $2" ' awk -v h="## $2" '
/^```/ { fence = !fence } /^```/ { fence = !fence }
!fence && $0 == h { skip = 1; next } !fence && $0 == h { skip = 1; next }
!fence && skip && /^## / { skip = 0 } !fence && skip && (/^## / || /^# /) { skip = 0 }
!skip { print }' "$1" !skip { print }' "$1"
} }
@@ -154,10 +159,15 @@ project_rules_extract() { # <file> <heading> <out.md> <globs-json>
[ -e "$out" ] && { echo "project-rules: $out exists" >&2; return 2; } [ -e "$out" ] && { echo "project-rules: $out exists" >&2; return 2; }
_rules_globs_all_match "$globs" || return 2 _rules_globs_all_match "$globs" || return 2
mkdir -p "$(dirname "$out")" 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" { printf -- '---\npaths: %s\n---\n\n# %s\n' "$globs" "$heading"
_rules_section_body "$src" "$heading"; } > "$out" _rules_section_body "$src" "$heading"; } > "$out"
tmp=$(mktemp) if ! { _rules_without_section "$src" "$heading" > "$tmp" \
_rules_without_section "$src" "$heading" > "$tmp" && cat "$tmp" > "$src" && cat "$tmp" > "$src"; }; then
rm -f "$tmp" "$out"
echo "project-rules: $src not rewritten, $out removed" >&2
return 2
fi
rm -f "$tmp" rm -f "$tmp"
echo "project-rules: moved '## $heading' to $out" echo "project-rules: moved '## $heading' to $out"
} }
+32 -4
View File
@@ -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 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 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 # 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 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 T7g-beta-kept "$(grep -c '^## Beta' CLAUDE.md)" 1
check T7h-fenced-line-kept "$(grep -c '^## not a heading' 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 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 # T8 extract refuses: missing heading, existing target, duplicate, fenced-only
bash "$PR" extract CLAUDE.md 'Alpha' .claude/rules/alpha2.md '["src/**"]' 2>/dev/null 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 T9c-nothing-written "$([ -e .claude/rules/beta.md ] && echo yes || echo no)" no
check T9d-beta-still-there "$(grep -c '^## Beta' CLAUDE.md)" 1 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 # T10 the hook appends one jq line, prints nothing, never fails
HOOK="$ROOT/hooks/instructions-loaded.sh" HOOK="$ROOT/hooks/instructions-loaded.sh"
LOG="$FIX/il.jsonl" 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=$? out=$(printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG=/proc/nowhere/il.jsonl bash "$HOOK"); rc=$?
check T10f-unwritable-log-rc0 "$rc" 0 check T10f-unwritable-log-rc0 "$rc" 0
check T10g-unwritable-log-stdout-empty "$out" "" 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" \ out=$(printf '%s' "$IN" \
| CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent "$BASH" "$HOOK"); rc=$? | CLAUDE_INSTRUCTIONS_LOG="$LOG" PATH=/nonexistent "$BASH" "$HOOK"); rc=$?
check T10h-no-jq-rc0 "$rc" 0 check T10h-empty-path-rc0 "$rc" 0
check T10i-no-jq-stdout-empty "$out" "" check T10i-empty-path-stdout-empty "$out" ""
check T10j-no-jq-nothing-appended "$(wc -l < "$LOG" | tr -d ' ')" 1 check T10j-empty-path-nothing-appended "$(wc -l < "$LOG" | tr -d ' ')" 1
head -c 5300000 /dev/zero | tr '\0' 'x' > "$LOG" head -c 5300000 /dev/zero | tr '\0' 'x' > "$LOG"
printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG="$LOG" bash "$HOOK" printf '%s' "$IN" | CLAUDE_INSTRUCTIONS_LOG="$LOG" bash "$HOOK"
check T10k-rotated "$([ -e "$LOG.1" ] && echo yes || echo no)" yes check T10k-rotated "$([ -e "$LOG.1" ] && echo yes || echo no)" yes
+11 -6
View File
@@ -117,6 +117,7 @@ L'agent génère :
- `.claudeignore` - `.claudeignore`
- `.gitignore` (safety check) - `.gitignore` (safety check)
- `.claude/tasks/TODO.md`, `.claude/memory/{decisions,learnings,blockers,journal,evals}.md` - `.claude/tasks/TODO.md`, `.claude/memory/{decisions,learnings,blockers,journal,evals}.md`
- `.claude/rules/<name>.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) - **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. 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 <ROOT> status --porcelain` empty (whole
tree) and the current branch is `develop` (or `main` when no `develop` 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 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 in-flight feature branch or dirty file would be classified on one version
and extracted on another. `.claude/rules/` already holding rules → list and extracted on another. `.claude/rules/` already holding rules → `bash
them, continue (new rules add to them). ~/.claude/lib/project-rules.sh -C <ROOT> 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 `<ROOT>` (refused → ask the user S2 — BASELINE. `claude -p "/context"` from `<ROOT>` (refused → ask the user
to run `! claude -p "/context"`); note the `Memory files` total and the 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 files; never a brace glob `*.{ts,tsx}`: one glob per extension, the
oracle does no brace expansion) and verify EVERY proposed glob with oracle does no brace expansion) and verify EVERY proposed glob with
`bash ~/.claude/lib/project-rules.sh -C <ROOT> matches '<glob>'` (rc 0) `bash ~/.claude/lib/project-rules.sh -C <ROOT> matches '<glob>'` (rc 0)
before showing it. A heading containing before showing it. Row shape, checked before a row enters the TABLE: `<name>` matches
`'` or `|`, or a glob containing `|`, is not split by this mode (the `[a-z0-9][a-z0-9-]*`; globs are relative, no `'`, no leading `/`, no
TABLE rows are `|`-separated; say so, the user renames or re-globs `..`, no `|`; the heading has no `'` and no `|` (the rows are
first). `|`-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: S5 — GATE (mandatory stop). Print the table, then end the turn: