diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index fde13a8..6174ec8 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -18,7 +18,7 @@ { "name": "claude-code-tools", "source": "./plugins/claude-code-tools", - "description": "Meta-tools for running Claude Code well: audit your permission allowlist, fix local toolchain gaps, and analyze usage costs." + "description": "Meta-tools for running Claude Code well: audit your permission allowlist, fix local toolchain gaps, analyze usage costs, and prune stale saved memories." }, { "name": "test-tools", diff --git a/README.md b/README.md index ff8f4a3..70124aa 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Add the marketplace, then install the plugin you want: - **[skill-tools](./plugins/skill-tools/)** — Tools for authoring and reviewing Claude Code skills. Includes the `skill-review` skill, which reviews skills against a closed 7-category quality rubric (Structural Discipline, Integrity, Test Coverage, Security, Content Quality, Convention, Cost) with structured JSON output and a determinism contract. - **[security-tools](./plugins/security-tools/)** — Harden GitHub Actions workflows against supply-chain and injection attacks. Includes the `secure-github-actions` skill (a 14-rule review checklist plus audit commands) and a hook that auto-loads it when you edit a workflow file. -- **[claude-code-tools](./plugins/claude-code-tools/)** — Meta-tools for running Claude Code well. `permissions-analyzer` vets your permission allowlist against a GREEN/YELLOW/RED safety model; `tool-misses` finds and fixes missing CLI tools / BSD-GNU incompatibilities; `cc-cost-analysis` is a framework for analyzing Claude Code usage costs from OpenTelemetry data. +- **[claude-code-tools](./plugins/claude-code-tools/)** — Meta-tools for running Claude Code well. `permissions-analyzer` vets your permission allowlist against a GREEN/YELLOW/RED safety model; `tool-misses` finds and fixes missing CLI tools / BSD-GNU incompatibilities; `cc-cost-analysis` is a framework for analyzing Claude Code usage costs from OpenTelemetry data; `audit-memory` verifies saved memories against current code and archives the stale ones. - **[test-tools](./plugins/test-tools/)** — Investigate and fix flaky tests. The `fix-flaky-tests` skill detects your framework and CI provider, classifies the flake, and enforces green-CI-as-the-only-verification discipline across RSpec, Jest, pytest, Go test, and more. - **[code-review-tools](./plugins/code-review-tools/)** — The `thermo-nuclear-code-review` skill runs an extremely strict structural and architectural review, hunting for "code judo" simplifications rather than correctness bugs or style nits. - **[pr-tools](./plugins/pr-tools/)** — Open well-formed GitHub pull requests from Claude Code and attach screenshots and recordings to them. Includes `create-pr` (intent-gathering, diff validation, public-repo safeguards) and `attach-github-assets` (upload local images/recordings to GitHub for use in PR and issue markdown). diff --git a/plugins/claude-code-tools/.claude-plugin/plugin.json b/plugins/claude-code-tools/.claude-plugin/plugin.json index 3c167ae..0e6a3a6 100644 --- a/plugins/claude-code-tools/.claude-plugin/plugin.json +++ b/plugins/claude-code-tools/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "claude-code-tools", - "version": "0.1.0", - "description": "Meta-tools for running Claude Code well: audit your permission allowlist, fix local toolchain gaps, and analyze usage costs.", + "version": "0.2.0", + "description": "Meta-tools for running Claude Code well: audit your permission allowlist, fix local toolchain gaps, analyze usage costs, and prune stale saved memories.", "author": { "name": "Fin 2x" }, @@ -10,7 +10,9 @@ "permissions", "cost", "telemetry", - "tooling" + "tooling", + "memory", + "context" ], "license": "MIT" } diff --git a/plugins/claude-code-tools/CHANGELOG.md b/plugins/claude-code-tools/CHANGELOG.md index d53e94b..b1b78c4 100644 --- a/plugins/claude-code-tools/CHANGELOG.md +++ b/plugins/claude-code-tools/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to the `claude-code-tools` plugin are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.2.0] - 2026-09-17 + +### Added + +- `audit-memory` skill — verifies saved memories against current code, PRs and tickets, then archives the stale ones with your approval. Never auto-fires; snapshots every file before any write, and treats an unverifiable claim as `NEEDS-` rather than stale. + ## [0.1.0] - 2026-07-09 ### Added diff --git a/plugins/claude-code-tools/README.md b/plugins/claude-code-tools/README.md index 4948681..bba0e1a 100644 --- a/plugins/claude-code-tools/README.md +++ b/plugins/claude-code-tools/README.md @@ -1,6 +1,6 @@ # claude-code-tools -Meta-tools for running Claude Code well: audit your permission allowlist, fix local toolchain gaps, and analyze usage costs. +Meta-tools for running Claude Code well: audit your permission allowlist, fix local toolchain gaps, analyze usage costs, and prune stale saved memories. Part of the [`fin-2x`](../../README.md) marketplace. @@ -16,6 +16,7 @@ Part of the [`fin-2x`](../../README.md) marketplace. - **[permissions-analyzer](./skills/permissions-analyzer/)** — Vets a Claude Code permission allowlist against a GREEN/YELLOW/RED safety model and merges the safe entries into `~/.claude/settings.json`. Runs on top of the built-in `/fewer-permission-prompts` scan, adding a RED override that never auto-allows shell interpreters or package-manager executors (`npm`, `uv`, `bundle`, `npx`, …). - **[tool-misses](./skills/tool-misses/)** — Scans recent Claude Code sessions for `command not found` errors and BSD/GNU incompatibilities on macOS, fixes them via Homebrew, and records availability in CLAUDE.md. - **[cc-cost-analysis](./skills/cc-cost-analysis/)** — A framework, ready-to-use query shapes, and cost-model formulas for analyzing Claude Code usage costs from exported OpenTelemetry data (per-user spend, expensive sessions, context bloat, model/token breakdowns). +- **[audit-memory](./skills/audit-memory/)** — Saved memories are point-in-time observations, and a memory that was true when written becomes a confidently wrong instruction to every future session. `/audit-memory` verifies each claim against current code, PRs and tickets, then archives the stale ones with your approval. It snapshots every file before touching it, never truth-checks a stated preference, and reports a claim it could not check as `NEEDS-` rather than as stale — absence of evidence never becomes evidence of staleness. ## Hooks diff --git a/plugins/claude-code-tools/skills/audit-memory/SKILL.md b/plugins/claude-code-tools/skills/audit-memory/SKILL.md new file mode 100644 index 0000000..be5b441 --- /dev/null +++ b/plugins/claude-code-tools/skills/audit-memory/SKILL.md @@ -0,0 +1,264 @@ +--- +name: audit-memory +description: | + Audit Claude's saved memories for claims that no longer hold true — verify each against current code, PRs and tickets, then archive the stale ones with your approval, and name the MCPs needed for anything unverifiable. +disable-model-invocation: true +allowed-tools: Bash Read Grep Glob Edit Write AskUserQuestion Agent +metadata: + user-invocable: true + argument-hint: "[project name to audit] [--root ]" +--- + +# Audit Memory + +Saved memories are point-in-time observations. Code moves, PRs merge, projects finish — and a memory that was true when written silently becomes a confidently wrong instruction to every future session. This skill verifies memories against reality and archives what no longer holds. + +**Never auto-fires** — it archives user data, so it runs only when someone types `/audit-memory`. + +## Core guarantees + +These are load-bearing. Violating any of them makes the skill untrustworthy: + +1. **Absence of evidence is never evidence of staleness.** A claim you cannot check is `NEEDS-`, `NOT-ATTEMPTED` or `NOT-CHECKABLE` — never stale, never offered for removal. A disconnected MCP must never turn valid memories into deletion candidates. Two mirrors of this also hold. Never report a check you skipped as a tool that was missing. And never over-apply it: a newer memory stating the old fact was removed **is** positive evidence, sufficient alone — an unreachable repo cannot demote it, because the evidence was never in the repo. +2. **Archive before you touch anything, so nothing is unrecoverable.** Memory files are not version-controlled and have no trash. Snapshot the original into the archive before *any* write or removal — claim removals, whole-file archiving, `MEMORY.md` pointer sync, and `lastReviewed` stamps alike. Removal does mean deleting the file; it is safe only because the verified snapshot precedes it. +3. **Preferences are not claims.** `type: feedback` and `type: user` memories are standing instructions. Never argue they are false — the user is the only authority on whether a preference still applies. +4. **No writes outside the resolved roots.** Only the memory root and archive root are ever written to. +5. **Name the root you actually audited**, before showing findings, and never claim you honoured `CLAUDE_MEMORY_ROOT` unless you read it. Auditing a different corpus than the caller meant is the worst failure here. + +## Step 1 — Resolve roots and discover projects + +Run this **exactly as written, as a single call**. It resolves both roots and lists every project in one step. + +The memory root resolves in this order: an explicit `--root ` argument, then `CLAUDE_MEMORY_ROOT`, then `~/.claude/projects`. If the caller passed `--root `, prefix the block with `CLAUDE_MEMORY_ROOT='' ` so both routes land in the same variable. + +**Single-quote it, and escape any single quote inside it** by replacing each `'` with `'\''`. Unquoted, a space or metacharacter splits the path; naively quoted, an apostrophe closes the quote early and the rest runs as shell. A path you cannot quote safely is one you refuse, not one you guess at. + +Shell variables do not survive between Bash calls, so never split root resolution from the work that uses it, and never pass a root in as `"$MEM_ROOT"` from an earlier call — it will be empty, which is why this block reads the environment directly. + +**If this block runs and fails, stop and report the error** — a nonexistent root, a permission error, a traceback. Never retry against `$HOME/.claude/projects` instead (guarantee 5). + +`Bash` being unavailable is different — the block never runs, so `CLAUDE_MEMORY_ROOT` is unreadable and you cannot know whether the default root is the intended corpus. That run is **read-only until the root is confirmed**: report findings against `~/.claude/projects`, say which root you used and that the environment was invisible, and make **no write at all** — no archive, no edit, no stamp — until the user confirms it. Findings can be discarded; an archive written against the wrong corpus cannot. + +**Never decode project directory names into filesystem paths.** The encoding is lossy: `-Users-me-src-claude-plugins` could be `src/claude-plugins` or `src/claude/plugins`, because path separators and literal hyphens both become `-`. The authoritative `cwd` comes from the project's session transcripts, which is what this block reads. + +**If `Bash` is unavailable, do not stop** — fall back to the tool-only path below. Sandboxes and eval harnesses routinely deny `Bash`, and a discovery step with no fallback turns that into a dead end. + +```bash +python3 <<'PY' +import glob, json, os, re, subprocess, time + +root = os.environ.get("CLAUDE_MEMORY_ROOT") or os.path.expanduser("~/.claude/projects") +# expanduser before resolving: --root is single-quoted, so a leading ~ reaches +# Python literally and would otherwise resolve against the cwd. realpath, not +# abspath, so a symlinked root cannot place the archive outside the resolved +# roots the no-external-writes guarantee is stated against. +root = os.path.realpath(os.path.expanduser(root)) +archive = os.path.join(os.path.dirname(root), "memory-archive", + time.strftime("%Y-%m-%d")) +print("MEMORY_ROOT=" + root) +print("ARCHIVE_ROOT=" + archive) +print("SOURCE=" + ("CLAUDE_MEMORY_ROOT" if os.environ.get("CLAUDE_MEMORY_ROOT") else "default")) +if not os.path.isdir(root): + raise SystemExit("memory root does not exist: " + root) + +for d in sorted(os.listdir(root)): + mem = os.path.join(root, d, "memory") + if not os.path.isdir(mem): + continue + # glob.escape the directory: a project dir holding [ ] * or ? would otherwise be + # read as a pattern and match the wrong memories, or none. + files = [f for f in glob.glob(glob.escape(mem) + "/*.md") + if os.path.basename(f) != "MEMORY.md"] + if not files and not os.path.exists(os.path.join(mem, "MEMORY.md")): + continue + cwd = None + for j in sorted(glob.glob(glob.escape(os.path.join(root, d)) + "/*.jsonl"), + key=os.path.getmtime, reverse=True)[:3]: + try: + for line in open(j): + o = json.loads(line) + if o.get("cwd"): + cwd = o["cwd"] + break + except Exception: + pass + if cwd: + break + # Skip harness debris only where it lives (a temp dir) and only on its actual + # shape: a name plus a "-" plus a generated suffix, e.g. skill-eval-4rscfuzs. + # Requiring that hyphen is what keeps a real repo named "skill-evaluator". + if cwd and re.match(r"(/private)?(/tmp|/var/folders/[^/]+/[^/]+/T)/", cwd) \ + and re.search(r"/(trigger-eval|skill-eval|skill-eval-origin|pytest)-[A-Za-z0-9_]+/", + cwd + "/"): + continue + # Fall back to cwd itself: a readable working tree that is not a git repo (or a + # machine with no git) still lets file-path and grep claims be checked, and + # reporting repo: null there wrongly downgrades every one of them. + repo = None + if cwd and os.path.isdir(cwd): + try: + r = subprocess.run(["git", "-C", cwd, "rev-parse", "--show-toplevel"], + capture_output=True, text=True) + repo = r.stdout.strip() or cwd + except (OSError, subprocess.SubprocessError): + repo = cwd + # An index-only project is kept above on purpose, so files can be empty; a + # project with memories but no MEMORY.md is equally valid. Age off whatever + # exists rather than assuming either is present. + dated = list(files) + [f for f in [os.path.join(mem, "MEMORY.md")] if os.path.exists(f)] + newest = max((os.path.getmtime(f) for f in dated), default=None) + age = int((time.time() - newest) / 86400) if newest else None + print(json.dumps({"dir": d, "cwd": cwd, "repo": repo, + "files": len(files), "newest_age_days": age})) +PY +``` + +### Fallback when `Bash` is denied + +**Read `references/no-bash-fallback.md` and follow it.** It gives the tool-only equivalent of every discovery step, and the rule that a run which could not confirm its root stays read-only. + +Then ask which projects to audit. List every project with its file count and newest-memory age; up to 16 fit in one `AskUserQuestion` call (4 questions × 4 options, `multiSelect: true`). Mark projects with `repo: null` as *code claims not checkable* so the choice is informed. + +**Skip the picker when there is nothing to choose** — exactly one project discovered, or the user named one as an argument. Audit it and continue to Step 2. + +It is also the *only* question asked before findings exist. Everything up to the first proposal is read-only, so never pause to ask whether to begin, to read the memories, or to proceed after discovery — that is how a run ends having audited nothing. Ask once you have something to decide on. + +## Step 2 — Fan out one subagent per selected project + +Spawn one `Agent` per project, `model: sonnet`, concurrently, giving each the project's memory directory and its resolved repo path. + +If a single project is selected and it holds fewer than ~10 memories, verify inline instead — at that size a subagent costs more than it saves. **Read the brief and follow it yourself when you do.** Its rules are about how to verify, not about being a subagent: skipping it is how an inline run reaches for `NOT-CHECKABLE` instead of naming the tool it needed. + +Require this exact return shape: + +```json +{ + "project": "", + "repo": "", + "preferences": [ + {"file": "feedback_x.md", "summary": "", + "age_days": 42, "mechanism": "ok" | "missing" | "unknown", + "mechanism_note": ""} + ], + "claims": [ + {"file": "project_y.md", "claim": "", + "verdict": "CONFIRMED" | "STALE" | "NEEDS-" | "NOT-ATTEMPTED" | "NOT-CHECKABLE", + "evidence": "", + "occurrences": [""], + "proposed_edit": ""} + ], + "archetype": {"project_y.md": "LIVING" | "JOURNAL" | "SNAPSHOT" | "NOTE"}, + "index_issues": [""] +} +``` + +Instruct each subagent to: + +Their brief lives in `references/subagent-brief.md` — **read it and pass it to each subagent**. It defines how to route by `type`, which checks are free, how to scope repo lookups, and when each verdict applies. Validate every report against it. + +**Validate every report before using it.** Reject and re-ask any subagent that returns a `STALE` claim with a null or missing `proposed_edit`, or whose `proposed_edit` does not appear verbatim in the file. A stale claim with no removable text is a finding that will otherwise be silently dropped — the memory stays wrong and the summary implies it was handled. Also sanity-check `age_days` against the file's own mtime and prefer your own measurement; subagents have reported `0` for every file. + +Where a needed MCP is not connected, offer once to connect it and re-run the affected subagents, rather than re-running the whole audit. Where verdicts are `NOT-ATTEMPTED`, offer to re-run those specific checks — the tool was there. + +## Step 3 — Preference pass + +Merge preferences across projects and dedupe near-identical ones (the same rule often lives in several project directories) — show it once, apply the decision to every copy. + +Skip anything already stamped `metadata.lastReviewed` unless its file changed since that date or its `mechanism` is now `missing`. + +Present **10 per round** as check-to-drop, using 3 `multiSelect` groups in a single `AskUserQuestion` call (4 + 3 + 3): + +- Frame it as **"check the ones to DROP"**. Options always start unselected, so an untouched round removes nothing — deletion must be a deliberate act. +- One line each: name, the ≤90-char summary, age, and `⚠ mechanism gone: ` when applicable. +- Never sort by age. Age does not predict staleness for preferences — the oldest rules are typically the most durable. + +After each round, ask whether to continue. + +On stopping, offer to stamp `metadata.lastReviewed: ` on every preference the user *kept and saw*, so the next run resumes instead of restarting. **Ask first** — once, naming the count and files. Stamping writes to files the user just chose to keep, and a file whose only instruction was "leave this alone" is the last place to spring a surprise write. Declining is fine; the next run simply re-asks. Snapshot stamped files like any other write. + +## Step 4 — Stale-claim pass + +Report `CONFIRMED` and `NOT-CHECKABLE` counts as a summary only. Report the two tool buckets **separately and never merged** — they mean opposite things: + +> 9 claims need an issue-tracker MCP (absent) — run `/mcp`, then re-run. +> 4 claims went unchecked though the telemetry MCP was available — re-run those? + +Offer **only `STALE` claims** for removal, 10 per round, same check-to-drop batching. One decision covers **all** of a claim's `occurrences` — never present the same fact twice, and never apply to one occurrence while leaving another. This holds even when the occurrences need *different* actions: correcting the body figure while removing a sentence elsewhere is still one approval that spells out what happens to each occurrence, never one approval per occurrence. Splitting it lets the user accept half and leave the file contradicting itself. + +For a claim whose text is only *partly* wrong — a drifted count, a moved line number, a renamed file — offer **correct** alongside **remove**, and default to correct. Deleting a whole sentence because one number inside it aged throws away a still-valid pointer, and it is exactly these claims whose text is interleaved with verified content, making removal the most destructive option available. + +Then, before writing anything, show the actual diffs for every checked claim and confirm once. **If the caller already authorised the changes in the invocation** ("archive anything stale, don't ask me"), that *is* the confirmation — still print the diffs, since they are the only record of what you changed, but do not stop for a second approval. Asking again after being told not to is how a pre-authorised run ends having done nothing. These are surgical edits inside files that run to thousands of words: removing a sentence can orphan a "see above", break a list, or strip the only context a neighbouring claim depended on. A checkbox cannot show that; a diff can. If a proposed removal would take verified content with it, say so and offer a narrower correction instead of the deletion. + +## Step 4b — Usefulness pass + +Truth and usefulness are independent: a memory can be perfectly accurate and still be pure context tax. **Read `references/usefulness-pass.md` before this pass** — it holds the per-archetype offer for `SNAPSHOT` and `JOURNAL`, and the one condition on archiving a file whole. Then present the `JOURNAL` and `SNAPSHOT` files, 10 per round, check-to-act. + +Open this pass with the corpus cost as a literal measured line, in this exact shape and even when the corpus is tiny: + +> Corpus: 125 memories, 41,800 words, ~60K tokens loaded every session. + +A file count is **not** a size — words and an approximate token count are both required, and "2 memory files" answers a different question. Measure it; do not estimate from the file count alone. Every other number here is about one file; this is the only one that says what the whole corpus charges each session, and it is the reason the pass exists. Never act on a `LIVING` file here — open work is the one thing worth its context. + +Leave `RULE` files to Step 3; usefulness of a preference is the user's call, not an archetype's. + +## Step 5 — Apply + +**Snapshot before every write, without exception** — not just removals; a `lastReviewed` stamp counts too. + +**First, if `MEMORY.md` exists, snapshot it** into the archive before the loop below, with step 1's command (it suffixes `.` rather than overwriting, so a second same-day audit cannot destroy the true baseline). Do it even if you are not sure yet that you will edit it: the loop is per-memory-file, so it never covers the index, and that gap is the one snapshot runs actually miss. **Check it exists** — a project with memory files and no index is valid and step 1 admits it, so an unconditional snapshot aborts the apply phase on a missing source, after approval and before any real snapshot. With no index, say so and skip both this snapshot and step 4's sync; never create one, since this skill audits memories rather than authoring them. + +Then, for every approved change, in this order: + +1. **Snapshot** the current file to `$ARCHIVE_ROOT//` before touching it, **with this command and not `Write`**: + + ```bash + python3 - '' '' <<'PY' + import os, shutil, sys + src, dst = sys.argv[1], sys.argv[2] + os.makedirs(os.path.dirname(dst), exist_ok=True) + for n in range(100): + cand = dst if n == 0 else "%s.%d" % (dst, n) + try: + fd = os.open(cand, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + continue + with os.fdopen(fd, "wb") as out, open(src, "rb") as f: + shutil.copyfileobj(f, out) + print("SNAPSHOT=" + cand) + break + else: + raise SystemExit("no free archive path for " + dst) + PY + ``` + + **Substitute both paths literally** (single-quoted, `'\''`-escaped) — never a shell variable: they do not survive between `Bash` calls, and empty arguments fail the archive before any approved mutation. + + `O_EXCL` is why this is a command and not a `Write`: it creates or fails, with no window between the two, so a snapshot can never land on an existing one. A `Glob`-then-`Write` cannot: two same-day audits can both see the path free, and the second overwrites the first's original with an already-edited copy. Use the path it prints; **that copy is the snapshot**, the only thing counted as one in the closing count. Without `Bash` this atomicity is unavailable: `Read` the path first, `Write` only if absent, and say in the report that a concurrent audit could have raced it. +2. **Append to `$ARCHIVE_ROOT/manifest.json`**: source path, project, intended action (`file-archived` or `claim-removed`), the removed text, the verdict, the evidence that justified it, and `outcome: "pending"`. **Set `outcome` to `applied` or `refused` once step 3 resolves.** The entry precedes the mutation, so one left at `pending` records an intention, and a manifest read as a change log would report work that never happened. +3. **Apply** — `Edit` to remove or correct an individual claim, covering every one of its `occurrences`. Remove the file from the corpus in exactly three cases, by this procedure and no other: **confirm the step 1 snapshot exists and its contents match the file, then `rm` the file.** That order is the whole safety property, so never `rm` before confirming, and never re-write the file to the base archive name to "make sure" — that is the overwrite step 1 avoided, landing on an earlier run's original. Verify the snapshot step 1 wrote, at the suffixed path if it resolved a collision. Without `Bash` you cannot `rm` at all — follow `references/no-bash-fallback.md`, which stubs the file and reports what remains. The three cases: every claim in it is stale, the user dropped the whole preference, or the user approved **archive whole** in the usefulness pass. For an approved **compress to outcome**, overwrite the body and keep the file, preserving `name` and the whole `metadata:` block exactly — that is what the memory system parses. **Rewrite `description` to match the new body** and show it in the diff: it is the line recall surfaces, so carrying the old one forward leaves the file describing content it no longer holds — the rot the compression was meant to end. Where a compression supersedes queued edits on the same file, fold those corrected facts in so nothing regresses. +4. **Sync `MEMORY.md`** (already snapshotted above) — remove the pointer line for any archived file, and **correct the hook line for any file whose claim you changed**, whenever that hook was among the claim's `occurrences`. Archiving is not the only edit that dates the index: correcting a figure in the body while its hook still asserts the old one leaves the index contradicting the file it points at, and the hook is what recall surfaces first. A pointer to a missing file is worse still than the stale memory was. +5. **Re-scan each edited file** for the fact you just removed — whole file, frontmatter included. A surviving copy means the file now contradicts itself, which is worse than the original staleness. Fix it in the same pass, or report it explicitly as unresolved; never leave it silent. + +Leave dangling `[[wiki-links]]` alone — an unmatched link is valid, marking something worth writing later. Report them; do not repair them. + +**Count what happened, not what you attempted.** Check the result of every write, and **never skip one because you expect it to be refused** — a predicted refusal is not a result, and an environment that blocked the last write may allow this one. Attempt it, then report what actually happened. One refusal does not mean the next was refused too — a later `Write` can succeed after an `Edit` was blocked, and treating the first denial as final reports the corpus untouched when it is not. List exactly which writes landed and which were refused. Reporting `Files touched: 0` after a write succeeded is worse than the staleness you set out to fix: the user will trust the corpus is unchanged and never look again. + +Finally, **verify the archive is a complete restore source**: every file this run modified or removed must have a snapshot. **Count step 1's memory-file copies and nothing else.** `manifest.json` is not a snapshot — counting it lets a run that changed two files report "2 snapshots" and look 1:1 covered while one has no restore point, exactly the failure this check exists to catch. Print both numbers on one line — `Corpus files changed: 3 / Snapshots written: 3` — never as narrative prose, and name the first one *corpus* so it is unambiguous whether archive writes count. **When they differ, give the reason on the same line** — `Corpus files changed: 0 / Snapshots written: 2 (both source edits refused)`. A mismatch is not automatically a fault — snapshotting then failing to edit leaves exactly this shape — but say so loudly: a partial archive invites a restore that silently leaves edits in place. + +Close with counts: verified, archived, claims removed, claims corrected, files compressed, the two tool buckets kept apart (absent vs unchecked), the archive path, and the one-line restore command. State plainly anything you could not complete — a dropped finding is worse than one never made, because the summary implies it was handled. + +## Response Style + +Narration compounds in a workflow this long. Present the picker, batches, diffs and counts directly — skip "Now I will…", "Let me…", and restating a step before doing it. While subagents run, say nothing until something is actionable or a report contradicts itself. + +## Guardrails + +- Never write outside `$MEM_ROOT` and `$ARCHIVE_ROOT`, and never write *through* a symlink: resolve each target to its real path first, and if that lands outside either root, skip the file and report the skip. Resolving the roots does not resolve a symlinked file inside them. +- Never `rm` a memory file until its archive snapshot exists and its contents match — the snapshot is what makes the removal reversible, so no snapshot means no removal. +- Never mark a claim stale on absent evidence. +- Never truth-check a `feedback` or `user` memory. +- Never edit `CLAUDE.md`, `.claude/rules/`, or any repo file — this skill audits saved memories only. +- Never act on a `STALE` claim whose `proposed_edit` you could not match verbatim in the file. +- Never remove one occurrence of a fact while leaving another standing. +- Never report an unattempted check as a missing tool. +- If zero projects have memories, say so and stop. diff --git a/plugins/claude-code-tools/skills/audit-memory/references/no-bash-fallback.md b/plugins/claude-code-tools/skills/audit-memory/references/no-bash-fallback.md new file mode 100644 index 0000000..247ccc2 --- /dev/null +++ b/plugins/claude-code-tools/skills/audit-memory/references/no-bash-fallback.md @@ -0,0 +1,20 @@ +# Discovery without `Bash` + +Sandboxes and eval harnesses routinely deny `Bash`, and a discovery step with no fallback turns that into a dead end. Every step has a tool-only equivalent. Use these, and report that you ran without `Bash`. + +| Need | Without `Bash` | +|---|---| +| memory root | the `--root ` argument if the caller gave one, resolved against the cwd if relative. **No tool exposes environment variables**, so `CLAUDE_MEMORY_ROOT` is invisible here — if no `--root` was passed, use `~/.claude/projects` and say outright that you audited the default root and could not see whether `CLAUDE_MEMORY_ROOT` was set | +| root exists at all | `Glob` `/*` **before anything else**. Empty means the root is absent *or* empty, and those need opposite responses — an absent root is an error to stop on, an empty one is a clean "nothing to audit". Distinguish them by globbing the parent for the root's own name; if you cannot, say which of the two you could not rule out rather than picking the reassuring one | +| memory files per project | `Glob` `/*/memory/*.md` | +| project → repo | `Grep` pattern `"cwd":\s*"[^"]+"` over `//*.jsonl`, `output_mode: "content"`, `head_limit: 1` — the transcript's own field, same authority as the script. Keep the `\s*`: transcripts are not always written compactly, and a pattern anchored to `"cwd":"` misses every pretty-printed line, which looks identical to a project having no resolvable repo | +| does the repo exist | `Glob` `/*` — non-empty means present | +| file ages | `Read` the memory's `metadata.modified`, and say so if you had no mtime available | + +**Escape glob metacharacters in every interpolated path.** The `Glob` patterns above splice a root, project or repo path into a pattern, and `[`, `]`, `?` and `*` are legal in a directory name — `~/src/app[v2]` globs as a character class and silently matches nothing, which is indistinguishable from an absent root. Wrap each such character in brackets (`[[]`, `[?]`, `[*]`) before splicing, and treat an empty result on a path containing one as unresolved rather than absent. The `Bash` path escapes these already (`glob.escape`); this path has to do it by hand. + +The rest of the audit needs no shell either: claims verify through `Read`, `Glob` and `Grep`, and edits through `Edit`. Only PR, issue and branch state genuinely requires `gh`/`git`; without them those claims are `NEEDS-gh`, which is honest — never `STALE`. + +**Whole-file archival cannot complete on this path.** Removal is a snapshot-then-`rm`, and `rm` needs a shell, so `Edit`/`Write` alone cannot take a file out of the corpus. Do not claim the file was archived. Instead: write the snapshot and the manifest entry as usual, then stub the file — **replace the frontmatter `description` as well as the body**, not the body alone. `description` is the line recall surfaces, so a stub carrying the original one keeps asserting the stale claim to every future session, which is the exact failure the removal was for. But **the stub must not say the file was archived or removed** — it has not been; that is the false report this whole path exists to avoid. Word both lines as *pending*: "superseded — pending removal, snapshot at ``". Keep `name` and the `metadata:` block so the file still parses. Then remove its `MEMORY.md` pointer, and say plainly that the stub remains and needs `Bash` (or a manual `rm`) to finish. A file reported as archived while still sitting in the corpus is the same false-report failure as miscounting writes. + +**The root is unconfirmed on this path.** Because `CLAUDE_MEMORY_ROOT` is unreadable, a run that fell back to the default root cannot know it is auditing the corpus the caller meant. Report findings, but make no write of any kind — no archive, no edit, no `lastReviewed` stamp — until the user confirms the root. Findings can be discarded; an archive written against the wrong corpus cannot. diff --git a/plugins/claude-code-tools/skills/audit-memory/references/subagent-brief.md b/plugins/claude-code-tools/skills/audit-memory/references/subagent-brief.md new file mode 100644 index 0000000..7e5822a --- /dev/null +++ b/plugins/claude-code-tools/skills/audit-memory/references/subagent-brief.md @@ -0,0 +1,35 @@ +# Subagent brief + +Hand this to every project subagent verbatim, alongside its memory directory and resolved repo path. The return shape is defined in SKILL.md Step 2. + +- **Route by `type` frontmatter.** `feedback`/`user` → `preferences` (no truth-checking; only report whether the *mechanism* they cite still exists, e.g. a script, hook or flag that is now gone). `project`/`reference`/untyped → `claims`. +- **Verify free things first**, at no MCP cost: cited file paths and `file:line` refs via Read/Glob; flag and env-var names via Grep; branch state via `git`. +- **PR and issue refs** — `gh pr view --json state,title,mergedAt`. The field is `mergedAt`, **not `merged`**: `gh` rejects an unknown field and fails the whole command, so one wrong name leaves every PR claim unverified rather than partly answered. A bare `#123` may be an issue, and `gh pr view` errors on an issue number — `gh issue view --json state,title` resolves both (GitHub treats PRs as issues), so reach for it when `pr view` refuses. +- **Scope every repo lookup to the project's own repo.** Pass `-R /` to `gh` and `-C ` to `git`, derived from the resolved repo — never rely on the invoking session's cwd. PR numbers collide across repositories, so an unscoped `gh pr view 3557` can confirm a claim against an entirely different project and report a false `CONFIRMED`. If you cannot determine the owner/repo for a memory, the claim is `NOT-CHECKABLE`, not confirmed. +- **Use MCPs when connected** — an issue-tracker MCP for ticket state, a warehouse or observability MCP for metric claims. This skill declares none of them, so whichever ones the session happens to have are best-effort: use them when present, and name them in the verdict when absent. +- **Require positive evidence for `STALE`.** A reverted PR, a deleted file, a removed flag, a closed-as-wontfix ticket, a superseding memory. "I could not find it" is `NOT-CHECKABLE`, not stale. +- **`NEEDS-` whenever *some* tool would settle it, and name that tool** in the verdict itself (`NEEDS-jira`, `NEEDS-datadog` — whatever the session would actually need). Metric claims need a warehouse or observability tool; ticket state needs the issue tracker; PR and branch state needs `gh`/`git`. Reserve `NOT-CHECKABLE` for what no tool could settle — a subjective judgment, a decision made in conversation, external state that is simply gone. Defaulting to `NOT-CHECKABLE` reads as "nothing can be done", so the user is never told which MCP to connect and the claim rots forever. +**Worked verdicts.** Match the claim to the closest row before reaching for a verdict of your own: + +| Claim | Verdict | Why | +|---|---|---| +| "the checkout endpoint serves ~40 req/s at p99 180ms" | `NEEDS-` | Telemetry would settle it. Not `NOT-CHECKABLE`: a named tool exists | +| "ABC-1234 tracks the fix" | `NEEDS-` | Ticket state is an issue-tracker lookup | +| "PR #3557 is still open" | `NEEDS-gh` if `gh` is absent, else check it | Scope with `-R owner/repo` | +| "the parser is at `lib/parse.rb`" | `CONFIRMED`/`STALE` via Read/Glob | Needs no MCP at all — check it | +| "we agreed Postgres was the wrong call" | `NOT-CHECKABLE` | No tool can settle a past conversation | +| "the repo has 120 migrations" with the repo absent | `NOT-CHECKABLE` | Nothing readable to count | + +A missing repo makes *that repo's* claims uncheckable. It does not make a telemetry or ticket claim uncheckable — those are settled by a different tool, so they stay `NEEDS-`. + +**You do not need to know which tracker to know a tracker would settle it.** An unfamiliar key like `ABC-1234` is still `NEEDS-` (name your best guess at the system) — never `NOT-CHECKABLE`. The user knows which system they use; your job is to say a lookup would answer it. Applying `NEEDS-` to the cost claim and `NOT-CHECKABLE` to the ticket claim in the same report is the specific inconsistency to avoid: both are external state a tool can read. + +- **Choose between the two tool verdicts with these questions, in order:** + 1. Is the tool I need listed among the tools I was given? **No → `NEEDS-`.** Stop. This is the usual case for MCPs, and it is a decision, not a hedge. + 2. It is listed — did I call it? **No → `NOT-ATTEMPTED`.** Yes → report what it returned. + + Naming the tool in your evidence text does not count; it has to be in the verdict. `NOT-ATTEMPTED` tells the orchestrator "it was available and I skipped it", so it offers a re-run that cannot possibly work, while `NEEDS-` tells the user which MCP to connect. Getting these backwards wastes the single action that would fix the claim. Never ask whether to attempt a tool you do not have — that hands back a question you can answer yourself. `NEEDS-` also covers unauthenticated and permission-denied; quote the error where there is one. +- **List every occurrence, including `description:` and the `MEMORY.md` line.** Before returning a `STALE` claim, grep the whole file for every other place the same fact is asserted, and put each exact string in `occurrences`. Two hide reliably: the frontmatter `description:`, and the file's one-line hook in `MEMORY.md`. Both are surfaced at recall time, so a stale one misleads every future session even after the body is fixed — scan them by name rather than trusting a body-only pass. +- **Quote occurrences in full — never elide.** No `…`, no `...`, no "[snip]". An abbreviated quote cannot be matched verbatim against the file, so it fails the validation below and cannot be reviewed by the user. A count or line-ref usually appears more than once; removing one instance and leaving the others makes the file self-contradictory, which is worse than leaving it uniformly stale. +- **Classify the file's archetype**: `LIVING` (open work, forward-looking), `JOURNAL` (history of finished work), `SNAPSHOT` (counts/metrics true only at capture time), `NOTE` (anything else). +- Never write, edit or delete anything. Subagents report only. diff --git a/plugins/claude-code-tools/skills/audit-memory/references/usefulness-pass.md b/plugins/claude-code-tools/skills/audit-memory/references/usefulness-pass.md new file mode 100644 index 0000000..019c829 --- /dev/null +++ b/plugins/claude-code-tools/skills/audit-memory/references/usefulness-pass.md @@ -0,0 +1,9 @@ +# Usefulness pass — the per-archetype offers + +Read this before running Step 4b. Correcting a stale number inside a `SNAPSHOT` only resets a timer — the same line will be wrong again next month. Fixing counts is the most expensive, most collateral-prone editing this skill does, and on a `SNAPSHOT` it buys nothing durable. So each file gets one of these offers instead: + +- **`SNAPSHOT`** → *replace the captured numbers with the query or command that regenerates them.* A memory holding "412 specs across 23 modules" should hold the `glob` that counts them instead. **Write the command out in full**, ready to run — `ls -d spec/*/*_spec.rb | wc -l`, the actual SQL, the actual `gh` invocation. Never a placeholder, a "this is stale" marker, or a bare archive-or-leave choice: a placeholder drops the information without replacing its value, which is worse than the stale number. If the repo is absent, still write your best command and label it unverified. +- **`JOURNAL`** → *compress to outcome.* A 1,700-word PR-by-PR history of finished work is worth two sentences: what shipped, and the one non-obvious thing worth remembering. +- Either → **archive whole**, but *only* after confirming the file holds **no forward-looking item** — no open decision, no pending step, nothing still blocked. Check before offering it, not at the diff stage. A file can be 95% finished history and still be the only record of one live question, and archiving it whole buries that where nobody will look for it. If you find one, offer *compress to the open item* instead. + +An approved compression is applied in Step 5 item 3, which keeps the file and rewrites `description` to match the new body.