Files
claude_mac/skills/prune-memory/SKILL.md
T
bchanot 9045a60f11 fix(scripts): close the BUGS-FOUND script items, fail closed on bad reads
profile-state.jq sanitizes printed values and shape-checks plugin ids (no forged plugin: line); the digest prints open: none or unknown instead of nothing; push-guard deny_lost checks every pipe stage, T63 split into ask and deny lists; prune-memory mktemp guarded.
2026-11-13 22:59:50 +01:00

22 KiB

name, effort, description, argument-hint, allowed-tools
name effort description argument-hint allowed-tools
prune-memory medium Use when .claude/memory/ registries grow too large or noisy — superseded entries verbose, similar entries cluttering, journal stale, caveman style drifted. Curates the 5 registries via mark-superseded + merge + inline caveman compression. Append-only safe (no hard delete). Git is the backup. Triggers: "prune memory", "compact memory", "clean memory", "memory hygiene", "trier memoire", "nettoyer memoire", "registres trop longs", "compresse les memoires".
optional
decisions|learnings|blockers|journal|evals — default all 5
Read
Edit
Write
Bash
Grep
Glob
AskUserQuestion

/prune-memory — Memory registry curation

Operates on .claude/memory/ in the current project (CWD). Curates the 5 registries: decisions.md, learnings.md, blockers.md, journal.md, evals.md.

Core principles

  • Git is the backup. Skill writes in-place. PRECHECK refuses to run if working tree dirty on registry files.
  • Append-only friendly. Marks entries with a superseded by <ID> or deprecated status written by memory.sh status instead of deleting. Body of old entry stays for history.
  • IDs stable. Never renumber. Merges create a new ID; sources keep their ID with superseded status.
  • Caveman style enforced. Per CLAUDE.md memory rule, all writes are caveman-style English. Compression rewrites prose to fragments.
  • User approves every category. No silent changes.

Quick reference

When Use
Add new entry this session /close
Curate: obsolete + merge + caveman /prune-memory (this skill)

STEP 0 — PRECHECK

test -d .claude/memory/ || { echo "no .claude/memory/ in $(pwd)"; exit 1; }
# RED-2 guard: a dirty tree is a HARD stop, enforced in-band (not a prose
# "STOP"). Git is the only backup; refuse to write over uncommitted state.
if [ -n "$(git status --short .claude/memory/ 2>/dev/null)" ]; then
  git status --short .claude/memory/
  echo "DIRTY: commit or stash .claude/memory/ first. Git is the only backup."
  exit 1
fi

If working tree is dirty on any registry file → STOP with: "Commit or stash pending changes in .claude/memory/ first. Skill writes in-place. Git is the only backup."

STEP 0b — Gitflow aiguillage (after PRECHECK, before any write)

PRECHECK first (clean tree = the backup). Then follow $HOME/.claude/lib/gitflow-aiguillage.md — this skill's TYPE = chore. On main/develop it branches to chore/<name> off develop so the curation lands on a branch; on a working branch it proceeds in place. Never gitflow finish.

STEP 1 — AUDIT (per registry)

For each target registry (filter by $ARGUMENTS or all 5):

Current statuses come from one reader for decisions and blockers, run once:

# Current statuses: one reader for decisions and blockers (BDR-129:
# strict word on v2, one status word on v1, never the ## Index, never a
# word in prose). Rows: ID<TAB>open<TAB>word | ID<TAB>unreadable<TAB>line;
# closed entries (resolved, superseded, deprecated) are omitted.
for k in decisions:BDR blockers:BLK; do
  f=".claude/memory/${k%%:*}.md"
  [ -f "$f" ] || { echo "== $f: no-file"; continue; }
  echo "== $f"
  ( . "$HOME/.claude/lib/reconcile.sh" \
      && reconcile_status_classify "$f" "${k#*:}" ) \
    || echo "== $f: reader-unavailable"
done

These rows are the ONLY status source of STEP 1.A: a status word in an entry's prose or title is never a status. With a $ARGUMENTS filter, use only the rows of the filtered registries. reader-unavailable → no status-based candidate for that registry this run (say so in STEP 2). unreadable rows → the [Status unreadable] count line (STEP 2), never an A candidate.

Read file. Classify candidates into A/B/C/D below. Use today's date for age comparisons. Today's date is in the system context.

A. Obsolete — mark-superseded candidates

  • Decisions whose word is proposed and whose date is older than 90 days → propose memory.sh status <ID> "deprecated, no follow-up after 90 days". Date = the newer of the memory.sh index decision Date cell and the date of the entry's last - **Status (YYYY-MM-DD)**: line; no date → not a candidate (v1 dialect dates such as | date | headings or date: … · lines give none).
  • Decisions whose body names a successor ("superseded by ", "Supersedes [[]]" on the newer one) but whose word is still accepted → propose memory.sh status <ID> "superseded by <that-ID>".
  • Blockers whose word is exactly open (never upstream, accepted or any other word) whose root cause matches a commit in last 30 days (grep git log --since=30.days --grep=<keyword>) → propose memory.sh status <ID> "resolved <commit>".
  • Journal entries older than 180 days with zero cross-reference from later entries → propose collapse into 1-line month summary (## YYYY-MM heading replaces detail). SAFETY-CRITICAL EXCEPTION (deterministic): an entry whose body holds an operational permanent rule is INTOUCHABLE — never collapse, summarize, or reword it, regardless of age or cross-reference. Trigger: any line with NEVER/ALWAYS/PERMANENT, or a negation + imperative (must not, do not, never deploy…). The detail IS the value; keep it verbatim.

B. Similar — merge candidates

  • Two+ entries sharing root keyword in title (e.g. pandoc, client-handover, CSS overlay).
  • Shared file paths in **Reference**: lines.
  • Same week + adjacent IDs + same domain.
  • Use semantic judgment on overlap; don't merge complementary entries that cover different angles of one concept.

C. Bloated — inline caveman-rewrite candidates

  • Body > 150 words AND prose-heavy.
  • Detect filler density: count \b(the|a|an|just|really|basically|actually|simply)\b matches; if > 5% of word count → bloated.

D. Feedback — noisy and promotion (phase 4d.4)

The recall feedback gate (/memory-feedback) writes ~/.claude/memory-feedback/FEEDBACK.md. Its Noisy: and Promotion candidates: lines list <repo tag> <ID> items; this run reads the ones of the current repo only. The cutoffs live in lib/memory-feedback/thresholds.ts (T.noisyHits, T.promoteHits, T.promoteSessions): cite them, never restate a number.

# Feedback rows for THIS repo. Rows: tag<TAB>T, date<TAB>D, noisy<TAB>ID,
# promote<TAB>ID, other<TAB>tag; or one word: no-git-root, no-feedback-run.
# The tag is the reader's (lib/memory-feedback/labels.ts tagOf).
fb="$HOME/.claude/memory-feedback/FEEDBACK.md"
root=$(git rev-parse --show-toplevel 2>/dev/null) \
  || { echo "no-git-root"; exit 0; }
sum=$(printf '%s' "$root" | { sha1sum 2>/dev/null || shasum -a 1; } \
  | cut -c1-6)
tag="$(basename "$root")#$sum"
[ -f "$fb" ] || { echo "no-feedback-run"; exit 0; }
printf 'tag\t%s\n' "$tag"
printf 'date\t%s\n' "$(sed -n '1s/^.*(\([^)]*\)).*$/\1/p' "$fb")"
items() {  # $1 = line prefix -> one "<tag> <ID>" item per line
  sed -n "s/^$1: //p" "$fb" | tr -d '\r' | awk '{ n = split($0, a, ", ")
    for (i = 1; i <= n; i++) if (a[i] != "none") print a[i] }'
}
rows() {  # $1 = line prefix, $2 = row kind
  items "$1" | while IFS= read -r it; do
    id=${it##* }
    case "$it" in
      "$tag "*) [[ $id =~ ^(BDR|LRN|BLK)-[0-9]+$ ]] || continue
                printf '%s\t%s\n' "$2" "$id" ;;
      *) printf 'other\t%s\n' "${it% *}" ;;
    esac
  done
}
promoted() {  # $1 = ID: rc 0 when its entry holds a "promoted to" line
  awk -v id="$1" '$0 ~ "^## " id "( |$)" { e = 1; next }
    /^## / { e = 0 }
    e && /^- \*\*Status \(.*promoted to/ { f = 1 }
    END { exit !f }' "$root"/.claude/memory/*.md 2>/dev/null
}
noisy_done() {  # $1 = ID: rc 0 when a curation commit rewrote it
  [ -n "$(git -C "$root" log -E --format=%s \
    --grep="noisy-rewrite $1([^0-9]|\$)" -- .claude/memory 2>/dev/null)" ]
}
{ rows Noisy noisy; rows 'Promotion candidates' promote; } |
  while IFS=$'\t' read -r kind id; do
    case "$kind" in
      noisy) noisy_done "$id" || printf 'noisy\t%s\n' "$id" ;;
      promote) promoted "$id" || printf 'promote\t%s\n' "$id" ;;
      *) printf 'other\t%s\n' "$id" ;;
    esac
  done | awk '!seen[$0]++'

Rules: the lines are matched anchored and case-sensitive (Noisy: , Promotion candidates: ), the literal none is skipped, the Actions section is never parsed. An item is <tag> <ID>, the ID being its last field; a , inside a repo basename would split an item (accepted limit). other rows name tags of other repos, for visibility only. A promote row is dropped once its entry holds a promoted to status line; a noisy row is dropped once a curation commit subject carries noisy-rewrite <ID> (STEP 3 item 4 names it). With a $ARGUMENTS filter, keep the rows whose ID prefix belongs to a filtered registry.

  • A noisy row → candidate: inline rewrite of the title and of the lesson sentence, narrowed to the concrete trigger so BM25 and the rerank stop picking it for unrelated prompts. The lesson sentence is the one the recall line shows: the first sentence (up to 280 characters) of the first labelled field, in the order BDR Decision; LRN Apply, Future application, Pattern; BLK Solution, Real cause. A title or sentence under the NEGATION GUARD (STEP 3.3) is skipped and reported as a manual rewrite. Limit: the tool matcher reads the backtick spans of the body, which this rewrite leaves alone.
  • A promote row → a BDR-100 proposal: name the mechanism (rule line, hook, guard, test) in STEP 2; the user decides.
  • no-feedback-run → one line in STEP 2. No noisy/promote row (only tag, date, other) → the none for <tag> line.

STEP 2 — PRESENT PLAN ★ MANDATORY STOP

Print one block per registry. Example:

PRUNE PLAN — decisions.md (N entries → M after if approved)
(IDs below are FICTIONAL — 9xx range, never a live registry entry — so this
 worked example cannot PRIME a real prune. Apply the same shapes to real IDs.)

[A. Obsolete — mark superseded]
  BDR-901 — example proposed decision — word proposed, dated <90+ days ago>
            → memory.sh status BDR-901 "deprecated, no follow-up after 90 days"
  BDR-902 — example decision — body says superseded by BDR-903
            → memory.sh status BDR-902 "superseded by BDR-903"

[B. Similar — merge]
  LRN-901 + LRN-902 — SAME concept (two notes on the identical bug)
            → propose: merge into NEW LRN-904 (learnings carry no status) with
              both bodies appended + caveman pass; sources:
              memory.sh status <ID> "superseded by LRN-904"
            (merge ONLY same-concept entries — complementary/different-angle stays split)

[C. Bloated — inline caveman rewrite]
  BDR-902 — body 612 words, filler density 7.2% → ~380 expected (-38%)

[Status unreadable — info only, never applied, not part of "all"]
  decisions.md: 3 (BDR-905, BDR-906, BDR-907)
  → you give the word per ID: memory.sh status <ID> "<word>"

[D. Feedback — noisy rewrite / promotion]  (run-level, repo <tag>, <date>)
  LRN-905 — noisy: picked for unrelated prompts
            → inline rewrite: title + lesson narrowed to the concrete
              trigger, "<narrowed title>" / "<narrowed lesson sentence>"
  LRN-906 — promotion candidate (a mechanism, not a note)
            → mechanism: <rule line | hook | guard | test>, a separate /feat
            → on accept: memory.sh status LRN-906 "<current word>, promoted
              to <mechanism>" (implemented when the entry has no word)

Approve per category? (all / a / b / c / d / edit <ID> / skip)

D is one run-level block after the per-registry ones. No feedback file prints [D. Feedback] no feedback run (~/.claude/memory-feedback/FEEDBACK.md absent); no row for this repo prints [D. Feedback] none for <tag>; no-git-root prints [D. Feedback] not in a git repo.

A [B] merge of decisions, blockers or evals names the merged entry's status word on its line (default: the sources' common word; sources differ → ask in edit <ID>). The count line folds IDs (first 10, then +N more); the word always comes from the user, never from the entry text. On a v1 file the status text carries one status word only (else it stays unreadable). A row heading level needs its heading fixed to ## ID first (memory.sh status cannot reach it).

Wait for user input. Default = nothing applied.

STEP 3 — APPLY APPROVED CHANGES

Order: safe → destructive. Registry writes follow lib/capitalize-commit.md § WRITE (single writer).

  1. Status flag updates — bash "$HOME/.claude/lib/memory.sh" status <ID> "<word> …" appends a dated status line (text starts with a status word: deprecated, no follow-up after 90 days); the body above stays verbatim.
  2. Merges — write the merged body to a scratch file, then bash "$HOME/.claude/lib/memory.sh" add <kind> --title "<title>" --body-file <file> --supersedes <first source> (next-free ID, forward link, the first source marked superseded); each other source: memory.sh status <ID> "superseded by <new-ID>". Source bodies stay verbatim for history. A STATUS LINE is any line of the entry that holds (case-insensitive) status, statut, resolved, reverted, upstream, superseded, deprecated or the word open, or a - **<label>**: line whose label holds status/resolution/action/ update/final. Add --status <word> (decisions, blockers, evals; the word shown on the [B] line; learnings none). Merged body:
    • Preserves all **Reference**: lines (dedupe identical paths).
    • Caveman pass on prose during merge.
    • Drops the sources' labelled status lines (- **Status…**:, Status: / statut lines, - **Resolution|Action|Update|Final…**:). The new entry's status is the --status word (v2: heading tag; v1: a - **Status**: body line, and a later prose STATUS LINE can make it unreadable: it then shows in the count line).
    • memory.sh add writes the heading (new ID, title, date) and the status; the body keeps the union of **Reference**: lines.
  3. Inline caveman compression — keep VERBATIM the heading line, every - **Label**: key and every STATUS LINE; rewrite only the other prose to fragments:
    • NEGATION GUARD (deterministic, overrides every rule below): never rewrite a sentence containing a negation token (not, never, no, cannot, or any *n't contraction). Keep such sentences VERBATIM — dropping a filler next to a not/never can silently invert meaning. Compression touches negation-free sentences only.
    • Drop articles (a, an, the) — negation-free sentences only.
    • Drop filler (just, really, basically, actually, simply) — negation-free sentences only.
    • Short synonyms (big not extensive, fix not implement a solution for).
    • Keep code blocks, URLs, error messages, file paths VERBATIM.
    • Keep IDs (BDR-XXX, LRN-XXX, commit hashes) verbatim.
  4. Feedback (D) — a noisy rewrite changes only the title TEXT (the ## <ID> — , the [status] tag and the (date) stay verbatim) and the one lesson sentence of STEP 1.D, under the same NEGATION GUARD as item 3; it is an inline edit under the curation commit, never a status line. A promotion is one line: bash "$HOME/.claude/lib/memory.sh" status <ID> "<current word>, promoted to <mechanism>", the current word from memory.sh index <kind> (implemented when none is readable), so a closed entry stays closed. The mechanism itself is a separate /feat, named in the final report.

STEP 4 — VERIFY

# Structure: heading shape + unique IDs + no open fence (v2 registries; a
# v1 one is named and skipped). Same verify the writer runs after every add.
bash "$HOME/.claude/lib/memory.sh" check .claude/memory \
  || echo "CHECK FAILED: fix the lines above before certifying"

# RED-5 fidelity guard (count-based, per-entry x per-category). STEP 0 ensured
# a clean tree, so git HEAD is the pre-prune backup. Fails the run if any
# negation/permanent token COUNT drops within an entry vs HEAD -- immune to the
# line-sharing false positives a removed-line grep produces. The STEP 3.3
# NEGATION GUARD keeps negation sentences verbatim; this proves none slipped.
# Journal entries are date-keyed and legitimately collapse, so the journal is
# restricted to {never,always,permanent} -- the markers the STEP 1.A safety
# exception protects from collapse (keys stay stable; casual not/no in a benign
# collapsed entry is not a loss). Contraction *n't is covered upstream by A.
census() {  # reads a registry file on stdin -> "KEY:CAT<TAB>COUNT" per entry
  awk '
    /^## /{ id=$2 }
    { L=tolower($0); gsub(/[^a-z]+/," ",L); n=split(L,w," ")
      for(i=1;i<=n;i++){ c=w[i]
        if(c=="never")          a[id":never"]++
        else if(c=="always")    a[id":always"]++
        else if(c=="permanent") a[id":perm"]++
        else if(c=="cannot")    a[id":cannot"]++
        else if(c=="not")       a[id":not"]++
        else if(c=="no")        a[id":no"]++ } }
    END{ for(k in a) if(a[k]>0) print k"\t"a[k] }'
}
fidelity_check() {  # $1 = registry basename; returns 1 (and prints) on a drop
  local fname="$1" f=".claude/memory/$1.md" cats drop
  [ -f "$f" ] || return 0
  git diff --quiet -- "$f" 2>/dev/null && return 0
  if [ "$fname" = journal ]; then cats='never|always|perm'
  else cats='never|always|perm|cannot|not|no'; fi
  # Tag working "W" / HEAD "H" explicitly -- NOT NR==FNR, which misclassifies
  # when the working census is empty (a fully-deleted safety entry = the case
  # we most need to catch).
  drop=$( { census < "$f"             | awk '{print "W\t"$0}'
            git show HEAD:"$f" | census | awk '{print "H\t"$0}'
          } | awk -F'\t' -v cats="^($cats)\$" '
        $1=="W" { w[$2]=$3; next }
        { n=split($2,p,":"); if (p[n] !~ cats) next
          if ((w[$2]+0) < $3) print "  "$2" (HEAD="$3" now="(w[$2]+0)")" }')
  if [ -n "$drop" ]; then
    echo "FIDELITY FAIL ($f): a negation/permanent token dropped within an entry:"
    printf '%s\n' "$drop"; return 1
  fi
  return 0
}
FIDFAIL=0
for fname in decisions learnings blockers journal evals; do
  fidelity_check "$fname" || FIDFAIL=1
done
[ "$FIDFAIL" = 1 ] && echo "Do NOT certify this run. Revert with: git checkout .claude/memory/"
echo "(blank above = OK)"

wc -l .claude/memory/*.md | grep -v "\.original\.md"

Report:

PRUNE COMPLETE
  decisions.md : 226 → 184 lines (-19%)
  learnings.md : 190 → 165 lines (-13%)
  blockers.md  : no candidates
  journal.md   :  88 → 62 lines (-30%)
  evals.md     : no candidates

CHECK: OK
NEXT: review `git diff .claude/memory/`, then `/commit-change`

After a noisy rewrite (D), the report also prints the exact commit subject chore(memory): noisy-rewrite <ID>[, <ID>…] and says /commit-change keeps it verbatim: STEP 1.D finds the rewrite again through that token. After a promotion it names the mechanism to build as a separate /feat.

What NOT to prune

  • Journal entries < 30 days old.
  • Decisions / learnings with commit references < 14 days old.
  • Entries whose status the user set this session.
  • The current session's just-capitalized entries (read journal.md tail to identify them).

Common mistakes

Mistake Fix
Renumbering IDs after a merge IDs are stable. Sources keep their ID + a superseded by <ID> status. New merged entry gets next-free ID.
Hard-deleting "obsolete" entries Forbidden by append-only rule. Use a deprecated status (memory.sh status). Body stays.
Compressing code blocks / URLs / error messages Caveman compression touches PROSE only. Code, URLs, IDs, error quotes stay verbatim.
Running on a dirty working tree PRECHECK blocks this. Commit first.
Compressing the current session's journal entry Excluded by "What NOT to prune" — current session capitalization is still useful.
Merging complementary entries that cover different angles Merge only when same concept, same scope. Different angles = keep separate.

Failure paths

Situation Behavior
.claude/memory/ missing STOP: no .claude/memory/ in current directory; run from project root
Working tree dirty on registry files STOP per PRECHECK; tell user to commit/stash first
User says skip at STEP 2 Exit cleanly, no writes
Merge produces an entry > 600 words Re-split — merge was too greedy. Re-prompt user to keep separate.
memory.sh check FAILED at STEP 4 Print its culprit lines. Do NOT auto-fix — user re-runs or hand-edits.
Caveman compression result < 20% of original AND original had code blocks Revert that entry's compression — flag as needing manual rewrite (likely stripped technical detail).
Same file already compressed in same session Skip C-category for that file; warn user that double-pass risks technical drift.

Rules

  • No silent writes — every change goes through STEP 2 approval gate.
  • No renumbering — IDs are stable across all operations.
  • No hard delete in v1 — only mark superseded. (Hard delete opt-in may arrive in v2 if explicit demand surfaces.)
  • Working tree must be clean before any write — git is the only backup.
  • Caveman compression touches prose only; code/URLs/error quotes verbatim per CLAUDE.md memory format rule.

TDD note (skill itself)

Baseline RED scenarios were run and their counters are embedded: the RED-2/RED-5/RED-6 guards live in the body above, and tests/ holds the fixtures (red3-negation, red4-journal, red6-check) plus run-deterministic.sh and run-behavioral.md. New rationalizations a subagent finds → add the fixture and its counter to the "Common mistakes" / "Failure paths" tables (tests/BACKLOG.md tracks candidates). STEP 2's approval gate remains the human safety net regardless.