15 KiB
PLAN r3 — rules-h3-extract (feat, 2026-10-27)
Contract: .claude/tasks/contracts/2026-10-27-rules-h3-extract-1326.md.
Base develop 925dafa. Our code (strict): lib/project-rules.sh 80 cols,
≤ 25 logic lines and ≤ 5 locals per function, shellcheck clean, mawk-safe
awk (no {n,m} intervals), no sed -i. r2 folds the 3-lens challenge
(S5 cell, separator loss, #1 title regression, arity, AC5 gate items,
parent-with-children test); r3 folds the confirmation pass (T13r locale
collation, re-emission gated on level 3, level-refusal flip, ####+ arm,
S0.3 wording, S5 anchor, 4-backtick fence). Edits anchor on TEXT, never
on line numbers.
Approach
- The heading argument carries its level: bare
<title>=## <title>(unchanged, including a title that starts with#such as#1 priority);### <title>= a level-3 section;## <title>is accepted as the explicit level-2 form.# x(H1) or####-and-deeper → rc 2heading level must be ## or ###. One helper_rules_heading_linenormalises the argument to the exact heading LINE; every awk helper takes that line and derives the level inside awk aslvl = index(h, " ") - 1. - A section of level L ends at the next heading of level ≤ L outside a
fence: awk test
match($0, /^#+ /) && RLENGTH - 1 <= lvl. - Separator rule, level 3 ONLY: when a
###section is removed and its end is a heading of a LOWER level (#/##), the trailing run of blank/---lines it carried is re-emitted in the source (it was the parent's closing separator); when the end is a same-level heading, the run goes with the section. A##section keeps today's behaviour exactly (its run always travels with it, an H1 end included): the awk condition islvl == 3 && RLENGTH - 1 < lvl. The rule body trims the run either way. sections [--depth 2|3] <file>: depth 2 is today's output byte for byte; depth 3 also lists each###subsection (its own chars, its line, the### <title>heading). A##parent's chars keep counting through its children (same number as depth 2). Exactly one positional argument after the optional flag, else rc 2 (a flag after the file is an error, not a silent depth 2). Lines come out in file order: awk prints at close, so the output is piped throughsort -t "$(printf '\t')" -k2,2n.- Rule title line:
# <title without its prefix>.
Files
1. lib/project-rules.sh
Header: replace the block that starts at the line beginning
# sections <file> and ends at the line before # emit <skeleton> with:
# sections [--depth 2|3] <file> chars, line, heading per ## section
# (--depth 3 adds the ### subsections; a section
# ends at the next heading of level ≤ its own)
# extract <file> <heading> <out> <globs-json> move one section to a
# rule (bare heading = ##; "### title" = a subsection;
# a ### moved last keeps its parent's trailing ---)
Every header line ≤ 80 chars.
Replace _rules_heading_count, _rules_section_body and
_rules_without_section (they now take the heading LINE), and add
_rules_heading_line before them:
_rules_heading_line() { # <heading arg> → "## t" | "### t" on stdout, rc 2
case "$1" in
'## '*|'### '*) printf '%s\n' "$1" ;;
'# '*|'####'*)
echo "project-rules: heading level must be ## or ###: $1" >&2
return 2 ;;
*) printf '## %s\n' "$1" ;;
esac
}
_rules_heading_count() { # <file> <heading line> → fence-aware count
awk -v h="$2" '/^```/ { fence = !fence }
!fence && $0 == h { n++ }
END { print n + 0 }' "$1"
}
_rules_section_body() { # <file> <heading line> → body, ---/blank trimmed
awk -v h="$2" '
BEGIN { lvl = index(h, " ") - 1 }
/^```/ { fence = !fence }
!fence && $0 == h { on = 1; next }
!fence && on && match($0, /^#+ /) && RLENGTH - 1 <= lvl { 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() { # <file> <heading line> → the file minus it
# a ### ended by a lower-level heading gives its trailing ---/blank run
# back to the source (the parent's closing separator); a ## keeps today's
# behaviour, its run travels with it
awk -v h="$2" '
BEGIN { lvl = index(h, " ") - 1 }
/^```/ { fence = !fence }
!fence && $0 == h { skip = 1; n = 0; next }
!fence && skip && match($0, /^#+ /) && RLENGTH - 1 <= lvl {
if (lvl == 3 && RLENGTH - 1 < lvl) for (i = 1; i <= n; i++) print buf[i]
skip = 0 }
skip { if ($0 == "" || $0 == "---") buf[++n] = $0; else n = 0; next }
{ print }' "$1"
}
('####'* without a trailing space catches every level ≥ 4.)
project_rules_sections becomes:
project_rules_sections() { # [--depth 2|3] <file> → chars, line, heading
local depth=2
if [ "${1:-}" = "--depth" ]; then depth="${2:-}"; shift 2; fi
case "$depth" in 2|3) ;; *)
echo "project-rules: --depth takes 2 or 3" >&2; return 2 ;; esac
[ $# -eq 1 ] \
|| { echo "project-rules: sections [--depth 2|3] <file>" >&2; return 2; }
[ -f "$1" ] || { echo "project-rules: $1 not found" >&2; return 2; }
awk -v depth="$depth" '
function flush2() {
if (h2 != "") printf "%d\t%d\t%s\n", c2, l2, h2; h2 = "" }
function flush3() {
if (h3 != "") printf "%d\t%d\t%s\n", c3, l3, h3; h3 = "" }
/^```/ { fence = !fence }
/^# / && !fence { flush3(); flush2() }
/^## / && !fence { flush3(); flush2(); h2 = $0; l2 = NR; c2 = 0 }
/^### / && !fence && depth == 3 { flush3(); h3 = $0; l3 = NR; c3 = 0 }
h2 != "" { c2 += length($0) + 1 }
h3 != "" { c3 += length($0) + 1 }
END { flush3(); flush2() }' "$1" | sort -t "$(printf '\t')" -k2,2n
}
(shift 2 with a lone --depth and set -u: ${2:-} is empty, the case
refuses it before the shift matters; if shellcheck or bash complains about
shift 2 on one argument, guard with [ $# -ge 2 ] &&.)
project_rules_extract becomes (locals: src out globs hline tmp):
project_rules_extract() { # <file> <heading> <out.md> <globs-json>
local src="$1" out="$3" globs="$4" hline tmp
hline=$(_rules_heading_line "$2") || return 2
[ "$(_rules_heading_count "$src" "$hline")" = 1 ] || {
echo "project-rules: heading must occur exactly once: $hline" >&2
return 2; }
[ -e "$out" ] && { echo "project-rules: $out exists" >&2; return 2; }
_rules_globs_all_match "$globs" || return 2
mkdir -p "$(dirname "$out")"
tmp=$(mktemp) || { echo "project-rules: no temp file" >&2; return 2; }
{ printf -- '---\npaths: %s\n---\n\n# %s\n' "$globs" "${hline#* }"
_rules_section_body "$src" "$hline"; } > "$out"
if ! { _rules_without_section "$src" "$hline" > "$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 '$hline' to $out"
}
Main dispatch: sections) project_rules_sections "${@:2}" ;;. The usage
*) arm becomes:
*) echo "usage: project-rules.sh [-C dir] check [rules-dir] | matches" \
"<glob> | sections [--depth 2|3] <file> | extract <file>" \
"<heading> <out> <globs-json> | emit <skeleton> <out>" >&2
return 2 ;;
2. lib/tests/project-rules.test.sh
No existing expectation changes (the "moved" message now prints the heading
line; no test greps it). Insert the block AFTER the T12 block's closing
cd "$FIX" || exit 1 and BEFORE the echo "PASS=$pass FAIL=$fail" line:
# T13 ### subsections: hidden at depth 2, listed at depth 3, extractable,
# a ### moved last gives its parent's --- back, a ## parent takes its ###
mkdir -p "$FIX/d3/src" && cd "$FIX/d3" || exit 1
echo x > src/a.ts
cat > CLAUDE.md <<'EOF'
# Top
## P
intro
### Sub
s1
```
### fenced
```
#### deep
s2
### Sub2
s3
---
## Q
q
EOF
cp CLAUDE.md "$FIX/orig3.md"
check T13-depth2-unchanged "$(bash "$PR" sections CLAUDE.md | cut -f1,3 | tr '\t\n' ' |')" '74 ## P|7 ## Q|'
out=$(bash "$PR" sections --depth 3 CLAUDE.md)
check T13b-depth3-file-order "$(printf '%s\n' "$out" | cut -f3 | tr '\n' '|')" '## P|### Sub|### Sub2|## Q|'
check T13c-sub-chars-and-line "$(printf '%s\n' "$out" | awk -F'\t' '$3=="### Sub"{print $1 "," $2}')" '44,6'
check T13d-parent-same-as-depth2 "$(printf '%s\n' "$out" | awk -F'\t' '$3=="## P"{print $1}')" 74
bash "$PR" sections --depth 4 CLAUDE.md 2>/dev/null; check T13e-bad-depth-rc "$?" 2
bash "$PR" sections CLAUDE.md --depth 3 2>/dev/null; check T13f-flag-after-file-rc "$?" 2
bash "$PR" extract CLAUDE.md '### Sub' .claude/rules/sub.md '["src/**"]' >/dev/null
check T13g-extract-sub-rc "$?" 0
check T13h-rule-title "$(sed -n '5p' .claude/rules/sub.md)" '# Sub'
# shellcheck disable=SC2016
check T13i-removed-lines "$(diff "$FIX/orig3.md" CLAUDE.md | grep '^< ' | cut -c3- | grep -vE '^(---)?$' | tr '\n' '|')" '### Sub|s1|```|### fenced|```|#### deep|s2|'
check T13j-rule-ends-before-sub2 "$(tail -1 .claude/rules/sub.md)" 's2'
cp CLAUDE.md "$FIX/mid3.md"
bash "$PR" extract CLAUDE.md '### Sub2' .claude/rules/sub2.md '["src/**"]' >/dev/null
check T13k-last-child-rc "$?" 0
check T13l-last-child-removed-lines "$(diff "$FIX/mid3.md" CLAUDE.md | grep '^< ' | cut -c3- | tr '\n' '|')" '### Sub2|s3|'
check T13m-parent-separator-kept "$(grep -c '^---$' CLAUDE.md)" 1
check T13n-no-additions "$(diff "$FIX/mid3.md" CLAUDE.md | grep -c '^> ')" 0
check T13o-q-kept "$(grep -c '^## Q' CLAUDE.md)" 1
bash "$PR" extract CLAUDE.md '#### deep' .claude/rules/deep.md '["src/**"]' 2>/dev/null
check T13p-level4-rc "$?" 2
check T13p2-level4-msg "$(bash "$PR" extract CLAUDE.md '#### deep' .claude/rules/deep.md '["src/**"]' 2>&1 >/dev/null | grep -c 'heading level must be ## or ###')" 1
bash "$PR" extract CLAUDE.md '# Top' .claude/rules/top.md '["src/**"]' 2>/dev/null
check T13q-level1-rc "$?" 2
check T13q2-level1-msg "$(bash "$PR" extract CLAUDE.md '# Top' .claude/rules/top.md '["src/**"]' 2>&1 >/dev/null | grep -c 'heading level must be ## or ###')" 1
check T13r-nothing-else-written "$(cd .claude/rules && printf '%s\n' * | wc -l | tr -d ' ')" 2
cp "$FIX/orig3.md" CLAUDE.md
bash "$PR" extract CLAUDE.md 'P' .claude/rules/p.md '["src/**"]' >/dev/null
check T13s-parent-takes-children "$(grep -c '^### Sub' .claude/rules/p.md)" 2
check T13t-parent-extract-q-kept "$(grep -c '^## Q' CLAUDE.md)" 1
printf '## #1 priority\nbody\n' > hash.md
bash "$PR" extract hash.md '#1 priority' .claude/rules/hash.md '["src/**"]' >/dev/null
check T13u-bare-title-starting-with-hash "$?" 0
cd "$FIX" || exit 1
(T13r counts files instead of listing them: glob order follows
LC_COLLATE, and make test does not pin the locale.)
Hand counts (each line length + 1, the heading line counted in its own
section): ### Sub = ### Sub(8) s1(3) ""(4) `### fenced`(11) ""(4) #### deep(10) s2(3) (1) = 44, at file line 6. `### Sub2` = 9+3+1+4+1 = 18. `## P` = `## P`(5) `intro`(6) (1) + 44 + 18 = 74.
## Q = 5+2 = 7. The rule file: lines 1-3 frontmatter, 4 blank, 5
# Sub, 6-11 the body. T13l: the diff of the Sub2 extract deletes exactly
### Sub2 and s3 (the blank, ---, blank run is re-emitted), so the
< lines are those two. Expected tally: 93 + 23 = 116.
3. skills/onboard/SKILL.md § SPLIT MODE S4 and S5
S4: the first sentence `bash ~/.claude/lib/project-rules.sh -C <ROOT> sections CLAUDE.md` lists every `##` section with its size. becomes
`bash ~/.claude/lib/project-rules.sh -C <ROOT> sections --depth 3 CLAUDE.md` lists every `##` section with its size and, under it, its `###` subsections with theirs (the parent's size includes them). and this
text is added right after that sentence:
An always-on parent (conventions, overview) whose subsections are path-bound (one module, one tool) keeps its intro and the subsections move, one row each, heading written ###