validate.sh 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. #!/usr/bin/env bash
  2. # claude-mods validation script
  3. # Validates YAML frontmatter, required fields, and naming conventions
  4. set -Eeuo pipefail
  5. # Colors for output
  6. RED='\033[0;31m'
  7. GREEN='\033[0;32m'
  8. YELLOW='\033[1;33m'
  9. NC='\033[0m' # No Color
  10. # Counters
  11. PASS=0
  12. FAIL=0
  13. WARN=0
  14. # Get script directory
  15. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  16. PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
  17. # Parse arguments
  18. YAML_ONLY=false
  19. NAMES_ONLY=false
  20. while [[ $# -gt 0 ]]; do
  21. case $1 in
  22. --yaml-only)
  23. YAML_ONLY=true
  24. shift
  25. ;;
  26. --names-only)
  27. NAMES_ONLY=true
  28. shift
  29. ;;
  30. *)
  31. echo "Unknown option: $1"
  32. exit 1
  33. ;;
  34. esac
  35. done
  36. # Helper functions
  37. log_pass() {
  38. echo -e "${GREEN}PASS${NC}: $1"
  39. PASS=$((PASS + 1))
  40. }
  41. log_fail() {
  42. echo -e "${RED}FAIL${NC}: $1"
  43. FAIL=$((FAIL + 1))
  44. }
  45. log_warn() {
  46. echo -e "${YELLOW}WARN${NC}: $1"
  47. WARN=$((WARN + 1))
  48. }
  49. # Check if file has valid YAML frontmatter
  50. check_yaml_frontmatter() {
  51. local file="$1"
  52. local content
  53. content=$(cat "$file")
  54. # Check for opening ---
  55. if [[ "$content" != ---* ]]; then
  56. log_fail "$file - Missing YAML frontmatter (no opening ---)"
  57. return 1
  58. fi
  59. # Check for closing ---
  60. local frontmatter
  61. frontmatter=$(echo "$content" | sed -n '1,/^---$/p' | tail -n +2)
  62. if [[ -z "$frontmatter" ]]; then
  63. log_fail "$file - Invalid YAML frontmatter (no closing ---)"
  64. return 1
  65. fi
  66. return 0
  67. }
  68. # Extract field from YAML frontmatter
  69. get_yaml_field() {
  70. local file="$1"
  71. local field="$2"
  72. # Extract frontmatter and get field value
  73. sed -n '2,/^---$/p' "$file" | grep "^${field}:" | sed "s/^${field}:[[:space:]]*//" | sed 's/^["'"'"']//' | sed 's/["'"'"']$//'
  74. }
  75. # Check required fields in agents/commands
  76. check_required_fields() {
  77. local file="$1"
  78. local type="$2"
  79. local name
  80. local description
  81. name=$(get_yaml_field "$file" "name")
  82. description=$(get_yaml_field "$file" "description")
  83. # Agents require both name and description
  84. if [[ "$type" == "agent" ]]; then
  85. if [[ -z "$name" ]]; then
  86. log_fail "$file - Missing required field: name"
  87. return 1
  88. fi
  89. if [[ -z "$description" ]]; then
  90. log_fail "$file - Missing required field: description"
  91. return 1
  92. fi
  93. fi
  94. # Commands only require description
  95. if [[ "$type" == "command" ]]; then
  96. if [[ -z "$description" ]]; then
  97. log_fail "$file - Missing required field: description"
  98. return 1
  99. fi
  100. fi
  101. return 0
  102. }
  103. # Check naming convention (kebab-case)
  104. check_naming() {
  105. local file="$1"
  106. local basename
  107. basename=$(basename "$file" .md)
  108. # Check if filename is kebab-case
  109. if [[ ! "$basename" =~ ^[a-z][a-z0-9]*(-[a-z0-9]+)*$ ]]; then
  110. log_warn "$file - Filename not kebab-case: $basename"
  111. return 1
  112. fi
  113. # Check if name field matches filename (for agents)
  114. local name
  115. name=$(get_yaml_field "$file" "name")
  116. if [[ -n "$name" && "$name" != "$basename" ]]; then
  117. log_warn "$file - Name field '$name' doesn't match filename '$basename'"
  118. return 1
  119. fi
  120. return 0
  121. }
  122. # Validate agents
  123. validate_agents() {
  124. echo ""
  125. echo "=== Validating Agents ==="
  126. local agent_dir="$PROJECT_DIR/agents"
  127. if [[ ! -d "$agent_dir" ]]; then
  128. log_warn "agents/ directory not found"
  129. return
  130. fi
  131. # Use find for better Windows compatibility
  132. while IFS= read -r -d '' file; do
  133. if ! $NAMES_ONLY; then
  134. if check_yaml_frontmatter "$file"; then
  135. if check_required_fields "$file" "agent"; then
  136. log_pass "$file - Valid agent"
  137. fi
  138. fi
  139. fi
  140. if ! $YAML_ONLY; then
  141. check_naming "$file" || true
  142. fi
  143. done < <(find "$agent_dir" -maxdepth 1 -name "*.md" -type f -print0)
  144. }
  145. # Validate commands
  146. validate_commands() {
  147. echo ""
  148. echo "=== Validating Commands ==="
  149. local cmd_dir="$PROJECT_DIR/commands"
  150. if [[ ! -d "$cmd_dir" ]]; then
  151. log_warn "commands/ directory not found"
  152. return
  153. fi
  154. # Check .md files directly in commands/
  155. while IFS= read -r -d '' file; do
  156. if ! $NAMES_ONLY; then
  157. if check_yaml_frontmatter "$file"; then
  158. if check_required_fields "$file" "command"; then
  159. log_pass "$file - Valid command"
  160. fi
  161. fi
  162. fi
  163. if ! $YAML_ONLY; then
  164. check_naming "$file" || true
  165. fi
  166. done < <(find "$cmd_dir" -maxdepth 1 -name "*.md" -type f -print0)
  167. # Check subdirectories (like g-slave/, session-manager/)
  168. while IFS= read -r -d '' subdir; do
  169. # Look for main command file (exclude README.md, LICENSE.md)
  170. while IFS= read -r -d '' file; do
  171. local basename
  172. basename=$(basename "$file")
  173. # Skip README and LICENSE files
  174. [[ "$basename" == "README.md" || "$basename" == "LICENSE.md" ]] && continue
  175. if ! $NAMES_ONLY; then
  176. if check_yaml_frontmatter "$file"; then
  177. # Commands in subdirs may have different required fields
  178. local desc
  179. desc=$(get_yaml_field "$file" "description")
  180. if [[ -n "$desc" ]]; then
  181. log_pass "$file - Valid subcommand"
  182. else
  183. log_warn "$file - Missing description"
  184. fi
  185. fi
  186. fi
  187. done < <(find "$subdir" -maxdepth 1 -name "*.md" -type f -print0)
  188. done < <(find "$cmd_dir" -mindepth 1 -maxdepth 1 -type d -print0)
  189. }
  190. # Validate skills
  191. validate_skills() {
  192. echo ""
  193. echo "=== Validating Skills ==="
  194. local skills_dir="$PROJECT_DIR/skills"
  195. if [[ ! -d "$skills_dir" ]]; then
  196. log_warn "skills/ directory not found"
  197. return
  198. fi
  199. while IFS= read -r -d '' skill_subdir; do
  200. # Skip shared helper dirs (e.g. _lib) - not skills, no SKILL.md expected.
  201. [[ "$(basename "$skill_subdir")" == _* ]] && continue
  202. local skill_file="$skill_subdir/SKILL.md"
  203. if [[ ! -f "$skill_file" ]]; then
  204. log_fail "$skill_subdir - Missing SKILL.md"
  205. continue
  206. fi
  207. if ! $NAMES_ONLY; then
  208. if check_yaml_frontmatter "$skill_file"; then
  209. local name
  210. local desc
  211. name=$(get_yaml_field "$skill_file" "name")
  212. desc=$(get_yaml_field "$skill_file" "description")
  213. if [[ -n "$name" && -n "$desc" ]]; then
  214. log_pass "$skill_file - Valid skill"
  215. else
  216. [[ -z "$name" ]] && log_fail "$skill_file - Missing name"
  217. [[ -z "$desc" ]] && log_fail "$skill_file - Missing description"
  218. fi
  219. fi
  220. fi
  221. done < <(find "$skills_dir" -mindepth 1 -maxdepth 1 -type d -print0)
  222. }
  223. # Fallback frontmatter measurer: counts the FULL value of a top-level field,
  224. # including block scalars (|, >, |-, >-) and indented continuation lines.
  225. # get_yaml_field reads only the first physical line, which measured a folded
  226. # description as 2 chars ('>-') and silently dropped a real over-cap skill
  227. # from the warn list (adversarial-review finding, 2026-07).
  228. frontmatter_field_len() { # $1=file $2=field -> prints char count
  229. awk -v key="$2" '
  230. BEGIN { fm=0; infield=0; len=0 }
  231. /^---[ \t]*$/ { fmc++; if (fmc==2) exit; fm=1; next }
  232. !fm { next }
  233. /^[A-Za-z0-9_-]+:/ {
  234. infield=0
  235. if (index($0, key ":") == 1) {
  236. infield=1
  237. val=$0; sub(/^[A-Za-z0-9_-]+:[ \t]*/, "", val)
  238. if (val != "" && val !~ /^[|>][+-]?[ \t]*$/) len+=length(val)
  239. }
  240. next
  241. }
  242. infield && /^[ \t]+[^ \t]/ {
  243. line=$0; sub(/^[ \t]+/, "", line)
  244. if (len>0) len+=1
  245. len+=length(line); next
  246. }
  247. infield && /^[ \t]*$/ { next }
  248. { infield=0 }
  249. END { print len }
  250. ' "$1"
  251. }
  252. # Validate the session-wide cost of skill descriptions
  253. validate_description_budget() {
  254. echo ""
  255. echo "=== Validating Skill Description Budget ==="
  256. # Flipped to fail 2026-07 after the great trim (catalog 55.4k -> 34.2k chars, 0 offenders).
  257. # The cap combines description + when_to_use because Claude Code loads both, so moving text between
  258. # fields does not reduce the per-session cost.
  259. DESC_BUDGET_MODE="fail" # warn|fail
  260. local skills_dir="$PROJECT_DIR/skills"
  261. local hard_cap=700
  262. local soft_budget=35000
  263. local catalog_total=0
  264. local name
  265. local combined_len
  266. local budget_rows
  267. if [[ ! -d "$skills_dir" ]]; then
  268. log_warn "skills/ directory not found"
  269. return
  270. fi
  271. # Probe by importing yaml, not `command -v`: on Windows the python3 name
  272. # resolves to the Microsoft Store app-execution-alias stub, which exists
  273. # on PATH but does not run Python (adversarial-review finding, 2026-07).
  274. local python_bin=""
  275. for candidate in python3 python; do
  276. if "$candidate" -c 'import yaml' >/dev/null 2>&1; then
  277. python_bin="$candidate"
  278. break
  279. fi
  280. done
  281. local python_status=1
  282. if [[ -n "$python_bin" ]]; then
  283. set +e
  284. budget_rows=$("$python_bin" - "$skills_dir" 2>/dev/null <<'PY'
  285. import pathlib
  286. import sys
  287. import yaml
  288. skills_dir = pathlib.Path(sys.argv[1])
  289. for skill_dir in sorted(path for path in skills_dir.iterdir() if path.is_dir() and not path.name.startswith("_")):
  290. skill_file = skill_dir / "SKILL.md"
  291. if not skill_file.is_file():
  292. continue
  293. lines = skill_file.read_text(encoding="utf-8-sig").splitlines()
  294. markers = [index for index, line in enumerate(lines) if line.strip() == "---"]
  295. if len(markers) < 2:
  296. continue
  297. frontmatter = yaml.safe_load("\n".join(lines[markers[0] + 1:markers[1]])) or {}
  298. description = str(frontmatter.get("description") or "")
  299. when_to_use = str(frontmatter.get("when_to_use") or "")
  300. print(f"{skill_dir.name}\t{len(description) + len(when_to_use)}")
  301. PY
  302. )
  303. python_status=$?
  304. set -e
  305. fi
  306. if ((python_status != 0)); then
  307. local skill_subdir
  308. local skill_file
  309. local description
  310. local when_to_use
  311. budget_rows=""
  312. while IFS= read -r -d '' skill_subdir; do
  313. [[ "$(basename "$skill_subdir")" == _* ]] && continue
  314. skill_file="$skill_subdir/SKILL.md"
  315. [[ -f "$skill_file" ]] || continue
  316. description=$(frontmatter_field_len "$skill_file" "description" || echo 0)
  317. when_to_use=$(frontmatter_field_len "$skill_file" "when_to_use" || echo 0)
  318. budget_rows+="$(printf '%s\t%s' "$(basename "$skill_subdir")" "$((description + when_to_use))")"$'\n'
  319. done < <(find "$skills_dir" -mindepth 1 -maxdepth 1 -type d -print0)
  320. fi
  321. # Windows python prints \r\n; a stray \r inside $((...)) is a syntax error.
  322. budget_rows=${budget_rows//$'\r'/}
  323. # A measurement that yields zero rows is a broken scan (interpreter stub,
  324. # malformed frontmatter across the board, wrong dir) — never a PASS.
  325. local row_count
  326. row_count=$(grep -c . <<< "$budget_rows" || true)
  327. if ((row_count == 0)); then
  328. log_fail "description budget self-check failed - measured zero skills (broken parser or path?)"
  329. return
  330. fi
  331. while IFS=$'\t' read -r name combined_len; do
  332. [[ -z "$name" ]] && continue
  333. catalog_total=$((catalog_total + combined_len))
  334. if ((combined_len > hard_cap)); then
  335. if [[ "$DESC_BUDGET_MODE" == "fail" ]]; then
  336. log_fail "$name - description + when_to_use is $combined_len chars (hard cap: $hard_cap)"
  337. else
  338. log_warn "$name - description + when_to_use is $combined_len chars (hard cap: $hard_cap)"
  339. fi
  340. fi
  341. done <<< "$budget_rows"
  342. if ((catalog_total > soft_budget)); then
  343. log_warn "Skill catalog descriptions total $catalog_total chars (soft budget: $soft_budget)"
  344. else
  345. log_pass "Skill catalog descriptions total $catalog_total chars (soft budget: $soft_budget)"
  346. fi
  347. }
  348. # Validate rules (optional YAML frontmatter with optional paths field)
  349. validate_rules() {
  350. echo ""
  351. echo "=== Validating Rules ==="
  352. local rules_dir="$PROJECT_DIR/templates/rules"
  353. if [[ ! -d "$rules_dir" ]]; then
  354. echo " (no templates/rules/ directory - skipping)"
  355. return
  356. fi
  357. while IFS= read -r -d '' file; do
  358. local basename
  359. basename=$(basename "$file")
  360. # Rules should be .md files
  361. if [[ "$file" != *.md ]]; then
  362. log_warn "$file - Rule file should be .md"
  363. continue
  364. fi
  365. # Check if file has content
  366. if [[ ! -s "$file" ]]; then
  367. log_fail "$file - Empty rule file"
  368. continue
  369. fi
  370. # Check for valid YAML frontmatter if present
  371. local content
  372. content=$(cat "$file")
  373. if [[ "$content" == ---* ]]; then
  374. # Has frontmatter - validate it
  375. local closing
  376. closing=$(echo "$content" | sed -n '2,${/^---$/=;}'| head -1)
  377. if [[ -z "$closing" ]]; then
  378. log_fail "$file - Invalid YAML frontmatter (no closing ---)"
  379. continue
  380. fi
  381. # If paths field exists, validate it's not empty
  382. local paths
  383. paths=$(get_yaml_field "$file" "paths")
  384. if grep -q "^paths:" "$file" && [[ -z "$paths" ]]; then
  385. log_warn "$file - paths field is empty"
  386. fi
  387. fi
  388. # Check naming convention (kebab-case)
  389. local name
  390. name=$(basename "$file" .md)
  391. if [[ ! "$name" =~ ^[a-z][a-z0-9]*(-[a-z0-9]+)*$ ]]; then
  392. log_warn "$file - Filename not kebab-case: $name"
  393. fi
  394. log_pass "$file - Valid rule"
  395. done < <(find "$rules_dir" -name "*.md" -type f -print0)
  396. }
  397. # Validate settings files (permissions and hooks)
  398. validate_settings() {
  399. echo ""
  400. echo "=== Validating Settings ==="
  401. local settings_file="$PROJECT_DIR/templates/settings.local.json"
  402. if [[ ! -f "$settings_file" ]]; then
  403. echo " (no templates/settings.local.json - skipping)"
  404. return
  405. fi
  406. # Check if valid JSON
  407. if ! jq empty "$settings_file" 2>/dev/null; then
  408. log_fail "$settings_file - Invalid JSON"
  409. return
  410. fi
  411. # Check for permissions structure
  412. if ! jq -e '.permissions' "$settings_file" >/dev/null 2>&1; then
  413. log_fail "$settings_file - Missing 'permissions' key"
  414. else
  415. # Check permissions has allow array
  416. if ! jq -e '.permissions.allow | type == "array"' "$settings_file" >/dev/null 2>&1; then
  417. log_fail "$settings_file - permissions.allow should be an array"
  418. else
  419. log_pass "$settings_file - Valid permissions structure"
  420. fi
  421. fi
  422. # Check for hooks structure (optional but if present should be object)
  423. if jq -e '.hooks' "$settings_file" >/dev/null 2>&1; then
  424. if ! jq -e '.hooks | type == "object"' "$settings_file" >/dev/null 2>&1; then
  425. log_fail "$settings_file - hooks should be an object"
  426. else
  427. # Validate hook event names if any hooks defined
  428. local hook_events
  429. hook_events=$(jq -r '.hooks | keys[]' "$settings_file" 2>/dev/null || true)
  430. local valid_events="PreToolUse PostToolUse PermissionRequest Notification UserPromptSubmit Stop SubagentStop PreCompact SessionStart SessionEnd"
  431. for event in $hook_events; do
  432. if [[ ! " $valid_events " =~ " $event " ]]; then
  433. log_warn "$settings_file - Unknown hook event: $event"
  434. fi
  435. done
  436. if [[ -n "$hook_events" ]]; then
  437. log_pass "$settings_file - Valid hooks structure"
  438. else
  439. log_pass "$settings_file - Hooks defined (empty)"
  440. fi
  441. fi
  442. fi
  443. }
  444. # Validate plugin + marketplace manifests (.claude-plugin/)
  445. #
  446. # The authoritative validator is `claude plugin validate` (it tracks the live
  447. # schema - it caught a bad plugin `source` shape and an `author` type error
  448. # that a hand-rolled jq check sailed past). We prefer it when the CLI is
  449. # present and fall back to lightweight structural jq checks otherwise. The
  450. # stray-root-file guard runs regardless, because the official tool validates
  451. # whatever path it is given and cannot see a misplaced copy.
  452. validate_plugin() {
  453. echo ""
  454. echo "=== Validating Plugin Manifests ==="
  455. local plugin_dir="$PROJECT_DIR/.claude-plugin"
  456. local plugin_file="$plugin_dir/plugin.json"
  457. local mkt_file="$plugin_dir/marketplace.json"
  458. # --- location guard (official tool can't see this) ---
  459. # The spec mandates .claude-plugin/marketplace.json. A copy at the repo
  460. # root is the regression that caused /plugin marketplace add to fail (#4).
  461. if [[ -f "$PROJECT_DIR/marketplace.json" ]]; then
  462. log_fail "marketplace.json found at repo root - must live at .claude-plugin/marketplace.json"
  463. fi
  464. [[ -f "$plugin_file" ]] || log_fail ".claude-plugin/plugin.json - Missing"
  465. [[ -f "$mkt_file" ]] || log_fail ".claude-plugin/marketplace.json - Missing (required for /plugin marketplace add)"
  466. # --- authoritative path: claude plugin validate ---
  467. if command -v claude >/dev/null 2>&1; then
  468. # Marketplace manifest (repo root resolves to the marketplace).
  469. if claude plugin validate "$PROJECT_DIR" >/dev/null 2>&1; then
  470. log_pass "marketplace.json - claude plugin validate passed"
  471. else
  472. log_fail "marketplace.json - claude plugin validate failed (run: claude plugin validate .)"
  473. fi
  474. # Plugin manifest: validate in isolation so it is not shadowed by the
  475. # marketplace manifest in the same .claude-plugin/ directory.
  476. if [[ -f "$plugin_file" ]]; then
  477. local tmp
  478. tmp=$(mktemp -d)
  479. mkdir -p "$tmp/.claude-plugin"
  480. cp "$plugin_file" "$tmp/.claude-plugin/plugin.json"
  481. if claude plugin validate "$tmp" >/dev/null 2>&1; then
  482. log_pass "plugin.json - claude plugin validate passed"
  483. else
  484. log_fail "plugin.json - claude plugin validate failed (unrecognized keys or wrong field types)"
  485. fi
  486. rm -rf "$tmp"
  487. fi
  488. return
  489. fi
  490. # --- fallback path: lightweight structural checks (jq) ---
  491. log_warn "claude CLI not found - using lightweight manifest checks only (install Claude Code for authoritative validation)"
  492. if [[ -f "$plugin_file" ]]; then
  493. if ! jq empty "$plugin_file" 2>/dev/null; then
  494. log_fail "$plugin_file - Invalid JSON"
  495. elif jq -e '.name | strings' "$plugin_file" >/dev/null 2>&1; then
  496. log_pass "$plugin_file - structurally OK (name present)"
  497. else
  498. log_fail "$plugin_file - Missing required field: name"
  499. fi
  500. fi
  501. if [[ -f "$mkt_file" ]]; then
  502. if ! jq empty "$mkt_file" 2>/dev/null; then
  503. log_fail "$mkt_file - Invalid JSON"
  504. else
  505. jq -e '.name | strings' "$mkt_file" >/dev/null 2>&1 \
  506. || log_fail "$mkt_file - Missing required field: name (string)"
  507. jq -e '.owner.name | strings' "$mkt_file" >/dev/null 2>&1 \
  508. || log_fail "$mkt_file - owner.name missing (owner must be an object with a name)"
  509. jq -e '.plugins | arrays' "$mkt_file" >/dev/null 2>&1 \
  510. || log_fail "$mkt_file - Missing required field: plugins (array)"
  511. if jq -e '.name and (.owner.name | strings) and (.plugins | arrays)' "$mkt_file" >/dev/null 2>&1; then
  512. log_pass "$mkt_file - structurally OK (run claude plugin validate for full schema)"
  513. fi
  514. fi
  515. fi
  516. }
  517. # Main
  518. main() {
  519. echo "claude-mods Validation"
  520. echo "======================"
  521. echo "Project: $PROJECT_DIR"
  522. validate_agents
  523. validate_commands
  524. validate_skills
  525. validate_description_budget
  526. validate_rules
  527. validate_settings
  528. validate_plugin
  529. echo ""
  530. echo "======================"
  531. echo -e "Results: ${GREEN}$PASS passed${NC}, ${RED}$FAIL failed${NC}, ${YELLOW}$WARN warnings${NC}"
  532. if [[ $FAIL -gt 0 ]]; then
  533. exit 1
  534. fi
  535. exit 0
  536. }
  537. main "$@"