/session-orchestrator:memory-cleanup [--dry-run | --apply-pending]from session-orchestrator
Manually consolidates and prunes Claude Code memory files under ~/.claude/projects/*/memory/. Use after major refactors, every 5+ sessions, or when memory quality degrades.
Ships in session-orchestrator. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
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'sskills/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.
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.
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:
MEMORY.md — index file (must stay under 200 lines; lines after 200 are truncated by the harness).name, description, metadata.type).The four memory types are user, feedback, project, reference (see global auto memory instructions for semantics). This skill never invents new types.
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. |
--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. |
Flags are mutually exclusive — passing both is an error. Absence of both = legacy interactive mode (Phases 1-4 below).
--dry-run flow:
applyPendingDream() in scripts/lib/auto-dream.mjs consumes ONLY the FIRST fenced code block in the sidecar body and writes it VERBATIM as the complete new MEMORY.md. It does NOT parse or apply git-style diff hunks. Therefore the proposal MUST ALWAYS be the complete new MEMORY.md body, in EXACTLY ONE fenced ```markdown block — never git-style unified-diff hunks (--- /+++ /@@ … @@ lines), and never multiple fences for MEMORY.md itself. Any topic-file (non-MEMORY.md) change needed by the plan CANNOT be carried inside that single fence — instead, append it AFTER the fence as a separate, clearly-delimited machine-readable section per topic file, using the heading ### Topic-file change: <path> followed by plain-language instruction text (not a diff). These sections are for a human to apply by hand; applyPendingDream() never reads past the first fence. If a ### Topic-file change: section needs to show illustrative code, use 4-space-indented code text, never a fenced ``` block — countFencedBlocks() counts every fence in the raw sidecar body (not just MEMORY.md's), so a second fence anywhere in the document trips the >1-fence unsupported-format guard and blocks the whole apply.writePendingDream({ repoRoot, diff, sourceSession, memoryLinesBefore, proposedLinesAfter }) from scripts/lib/auto-dream.mjs, passing the single-fence MEMORY.md body (plus any ### Topic-file change: sections) as diff.pending-dream written: <N> lines proposed (or no consolidation needed (MEMORY.md is healthy) when the plan is empty).--apply-pending flow:
applyPendingDream({ repoRoot, memoryDir }) from scripts/lib/auto-dream.mjs.applied: true → print auto-dream applied: -<linesBefore-linesAfter> lines, +<entries> consolidated entries and exit 0.applied: false, reason: 'missing' → print no pending dream to apply and exit 1.applied: false, reason: 'stale' → print pending dream is stale (>14d), re-run --dry-run and exit 1.applied: false, reason: 'stale-index' (#788) → print MEMORY.md changed since the producing --dry-run; re-run --dry-run. and exit 1. The sidecar is preserved and MEMORY.md is left untouched (MEMORY.md's mtime is newer than the sidecar's generated_at, so applying the frozen dry-run snapshot would clobber the interim edits).applied: false, reason: 'unsupported-format' → print auto-dream NOT applied: pending-dream.md contains git-style diff hunks this applier cannot consume. MEMORY.md left untouched, sidecar preserved. Re-run /memory-cleanup --dry-run to regenerate a complete-body proposal. and exit 1.stale / stale-index), missing sidecar, or unsupported-format never deletes anything.Both flag-driven flows delegate atomicity and staleness enforcement to scripts/lib/auto-dream.mjs. The interactive Phases 1-4 below remain unchanged.
Understand the current memory state before making changes.
List all files in the memory directory:
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).
Read MEMORY.md (the index file) — note its line count:
wc -l <memory-dir>/MEMORY.md
Skim each topic file referenced in the index. Build a mental map:
Goal: Improve existing files, never create duplicates.
Find what's changed since the last consolidation.
Git history — recent commits give the timeline for "did this fact change?":
git log --oneline -20
Stale references — for each file/function/symbol mentioned in memory, verify it still exists:
grep -rn "specific-file-or-function" src/ lib/ scripts/ 2>/dev/null
Relative dates — find temporal references that need conversion:
grep -rni "yesterday\|today\|tomorrow\|last week\|this week\|gestern\|heute\|morgen\|letzte woche" <memory-dir>/
Version drift — package versions stored in memory vs reality:
cat package.json | grep '"version"'
Test/issue-count drift — claims like "5001 passed" or "8 open issues" age fast. Cross-check with current state if mentioned.
Apply maintenance operations to memory files.
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:
If multiple files or entries describe the same thing, combine them into one authoritative entry. Update inbound [[wiki-link]]s accordingly.
"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.
git log --diff-filter=R surfaces renames).decisions.md-style note that the decision was reversed, with the reason — don't silently overwrite).If two memory entries conflict, check the codebase to determine which is current. Delete the outdated entry. Never leave contradictions.
Keep MEMORY.md clean and under the 200-line limit.
Check line count:
wc -l <memory-dir>/MEMORY.md
If over 180 lines, extract detailed content into topic files. Suggested naming:
project_sessions.md or session-YYYY-MM-DD-<slug>.mdreference_decisions.mdreference_packages.md{type}_{topic}.mdTopic file frontmatter (required):
---
name: descriptive-name
description: one-line description for relevance matching
metadata:
type: project # one of: user | feedback | project | reference
---
Update the index:
MEMORY.md is an index, not a dump.- [Title](file.md) — hook entries.Final verification:
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>
Skip if
persistence: falsein 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.
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 --porcelainon the blank-line delimiter; for eachworktreeentry, skip the main checkout, then require the basename to start with<repoName>-and the suffix to parse as asemanticsession-id viaparseSessionId()(UUID / random suffixes excluded). Each match yields{ wtPath, sessionId, branch }. Any git failure →[](conservative no-op). Git invocation is via the injection-safeopts.execFileFn(defaultexecFileSyncwith an args array — #577 HARDEN-001).
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 iffDate.now() - stat.mtimeMs > staleBranchDays × 24 × 60 × 60 × 1000. A missing or unreadable path →false(conservative no-op).
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.
}
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).`,
},
],
}],
});
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.
stale-branch-days config: scripts/lib/config.mjs:138 (default: 7)parseSessionId() from scripts/lib/session-id.mjslistAutoPromotedWorktrees() + isWorktreeStale() from scripts/lib/memory-cleanup/worktree-sweep.mjsdiscoverActiveSessions(repoRoot) from scripts/lib/session-discovery.mjs — flags stale candidates whose wtPath matches an active session so the AUQ warns before removal.claude/rules/parallel-sessions.mdAfter completing all four phases, report:
MEMORY.md line count (before → after).AskUserQuestion rather than guessing).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.
mode, never in whether you emit.events.jsonl. Route through emit-event.mjs → emitEvent(); hand-rolled appenders drift from the canonical record shape (the stop vs orchestrator.session.stopped divergence, #609).semantic_session_id is the semantic id (main-2026-08-17-session-1), not the UUID — sessions.jsonl session_id lives in that same space, and the matcher compares against it. Omitting the field is tolerated (the event is then claimed on the time window alone), but supplying it is what makes attribution exact when two sessions overlap.memory_cleanup_at already on the record WINS over derivation and is never overwritten. That path exists for backfills and tests, not for normal operation.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.
user, feedback, project, reference) is load-bearing for the relevance heuristic.MEMORY.md if line-count is already healthy. Re-ordering for its own sake creates churn without value.What SKILL.md sets; muted values are Claude Code's defaults
sonnetnpx claudepluginhub kanevry/session-orchestrator --plugin session-orchestrator55 skills in this plugin
/architectureUse when the user asks to improve architecture, find refactoring opportunities, surface deepening opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable. Surfaces shallow modules and hypothetical seams using a precise vocabulary (Module / Interface / Implementation / Depth / Seam / Adapter / Leverage / Locality from LANGUAGE.md)./autopilotUse this skill when running an autonomous session-orchestration loop. Chains session-start → session-plan → wave-executor → session-end for N iterations with all 10 kill-switches (SPIRAL, FAILED wave, carryover > 50%, max-hours, max-sessions, resource-overload, token-budget, stall-timeout, sub-threshold confidence, user-abort). Reads Mode-Selector output (Phase B) to decide auto-execute vs. fallback. Writes one autopilot.jsonl record per loop run. Phase C scaffold (issue #277); implementation lives in scripts/lib/autopilot.mjs (Phase C-1 follow-up).
/backlogOther plugins' skills for the same job