Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

fix(skill-stocktake): reconcile resumed live inventories safely

Yann Robertobb39e5da7fbb
diff --git a/manifests/context-packs/[email protected] b/manifests/context-packs/[email protected]
index 757fc0218..d4074a6fa 100644
--- a/manifests/context-packs/[email protected]
+++ b/manifests/context-packs/[email protected]
@@ -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":"05b0793ddaad74a794b6f7fcb4f4704b0c1ddeba4edec8347859eebbc394c47e","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":"6f30cf67553729dbc7be4a6f765fd3714ced362669e40a45656ea9eb40fbc0a2","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 720f56cf6..2451c29ea 100644
--- a/skills/skill-stocktake/SKILL.md
+++ b/skills/skill-stocktake/SKILL.md
@@ -77,7 +77,20 @@ Run this entire block in **one Bash invocation**. It prints the inventory for th
CACHE_STATUS=$(jq -r '.batch_progress.status // ""' "$RESULTS_JSON")
fi
if [[ "$CACHE_STATUS" == "in_progress" ]]; then
- printf '%s\n' 'Resuming existing full evaluation; cache preserved.' >&2
+ RESUMED_RESULTS=$(jq --slurpfile saved "$RESULTS_JSON" '
+ . as $inventory | $saved[0]
+ | .skills = (.skills | to_entries
+ | map(.key = (.value.path // .key))
+ | map(select(.key as $p | any($inventory.skills[]; .path == $p)))
+ | 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: {},
@@ -104,7 +117,7 @@ Scanning:
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.
-`--replace` replaces the entire cached evaluation, removing archived or deleted skills and stale metadata. The block skips initialization when resuming an `in_progress` evaluation. Later chunks, completion updates, and Quick Scans must omit `--replace` so they merge into the current run instead of losing earlier results.
+`--replace` writes a complete cache snapshot. A new run starts with an empty evaluation; a resumed run instead keeps every saved evaluation whose path is still in the live inventory, 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.
### Phase 2 — Quality Evaluation
@@ -137,7 +150,7 @@ After all skills are evaluated, persist completion before proceeding to Phase 3:
)
```
-**Resume detection:** If `status: "in_progress"` is found on startup, read the saved `skills` map and evaluate only inventory paths not already present. Preserve completed batches.
+**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 for surviving paths are preserved; newly added paths still require evaluation.
Each skill is evaluated against this checklist:
@@ -213,7 +226,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/scan.sh b/skills/skill-stocktake/scripts/scan.sh
index 7f404fbe8..8b82086f2 100755
--- a/skills/skill-stocktake/scripts/scan.sh
+++ b/skills/skill-stocktake/scripts/scan.sh
@@ -128,8 +128,9 @@ scan_dir_to_json() {
# literal newline can't desync record boundaries — paths here are untrusted.
# 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
+ 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"
diff --git a/tests/scripts/skill-stocktake-discovery.test.js b/tests/scripts/skill-stocktake-discovery.test.js
index c1aa26190..f82548bc6 100644
--- a/tests/scripts/skill-stocktake-discovery.test.js
+++ b/tests/scripts/skill-stocktake-discovery.test.js
@@ -200,6 +200,25 @@ if (process.platform !== 'win32') {
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 cyclePath = path.join(skillsDir, 'cycle');
+ const scanTmp = path.join(tempRoot, `${scope}-scan-tmp`);
+ fs.mkdirSync(scanTmp);
+ fs.symlinkSync(skillsDir, cyclePath, 'dir');
+ try {
+ const result = runBash(scanScript, [], { ...env, TMPDIR: scanTmp });
+ 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(cyclePath), 'Preserve the failing path from find stderr');
+ assert.deepStrictEqual(fs.readdirSync(scanTmp), [], 'Clean discovery files on failure');
+ } finally {
+ fs.unlinkSync(cyclePath);
+ }
+ });
+ }
+
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);