brewdoc:memory
Optimizes Claude Code memory in 4 interactive steps - removes duplicates, migrates to rules/CLAUDE.md, compresses, validates with cleanup
What this skill does
# Memory Optimizer
Optimizes Claude Code memory files through 4 interactive steps.
> **No `context: fork`** — must run in main conversation to spawn agents.
## Phase 0: Load Context
0. **Determine memory directory (`$MEMORY_DIR`):**
```bash
CUSTOM_DIR=$(cat .claude/settings.json 2>/dev/null | jq -r '.autoMemoryDirectory // empty')
if [ -n "$CUSTOM_DIR" ]; then
MEMORY_DIR="$(git rev-parse --show-toplevel)/$CUSTOM_DIR"
else
MEMORY_DIR=~/.claude/projects/<hash>/memory
fi
```
Read `.claude/settings.json` (if exists) → extract `autoMemoryDirectory`.
If set → resolve as `<git-root>/<autoMemoryDirectory>`.
If not set → use legacy `~/.claude/projects/<hash>/memory/` glob pattern.
1. Glob all memory files: `$MEMORY_DIR/*.md` (or `~/.claude/projects/**/memory/*.md` for legacy)
2. Read `~/.claude/CLAUDE.md` and project `CLAUDE.md` (if exists)
3. Glob `.claude/rules/*.md` — read all project rules
4. Read `~/.claude/rules/*.md` — read all global rules
Build context map:
```
memory_dir: $MEMORY_DIR
memory_files: [paths]
claude_md_sections: [sections]
rules_files: [paths with content]
```
## Step 1: Analysis — Remove Duplicates (Interactive)
**Goal:** Find memory entries that duplicate content already in CLAUDE.md or rules.
1. Spawn `Explore` agent to cross-reference all loaded files
2. Identify entries where:
- Same rule already in CLAUDE.md
- Same pattern already in a rules file
- Contradicts CLAUDE.md (CLAUDE.md wins)
3. Show analysis:
```
Found X duplicate/redundant entries (Y% of memory):
| Entry | Memory File | Already In | Action |
|-------|-------------|------------|--------|
| "Use grepai first" | MEMORY.md:5 | rules/grepai-first.md | DELETE |
...
```
4. `AskUserQuestion`: "Delete X duplicate entries (Y% of memory)? This is safe — content exists elsewhere."
- Options: "Yes, delete all" / "Review each" / "Skip this step"
5. Apply deletion using `Edit` tool if approved
## Step 2: Migration — Move to Rules/CLAUDE.md (Interactive)
**Goal:** Identify remaining memory entries better suited to persistent config files.
Decision tree (per entry):
- Applies to ALL projects + IS a rule/constraint → `~/.claude/rules/`
- Applies to THIS project only + IS a rule → `.claude/rules/`
- IS an architectural decision → project `CLAUDE.md`
- IS a fact/pattern reusable across sessions → KEEP in memory
1. Show categorization:
```
X entries suitable for migration:
| Entry | Current Location | Target | Reduction |
|-------|-----------------|--------|-----------|
| "Always use BD_PLUGIN_ROOT" | MEMORY.md:12 | .claude/rules/brewdoc.md | 15 tokens |
...
Total: X entries → ~Y tokens saved
```
2. `AskUserQuestion`: "Migrate X entries to rules/CLAUDE.md?"
- Options: "Yes, migrate all" / "Review each" / "Skip this step"
3. If approved:
- Create/append to target rule files via `Edit`
- Remove migrated entries from memory via `Edit`
- If target file doesn't exist, create it
## Step 3: Compression (Interactive)
**Goal:** Compress remaining entries using LLM-efficient formatting.
Compression techniques:
- Prose → table row
- Multiple related entries → single table
- Verbose description → imperative one-liner
- List of examples → pattern + one example
1. Show compression preview:
```
Compression opportunities found:
| Before | After | Savings |
|--------|-------|---------|
| "When you need to... always use..." | "Use X for Y" | 8 tokens |
...
Total: ~Y% token reduction (~Z tokens)
```
Show 2-3 specific before/after samples.
2. `AskUserQuestion`: "Compress remaining memory? (~Y% reduction)"
- Options: "Yes, compress all" / "Skip compression"
3. Apply compression via `Edit` (bottom-up order to preserve line numbers)
## Step 4: Validation (Automatic)
**Goal:** Verify final state and clean orphaned references.
1. Spawn `reviewer` agent to verify:
- No broken file path references in memory files
- No contradictions between memory and CLAUDE.md
- Memory files are well-formed markdown
2. Clean broken references (Edit tool)
3. Check for orphaned memory files (files in `$MEMORY_DIR` with no MEMORY.md reference)
4. Report orphaned files and ask to delete
**Final Report:**
```markdown
## Memory Optimization Complete
### Summary
| Metric | Before | After | Saved |
|--------|--------|-------|-------|
| Total entries | X | Y | Z |
| Duplicate entries | X | 0 | — |
| Migrated entries | — | — | X |
| Token estimate | ~X | ~Y | ~Z (~P%) |
### Changes Made
- Step 1: Deleted X duplicate entries
- Step 2: Migrated X entries to rules/CLAUDE.md
- Step 3: Compressed X entries (Y% reduction)
- Step 4: Fixed X broken references, removed X orphaned files
### Final Memory Structure
{directory listing of $MEMORY_DIR}
```
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.