Repository navigation
Expand file tree
/
Copy pathci-gates.sh
More file actions
1904 lines (1811 loc) · 99.6 KB
/
Copy pathci-gates.sh
File metadata and controls
1904 lines (1811 loc) · 99.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# ci-gates.sh — production helper enforcing this repo's documented gates.
#
# scripts/test-ci-gates.sh pins this contract; keep the two in sync. Every
# subcommand FAILS CLOSED: a missing input, an empty policy, or a real violation
# exits non-zero. There is deliberately no `|| true`, no always-success
# fallback, and no pipeline that swallows the exit status of the real work — the
# caller (CI, or the harness) sees the true result.
#
# Subcommands:
# privacy --banlist <file> <path...> scan paths for banned patterns (files only, never content)
# routing [--max-bytes N] <skill-dir> every references/*.md routed from SKILL.md; SKILL.md over N bytes FAILS (no allowlist)
# version <root> VERSION is byte-exact ASCII core semver; first CHANGELOG heading announces it
# install --src <dir> --dest <dir> --mode <claude|minimal|full|codex|overlays|gates|recommend>
# run the real installer, then verify vendored docs are real (not placeholders)
# enumeration <root> every shipped skill is present in all five hand-maintained lists
# size --config <file> <root> every shipped SKILL.md/references/*.md is within its frozen size-budgets.tsv byte budget
# size-ratchet --base <ref> --config <file> <root>
# no size-budgets.tsv row may increase vs <ref> without a `size-budget-raise:` marker (fail closed on unresolvable base)
# fragments [--config <file>] <dir> every <dir>/*.md changelog fragment: its `size-budget-raise:` lines are the exact marker size-ratchet greps (path a row of <file>), no "## " heading
# binaries <root> no git-tracked file at a banned image/media/archive/build-output extension (allowlist: scripts/binaries-allowlist.tsv)
# mustload --config <file> <root> every SKILL.md load-map archetype's MUST-LOAD token-est total is within its frozen mustload-budgets.tsv ceiling; the Phase 0-2 floor equals its pin exactly, and every " when " ref is a pinned phase-conditional row
# rules --baseline <file> [--base <ref>] [--list] <root>
# every MUST/NEVER/ALWAYS (or bold "Never") rule line in a SKILL.md must sit in a paragraph that names a mechanism (scripts/, ci-gates, evals, hook) or says "advisory"; unenforced rules not in the baseline FAIL (ratchet); --base: baseline rows added vs <ref> need a `rule-baseline-raise:` commit marker
# tests-wired --allowlist <file> <root>
# every scripts/test_*.py and scripts/test-*.sh is run by CI (named in scripts/ci-tests.d/*.sh, .github/workflows/*.yml or a test they run) or listed in <file> with a reason; a stale row FAILS
# rails [--audit] <root> every guard/hook script (name ends _guard/_gate/_cap/_hook, or a hook template wires it) carries `# rail: owner=..., why=..., review=YYYY-MM-DD`; a missing or empty field or a bad date FAILS; --audit lists rails past their review date (never removes one)
# guard-registry --registry <file> [--report [--days N]] <root>
# every hook a shipped template runs or install.sh writes under .githooks/, and every subcommand here, has one row (owner role, reason, review-by date) in <file>; a missing row, an empty reason, a bad date or a row for a guard that is gone FAILS; --report (read-only) lists rows past review-by and guards with no fire in N days, `unknown` where there is no fire log
#
set -euo pipefail
# This repo's own root (one level up from this script) — used only to locate
# canonical shipped-skill scripts this helper delegates to (e.g.
# `binaries` -> deep-code-review/scripts/binaries_gate.py), independent of
# whatever <root>/<path> a subcommand is asked to SCAN.
CI_GATES_REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
die() { printf 'ci-gates: %s\n' "$*" >&2; exit 1; }
# collect_patterns <file> — append each actionable banlist pattern (non-blank
# line whose first non-space char is not '#') from <file> to the caller's
# `patterns` array. Bash's dynamic scoping makes that caller-local array visible
# here, so both the committed primary banlist and its optional sibling local
# override funnel through one collector.
# frozen_pinned FILE REPO_RELATIVE_PATH: true if scripts/secret-scan-allow.txt pins that path and FILE still hashes to the pin.
frozen_pinned() {
local want
# awk-v-ok: one repo-relative path
want="$(awk -v p="$2" '$2 == p { print $1 }' "$(dirname "${BASH_SOURCE[0]}")/secret-scan-allow.txt")"
[ -n "$want" ] && [ "$(shasum -a 256 <"$1" | cut -d' ' -f1)" = "$want" ]
}
# Patterns under a "# --- Secret" or "# --- Hard-coded credential" header also join `secret_pats`: a file hit there is re-checked and
# dropped when every match's own text looks like a placeholder (secret_scan.py PLACEHOLDER). Names and PII patterns are never relaxed.
collect_patterns() {
local _line _trimmed _sec=0
while IFS= read -r _line || [ -n "$_line" ]; do
_trimmed="${_line#"${_line%%[![:space:]]*}"}" # strip leading whitespace
case "$_trimmed" in
'# --- Secret'*|'# --- Hard-coded credential'*) _sec=1; continue ;;
'# ---'*) _sec=0; continue ;;
''|'#'*) continue ;;
esac
patterns+=("$_trimmed")
[ "$_sec" -eq 0 ] || secret_pats+=("$_trimmed")
done < "$1"
}
usage() {
cat >&2 <<'EOF'
ci-gates.sh — enforce the deep-code-review repo's documented gates.
Usage:
ci-gates.sh privacy --banlist <file> <path...>
ci-gates.sh routing [--max-bytes N] <skill-dir>
ci-gates.sh version <root>
ci-gates.sh install --src <dir> --dest <dir> --mode <claude|minimal|full|codex|overlays|gates|recommend>
ci-gates.sh enumeration <root>
ci-gates.sh size --config <file> <root>
ci-gates.sh size-ratchet --base <ref> --config <file> <root>
ci-gates.sh fragments [--config <file>] <dir>
ci-gates.sh binaries <root>
ci-gates.sh mustload --config <file> <root>
ci-gates.sh tests-wired --allowlist <file> <root>
ci-gates.sh rails [--audit] <root>
ci-gates.sh guard-registry --registry <file> [--report [--days N]] <root>
EOF
}
# scan_files <path> — NUL-separated list of the files a repo scan may read.
# When <path> is a git work-tree root: `git ls-files -co --exclude-standard`
# (tracked + untracked-not-ignored), so nested worktrees and gitignored build
# dirs are never walked. Only outside a git root (a bare fixture dir, a tarball)
# does it fall back to `find`. A plain file argument is returned as-is.
scan_files() {
local p="$1" top f
# a symlink target is skipped like a symlink found under a directory (a dangling one would make grep exit 2)
if [ ! -d "$p" ]; then [ -L "$p" ] || printf '%s\0' "$p"; return 0; fi
if top="$(git -C "$p" rev-parse --show-toplevel 2>/dev/null)" \
&& [ "$(cd "$top" && pwd -P)" = "$(cd "$p" && pwd -P)" ]; then
git -C "$p" ls-files -z -co --exclude-standard | while IFS= read -r -d '' f; do
if [ -f "$p/$f" ] && [ ! -L "$p/$f" ]; then printf '%s\0' "$p/$f"; fi
done
else
find "$p" -name .git -prune -o -type f -print0
fi
}
# ---------------------------------------------------------------------------
# privacy — banned-term hygiene + secret detection.
#
# Fails closed unless the banlist exists AND holds at least one actionable
# (non-blank, non-comment) pattern; a comments-only or empty policy is treated
# as "no policy", not "nothing banned". Reports matching FILE NAMES only, never
# the matched content, so a real secret is never echoed into a log.
# ---------------------------------------------------------------------------
cmd_privacy() {
local banlist=""
local -a targets=()
while [ "$#" -gt 0 ]; do
case "$1" in
--banlist) banlist="${2:-}"; shift 2 ;;
--banlist=*) banlist="${1#*=}"; shift ;;
--) shift; while [ "$#" -gt 0 ]; do targets+=("$1"); shift; done ;;
-*) die "privacy: unknown option: $1" ;;
*) targets+=("$1"); shift ;;
esac
done
[ -n "$banlist" ] || die "privacy: --banlist <file> is required (fail closed)"
[ -f "$banlist" ] || die "privacy: banlist not found: $banlist (fail closed)"
[ "${#targets[@]}" -gt 0 ] || die "privacy: at least one scan path is required (fail closed)"
# The committed primary banlist supplies the baseline policy and must, as
# before, hold at least one actionable (non-blank, non-comment) pattern.
local -a patterns=() secret_pats=()
collect_patterns "$banlist"
[ "${#patterns[@]}" -gt 0 ] \
|| die "privacy: banlist has no actionable patterns (only blanks/comments): $banlist"
local banlist_base
banlist_base="$(basename "$banlist")"
local -a skip_bases=( "$banlist_base" )
# Optional sibling local override: insert '.local' before the primary's
# extension (.banlist.txt -> .banlist.local.txt). Missing is normal; a present
# sibling extends the committed policy for this run only. Its actionable
# patterns join the scan set (an empty/comment-only sibling contributes
# nothing), its EREs are validated on the same fail-closed, content-withheld
# footing below, and its basename is excluded from the recursive scan so it
# can never match itself.
local banlist_local banlist_local_base
banlist_local="${banlist%.*}.local.${banlist##*.}"
if [ -f "$banlist_local" ]; then
collect_patterns "$banlist_local"
banlist_local_base="$(basename "$banlist_local")"
skip_bases+=( "$banlist_local_base" )
else
# Fail closed in a linked worktree: gitignored files are not checked out there, so a missing local
# banlist would silently skip identifier scans while the main checkout holds one.
local gd gc main_local
gd="$(git -C "$(dirname "$banlist")" rev-parse --absolute-git-dir 2>/dev/null)" || gd=""
gc="$(git -C "$(dirname "$banlist")" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" || gc=""
main_local="$(dirname "$gc")/$(basename "$banlist_local")"
if [ -n "$gd" ] && [ "$gd" != "$gc" ] && [ -f "$main_local" ]; then
die "privacy: worktree lacks $(basename "$banlist_local") but the main checkout has it (fail closed); fix: cp '$main_local' '$banlist_local'"
fi
fi
# Fail closed on a malformed policy: every actionable pattern must be a valid
# ERE. Probe each against empty input BEFORE scanning so we can tell grep
# exit 1 (valid pattern, simply no match) apart from exit 2 (invalid regex).
local pat probe_status
for pat in "${patterns[@]}"; do
printf '' | grep -qE -e "$pat" 2>/dev/null && probe_status=0 || probe_status=$?
[ "$probe_status" -le 1 ] \
|| die "privacy: a banlist pattern is not a valid ERE (content withheld); failing closed"
done
# Enumerate once (git ls-files in a repo root, see scan_files); the banlists
# are skipped by basename so they can never match themselves.
local -a scan=()
local t f b skip sp
for t in "${targets[@]}"; do
while IFS= read -r -d '' f; do
skip=0
for b in "${skip_bases[@]}"; do [ "${f##*/}" = "$b" ] && skip=1; done
# frozen synthetic leak/decoy corpora of the held-out secret benches (exact paths, no glob, and the sha256 pinned in secret-scan-allow.txt, so an edited file is scanned): fictional values by design, immutable once landed
case "${f##*/}" in secret-leaks.txt|secret-decoys.txt) # repo-relative path, so scanning a subdir still resolves it
local d top; d="$(cd "$(dirname "$f")" && pwd -P)"; top="$(git -C "$d" rev-parse --show-toplevel 2>/dev/null)" || top=""
case "${d#"$top"/}/${f##*/}" in docs/bench/security-gates-heldout-1024/secret-leaks.txt|docs/bench/security-gates-heldout-1024/secret-decoys.txt|docs/bench/security-gates-heldout2-1024/secret-leaks.txt|docs/bench/security-gates-heldout2-1024/secret-decoys.txt|docs/bench/security-gates-heldout3-1024/secret-leaks.txt|docs/bench/security-gates-heldout3-1024/secret-decoys.txt|docs/bench/secrets-heldout4-1025/secret-leaks.txt|docs/bench/secrets-heldout4-1025/secret-decoys.txt|docs/bench/secrets-heldout5-1025/secret-leaks.txt|docs/bench/secrets-heldout5-1025/secret-decoys.txt|docs/bench/secrets-heldout6-1025/secret-leaks.txt|docs/bench/secrets-heldout6-1025/secret-decoys.txt|docs/bench/secrets-heldout7-1025/secret-leaks.txt|docs/bench/secrets-heldout7-1025/secret-decoys.txt|docs/bench/secrets-heldout8-1025/secret-leaks.txt|docs/bench/secrets-heldout8-1025/secret-decoys.txt|docs/bench/secrets-heldout9-1025/secret-leaks.txt|docs/bench/secrets-heldout9-1025/secret-decoys.txt|docs/bench/secrets-heldout10-1025/secret-leaks.txt|docs/bench/secrets-heldout10-1025/secret-decoys.txt|docs/bench/secrets-heldout11-1025/secret-leaks.txt|docs/bench/secrets-heldout11-1025/secret-decoys.txt|docs/bench/secrets-heldout12-1025/secret-leaks.txt|docs/bench/secrets-heldout12-1025/secret-decoys.txt|docs/bench/secrets-heldout14-1026/secret-leaks.txt|docs/bench/secrets-heldout14-1026/secret-decoys.txt|docs/bench/secrets-heldout15-1026/secret-leaks.txt|docs/bench/secrets-heldout15-1026/secret-decoys.txt|docs/bench/secrets-heldout16-1026/secret-leaks.txt|docs/bench/secrets-heldout16-1026/secret-decoys.txt) [ -n "$top" ] && frozen_pinned "$f" "${d#"$top"/}/${f##*/}" && skip=1 ;; esac ;;
esac
[ "$skip" -eq 1 ] || scan+=("$f")
done < <(scan_files "$t")
done
# Prefilter: ONE pass of `grep -f` over every pattern at once (same flags and 1000-file batches as the per-pattern greps below)
# lists the only files any pattern can match, so a clean tree is read once, not once per pattern. Every pattern already passed
# the ERE probe above, so the list holds only valid EREs. Same status rule as below: 0 = candidates, 1 = none, anything else
# = gate error, which fails closed (a failed prefilter must never read as "no candidates"). The list is newline-delimited, so a
# path holding a newline cannot round-trip (a hit would read as the clean files named after its pieces): such a tree skips the
# prefilter and every file goes to the per-pattern scan below, as before.
local i out cs nl_path=0
local -a cand=()
[ "${#scan[@]}" -eq 0 ] || case "${scan[*]}" in *$'\n'*) nl_path=1; cand=("${scan[@]}") ;; esac
for ((i = 0; nl_path == 0 && i < ${#scan[@]}; i += 1000)); do
out="$(grep -IlE -D skip -f <(printf '%s\n' "${patterns[@]}") -- "${scan[@]:i:1000}" 2>/dev/null)" && cs=0 || cs=$?
case "$cs" in
0) while IFS= read -r f; do cand+=("$f"); done <<<"$out" ;;
1) : ;;
*) die "privacy: grep failed while prefiltering (exit $cs); failing closed" ;;
esac
done
local hit=0 files status
[ "${#cand[@]}" -eq 0 ] || for pat in "${patterns[@]}"; do
# -l: report file names only. -I: skip binaries. -D skip: never open a
# FIFO/device (a stray named pipe blocks the scan forever). `--` guards dash-leading
# target paths from being read as options. Capture grep's exit status
# explicitly: 0 = matches, 1 = clean, anything else = gate error (no
# always-success fallback, so a broken scan fails closed).
# Chunked: one argv holding every path overflows ARG_MAX on large trees
# (macOS fails at ~15K files with exit 126). Merge per-chunk statuses so a
# match anywhere wins over clean and any error still fails closed.
files="" status=1
for ((i = 0; i < ${#cand[@]}; i += 1000)); do
out="$(grep -IlE -D skip -e "$pat" -- "${cand[@]:i:1000}" 2>/dev/null)" && cs=0 || cs=$?
case "$cs" in
0) files+="${files:+$'\n'}$out"; [ "$status" -gt 1 ] || status=0 ;;
1) : ;;
*) status=$cs; break ;;
esac
done
if [ "$status" -eq 0 ]; then
for sp in ${secret_pats[@]+"${secret_pats[@]}"}; do
[ "$sp" = "$pat" ] || continue
files="$(printf '%s\n' "$files" | tr '\n' '\0' | xargs -0 python3 -I "$(dirname "${BASH_SOURCE[0]}")/secret_scan.py" --refilter "$pat")" \
|| die "privacy: secret_scan.py --refilter failed; failing closed"
[ -n "$files" ] || status=1
done
fi
case "$status" in
0)
printf 'BLOCK: a banned pattern matched (content withheld); files:\n' >&2
printf '%s\n' "$files" | sed 's/^/ /' >&2
hit=1 ;;
1) : ;; # clean: this pattern matched nothing
*) die "privacy: grep failed while scanning (exit $status); failing closed" ;;
esac
done
# Union with the gitleaks default rules (scripts/secret_scan.py): live-format secrets the banlist has no pattern for.
# Fail closed: python3 missing or the scanner erroring blocks, never passes.
if [ "${#scan[@]}" -gt 0 ]; then
local sstatus=0 sout
sout="$(printf '%s\0' "${scan[@]}" | xargs -0 -n 1000 -P "$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 8)" python3 -I "$(dirname "${BASH_SOURCE[0]}")/secret_scan.py")" || sstatus=$?
if [ "$sstatus" -eq 0 ]; then :
elif [ -n "$sout" ]; then printf 'BLOCK: a gitleaks rule matched (content withheld); files:\n%s\n' "$sout" >&2; hit=1
else die "privacy: secret_scan.py failed (exit $sstatus); failing closed"
fi
fi
[ "$hit" -eq 0 ] || die "privacy: banned pattern(s) present (see files above)"
printf 'privacy: clean (%d pattern(s) + gitleaks rules scanned)\n' "${#patterns[@]}"
}
# ---------------------------------------------------------------------------
# routing — progressive disclosure integrity.
#
# Every references/*.md must be routed by basename from SKILL.md (or, when the
# skill has a references/full-map.md, from that map, which SKILL.md itself must
# name), and every route named in either file must resolve to a file. An
# oversized SKILL.md FAILS the gate against the documented byte budget, for every skill (no allowlist);
# broken routing always fails.
# ---------------------------------------------------------------------------
cmd_routing() {
local max_bytes=""
local -a dirs=()
while [ "$#" -gt 0 ]; do
case "$1" in
--max-bytes) max_bytes="${2:-}"; shift 2 ;;
--max-bytes=*) max_bytes="${1#*=}"; shift ;;
-*) die "routing: unknown option: $1" ;;
*) dirs+=("$1"); shift ;;
esac
done
[ "${#dirs[@]}" -eq 1 ] || die "routing: exactly one skill directory is required"
local skill_dir="${dirs[0]}"
local skill_md="$skill_dir/SKILL.md"
[ -f "$skill_md" ] || die "routing: SKILL.md not found: $skill_md (fail closed)"
local fail=0 f base p
# A skill may route its references through references/full-map.md; the map
# itself must then be routed from SKILL.md (checked by the loop below).
local -a route_srcs=("$skill_md")
if [ -f "$skill_dir/references/full-map.md" ]; then route_srcs+=("$skill_dir/references/full-map.md"); fi
# 1) Every reference file is routed from SKILL.md (or from full-map.md).
if [ -d "$skill_dir/references" ]; then
for f in "$skill_dir"/references/*.md; do
[ -e "$f" ] || continue # nullglob-safe: skip the literal when no matches
base="$(basename "$f")"
# Fixed-string (-F) so a literal '.' in the basename matches only a dot;
# a regex match would let 'literal.md' spuriously match 'literalXmd'.
# full-map.md never counts as routing itself: SKILL.md must name it.
if [ "$base" = full-map.md ]; then
grep -qF -e "$base" -- "$skill_md" && continue
elif grep -qF -e "$base" -- "${route_srcs[@]}"; then
continue
fi
printf 'UNROUTED: references/%s\n' "$base" >&2
fail=1
done
fi
# 2) Every route named in SKILL.md (and full-map.md) resolves to a file.
while IFS= read -r p; do
[ -n "$p" ] || continue
if [ ! -f "$skill_dir/$p" ]; then
printf 'DANGLING ROUTE: %s\n' "$p" >&2
fail=1
fi
done < <(grep -ohE 'references/[A-Za-z0-9._-]+\.md' "${route_srcs[@]}" | sort -u)
# 3) Size budget — FAILS on bloat (the ratchet has teeth) for every skill, with
# no per-skill allowlist: an oversized SKILL.md moves depth into a routed
# references/ file instead of earning an exemption.
if [ -n "$max_bytes" ]; then
local size
size="$(wc -c < "$skill_md" | tr -d '[:space:]')"
if [ "$size" -gt "$max_bytes" ]; then
printf 'SIZE FAIL: %s SKILL.md is %s bytes (exceeds %s-byte budget)\n' \
"$(basename "$skill_dir")" "$size" "$max_bytes" >&2
fail=1
fi
fi
[ "$fail" -eq 0 ] || die "routing: unrouted and/or dangling references present"
printf 'routing: ok\n'
}
# ---------------------------------------------------------------------------
# version — VERSION is byte-exact ASCII core semver; first CHANGELOG heading announces it.
#
# Accepts a flat fixture root (<root>/VERSION) or the real repo, where VERSION
# lives nested in the skill and CHANGELOG.md sits at the repo root.
# ---------------------------------------------------------------------------
cmd_version() {
local -a roots=()
while [ "$#" -gt 0 ]; do
case "$1" in
-*) die "version: unknown option: $1" ;;
*) roots+=("$1"); shift ;;
esac
done
[ "${#roots[@]}" -eq 1 ] || die "version: exactly one root directory is required"
local root="${roots[0]}"
# Prefer the real nested skill VERSION; fall back to a flat fixture root.
local version_file=""
if [ -f "$root/.claude/skills/deep-code-review/VERSION" ]; then
version_file="$root/.claude/skills/deep-code-review/VERSION"
elif [ -f "$root/VERSION" ]; then
version_file="$root/VERSION"
else
die "version: no VERSION file found under $root (fail closed)"
fi
local changelog="$root/CHANGELOG.md"
[ -f "$changelog" ] || die "version: no CHANGELOG.md under $root (fail closed)"
# Validate raw bytes before converting them to a shell string. Bash command
# substitution cannot carry NUL; the hexadecimal representation can. This
# permits only ASCII core SemVer with no leading zero in any multi-digit part,
# plus one optional terminal LF. No normalization is performed.
local version_hex
version_hex="$(LC_ALL=C od -An -v -tx1 "$version_file" | tr -d '[:space:]')"
[[ "$version_hex" =~ ^(30|3[1-9](3[0-9])*)2e(30|3[1-9](3[0-9])*)2e(30|3[1-9](3[0-9])*)(0a)?$ ]] \
|| die "version: VERSION must be byte-exact ASCII core semver with optional final LF"
# Safe only after raw-byte validation above: the input cannot contain NUL,
# whitespace except an optional terminal LF, or more than one line.
local ver
ver="$(LC_ALL=C tr -d '\n' < "$version_file")"
printf 'VERSION=%s (from %s)\n' "$ver" "$version_file"
# The current release must be the first release heading. Searching later
# headings would allow stale changelog ordering to pass provenance checks.
local first_heading
first_heading="$(LC_ALL=C grep -m1 '^## ' "$changelog" || true)"
[ -n "$first_heading" ] || die "version: CHANGELOG has no release heading"
case "$first_heading" in
"## $ver"|"## $ver "*|"## [$ver]"|"## [$ver] "*) ;;
*) die "version: first CHANGELOG release heading does not announce $ver" ;;
esac
# The plugin manifest must carry the same version (land-release.sh stamps it); the marketplace entry
# must carry none, because plugin.json silently wins when both are set.
local pj="$root/.claude-plugin/plugin.json" mj="$root/.claude-plugin/marketplace.json"
local hm
for hm in "$pj" "$root/.codex-plugin/plugin.json" "$root/gemini-extension.json"; do
[ -f "$hm" ] || continue
[ "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("version",""))' "$hm" 2>/dev/null)" = "$ver" ] \
|| die "version: ${hm#"$root"/} version does not equal $ver"
done
if [ -f "$mj" ] && grep -q '"version"' "$mj"; then
die "version: marketplace.json must not set a version (plugin.json is the single source)"
fi
printf 'version: ok (%s announced in CHANGELOG)\n' "$ver"
}
# ---------------------------------------------------------------------------
# install — drive the real installer and verify what it vendored.
#
# Calls the repo's own install.sh (never a reimplementation), then checks that
# the docs the skill cites were copied in as their REAL content, not left as a
# preexisting placeholder. Fails closed if either docs source or installed copy
# is missing or mismatched.
# ---------------------------------------------------------------------------
cmd_install() {
local src="" dest="" mode=""
while [ "$#" -gt 0 ]; do
case "$1" in
--src) src="${2:-}"; shift 2 ;;
--src=*) src="${1#*=}"; shift ;;
--dest) dest="${2:-}"; shift 2 ;;
--dest=*) dest="${1#*=}"; shift ;;
--mode) mode="${2:-}"; shift 2 ;;
--mode=*) mode="${1#*=}"; shift ;;
-*) die "install: unknown option: $1" ;;
*) die "install: unexpected argument: $1" ;;
esac
done
[ -n "$src" ] || die "install: --src <dir> is required"
[ -n "$dest" ] || die "install: --dest <dir> is required"
[ -n "$mode" ] || die "install: --mode <claude|minimal|full|codex|overlays|gates|recommend> is required"
[ -d "$src" ] || die "install: --src not found: $src"
[ -d "$dest" ] || die "install: --dest not found: $dest"
local installer="$src/install.sh"
[ -f "$installer" ] || die "install: real installer not found: $installer"
local -a mode_flags=()
case "$mode" in
claude) mode_flags=(--claude-only) ;;
minimal) mode_flags=(--minimal) ;;
codex) mode_flags=(--with-codex) ;; # multi-path plus codex adapter
full|default) : ;; # agent-agnostic multi-path default (review only)
overlays) mode_flags=(--full) ;; # review + delivery + critic
gates) mode_flags=(--claude-only --with-gates) ;; # CI-gates wiring, review-only host
recommend) mode_flags=(--recommend) ;; # inspect only; no writes
*) die "install: unsupported mode: $mode (want claude|minimal|full|codex|overlays|gates|recommend)" ;;
esac
# Run the REAL installer; set -e preserves its exit code (no || true).
bash "$installer" ${mode_flags[@]+"${mode_flags[@]}"} "$dest"
if [ "$mode" = "recommend" ]; then
# Recommend must not create skill trees or AGENTS.md.
if [ -e "$dest/.claude" ] || [ -e "$dest/AGENTS.md" ]; then
die "install: --recommend wrote to the destination (must be read-only)"
fi
printf 'install: ok (recommend mode; no writes)\n'
return 0
fi
# Postcondition: the installer vendors the repo's docs into the installed
# skill's references/, and the result is the real content (not a placeholder).
local skill_rel=".claude/skills/deep-code-review"
local -a pairs=(
"docs/standards-index.md:${skill_rel}/references/standards-index.md"
"docs/example-review-report.md:${skill_rel}/references/example-review-report.md"
)
local pair srcdoc inst
for pair in "${pairs[@]}"; do
srcdoc="$src/${pair%%:*}"
inst="$dest/${pair##*:}"
[ -f "$srcdoc" ] || die "install: docs source missing in --src: $srcdoc"
[ -f "$inst" ] || die "install: installed reference missing: $inst"
! grep -q 'PLACEHOLDER' "$inst" \
|| die "install: installed reference is still a placeholder: $inst"
cmp -s "$inst" "$srcdoc" \
|| die "install: installed reference does not equal docs source: $inst"
done
if [ "$mode" = "overlays" ]; then
[ -f "$dest/.claude/skills/agentic-delivery/SKILL.md" ] \
|| die "install: overlays mode missing agentic-delivery"
[ -f "$dest/.claude/skills/idea-critic/SKILL.md" ] \
|| die "install: overlays mode missing idea-critic"
else
# Default review-only modes must not dump overlays.
if [ -e "$dest/.claude/skills/agentic-delivery" ] \
|| [ -e "$dest/.claude/skills/idea-critic" ]; then
die "install: review-only mode installed an overlay skill"
fi
fi
printf 'install: ok (%s mode; docs vendored and verified)\n' "$mode"
}
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# enumeration — every shipped skill is present in every hand-maintained list.
#
# Catches the drift class that shipped despite green CI: a new skill missing from
# agentic-ceo's registry (unroutable), from install.sh (uninstallable), from the
# ci.yml routing lines (ungated), from the checksum find-list (unpinned), or from
# recommend-overlays.py (mis-classified). These lists are hand-enumerated, so the
# globbed self-tests cannot see a gap. Fail closed. Directional: it catches a skill
# on disk that is missing from a list, not a stale list entry for a deleted skill.
# ---------------------------------------------------------------------------
cmd_enumeration() {
local root="."
while [ "$#" -gt 0 ]; do
case "$1" in
-*) die "enumeration: unknown option: $1" ;;
*) root="$1"; shift ;;
esac
done
local skills_dir="$root/.claude/skills"
[ -d "$skills_dir" ] || die "enumeration: no skills dir at $skills_dir (fail closed)"
local ci="$root/.github/workflows/ci.yml"
local checksums="$root/scripts/write-checksums.sh"
local installer="$root/install.sh"
local registry="$skills_dir/agentic-ceo/SKILL.md"
local recommend="$root/scripts/recommend-overlays.py"
local f
for f in "$ci" "$checksums" "$installer" "$registry" "$recommend"; do
[ -f "$f" ] || die "enumeration: missing required file: $f (fail closed)"
done
local bt='`'
local fail=0 d name sver fmver fmline has_skill has_ver vname
# check #7 allowlist: the skills whose SKILL.md enumerates EVERY eval id.
local verif_enum="business-ops contribution growth-analytics positioning product-discovery product-output-safety"
for d in "$skills_dir"/*/; do
[ -d "$d" ] || continue
name="$(basename "$d")"
# 1) ci.yml routing INVOCATION (per-skill line, or the glob loop below). Anchored to
# the `ci-gates.sh routing` call so a bare mention (a comment) cannot satisfy it.
# A glob loop (`for d in .claude/skills/*/` calling `routing ... "$d"`) covers every
# skill, so adding one edits no shared list.
grep -qE "ci-gates\.sh routing .*\.claude/skills/${name}[[:space:]]*\$" "$ci" \
|| { grep -qE '^[[:space:]]*for [a-z_]+ in \.claude/skills/\*/; do' "$ci" && grep -qE '^[[:space:]]*[^#[:space:]].*ci-gates\.sh routing .*"\$d"' "$ci"; } \
|| { printf 'ENUM: %s has no ci.yml routing line\n' "$name" >&2; fail=1; }
# 2) write-checksums.sh find-list (else the skill tree is unpinned). The path
# followed by whitespace matches the `find` argument list; write-checksums.sh
# holds no other skill paths, so a bare-mention false-PASS has no vector here.
# Or the glob `find .claude/skills/*/` (a non-comment line), which pins every skill dir.
grep -qE "\.claude/skills/${name}[[:space:]]" "$checksums" \
|| grep -qE '^[[:space:]]*find \.claude/skills/\*/' "$checksums" \
|| { printf 'ENUM: %s absent from write-checksums.sh find-list\n' "$name" >&2; fail=1; }
# 3) install.sh — the base ships always; every overlay needs a SKILLS+= line
if [ "$name" != "deep-code-review" ]; then
grep -qF "SKILLS+=(\"${name}\")" "$installer" \
|| { printf 'ENUM: %s has no install.sh SKILLS+= line\n' "$name" >&2; fail=1; }
fi
# 4) agentic-ceo registry — a table ROW (^| `name` |...), not merely prose. Tolerates
# any cell padding before the closing pipe so a table reformat is not a false FAIL.
if [ "$name" != "agentic-ceo" ]; then
grep -qE "^\| ${bt}${name}${bt}[[:space:]]*\|" "$registry" \
|| { printf 'ENUM: %s has no agentic-ceo registry row\n' "$name" >&2; fail=1; }
fi
# 5) recommend-overlays.py knows the skill (else it mis-classifies at --recommend).
# Quoted set-literal form so a name is not a substring false-match ("critic" is
# not a substring of "idea-critic").
grep -qF "\"${name}\"" "$recommend" \
|| { printf 'ENUM: %s not named in recommend-overlays.py\n' "$name" >&2; fail=1; }
# 6) A skill dir must carry BOTH a SKILL.md and a VERSION, and the SKILL.md
# frontmatter metadata.version must equal that VERSION. Fail closed: nothing
# reads the stamp at runtime, so without this check a drift — or a missing
# VERSION — is invisible to every other gate (the stamp slid on the lockstep
# skills for seven releases, v1.101.0–v1.107.0, before it existed). The stamp
# is read as metadata.version — the version: key inside the frontmatter
# metadata: block — so neither a body line nor a description block-scalar
# version: can satisfy it. A dir under skills/ with NEITHER file is a
# malformed (half-added or stray) skill dir — a *fully-enumerated* one still
# passes checks 1–5, so check #6 fails it closed here rather than relying on a
# separate CI step (the globbed name-matches-dir job and `routing`).
has_skill=0; has_ver=0
if [ -f "$d/SKILL.md" ]; then has_skill=1; fi
if [ -f "$d/VERSION" ]; then has_ver=1; fi
if [ "$has_skill" = 0 ] && [ "$has_ver" = 0 ]; then
printf 'ENUM: %s has neither SKILL.md nor VERSION (fail closed)\n' "$name" >&2; fail=1
elif [ "$has_skill" = 1 ] && [ "$has_ver" = 0 ]; then
printf 'ENUM: %s has a SKILL.md but no VERSION (fail closed)\n' "$name" >&2; fail=1
elif [ "$has_ver" = 1 ] && [ "$has_skill" = 0 ]; then
printf 'ENUM: %s has a VERSION but no SKILL.md (fail closed)\n' "$name" >&2; fail=1
elif [ "$has_skill" = 1 ] && [ "$has_ver" = 1 ]; then
sver="$(LC_ALL=C tr -d '\n' < "$d/VERSION")"
# Extract metadata.version, anchored to the metadata: block. `|| true`: no
# match yields grep exit 1, which would abort under `set -o pipefail`; the
# empty result is the signal the absent/unparseable branches act on.
# Match version: only as a DIRECT child of metadata: (the repo's 2-space
# convention, verified across all skills). A deeper-nested `sub:\n version:`
# is skipped, so a nested decoy cannot mask a drift of the real stamp; a skill
# that deviates from 2-space reads as "no stamp" and fails closed.
fmline="$(awk '
/^---[[:space:]]*$/ {c++; next}
c!=1 {next}
/^metadata:[[:space:]]*$/ {inmeta=1; next}
/^[^[:space:]]/ {inmeta=0}
inmeta && /^ version:[[:space:]]/ {print; exit}
' "$d/SKILL.md" || true)"
fmver="$(printf '%s' "$fmline" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true)"
if [ -z "$fmline" ]; then
printf 'ENUM: %s SKILL.md has no metadata.version stamp\n' "$name" >&2; fail=1
elif [ -z "$fmver" ]; then
printf 'ENUM: %s SKILL.md metadata.version is unparseable (%s)\n' "$name" "$(printf '%s' "$fmline" | tr -s '[:space:]' ' ')" >&2; fail=1
elif [ "$fmver" != "$sver" ]; then
printf 'ENUM: %s SKILL.md frontmatter version (%s) != VERSION (%s)\n' "$name" "$fmver" "$sver" >&2; fail=1
fi
fi
# 7) Verification-list completeness — a skill that enumerates EVERY eval id in
# its SKILL.md (one bullet per eval, ids in backticks, closed by "plants these
# cases") must name every id in evals/evals.json, so a later-added eval cannot
# leave its Verification bullet forgotten. Matches the backticked `id` so a bare
# substring elsewhere in the prose cannot satisfy it. CLOSED, MANUAL allowlist
# (`verif_enum`): the "plants" marker is ambiguous — idea-critic and agentic-ceo
# carry it but name only KEY cases, and the large skills (deep-code-review,
# agentic-delivery) do not enumerate, so an unscoped check would false-flag them
# (already-litigated). UNLIKE checks 1–5, this list does NOT self-gate: a new
# enumerate-every-id skill left off it is silently uncovered (fail-open on the
# ADDITION), so it must be added by hand. The resolves-check after the loop
# fail-closes a typo'd/stale entry, but cannot catch a missing addition. This
# doc-sync class surfaced FOUR times before this gate — product-output-safety
# (eval added v1.75.0, bullet forgotten until this wave found it), v1.125.0, and
# two caught in review at v1.133.0 — with nothing referencing eval ids.
case " $verif_enum " in
*" $name "*)
if [ -f "$d/evals/evals.json" ]; then
while IFS= read -r eid; do
[ -n "$eid" ] || continue
grep -qF -- "${bt}${eid}${bt}" "$d/SKILL.md" \
|| { printf 'ENUM: %s eval id "%s" is missing from its SKILL.md Verification list (doc-sync)\n' "$name" "$eid" >&2; fail=1; }
done < <(grep -oE '"id"[[:space:]]*:[[:space:]]*"[^"]+"' "$d/evals/evals.json" | sed -E 's/.*"([^"]+)"$/\1/' || true)
else
printf 'ENUM: %s is Verification-enumerated but has no evals/evals.json (fail closed)\n' "$name" >&2; fail=1
fi
;;
esac
done
# check-#7 allowlist drift: on the real suite (guarded by the base skill's presence,
# so a minimal test fixture that legitimately omits these overlays is skipped), every
# name in verif_enum must resolve to a skill dir — else a typo or a post-rename stale
# entry silently disables the check (fail-open on a fail-closed gate; the exact
# hand-list drift cmd_enumeration exists to catch).
if [ -d "$skills_dir/deep-code-review" ]; then
for vname in $verif_enum; do
[ -d "$skills_dir/$vname" ] \
|| { printf 'ENUM: check-#7 allowlist names "%s", not a skill dir (typo or stale — fix verif_enum)\n' "$vname" >&2; fail=1; }
done
fi
[ "$fail" -eq 0 ] || die "enumeration: one or more skills are not fully enumerated"
printf 'enumeration: ok\n'
}
# ---------------------------------------------------------------------------
# size — frozen byte-count budgets for shipped skill docs (dogfoods this
# repo's own skill-authoring-and-size.md: "A documented budget, enforced").
#
# Measured in BYTES (`wc -c`), not lines: a line-count budget can be beaten by
# packing more prose onto fewer, longer lines — the file gets bigger (more
# context tokens paid on load) while its line count goes down or holds still.
# Bytes track the actual on-load cost skill-authoring-and-size.md is pricing.
#
# POLICY = FREEZE-RATCHET: scripts/size-budgets.tsv pins each file's budget at
# its size when adopted; a budget only ever moves down (consolidation), never
# up (see cmd_size_ratchet below for the CI-checkable version of that rule).
# Fails closed in BOTH directions: a shipped SKILL.md/references/*.md with
# no row in the config is a failure (forces a new file to declare a budget,
# mirroring cmd_routing's "every reference is routed"), and a config row whose
# file no longer exists is also a failure (a stale entry cannot silently mask
# a rename/delete). Plain indexed arrays only (no `declare -A`): the repo's own
# local bash is 3.2, which has no associative arrays.
# ---------------------------------------------------------------------------
cmd_size() {
local config="" root=""
while [ "$#" -gt 0 ]; do
case "$1" in
--config) config="${2:-}"; shift 2 ;;
--config=*) config="${1#*=}"; shift ;;
-*) die "size: unknown option: $1" ;;
*) [ -z "$root" ] || die "size: unexpected extra argument: $1"; root="$1"; shift ;;
esac
done
[ -n "$config" ] || die "size: --config <file> is required (fail closed)"
[ -f "$config" ] || die "size: config not found: $config (fail closed)"
[ -n "$root" ] || die "size: <root> directory is required (fail closed)"
[ -d "$root" ] || die "size: root not found: $root (fail closed)"
# The unit declaration is mandatory: without it size-ratchet would read the
# config as pre-byte-adoption and skip, so deleting the line (then re-adding
# it alongside a raise) would bypass the ratchet. Fail closed when absent.
grep -q '^# unit: bytes$' "$config" \
|| die "size: config lacks the required '# unit: bytes' line: $config (fail closed)"
# Parse actionable rows (path<TAB>budget); blank/comment lines are skipped.
# Plain parallel arrays, aligned by index — portable to bash 3.2.
local -a cfg_paths=() cfg_budgets=()
local _line _trimmed _path _budget
while IFS= read -r _line || [ -n "$_line" ]; do
_trimmed="${_line#"${_line%%[![:space:]]*}"}" # strip leading whitespace
case "$_trimmed" in
''|'#'*) continue ;;
esac
_path="${_trimmed%%$'\t'*}"
[ "$_path" != "$_trimmed" ] \
|| die "size: malformed row (no TAB separator) in $config: $_trimmed"
_budget="${_trimmed#*$'\t'}"
case "$_budget" in
''|*[!0-9]*) die "size: malformed budget \"$_budget\" for $_path in $config (fail closed)" ;;
esac
cfg_paths+=("$_path")
cfg_budgets+=("$_budget")
done < "$config"
[ "${#cfg_paths[@]}" -gt 0 ] \
|| die "size: config has no actionable rows (only blanks/comments): $config"
local fail=0 f rel i found budget bytes
# 1) Every shipped SKILL.md / references/*.md on disk must have a budget row.
while IFS= read -r f; do
[ -n "$f" ] || continue
rel="${f#"$root"/}"
found=0
for i in "${!cfg_paths[@]}"; do
if [ "${cfg_paths[$i]}" = "$rel" ]; then found=1; break; fi
done
if [ "$found" -eq 0 ]; then
printf 'SIZE MISSING BUDGET: %s has no row in %s (fail closed)\n' "$rel" "$config" >&2
fail=1
fi
done < <(scan_files "$root" | tr '\0' '\n' | grep -E '/\.claude/skills/(.*/)?(SKILL\.md|references/[^/]*\.md)$' | LC_ALL=C sort)
# 2) Every budget row must resolve to a real file and stay within budget.
for i in "${!cfg_paths[@]}"; do
rel="${cfg_paths[$i]}"
budget="${cfg_budgets[$i]}"
f="$root/$rel"
if [ ! -f "$f" ]; then
printf 'SIZE DANGLING: %s in %s does not exist on disk (fail closed)\n' "$rel" "$config" >&2
fail=1
continue
fi
bytes="$(LC_ALL=C wc -c < "$f" | tr -d '[:space:]')"
if [ "$bytes" -gt "$budget" ]; then
printf 'SIZE FAIL: %s is %s bytes (budget %s) — consolidate; budgets ratchet down, never up\n' \
"$rel" "$bytes" "$budget" >&2
fail=1
fi
# Core cap: consumers cap each skill core at ~4,000 tokens (chars/4), so every
# SKILL.md must be <=16000 bytes. Allowlist = the one core still over it (deep-code-review) when
# the cap was adopted; its row budget above freezes it (may shrink, never grow).
case "$rel" in
*/SKILL.md)
case "$rel" in
.claude/skills/deep-code-review/SKILL.md) ;;
*) if [ "$bytes" -gt 16000 ]; then
printf 'SIZE FAIL: %s is %s bytes (core cap 16000) — move depth into a routed references/ file\n' \
"$rel" "$bytes" >&2
fail=1
fi ;;
esac ;;
esac
done
[ "$fail" -eq 0 ] \
|| die "size: one or more files exceed their frozen budget, or are un-budgeted/dangling"
printf 'size: ok (%d file(s) within budget)\n' "${#cfg_paths[@]}"
}
# ---------------------------------------------------------------------------
# size-ratchet — CI-checkable enforcement of cmd_size's freeze-ratchet POLICY:
# no row in a byte-budget config (e.g. scripts/size-budgets.tsv) may increase
# versus a base ref's copy of that same config, unless a commit message in
# <base>..HEAD, or a CHANGELOG.md line ADDED since <base> (and absent from the
# base's CHANGELOG.md), carries an explicit marker line naming the exact raise:
#
# size-budget-raise: <path> <old-bytes>→<new-bytes> <reason>
#
# <old-bytes> is the larger of the file's size at <base> and its row there (an
# unlanded base's rows are stale because lanes do not commit them; a hand-kept
# row above the size is a budget).
#
# A marker already in the base's CHANGELOG.md never approves a new raise: only
# lines the change itself adds count. Wired into ci.yml ("Size budgets ratchet
# down") against the PR base / push before-SHA; run locally as:
#
# bash scripts/ci-gates.sh size-ratchet --base <ref> \
# --config scripts/size-budgets.tsv .
#
# The working-tree config must declare `# unit: bytes` (fail closed, like
# cmd_size). The one skip: a base config WITHOUT that line predates byte
# adoption (its rows are line counts), so rows are not comparable. cmd_size
# requires the line, so after adoption a base without it cannot exist.
#
# Fails closed: an unresolvable --base (bad ref, shallow clone missing the
# commit, not a git repo) is a hard failure, never a silent skip. A config
# row that is new at HEAD (absent from the base ref's copy) has nothing to
# ratchet against and is not a violation. A row present in both that shrank
# or held steady is never a violation. Only a row present in both whose
# budget is strictly greater at HEAD than at the base ref requires the
# marker. Plain indexed arrays only (no `declare -A`/`local -n`): the repo's
# own local bash is 3.2, which has neither associative arrays nor namerefs —
# so the base-ref and working-tree configs are parsed with two separate
# inline loops into their own arrays, mirroring cmd_size's style.
#
# Silent row deletion is caught too: a row present at base but absent at HEAD
# is only legitimate when the file it names is actually gone from the working
# tree (a real deletion, nothing to budget any more). If the file still
# exists on disk, dropping its row would let it grow unbounded and unbudgeted
# forever without a single ratchet failure — so a row that just vanishes
# while its file survives is a hard fail, no marker can approve it (this
# isn't a raise, there is nothing to document). Covers hand-kept rows outside
# `cmd_size`'s `.claude/skills` glob (e.g. `README.md`), not only auto-scanned
# ones.
# ---------------------------------------------------------------------------
cmd_size_ratchet() {
local base="" config="" root=""
while [ "$#" -gt 0 ]; do
case "$1" in
--base) base="${2:-}"; shift 2 ;;
--base=*) base="${1#*=}"; shift ;;
--config) config="${2:-}"; shift 2 ;;
--config=*) config="${1#*=}"; shift ;;
-*) die "size-ratchet: unknown option: $1" ;;
*) [ -z "$root" ] || die "size-ratchet: unexpected extra argument: $1"; root="$1"; shift ;;
esac
done
[ -n "$base" ] || die "size-ratchet: --base <ref> is required (fail closed)"
[ -n "$config" ] || die "size-ratchet: --config <file> is required (fail closed)"
[ -f "$config" ] || die "size-ratchet: config not found: $config (fail closed)"
[ -n "$root" ] || die "size-ratchet: <root> directory is required (fail closed)"
[ -d "$root" ] || die "size-ratchet: root not found: $root (fail closed)"
git -C "$root" rev-parse --git-dir >/dev/null 2>&1 \
|| die "size-ratchet: $root is not a git repository (fail closed)"
git -C "$root" rev-parse --verify --quiet "${base}^{commit}" >/dev/null \
|| die "size-ratchet: base ref \"$base\" does not resolve to a commit (fail closed; unresolvable base)"
# Resolve config's path relative to the repo top level, so it can be looked
# up inside the base ref's tree via `git show <base>:<relpath>`.
local config_abs root_abs relconfig
config_abs="$(cd "$(dirname "$config")" && pwd)/$(basename "$config")" \
|| die "size-ratchet: cannot resolve config path: $config"
root_abs="$(cd "$root" && pwd)" || die "size-ratchet: cannot resolve root path: $root"
case "$config_abs" in
"$root_abs"/*) relconfig="${config_abs#"$root_abs"/}" ;;
*) die "size-ratchet: config ($config) must live under root ($root)" ;;
esac
# Parse the current (working-tree) config — same row grammar as cmd_size.
local -a new_paths=() new_budgets=()
local _line _trimmed _path _budget
while IFS= read -r _line || [ -n "$_line" ]; do
_trimmed="${_line#"${_line%%[![:space:]]*}"}"
case "$_trimmed" in
''|'#'*) continue ;;
esac
_path="${_trimmed%%$'\t'*}"
[ "$_path" != "$_trimmed" ] \
|| die "size-ratchet: malformed row (no TAB separator) in $config: $_trimmed"
_budget="${_trimmed#*$'\t'}"
case "$_budget" in
''|*[!0-9]*) die "size-ratchet: malformed budget \"$_budget\" for $_path in $config (fail closed)" ;;
esac
new_paths+=("$_path")
new_budgets+=("$_budget")
done < "$config"
[ "${#new_paths[@]}" -gt 0 ] \
|| die "size-ratchet: config has no actionable rows (only blanks/comments): $config"
grep -q '^# unit: bytes$' "$config" \
|| die "size-ratchet: config lacks the required '# unit: bytes' line: $config (fail closed)"
# Parse the base ref's copy of the same config, if it existed there. A
# config absent at base (new file since then) means every current row is
# new — nothing to ratchet against, not a failure.
local -a old_paths=() old_budgets=()
local old_content
if old_content="$(git -C "$root" show "${base}:${relconfig}" 2>/dev/null)"; then
# Base predates byte adoption (its budgets are line counts): rows are not
# comparable across units, so the adoption commit cannot ratchet — say so,
# pass. Only the BASE is consulted; the working tree must carry the line.
if ! grep -q '^# unit: bytes$' <<<"$old_content"; then
printf 'size-ratchet: base %s budgets use a different unit (pre-byte adoption) -- not comparable, skipped\n' "$base"
return 0
fi
while IFS= read -r _line || [ -n "$_line" ]; do
_trimmed="${_line#"${_line%%[![:space:]]*}"}"
case "$_trimmed" in
''|'#'*) continue ;;
esac
_path="${_trimmed%%$'\t'*}"
[ "$_path" != "$_trimmed" ] || continue
_budget="${_trimmed#*$'\t'}"
case "$_budget" in
''|*[!0-9]*) continue ;;
esac
old_paths+=("$_path")
old_budgets+=("$_budget")
done <<<"$old_content"
fi
# Marker sources, computed once: commit messages in range, and only the
# CHANGELOG.md / changelog.d fragment lines added since base (working tree vs base, so a local
# pre-commit run sees the same thing CI sees on a clean checkout). A line
# that already exists in the base's CHANGELOG.md is dropped, so moving or
# re-adding an old marker cannot approve a new raise.
local range_msgs added_log base_log
range_msgs="$(git -C "$root" log --format=%B "${base}..HEAD" 2>/dev/null)" \
|| die "size-ratchet: cannot read commit messages in ${base}..HEAD (fail closed)"
base_log="$(git -C "$root" show "${base}:CHANGELOG.md" 2>/dev/null || true)"
added_log="$(git -C "$root" diff --no-color --no-ext-diff -U0 "$base" -- CHANGELOG.md changelog.d 2>/dev/null \
| grep -E '^\+' | grep -vE '^\+\+\+ ' | sed 's/^+//' || true)"
local fail=0 i j p new_b old_b found marker base_sz
for i in "${!new_paths[@]}"; do
p="${new_paths[$i]}"
new_b="${new_budgets[$i]}"
found=0
old_b=""
for j in "${!old_paths[@]}"; do
if [ "${old_paths[$j]}" = "$p" ]; then found=1; old_b="${old_budgets[$j]}"; break; fi
done
[ "$found" -eq 1 ] || continue
# Rows are rebuilt at land time (regen-unlanded.sh), so a base from an unlanded wave carries stale rows:
# the raise is measured from the larger of the base row and the file's real size at base (a hand-kept
# row above the size is a budget and stays one).
base_sz="$(git -C "$root" cat-file -s "${base}:${p}" 2>/dev/null)" && [ "$base_sz" -gt "$old_b" ] && old_b="$base_sz"
[ "$new_b" -gt "$old_b" ] || continue
# Only the files scripts/skill_index.py generates (.claude/skills/INDEX.md, <skill>/INDEX.md,
# <skill>/INDEX-scripts.md; exact depth) are exempt: they derive from reference files that are
# themselves ratcheted and are regenerated by CI, so their budget row may rise freely. Hand-written
# INDEX.md files elsewhere (e.g. docs/INDEX.md) still need a raise line.
[[ "$p" =~ ^\.claude/skills/(INDEX|[^/]+/INDEX(-scripts)?)\.md$ ]] && continue
marker="size-budget-raise: $p ${old_b}→${new_b}"
# here-strings, not `printf | grep -q`: under pipefail grep -q's early exit SIGPIPEs printf (141) on a big log
if grep -qF -- "$marker" <<<"$range_msgs" \
|| { grep -qF -- "$marker" <<<"$added_log" \
&& ! grep -qF -- "$marker" <<<"$base_log"; }; then
printf 'size-ratchet: %s raised %s->%s with a documented marker (ok)\n' "$p" "$old_b" "$new_b"
else
printf 'RATCHET FAIL: %s raised %s->%s bytes with no "%s <reason>" line in the %s..HEAD commit range or among CHANGELOG.md / changelog.d lines added since base\n' \
"$p" "$old_b" "$new_b" "$marker" "$base" >&2
printf ' fix: paste into changelog.d/<slug>.md: %s <reason>\n' "$marker" >&2
fail=1
fi
done
# A row present at base but missing at HEAD is only legitimate when its
# file is actually gone from the working tree; if the file still exists,
# the row was dropped silently and the gate must fail closed.
for j in "${!old_paths[@]}"; do
p="${old_paths[$j]}"
found=0
for i in "${!new_paths[@]}"; do
if [ "${new_paths[$i]}" = "$p" ]; then found=1; break; fi
done
[ "$found" -eq 0 ] || continue
if [ -f "$root/$p" ]; then
printf 'RATCHET FAIL: %s had a budget row at %s with no row at HEAD, but the file still exists (silent row deletion; fail closed)\n' \
"$p" "$base" >&2
fail=1
fi
done
[ "$fail" -eq 0 ] \
|| die "size-ratchet: one or more budget rows increased vs $base with no documented size-budget-raise marker, or a row was silently dropped for a file that still exists"
printf 'size-ratchet: ok (no undocumented budget increases vs %s)\n' "$base"
}
# ---------------------------------------------------------------------------
# fragments — changelog.d/*.md fragments carry what the release path needs from them.
#
# land-release.sh folds every fragment verbatim under one new release heading, so a fragment's lines become
# CHANGELOG.md lines. Two defects then show only at release time; this fails them at the fragment instead:
# 1. A `size-budget-raise:` marker line (a list bullet may precede it) that is not exactly
# `size-budget-raise: <path> <old>→<new> <reason>` with <path> a row of --config. size-ratchet greps that
# text, so an ASCII `->`, two files on one line or a bare file name never approves the raise and the release
# commit fails RATCHET. A line is a marker attempt only when it starts with the marker word and carries a
# digit; prose that merely names the marker is not one.
# 2. A `## ` heading: publish and release.yml end a release's notes at the next one, silently cutting the rest.
# Checks <dir>/*.md; a missing <dir> or no fragment is ok (changelog.d leaves the tree once every fragment has
# landed). Run by land-release.sh before it stamps, .githooks/pre-commit on the staged blobs, the pre-push fast
# gates and CI: one implementation of the rules.
# ---------------------------------------------------------------------------
cmd_fragments() {
local config="" dir="" f line path rows="" n=0 fail=0
while [ "$#" -gt 0 ]; do
case "$1" in
--config) config="${2:-}"; shift 2 ;;
-*) die "fragments: unknown option: $1" ;;