diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index b478a347e2f..8cc0c049e9f 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -1 +1 @@ -{"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"a4abb961bbb5032e40d14e9aeef7e8c652d3517458b7ab72086b768c2e8b5a8b","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"} +{"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"ff679d1b547a315da6316e3d0d78008ff3e6de5cd9b65625b8b171b7002bad6b","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"} diff --git a/skills/skill-stocktake/SKILL.md b/skills/skill-stocktake/SKILL.md index 6f207320df0..aa4d16bfd22 100644 --- a/skills/skill-stocktake/SKILL.md +++ b/skills/skill-stocktake/SKILL.md @@ -20,6 +20,8 @@ The command targets the following paths **relative to the directory where it is **At the start of Phase 1, the command explicitly lists which paths were found and scanned.** +Directories named `.trash` are excluded from both scan modes: archived skills are not part of the live inventory. If an older `results.json` contains `.trash` entries, start a new Full Stocktake using the cache initialization below before resuming Quick Scan. An ordinary save merges entries and does not remove archived records. + ### Targeting a specific project To include project-level skills, run from that project's root directory: @@ -38,6 +40,8 @@ If the project has no `.claude/skills/` directory, only global skills and comman | Quick Scan | `results.json` exists (default) | 5–10 min | | Full Stocktake | `results.json` absent, or `/skill-stocktake full` | 20–30 min | +The shell scripts require Bash, Node.js, and `jq` on `PATH`. + **Results cache:** `~/.claude/skills/skill-stocktake/results.json` ## Quick Scan Flow @@ -59,7 +63,47 @@ Re-evaluate only skills that have changed since the last run (5–10 min). ### Phase 1 — Inventory -Run: `bash ~/.claude/skills/skill-stocktake/scripts/scan.sh` +Run this entire block in **one Bash invocation**. It prints the inventory for the agent and initializes a new full run only when there is no unfinished run to resume: + +```bash +( + set -euo pipefail + SCAN_JSON=$(bash ~/.claude/skills/skill-stocktake/scripts/scan.sh) + printf '%s\n' "$SCAN_JSON" + RESULTS_JSON=~/.claude/skills/skill-stocktake/results.json + + CACHE_STATUS="" + if [[ -f "$RESULTS_JSON" ]]; then + CACHE_STATUS=$(jq -r '.batch_progress.status // ""' "$RESULTS_JSON") + fi + if [[ "$CACHE_STATUS" == "in_progress" ]]; then + RESUMED_RESULTS=$(jq --slurpfile saved "$RESULTS_JSON" ' + . as $inventory | $saved[0] + | .skills = (.skills | to_entries + | map(.key = (.value.path // .key)) + | map(select(. as $entry + | $entry.value.mtime != null + and any($inventory.skills[]; + .path == $entry.key and .mtime == $entry.value.mtime))) + | from_entries) + | .mode = "full" + | .batch_progress = { + total: ($inventory.skills | length), + evaluated: (.skills | length), status: "in_progress" + } + ' <<< "$SCAN_JSON") + bash ~/.claude/skills/skill-stocktake/scripts/save-results.sh \ + "$RESULTS_JSON" --replace <<< "$RESUMED_RESULTS" + else + INITIAL_RESULTS=$(printf '%s\n' "$SCAN_JSON" | jq '{ + mode: "full", skills: {}, + batch_progress: {total: (.skills | length), evaluated: 0, status: "in_progress"} + }') + bash ~/.claude/skills/skill-stocktake/scripts/save-results.sh \ + "$RESULTS_JSON" --replace <<< "$INITIAL_RESULTS" + fi +) +``` The script enumerates skill files, extracts frontmatter, and collects UTC mtimes. Project dir is auto-detected from `$PWD/.claude/skills`; pass it explicitly only if needed. @@ -74,35 +118,42 @@ Scanning: | Skill | 7d use | 30d use | Description | |-------|--------|---------|-------------| -### Phase 2 — Quality Evaluation - -Launch an Agent tool subagent (**general-purpose agent**) with the full inventory and checklist: +Usage counts come from the optional `~/.claude/observations.jsonl` file (overridable with `SKILL_STOCKTAKE_OBSERVATIONS`), which Claude Code does not create by default. When the file is absent, `use_7d` and `use_30d` are JSON `null`; display them as **unmeasured** in inventory and summary tables. A numeric `0` means the file exists but contains no matching Read observations in that window. Missing usage data is never evidence for retiring a skill. -```text -Agent( - subagent_type="general-purpose", - prompt=" -Evaluate the following skill inventory against the checklist. +`--replace` writes a complete cache snapshot. A new run starts with an empty evaluation; a resumed run instead keeps a saved evaluation only when its path is still live and its saved, non-null mtime matches the fresh inventory. Changed skills and entries without an mtime require re-evaluation. It removes archived/deleted entries and refreshes the progress counts even when no new batch remains. Existing name-keyed entries are normalized using their saved `path`. Never use the empty initialization payload for a resume. Later chunks, completion updates, and Quick Scans must omit `--replace` so they merge into the current run instead of losing earlier results. -[INVENTORY] +### Phase 2 — Quality Evaluation -[CHECKLIST] +Launch an Agent tool subagent (**general-purpose agent**) with the actual JSON emitted by Phase 1 and the checklist below. Copy the inventory values into the prompt itself; shell variables do not carry over into Agent calls. Include the full inventory for overlap checks and explicitly identify the paths in the current batch to evaluate. Do not send literal inventory or checklist placeholders. -Return JSON for each skill: -{ \"verdict\": \"Keep\"|\"Improve\"|\"Update\"|\"Retire\"|\"Merge into [X]\", \"reason\": \"...\" } -" -) -``` +The subagent reads each assigned skill, applies the checklist, and returns a JSON object with a `skills` map keyed by the inventory path. Each entry includes its `path`, scanned `mtime`, `verdict`, and self-contained `reason`. Use the same path keys across all batches so merging results cannot overwrite a different skill with the same name. -The subagent reads each skill, applies the checklist, and returns per-skill JSON: +**Chunk guidance:** Process ~20 skills per subagent invocation to keep context manageable. After each chunk, wrap its returned `skills` map with `mode: "full"` and `batch_progress: {total, evaluated, status: "in_progress"}`. Set `total` to the inventory size and `evaluated` to the cumulative number of distinct evaluated paths, including saved batches. Assign this JSON to `CHUNK_RESULTS` and run the following command in the **same Bash invocation as that assignment**: -`{ "verdict": "Keep"|"Improve"|"Update"|"Retire"|"Merge into [X]", "reason": "..." }` +```bash +bash ~/.claude/skills/skill-stocktake/scripts/save-results.sh \ + ~/.claude/skills/skill-stocktake/results.json <<< "$CHUNK_RESULTS" +``` -**Chunk guidance:** Process ~20 skills per subagent invocation to keep context manageable. Save intermediate results to `results.json` (`status: "in_progress"`) after each chunk. +After all skills are evaluated, persist completion before proceeding to Phase 3: -After all skills are evaluated: set `status: "completed"`, proceed to Phase 3. +```bash +( + set -euo pipefail + RESULTS_JSON=~/.claude/skills/skill-stocktake/results.json + COMPLETED_RESULTS=$(jq -e ' + if (.skills | length) == .batch_progress.total then + {skills: {}, mode: "full", batch_progress: (.batch_progress + { + evaluated: (.skills | length), status: "completed" + })} + else error("Inventory still has unevaluated skills") end + ' "$RESULTS_JSON") + bash ~/.claude/skills/skill-stocktake/scripts/save-results.sh \ + "$RESULTS_JSON" <<< "$COMPLETED_RESULTS" +) +``` -**Resume detection:** If `status: "in_progress"` is found on startup, resume from the first unevaluated skill. +**Resume detection:** If `status: "in_progress"` is found on startup, run Phase 1 to reconcile the saved results with the fresh inventory, then evaluate only paths absent from the reconciled `skills` map. If none remain, persist completion immediately. Completed evaluations are preserved only for surviving paths with matching, non-null mtimes; new or changed skills and entries without an mtime require evaluation. Each skill is evaluated against this checklist: @@ -110,7 +161,7 @@ Each skill is evaluated against this checklist: - [ ] Content overlap with other skills checked - [ ] Overlap with MEMORY.md / CLAUDE.md checked - [ ] Freshness of technical references verified (use WebSearch if tool names / CLI flags / APIs are present) -- [ ] Usage frequency considered +- [ ] Usage frequency considered when measured; missing observations marked unmeasured, not treated as zero ``` Verdict criteria: @@ -178,7 +229,7 @@ Obtain via Bash: `date -u +%Y-%m-%dT%H:%M:%SZ`. Never use a date-only approximat "status": "completed" }, "skills": { - "skill-name": { + "~/.claude/skills/skill-name/SKILL.md": { "path": "~/.claude/skills/skill-name/SKILL.md", "verdict": "Keep", "reason": "Concrete, actionable, unique value for X workflow", diff --git a/skills/skill-stocktake/scripts/quick-diff.sh b/skills/skill-stocktake/scripts/quick-diff.sh index b22d42e11e7..da36fa0f135 100755 --- a/skills/skill-stocktake/scripts/quick-diff.sh +++ b/skills/skill-stocktake/scripts/quick-diff.sh @@ -76,7 +76,8 @@ process_dir() { # exit non-zero, which would otherwise silently under-count skills. # NUL-delimited (-print0 / sort_nul_file / read -d '') so a path containing a # literal newline can't desync record boundaries — paths here are untrusted. - if ! find -L "$dir" -name "SKILL.md" -type f -print0 >"$find_out" 2>"$find_err"; then + # Archived skills are not live inventory; prune the entire trash subtree. + if ! find -L "$dir" -type d -name ".trash" -prune -o -name "SKILL.md" -type f -print0 >"$find_out" 2>"$find_err"; then echo "Warning: find encountered errors while scanning $dir (broken symlinks or permission issues may cause skills to be missed):" >&2 cat "$find_err" >&2 fi diff --git a/skills/skill-stocktake/scripts/save-results.sh b/skills/skill-stocktake/scripts/save-results.sh index 32952007217..d5ade12bb2e 100755 --- a/skills/skill-stocktake/scripts/save-results.sh +++ b/skills/skill-stocktake/scripts/save-results.sh @@ -1,21 +1,28 @@ #!/usr/bin/env bash # save-results.sh — merge evaluated skills into results.json with correct UTC timestamp -# Usage: save-results.sh RESULTS_JSON <<< "$EVAL_JSON" +# Usage: save-results.sh RESULTS_JSON [--replace] <<< "$EVAL_JSON" # # stdin format: # { "skills": {...}, "mode"?: "full"|"quick", "batch_progress"?: {...} } # # Always sets evaluated_at to current UTC time via `date -u`. -# Merges stdin .skills into existing results.json (new entries override old). +# By default, merges stdin .skills into results.json (new entries override old). # Optionally updates .mode and .batch_progress if present in stdin. +# --replace starts a new full evaluation; subsequent chunks must use merge mode. set -euo pipefail RESULTS_JSON="${1:-}" +SAVE_MODE="${2:-}" if [[ -z "$RESULTS_JSON" ]]; then echo "Error: RESULTS_JSON argument required" >&2 - echo "Usage: save-results.sh RESULTS_JSON <<< \"\$EVAL_JSON\"" >&2 + echo "Usage: save-results.sh RESULTS_JSON [--replace] <<< \"\$EVAL_JSON\"" >&2 + exit 1 +fi + +if [[ $# -gt 2 || ( -n "$SAVE_MODE" && "$SAVE_MODE" != "--replace" ) ]]; then + echo "Error: expected RESULTS_JSON [--replace]" >&2 exit 1 fi @@ -28,29 +35,40 @@ if ! echo "$input_json" | jq empty 2>/dev/null; then exit 1 fi -if [[ ! -f "$RESULTS_JSON" ]]; then +# A replacement must be one complete object, not empty input or a JSON stream. +# Validate before creating a temp file or changing the existing cache. +if [[ "$SAVE_MODE" == "--replace" ]] && ! echo "$input_json" | jq -e -s \ + 'length == 1 and (.[0] | type == "object" and (.skills | type == "object"))' >/dev/null 2>&1; then + echo "Error: --replace requires one JSON object with a skills object" >&2 + exit 1 +fi + +if [[ ! -f "$RESULTS_JSON" && "$SAVE_MODE" != "--replace" ]]; then # Bootstrap: create new results.json from stdin JSON + current UTC timestamp echo "$input_json" | jq --arg ea "$EVALUATED_AT" \ '. + { evaluated_at: $ea }' > "$RESULTS_JSON" exit 0 fi -# Merge: new .skills override existing ones; old skills not in input_json are kept. -# Optionally update .mode and .batch_progress if provided. -# # Use mktemp for a collision-safe temp file (concurrent runs on the same RESULTS_JSON # would race on a predictable ".tmp" suffix; random suffix prevents silent overwrites). tmp=$(mktemp "${RESULTS_JSON}.XXXXXX") trap 'rm -f "$tmp"' EXIT -jq -s \ - --arg ea "$EVALUATED_AT" \ - '.[0] as $existing | .[1] as $new | - $existing | - .evaluated_at = $ea | - .skills = ($existing.skills + ($new.skills // {})) | - if ($new | has("mode")) then .mode = $new.mode else . end | - if ($new | has("batch_progress")) then .batch_progress = $new.batch_progress else . end' \ - "$RESULTS_JSON" <(echo "$input_json") > "$tmp" +if [[ "$SAVE_MODE" == "--replace" ]]; then + echo "$input_json" | jq --arg ea "$EVALUATED_AT" \ + '. + { evaluated_at: $ea }' > "$tmp" +else + # Keep previously evaluated skills during quick scans and full-run chunks. + jq -s \ + --arg ea "$EVALUATED_AT" \ + '.[0] as $existing | .[1] as $new | + $existing | + .evaluated_at = $ea | + .skills = ($existing.skills + ($new.skills // {})) | + if ($new | has("mode")) then .mode = $new.mode else . end | + if ($new | has("batch_progress")) then .batch_progress = $new.batch_progress else . end' \ + "$RESULTS_JSON" <(echo "$input_json") > "$tmp" +fi mv "$tmp" "$RESULTS_JSON" diff --git a/skills/skill-stocktake/scripts/scan.sh b/skills/skill-stocktake/scripts/scan.sh index 02c9c3dab31..8b82086f253 100755 --- a/skills/skill-stocktake/scripts/scan.sh +++ b/skills/skill-stocktake/scripts/scan.sh @@ -78,7 +78,7 @@ date_ago() { count_obs() { local file="$1" cutoff="$2" if [[ ! -f "$OBSERVATIONS" ]]; then - echo 0 + echo null return fi jq -r --arg p "$file" --arg c "$cutoff" \ @@ -104,9 +104,12 @@ scan_dir_to_json() { # Pre-aggregate observation counts in two passes (one per window) instead of # calling jq per-file — reduces from O(n*m) to O(n+m) jq invocations. local obs_7d_counts obs_30d_counts + # Zero is meaningful only when an observations file is available. + local usage_default=null obs_7d_counts="" obs_30d_counts="" if [[ -f "$OBSERVATIONS" ]]; then + usage_default=0 obs_7d_counts=$(jq -r --arg c "$c7" \ 'select(.tool=="Read" and .timestamp>=$c) | .path' \ "$OBSERVATIONS" 2>/dev/null | sort | uniq -c) @@ -123,9 +126,11 @@ scan_dir_to_json() { # exit non-zero, which would otherwise silently under-count skills. # NUL-delimited (-print0 / sort_nul_file / read -d '') so a path containing a # literal newline can't desync record boundaries — paths here are untrusted. - if ! find -L "$dir" -name "SKILL.md" -type f -print0 >"$find_out" 2>"$find_err"; then - echo "Warning: find encountered errors while scanning $dir (broken symlinks or permission issues may cause skills to be missed):" >&2 + # Archived skills are not live inventory; prune the entire trash subtree. + if ! find -L "$dir" -type d -name ".trash" -prune -o -name "SKILL.md" -type f -print0 >"$find_out" 2>"$find_err"; then + echo "Error: find encountered errors while scanning $dir; refusing an incomplete inventory:" >&2 cat "$find_err" >&2 + return 1 fi sort_nul_file "$find_out" @@ -143,9 +148,9 @@ scan_dir_to_json() { # Use awk exact field match to avoid substring false-positives from grep -F. # uniq -c output format: " N /path/to/file" — path is always field 2. u7=$(echo "$obs_7d_counts" | awk -v f="$file" '$2 == f {print $1}' | head -1) - u7="${u7:-0}" + u7="${u7:-$usage_default}" u30=$(echo "$obs_30d_counts" | awk -v f="$file" '$2 == f {print $1}' | head -1) - u30="${u30:-0}" + u30="${u30:-$usage_default}" fi dp="${file/#$HOME/~}" diff --git a/tests/scripts/skill-stocktake-discovery.test.js b/tests/scripts/skill-stocktake-discovery.test.js index 92c13c6df2a..270c8854715 100644 --- a/tests/scripts/skill-stocktake-discovery.test.js +++ b/tests/scripts/skill-stocktake-discovery.test.js @@ -46,7 +46,8 @@ console.log('\nSkill stocktake discovery tests:'); test('both scanners use canonical, error-visible, NUL-delimited discovery', () => { for (const scriptPath of [scanScript, quickDiffScript]) { const source = fs.readFileSync(scriptPath, 'utf8'); - assert.match(source, /find -L "\$dir" -name "SKILL\.md" -type f -print0/); + assert.match(source, /find -L "\$dir"/); + assert.match(source, /-name "SKILL\.md" -type f -print0/); assert.match(source, /sort_nul_file "\$find_out"/); assert.match(source, /records\.sort\(Buffer\.compare\)/); assert.doesNotMatch(source, /sort -z/, `${path.basename(scriptPath)} still requires GNU sort`); @@ -147,6 +148,211 @@ if (process.platform === 'win32') { } } +if (process.platform !== 'win32') { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-stocktake-inventory-')); + try { + const globalSkills = path.join(tempRoot, 'global', '.claude', 'skills'); + const projectSkills = path.join(tempRoot, 'project', '.claude', 'skills'); + const liveSkills = [ + [path.join(globalSkills, 'active'), 'global-active'], + [path.join(globalSkills, '.trash-archive'), 'global-trash-archive'], + [path.join(projectSkills, 'active'), 'project-active'], + [path.join(projectSkills, '.trashcan'), 'project-trashcan'], + [path.join(projectSkills, 'space skill'), 'space-skill'], + [path.join(projectSkills, 'newline\nskill'), 'newline-skill'], + ]; + for (const [skillDir, name] of liveSkills) writeSkill(skillDir, name); + for (const [scope, skillsDir] of [['global', globalSkills], ['project', projectSkills]]) { + writeSkill(path.join(skillsDir, '.trash', 'deleted'), `${scope}-deleted`); + writeSkill(path.join(skillsDir, 'bundle', '.trash', 'nested'), `${scope}-nested-deleted`); + } + const linkedTarget = path.join(tempRoot, 'shared', 'linked'); + const linkedSkill = path.join(projectSkills, 'linked'); + writeSkill(linkedTarget, 'linked-skill'); + fs.symlinkSync(linkedTarget, linkedSkill, 'dir'); + const expectedPaths = [...liveSkills.map(([skillDir]) => path.join(skillDir, 'SKILL.md')), + path.join(linkedSkill, 'SKILL.md')].sort(); + const resultsPath = path.join(tempRoot, 'results.json'); + fs.writeFileSync(resultsPath, JSON.stringify({ evaluated_at: '2099-01-01T00:00:00Z', skills: [] })); + const emptyObservations = path.join(tempRoot, 'empty-observations.jsonl'); + fs.writeFileSync(emptyObservations, ''); + const env = { + SKILL_STOCKTAKE_GLOBAL_DIR: globalSkills, + SKILL_STOCKTAKE_PROJECT_DIR: projectSkills, + SKILL_STOCKTAKE_OBSERVATIONS: path.join(tempRoot, 'missing-observations.jsonl'), + }; + + test('scan excludes root and nested .trash directories in both scopes, preserving live skills', () => { + const result = runBash(scanScript, [], env); + assert.strictEqual(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.deepStrictEqual(output.skills.map(skill => skill.path).sort(), expectedPaths); + assert.strictEqual(output.scan_summary.global.count, 2); + assert.strictEqual(output.scan_summary.project.count, 5); + }); + + test('quick diff excludes .trash in both scopes while preserving similarly named and linked skills', () => { + const result = runBash(quickDiffScript, [resultsPath], env); + assert.strictEqual(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.deepStrictEqual(output.map(skill => skill.path).sort(), expectedPaths); + assert.ok(output.every(skill => skill.is_new === true)); + }); + + for (const [scope, skillsDir] of [['global', globalSkills], ['project', projectSkills]]) { + test(`scan rejects incomplete ${scope} discovery and cleans temporary files`, () => { + const binDir = path.join(tempRoot, `${scope}-bin`); + const scanTmp = path.join(tempRoot, `${scope}-scan-tmp`); + fs.mkdirSync(binDir); + fs.mkdirSync(scanTmp); + const findResult = spawnSync('bash', ['-c', 'command -v find'], { encoding: 'utf8' }); + assert.strictEqual(findResult.status, 0, findResult.stderr); + const realFind = findResult.stdout.trim(); + assert.ok(path.isAbsolute(realFind), 'Resolve the real find before overriding PATH'); + // Directory cycles do not fail consistently across GNU and BSD find. + // Emit a real partial record, then fail only the selected scope. + fs.writeFileSync(path.join(binDir, 'find'), [ + '#!/usr/bin/env bash', + 'if [[ "$2" == "$ECC_TEST_FIND_DIR" ]]; then', + ' printf "%s\\0" "$ECC_TEST_FIND_PARTIAL"', + ' printf "fixture find failure: %s\\n" "$ECC_TEST_FIND_DIR" >&2', + ' exit 1', + 'fi', + 'exec "$ECC_TEST_REAL_FIND" "$@"', + '', + ].join('\n'), { mode: 0o755 }); + const result = runBash(scanScript, [], { + ...env, TMPDIR: scanTmp, + PATH: `${binDir}${path.delimiter}${process.env.PATH}`, + ECC_TEST_FIND_DIR: skillsDir, + ECC_TEST_FIND_PARTIAL: path.join(skillsDir, 'active', 'SKILL.md'), + ECC_TEST_REAL_FIND: realFind, + }); + assert.strictEqual(result.status, 1, 'A failed find must not publish a partial inventory'); + assert.strictEqual(result.stdout, '', 'Incomplete discovery must not produce inventory JSON'); + assert.match(result.stderr, /Error: find encountered errors while scanning/); + assert.ok(result.stderr.includes(`fixture find failure: ${skillsDir}`), 'Preserve find stderr'); + assert.deepStrictEqual(fs.readdirSync(scanTmp), [], 'Clean discovery files on failure'); + }); + } + + for (const name of ['project-active', 'space-skill', 'newline-skill']) { + test(`scan reports unknown usage for ${name} when observations are missing`, () => { + const result = runBash(scanScript, [], env); + assert.strictEqual(result.status, 0, result.stderr); + const skill = JSON.parse(result.stdout).skills.find(entry => entry.name === name); + assert.ok(skill, `missing live skill: ${name}`); + assert.strictEqual(skill.use_7d, null); + assert.strictEqual(skill.use_30d, null); + }); + } + + test('scan reports numeric zero for unobserved skills when an empty observation file exists', () => { + const result = runBash(scanScript, [], { ...env, SKILL_STOCKTAKE_OBSERVATIONS: emptyObservations }); + assert.strictEqual(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.ok(output.skills.length > 0); + for (const skill of output.skills) { + assert.strictEqual(skill.use_7d, 0, skill.path); + assert.strictEqual(skill.use_30d, 0, skill.path); + } + }); + + test('scan preserves exact usage counts and date windows for normal and whitespace paths', () => { + const observationsPath = path.join(tempRoot, 'matching-observations.jsonl'); + const observedPaths = [path.join(linkedSkill, 'SKILL.md'), + ...liveSkills.filter(([, name]) => ['space-skill', 'newline-skill'].includes(name)) + .map(([skillDir]) => path.join(skillDir, 'SKILL.md'))]; + const timestamp = days => new Date(Date.now() - days * 86400000).toISOString(); + const observations = observedPaths.flatMap(skillPath => [ + { tool: 'Read', path: skillPath, timestamp: timestamp(0) }, + { tool: 'Read', path: skillPath, timestamp: timestamp(1) }, + { tool: 'Read', path: skillPath, timestamp: timestamp(10) }, + { tool: 'Read', path: skillPath, timestamp: timestamp(40) }, + { tool: 'Write', path: skillPath, timestamp: timestamp(0) }, + { tool: 'Read', path: `${skillPath}.backup`, timestamp: timestamp(0) }, + ]); + fs.writeFileSync(observationsPath, `${observations.map(record => JSON.stringify(record)).join('\n')}\n`); + const result = runBash(scanScript, [], { ...env, SKILL_STOCKTAKE_OBSERVATIONS: observationsPath }); + assert.strictEqual(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + for (const skillPath of observedPaths) { + const skill = output.skills.find(entry => entry.path === skillPath); + assert.ok(skill, `missing observed skill: ${skillPath}`); + assert.strictEqual(skill.use_7d, 2, skillPath); + assert.strictEqual(skill.use_30d, 3, skillPath); + } + const unobserved = output.skills.find(entry => entry.name === 'global-active'); + assert.strictEqual(unobserved.use_7d, 0); + assert.strictEqual(unobserved.use_30d, 0); + }); + } catch (error) { + console.log(` ✗ inventory fixture setup: ${error.message}`); + failed++; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +} + +if (process.platform !== 'win32') { + const skillSource = fs.readFileSync(path.join(repoRoot, 'skills', 'skill-stocktake', 'SKILL.md'), 'utf8'); + const inventorySection = skillSource.split('### Phase 1')[1].split('### Phase 2')[0]; + const inventoryBlock = inventorySection.match(/```bash\n([\s\S]*?)\n```/)[1]; + for (const scenario of ['changed', 'missing mtime', 'null mtime', 'matching', 'legacy matching']) { + test('documented resume reevaluates stale skills and preserves current evaluations (' + scenario + ')', () => { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-stocktake-resume-')); + try { + const home = path.join(tempRoot, 'home'); + const skills = path.join(home, '.claude', 'skills'); + const stocktake = path.join(skills, 'skill-stocktake'); + fs.mkdirSync(stocktake, { recursive: true }); + fs.cpSync(path.dirname(scanScript), path.join(stocktake, 'scripts'), { recursive: true }); + const skillDir = path.join(skills, 'live'); + writeSkill(skillDir, 'live'); + const skillPath = path.join(skillDir, 'SKILL.md'); + fs.utimesSync(skillPath, new Date('2025-01-01T00:00:00Z'), new Date('2025-01-01T00:00:00Z')); + const env = { + ...process.env, + HOME: home, + SKILL_STOCKTAKE_GLOBAL_DIR: skills, + SKILL_STOCKTAKE_PROJECT_DIR: path.join(tempRoot, 'missing-project'), + SKILL_STOCKTAKE_OBSERVATIONS: path.join(tempRoot, 'missing-observations'), + }; + const runInventory = () => spawnSync('bash', ['-c', inventoryBlock], { + cwd: tempRoot, env, encoding: 'utf8', timeout: 30000, + }); + const initial = runInventory(); + assert.strictEqual(initial.status, 0, initial.stderr); + const scanned = JSON.parse(initial.stdout).skills[0]; + const entry = { + path: scanned.path, verdict: 'Keep', reason: 'Preserve the reviewed content', + ...(scenario === 'missing mtime' ? {} : { mtime: scenario === 'null mtime' ? null : scanned.mtime }), + }; + const resultsPath = path.join(stocktake, 'results.json'); + fs.writeFileSync(resultsPath, JSON.stringify({ + mode: 'full', + skills: { [scenario === 'legacy matching' ? 'live' : scanned.path]: entry }, + batch_progress: { total: 1, evaluated: 1, status: 'in_progress' }, + })); + if (scenario === 'changed') { + fs.appendFileSync(skillPath, '\nContent changed after its evaluation.\n'); + fs.utimesSync(skillPath, new Date('2025-01-02T00:00:00Z'), new Date('2025-01-02T00:00:00Z')); + } + const resumed = runInventory(); + assert.strictEqual(resumed.status, 0, resumed.stderr); + const output = JSON.parse(fs.readFileSync(resultsPath, 'utf8')); + const preserved = scenario === 'matching' || scenario === 'legacy matching'; + assert.deepStrictEqual(output.skills, preserved ? { [scanned.path]: entry } : {}); + assert.deepStrictEqual(output.batch_progress, { + total: 1, evaluated: preserved ? 1 : 0, status: 'in_progress', + }); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }); + } +} + console.log(`\nPassed: ${passed}`); console.log(`Failed: ${failed}`); process.exit(failed > 0 ? 1 : 0); diff --git a/tests/scripts/skill-stocktake-save-results.test.js b/tests/scripts/skill-stocktake-save-results.test.js new file mode 100755 index 00000000000..ea648e595ab --- /dev/null +++ b/tests/scripts/skill-stocktake-save-results.test.js @@ -0,0 +1,156 @@ +#!/usr/bin/env node + +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const repoRoot = path.resolve(__dirname, '..', '..'); +const saveScript = path.join(repoRoot, 'skills', 'skill-stocktake', 'scripts', 'save-results.sh'); +let passed = 0; +let failed = 0; + +function test(description, fn) { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-stocktake-save-')); + try { + fn(path.join(tempRoot, 'results.json')); + console.log(` ✓ ${description}`); + passed++; + } catch (error) { + console.log(` ✗ ${description}: ${error.message}`); + failed++; + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +} + +function save(resultsPath, input, args = []) { + return spawnSync('bash', [saveScript, resultsPath, ...args], { + encoding: 'utf8', + input: typeof input === 'string' ? input : JSON.stringify(input), + env: process.env, + }); +} + +function readResults(resultsPath) { + const output = JSON.parse(fs.readFileSync(resultsPath, 'utf8')); + assert.match(output.evaluated_at, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/); + assert.ok(Math.abs(Date.now() - Date.parse(output.evaluated_at)) < 60000); + return output; +} + +console.log('\nSkill stocktake save-results tests:'); + +if (process.platform === 'win32') { + console.log(' ↷ Bash integration cases skipped on Windows'); +} else { + for (const mode of [undefined, 'quick']) { + test(`default save merges ${mode || 'legacy'} results and retains unchanged skills`, resultsPath => { + const unchanged = { verdict: 'Keep', reason: 'unchanged skill' }; + fs.writeFileSync(resultsPath, JSON.stringify({ + evaluated_at: '2000-01-01T00:00:00Z', + mode: 'full', + batch_progress: { completed: 1, total: 2 }, + skills: { unchanged, updated: { verdict: 'Improve' } }, + })); + const input = { + skills: { updated: { verdict: 'Keep' }, added: { verdict: 'Keep' } }, + ...(mode ? { mode } : {}), + }; + const result = save(resultsPath, input); + assert.strictEqual(result.status, 0, result.stderr); + const output = readResults(resultsPath); + assert.deepStrictEqual(output.skills, { unchanged, ...input.skills }); + assert.strictEqual(output.mode, mode || 'full'); + assert.deepStrictEqual(output.batch_progress, { completed: 1, total: 2 }); + }); + } + + test('full-mode intermediate saves still merge completed batches for resume', resultsPath => { + const completed = { verdict: 'Keep' }; + fs.writeFileSync(resultsPath, JSON.stringify({ + mode: 'full', batch_progress: { completed: 1, total: 2 }, skills: { completed }, + })); + const input = { + mode: 'full', batch_progress: { completed: 2, total: 2 }, skills: { next: { verdict: 'Improve' } }, + }; + const result = save(resultsPath, input); + assert.strictEqual(result.status, 0, result.stderr); + const output = readResults(resultsPath); + assert.deepStrictEqual(output.skills, { completed, ...input.skills }); + assert.deepStrictEqual(output.batch_progress, input.batch_progress); + }); + + test('explicit replacement saves only the live inventory and drops obsolete metadata', resultsPath => { + fs.writeFileSync(resultsPath, JSON.stringify({ + evaluated_at: '2000-01-01T00:00:00Z', + mode: 'quick', + batch_progress: { completed: 1, total: 2 }, + obsolete_summary: 'old cache', + skills: { + '~/.claude/skills/.trash/deleted/SKILL.md': { verdict: 'Keep' }, + '~/.claude/skills/removed/SKILL.md': { verdict: 'Keep' }, + }, + })); + const input = { + mode: 'full', + evaluated_at: '1999-01-01T00:00:00Z', + skills: { '~/.claude/skills/live/SKILL.md': { verdict: 'Keep' } }, + }; + const result = save(resultsPath, input, ['--replace']); + assert.strictEqual(result.status, 0, result.stderr); + const output = readResults(resultsPath); + assert.deepStrictEqual(output, { ...input, evaluated_at: output.evaluated_at }); + }); + + test('explicit replacement with an empty inventory removes all cached skills', resultsPath => { + fs.writeFileSync(resultsPath, JSON.stringify({ + skills: { stale: { verdict: 'Keep' } }, batch_progress: { completed: 1, total: 2 }, + })); + const input = { mode: 'full', skills: {} }; + const result = save(resultsPath, input, ['--replace']); + assert.strictEqual(result.status, 0, result.stderr); + const output = readResults(resultsPath); + assert.deepStrictEqual(output, { ...input, evaluated_at: output.evaluated_at }); + }); + + test('invalid JSON during replacement preserves the existing results byte for byte', resultsPath => { + const original = '{\n "skills": {"keep": {"verdict": "Keep"}}\n}\n'; + fs.writeFileSync(resultsPath, original); + const result = save(resultsPath, '{"skills":', ['--replace']); + assert.notStrictEqual(result.status, 0); + assert.match(result.stderr, /not valid JSON/); + assert.strictEqual(fs.readFileSync(resultsPath, 'utf8'), original); + assert.deepStrictEqual(fs.readdirSync(path.dirname(resultsPath)), ['results.json']); + }); + + test('replacement rejects absent, non-object, or multiple inventories without altering the cache', resultsPath => { + const original = '{\n "skills": {"keep": {"verdict": "Keep"}}\n}\n'; + const invalidInputs = ['', 'null', '[]', '{}', '{"skills":[]}', '{"skills":null}', + '{"skills":{}}\n{"skills":{}}']; + for (const input of invalidInputs) { + fs.writeFileSync(resultsPath, original); + const result = save(resultsPath, input, ['--replace']); + assert.notStrictEqual(result.status, 0, `accepted invalid replacement: ${JSON.stringify(input)}`); + assert.strictEqual(fs.readFileSync(resultsPath, 'utf8'), original); + assert.deepStrictEqual(fs.readdirSync(path.dirname(resultsPath)), ['results.json']); + } + }); + + for (const args of [[], ['--replace']]) { + test(`${args.length ? 'replacement' : 'default'} save bootstraps a new results file`, resultsPath => { + const input = { mode: 'full', skills: { live: { verdict: 'Keep' } } }; + const result = save(resultsPath, input, args); + assert.strictEqual(result.status, 0, result.stderr); + const output = readResults(resultsPath); + assert.deepStrictEqual(output, { ...input, evaluated_at: output.evaluated_at }); + }); + } +} + +console.log(`\nPassed: ${passed}`); +console.log(`Failed: ${failed}`); +process.exit(failed > 0 ? 1 : 0);