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/evals.md (created | unchanged)
✅ .claude/audits/ (created | unchanged)
[✅ .claude/rules/<name>.md] (per skeleton that matched: docker | testing | ci)
[✅ ROADMAP.md] (if generate_roadmap)
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
`bash ~/.claude/lib/project-rules.sh -C <PROJECT_ROOT>`.
S0 — PREFLIGHT (no write before every row passes):
- `git -C <PROJECT_ROOT> status --porcelain` is empty, else STOP.
- gitignore: `git -C <PROJECT_ROOT> 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 `<PROJECT_ROOT>/.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 <PROJECT_ROOT>/.gitignore)" ] && echo >>
<PROJECT_ROOT>/.gitignore` so the negation never glues onto the last
line. Then:
`printf '!.claude/rules/\n' >> <PROJECT_ROOT>/.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
<PROJECT_ROOT> 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 `## <heading>` exactly once;
`<PROJECT_ROOT>/.claude/rules/<name>.md` does not exist; every glob of
`<globs-json>` passes `PR matches '<glob>'` (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 <PROJECT_ROOT> 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):
`<name>` 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 `## <heading>` exactly once;
`<PROJECT_ROOT>/.claude/rules/<name>.md` does not exist; every glob of
`<globs-json>` passes `PR matches '<glob>'` (rc 0). Any failure → STOP
with the row and the reason.
5. gitignore, in this order:
a. `git -C <PROJECT_ROOT> check-ignore -q .claude/rules/probe.md`;
rc 1 → nothing to do, `GITIGNORE_TOUCHED` stays unset, go to S1.
b. rc 0 and `<PROJECT_ROOT>/.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 <PROJECT_ROOT>/.gitignore)" ]
&& echo >> <PROJECT_ROOT>/.gitignore` (rc 1 when already
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):
```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
matching their `paths:` (never at session start): <name>, <name>.
```
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 >> <PROJECT_ROOT>/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 <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.
```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 →
```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>"
```
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
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.
+18 -8
View File
@@ -8,11 +8,15 @@
# path; rc 2 with the culprit named
# matches <glob> rc 0 + the first hits, rc 1 none
# 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
# emit <skeleton> <out> 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() { # <glob> → rc 0 + the first 3 hits, rc 1 none
project_rules_sections() { # <file> → 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() { # <file> <heading> → fence-aware count of "## h"
@@ -121,7 +126,7 @@ _rules_section_body() { # <file> <heading> → 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() { # <file> <heading> → 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() { # <file> <heading> <out.md> <globs-json>
[ -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"
}
+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 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
+11 -6
View File
@@ -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/<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)
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`
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 <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
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 <ROOT> matches '<glob>'` (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: `<name>` 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: