Memory cleanup

From Kanevry/session-orchestrator · View interactive version

Memory cleanup is an AI agent skill from the GitHub repository Kanevry/session-orchestrator. Use this skill when performing manual memory consolidation (Dream-equivalent). Reviews, consolidates, and prunes memory files under ~/.claude/projects/*/memory/. Run after major refactors, every 5+ sessions, or when memory quality degrades (broken links, stale references, contradictions, MEMORY.md >

How to use this skill

Skill file

Memory Cleanup — Manual Dream Process

Plugin root: ${CLAUDE_PLUGIN_ROOT}. Claude Code replaces this with the plugin's absolute path when it loads this file. Where it appears unreplaced — in a file this skill reads with the Read tool, or on Codex, Cursor or Pi — the plugin root is the directory that contains this skill's skills/ folder (two levels above the folder of this SKILL.md). Write that absolute path literally into every command that starts a plugin script: the Bash tool has no plugin variable, and shell variables do not survive between tool calls.

Invocation

The user invoked /memory-cleanup with arguments: $ARGUMENTS. Parse them before anything else — two optional, mutually-exclusive flags are recognised (--dry-run, --apply-pending, see PRD #502); passing both is an error, and the absence of both selects the legacy interactive 4-phase mode. The per-flag behaviour, the exact status lines and the exit codes are in § Argument Handling (Phase 0) below; the interactive default runs Phases 1-4 (Orient → Gather Signal → Consolidate → Prune & Index) against ~/.claude/projects/<encoded-cwd>/memory/ and reports per § Output.

Sidecar producer/consumer contract: session-start's maintenance-due probe uses scripts/lib/auto-dream.mjs to report when cleanup is due; the former session-end Phase 3.6.5 nudge was retired in #1288. Neither path generates the sidecar. The only real producer of .orchestrator/pending-dream.md is a manual /memory-cleanup --dry-run run; --apply-pending is the operator-confirmed consumer in a later session. The sidecar file is single-writer — concurrent sessions cannot collide because the writer holds the session-lock. <!-- path-check: example -->

Implements the 4-phase memory consolidation process modelled after Claude Code's Auto Dream feature. Run after major refactors, framework migrations, or every 5+ sessions in a repo.

The memory system lives at ~/.claude/projects/<encoded-cwd>/memory/ and consists of:

The four memory types are user, feedback, project, reference (see global auto memory instructions for semantics). This skill never invents new types.

Argument Handling (Phase 0)

This skill accepts two optional flags. Default (no flag) runs the interactive 4-phase consolidation defined below.

| Flag | Behavior |

|---|---|

| --dry-run | Run Phases 1-3 read-only; instead of mutating MEMORY.md / topic files, write a complete-body MEMORY.md proposal (single fenced block — never a unified-diff) to .orchestrator/pending-dream.md (atomic). Exit 0. <!-- path-check: example --> |

| --apply-pending | Read .orchestrator/pending-dream.md; refuse if older than 14 days (stale) or if MEMORY.md changed since the producing --dry-run (stale-index, #788); apply diff; delete pending file; print auto-dream applied: -<X> lines, +<Y> entries. Exit 0. <!-- path-check: example --> |

Flags are mutually exclusive — passing both is an error. Absence of both = legacy interactive mode (Phases 1-4 below).

--dry-run flow:

--apply-pending flow:

Both flag-driven flows delegate atomicity and staleness enforcement to scripts/lib/auto-dream.mjs. The interactive Phases 1-4 below remain unchanged.

Phase 1: Orient

Understand the current memory state before making changes.

  1. List all files in the memory directory:

```bash

ls -la ~/.claude/projects/*/memory/ 2>/dev/null | grep "$(basename "$(pwd)")"

```

Or directly list the project's memory dir (the path is in the auto memory system instructions).

  1. Read MEMORY.md (the index file) — note its line count:

```bash

wc -l <memory-dir>/MEMORY.md

```

  1. Skim each topic file referenced in the index. Build a mental map:

Goal: Improve existing files, never create duplicates.

Phase 2: Gather Signal

Find what's changed since the last consolidation.

  1. Git history — recent commits give the timeline for "did this fact change?":

```bash

git log --oneline -20

```

  1. Stale references — for each file/function/symbol mentioned in memory, verify it still exists:

```bash

grep -rn "specific-file-or-function" src/ lib/ scripts/ 2>/dev/null

```

  1. Relative dates — find temporal references that need conversion:

```bash

grep -rni "yesterday\|today\|tomorrow\|last week\|this week\|gestern\|heute\|morgen\|letzte woche" <memory-dir>/

```

  1. Version drift — package versions stored in memory vs reality:

```bash

cat package.json | grep '"version"'

```

  1. Test/issue-count drift — claims like "5001 passed" or "8 open issues" age fast. Cross-check with current state if mentioned.

Phase 3: Consolidate

Apply maintenance operations to memory files.

3·0: Find dead index links first (#1801)

Before rewriting anything, list every MEMORY.md link whose target file is missing (the BROKEN: check from Phase 4 step 5, run now). It calls listDeadIndexLinks(), the same definition behind the session-start count memory: <N> tote Index-Links. Per dead link:

3a: Merge overlapping entries

If multiple files or entries describe the same thing, combine them into one authoritative entry. Update inbound [[wiki-link]]s accordingly.

3b: Convert relative dates to absolute

"Yesterday we decided X" → "On 2026-03-24 we decided X". Always use ISO date format (YYYY-MM-DD). This rule applies on write, but cleanup catches what slipped through.

3c: Remove stale references

3d: Update outdated facts

3e: Resolve contradictions

If two memory entries conflict, check the codebase to determine which is current. Delete the outdated entry. Never leave contradictions.

Phase 4: Prune & Index

Keep MEMORY.md clean and under the 200-line limit.

  1. Check line count:

```bash

wc -l <memory-dir>/MEMORY.md

```

  1. If over 180 lines, extract detailed content into topic files. Suggested naming:
  1. Topic file frontmatter (required):

```yaml


name: descriptive-name

description: one-line description for relevance matching

metadata:

type: project # one of: user | feedback | project | reference


```

  1. Update the index:
  1. Final verification:

```bash

wc -l <memory-dir>/MEMORY.md # must be < 200

# dead index links (the session-start definition) — must print nothing; throws without MEMORY.md

node --input-type=module -e "const { listDeadIndexLinks } = await import('${CLAUDE_PLUGIN_ROOT}/scripts/lib/auto-dream.mjs'); const d = listDeadIndexLinks(process.argv[1]); if (!d) throw new Error('no MEMORY.md'); for (const t of d) console.log('BROKEN: ' + t);" <memory-dir>

```

Phase 4.5: Worktree-Stale-Sweep (#575 P3.2)

Skip if persistence: false in Session Config. Silent no-op if no Auto-promoted sibling worktrees exist or none are stale.

Detect stale Auto-promoted worktrees (older than stale-branch-days from Session Config, default 7 days) and offer them for batch-removal alongside the other housekeeping prune actions from Phase 4. This sub-phase is additive — it appends candidates to the existing prune flow rather than introducing a separate independent confirmation cycle.

Detection: list candidate auto-promoted worktrees

Auto-promoted worktrees follow the layout <parentDir>/<repoName>-<sessionId>/, where <sessionId> is a semantic session-id (per parseSessionId() from scripts/lib/session-id.mjs). Random-suffix worktrees (UUID-format) are NOT auto-promoted and MUST be ignored.

Authoritative impl: scripts/lib/memory-cleanup/worktree-sweep.mjs — listAutoPromotedWorktrees(repoRoot, mainCheckoutRoot, opts). Import and call; do NOT re-implement from this doc.

Algorithm: split git worktree list --porcelain on the blank-line delimiter; for each worktree entry, skip the main checkout, then require the basename to start with <repoName>- and the suffix to parse as a semantic session-id via parseSessionId() (UUID / random suffixes excluded). Each match yields { wtPath, sessionId, branch }. Any git failure → [] (conservative no-op). Git invocation is via the injection-safe opts.execFileFn (default execFileSync with an args array — #577 HARDEN-001).

Staleness check

A worktree is stale iff mtime(worktree-dir) < now - stale-branch-days × 86400 × 1000. Read stale-branch-days from Session Config (default 7):

Authoritative impl: scripts/lib/memory-cleanup/worktree-sweep.mjs — isWorktreeStale(wtPath, staleBranchDays). Import and call; do NOT re-implement from this doc.

Algorithm: statSync(wtPath); stale iff Date.now() - stat.mtimeMs > staleBranchDays × 24 × 60 × 60 × 1000. A missing or unreadable path → false (conservative no-op).

Integration with the existing housekeeping prune AUQ

After Phase 4 (Prune & Index) compiles its list of items to offer for removal, ALSO include any stale auto-promoted worktrees. The user sees them in the same AUQ ("batch-decide" per PRD §3 P3 Gherkin row 4):

import { execFileSync } from '${CLAUDE_PLUGIN_ROOT}/scripts/lib/native-command.mjs';
import { listAutoPromotedWorktrees, isWorktreeStale } from '${CLAUDE_PLUGIN_ROOT}/scripts/lib/memory-cleanup/worktree-sweep.mjs';
import { discoverActiveSessions } from '${CLAUDE_PLUGIN_ROOT}/scripts/lib/session-discovery.mjs';

const staleBranchDays = $CONFIG['stale-branch-days'] ?? 7;
const candidates = listAutoPromotedWorktrees(process.cwd(), mainCheckoutRoot);
const stale = candidates.filter((c) => isWorktreeStale(c.wtPath, staleBranchDays));

if (stale.length === 0) {
  // Silent no-op — no stale worktrees to offer.
} else {
  // #580-HARDEN-002: cross-check candidates against LIVE peer sessions before offering removal.
  // A stale-by-mtime worktree may still be the checkout of an active parallel session — removing
  // it would disrupt that session (PSA-002 overlap). Flag any such candidate so the AUQ can warn.
  const active = await discoverActiveSessions(mainCheckoutRoot);
  const livePaths = new Set(active.map((s) => s.worktreePath));
  const annotated = stale.map((wt) => ({ ...wt, activePeer: livePaths.has(wt.wtPath) }));

  // Add to the existing housekeeping prune AUQ. Each stale worktree becomes one option line:
  // Format: `[ ] Stale auto-promoted worktree: <basename> (age <N>d) — the operator removes it via 'git worktree remove --force' in their own terminal`
  // If `activePeer` is true, prefix the option with "⚠ ACTIVE PEER SESSION" and make Behalten the default.
  //
  // If memory-cleanup currently presents per-item AUQs (one question per prune candidate),
  // append one question per stale worktree.
  //
  // If memory-cleanup uses a single multiSelect AUQ for the whole batch,
  // add stale worktrees as additional options.
  //
  // Operator selects which to remove; coordinator runs (arg-array, no shell — #577 HARDEN-001):
  //   execFileSync('git', ['-C', mainCheckoutRoot, 'worktree', 'remove', '--force', wtPath])
  // for each selected. WARN line per removal.
}

AUQ example (per-item)

When the candidate's wtPath matches a LIVE peer session (wt.activePeer === true, from discoverActiveSessions() above), the AUQ MUST surface a ⚠ ACTIVE PEER SESSION warning and keep Behalten as the safe default — removing a live session's worktree mid-flight is a PSA-002 overlap that can corrupt another session's working state.

const peerWarning = wt.activePeer
  ? ' ⚠ ACTIVE PEER SESSION — removing may disrupt a live session.'
  : '';

AskUserQuestion({
  questions: [{
    question: `Auto-promoted worktree ${path.basename(wt.wtPath)} is ${ageDays}d old (branch ${wt.branch}).${peerWarning} Remove?`,
    header: "Worktree",
    multiSelect: false,
    options: [
      {
        label: "Behalten (Recommended)",
        description: wt.activePeer
          ? "Keep this worktree — a LIVE peer session is using it. Removal would disrupt the active session."
          : "Keep this worktree. Re-evaluate at next /memory-cleanup run.",
      },
      {
        label: "Entfernen",
        description: wt.activePeer
          ? `⚠ ACTIVE PEER SESSION detected. Only choose this if you have confirmed no live session needs it, then run 'git worktree remove --force ${wt.wtPath}' in your own terminal (the agent may not: #1789).`
          : `Run 'git worktree remove --force ${wt.wtPath}' in your own terminal (the agent may not: #1789).`,
      },
    ],
  }],
});

PSA-003 compliance

Per .claude/rules/parallel-sessions.md PSA-003: every git worktree remove is destructive — operator must explicitly authorize. The AUQ above satisfies this. Never auto-remove without user confirmation, even for stale worktrees. The --force removal is the OPERATOR's, run in their own terminal after the AUQ consent: the destructive guard (worktree-remove-unsafe, #1789) denies every forced git worktree remove from an agent. After "Entfernen", print the exact command for each selected worktree; never offer it for worktrees the operator did not select.

Cross-references

Output

After completing all four phases, report:

Session-End Signal: "cleanup ran this session" (#699)

A completed cleanup — including a healthy no-op where MEMORY.md was already healthy and no files were mutated — counts as a cleanup run. The session-end skill MUST stamp memory_cleanup_at on the session record whenever /memory-cleanup ran in THIS session, regardless of outcome (dry-run, apply-pending, or no-op).

This advances the auto-dream cadence marker (readDreamSignals → lastCleanupAt in scripts/lib/auto-dream.mjs) so shouldDispatchAutoDream does not fire a false nudge on the next session.

Signalling contract — emit the event, do not rely on remembering.

As the LAST step of every completed run — dry-run, apply-pending, or healthy no-op alike — emit the completion event. This is mandatory and it is the whole mechanism; there is no second, prose-only path that also works:

node "${CLAUDE_PLUGIN_ROOT}/scripts/emit-event.mjs" \
  --type orchestrator.memory.cleanup_completed \
  --payload "{\"semantic_session_id\":\"<the session: value from STATE.md frontmatter>\",\"mode\":\"<dry-run|apply-pending|no-op>\"}"

scripts/emit-session.mjs then DERIVES memory_cleanup_at from that event at session-close time via deriveMemoryCleanupSignal() (scripts/lib/memory-cleanup-stamp.mjs), matching events whose timestamp falls inside the session's own [started_at, completed_at] window. Nothing downstream depends on the coordinator recalling that a cleanup happened.

Why this is mechanical and not a prose instruction: it used to be one. On 2026-08-14 a /memory-cleanup ran and produced a documented yield, the coordinator did not execute the prose step, and all three session records of that day carried memory_cleanup_at: null — so the session-start banner reported "last cleanup 29 days ago" while the operator's own notes said 3. stampMemoryCleanup() had zero production callers at the time; every reference to it was an instruction asking an LLM to remember. Same failure class as the STATE.md write-race that Epic #583 replaced with a lock: Disziplin statt Mechanik.

Anti-Patterns

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.