plugins/code-analysis/skills/mnemex-search/SKILL.md
Performs semantic code search and AST analysis via mnemex MCP/CLI — map, symbol, callers, callees, context, PageRank. Use when searching code, mapping a codebase, or auditing callers before refactor.
npx skillsauth add madappgang/magus mnemex-searchInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
This Skill provides comprehensive guidance on leveraging mnemex v0.7.0+ with AST-based structural analysis, code analysis commands, and framework documentation for intelligent codebase understanding.
Before starting any investigation, classify the task to pick the right tool.
| Task Type | Example | Use |
|-----------|---------|-----|
| "How does X work?" | "How does authentication work?" | mnemex search |
| Find implementations | "Find all API endpoints" | mnemex search |
| Architecture questions | "Map the service layer" | mnemex --agent map |
| Trace data flow | "How does user data flow?" | mnemex search |
| Audit integrations | "Audit Prime API usage" | mnemex search |
| Exact string match | "Find 'DEPRECATED_FLAG'" | Grep |
| Count occurrences | "How many TODO comments?" | Grep -c |
| Find specific symbol | "Find class UserService" | Grep |
| File patterns | "Find all *.config.ts" | Glob |
Rule: Use mnemex for semantic/conceptual queries. Use Grep/Glob for exact matches only.
mnemex status
| Status | Meaning | Next Action | |--------|---------|-------------| | Shows chunk count ("938 chunks") | Indexed | USE mnemex | | "No index found" | Not indexed | Offer to index | | "command not found" | Not installed | Fall back to Grep |
| Approach | Token Cost | Result Quality |
|----------|------------|----------------|
| Read 5+ files sequentially | ~5000 tokens | No ranking |
| Glob → Read all matches | ~3000+ tokens | No semantic understanding |
| mnemex search once | ~500 tokens | Ranked by relevance |
Claudemem results include context around matches — you often don't need to read full files.
Before executing bulk file operations, consider semantic search alternatives.
| Situation | Intercept? | Action | |-----------|-----------|--------| | Read 1–2 specific files | No | Proceed with Read | | Read 3+ files in investigation | YES | Convert to mnemex search | | Glob for exact filename | No | Proceed with Glob | | Glob for pattern discovery | YES | Convert to mnemex search | | Grep for exact string | No | Proceed with Grep | | Grep for semantic concept | YES | Convert to mnemex search | | Files mentioned in prompt | YES | Search semantically first |
Instead of reading multiple files:
Read src/services/auth/login.ts
Read src/services/auth/session.ts
Read src/services/auth/jwt.ts
Read src/services/auth/middleware.ts
Do:
mnemex search "authentication login session JWT middleware" -n 15
Instead of glob + sequential reads:
Glob("src/**/*.controller.ts") → Read all 15 controllers
Do:
mnemex search "HTTP controller endpoint route handler" -n 20
Interception protocol:
mnemex status — check if indexedmnemex index -y, then search┌─────────────────────────────────────────────────────────────────┐
│ CLAUDEMEM v0.3.0 ARCHITECTURE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ AST STRUCTURAL LAYER ⭐NEW │ │
│ │ Tree-sitter Parse → Symbol Graph → PageRank Ranking │ │
│ │ map | symbol | callers | callees | context │ │
│ └───────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ SEARCH LAYER │ │
│ │ Query → Embed → Vector Search + BM25 → Ranked Results │ │
│ └───────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ INDEX LAYER │ │
│ │ AST Parse → Chunk → Embed → LanceDB + Symbol Graph │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
v0.3.0 adds AST tree navigation with symbol graph analysis:
In Claude Code with code-analysis plugin enabled, mnemex tools are available directly as MCP tools — no CLI invocation needed.
Navigation & Search (9 tools):
| Tool | Purpose |
|------|---------|
| map | Repository structure with PageRank ranking |
| symbol | Find symbol definition (file:line) |
| callers | What calls this symbol? |
| callees | What does this symbol call? |
| context | Full call chain (callers + callees + dependencies) |
| search | Semantic vector search |
| search-with-context | Search + repository context |
| references | All references to a symbol (LSP-backed) |
| definition | Symbol definition with surrounding context |
Edit & Refactor (4 tools) — prefer over Read+Edit for symbol modifications:
| Tool | Purpose |
|------|---------|
| edit_symbol | Replace a symbol's body by name. IMPORTANT: Always call think first. |
| edit_lines | Replace a line range. Use when symbol boundary is unclear. |
| restore_edit | Undo the last edit. ALWAYS available as a safety net. |
| rename_symbol | Rename across the entire codebase via LSP refactoring. Use dryRun=true first. |
LSP Navigation (2 tools):
| Tool | Purpose |
|------|---------|
| define | Jump to declaration via live LSP — more precise than symbol for overloaded names |
| hover | Get type signature and documentation — richer than symbol's docstring field |
Memory (4 tools) — persist findings across sessions:
| Tool | Purpose |
|------|---------|
| memory_write | Write a named note. Key convention: {project}/{topic} |
| memory_read | Read a previously written note by key |
| memory_list | List all memory keys, optionally filtered |
| memory_delete | Delete a memory entry (irreversible) |
Reasoning (1 tool):
| Tool | Purpose |
|------|---------|
| think | Structured reflection. Returns a self-check prompt. Call before any edit. |
Legacy Tools (9) — available but lower priority than Navigation & Search equivalents:
| Tool | Purpose |
|------|---------|
| dead-code | Find unreferenced symbols for cleanup |
| test-gaps | High-importance symbols missing tests |
| impact | BFS transitive caller analysis |
| dependency-graph | Transitive dependency visualization |
| import-paths | Analyze import patterns |
| test-impact | Impact analysis for tests |
| trace-execution | Execution flow analysis |
| dependency-analyzer | Dependency tree analysis |
| ast-structure | AST visualization |
| Anti-Pattern | Why It's Wrong | Preferred Alternative |
|--------------|---------------|----------------------|
| Read whole file to find a function | Wastes tokens; index has exact locations | symbol → Read specific line range |
| Grep for text to find call sites | Misses type-aliased calls, cross-file calls | callers (AST-backed) |
| Manual search-and-replace for rename | Misses type annotations, generics, docs | rename_symbol with dryRun=true |
| Read + Edit to modify function body | Line numbers go stale after edits | edit_symbol (symbol-name-based) |
| define on every symbol | Expensive LSP call; index is usually sufficient | Use define only for overloaded names |
| memory_read on all available keys | Unnecessary context; slows session start | Read only keys relevant to task name |
Both modes access the same index. Choose based on context:
| Mode | When to Use | How |
|------|-------------|-----|
| MCP tools | Direct invocation in Claude Code | Call map, symbol, etc. directly |
| CLI via Bash | Shell scripts, orchestration | Bash("mnemex --agent map 'query'") |
# MCP mode (preferred in Claude Code — call tools directly)
# Call the 'map' MCP tool with query: "authentication flow"
# Call the 'symbol' MCP tool with name: "AuthService"
# CLI mode (Bash tool — for scripts or orchestration)
mnemex --agent map "authentication flow"
mnemex --agent symbol AuthService
# For agentic use, always use --agent flag for clean output
mnemex --agent <command>
# Core commands for agents
mnemex --agent map [query] # Get structural overview (repo map)
mnemex --agent symbol <name> # Find symbol definition
mnemex --agent callers <name> # What calls this symbol?
mnemex --agent callees <name> # What does this symbol call?
mnemex --agent context <name> # Full context (symbol + dependencies)
mnemex --agent search <query> # Semantic search (clean output)
mnemex --agent search <query> --map # Search + include repo map context
Claudemem has evolved significantly. Check your version before using commands:
mnemex --version
| Command | Minimum Version | Status | Purpose |
|---------|-----------------|--------|---------|
| map | v0.3.0 | ✅ Available | Architecture overview with PageRank |
| symbol | v0.3.0 | ✅ Available | Find exact file:line location |
| callers | v0.3.0 | ✅ Available | What calls this symbol? |
| callees | v0.3.0 | ✅ Available | What does this symbol call? |
| context | v0.3.0 | ✅ Available | Full call chain (callers + callees) |
| search | v0.3.0 | ✅ Available | Semantic vector search |
| dead-code | v0.4.0+ | ⚠️ Check version | Find unused symbols |
| test-gaps | v0.4.0+ | ⚠️ Check version | Find high-importance untested code |
| impact | v0.4.0+ | ⚠️ Check version | BFS transitive caller analysis |
| docs | v0.7.0+ | ✅ Available | Framework documentation fetching |
# Get version number
VERSION=$(mnemex --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
# Check if v0.4.0+ features available
if [ -n "$VERSION" ] && printf '%s\n' "0.4.0" "$VERSION" | sort -V -C; then
# v0.4.0+ available
mnemex --agent dead-code mnemex --agent test-gaps mnemex --agent impact SymbolNameelse
echo "Code analysis commands require mnemex v0.4.0+"
echo "Current version: $VERSION"
echo "Fallback to v0.3.0 commands (map, symbol, callers, callees)"
fi
When using v0.4.0+ commands, always provide fallback:
# Try impact analysis (v0.4.0+), fallback to callers (v0.3.0)
IMPACT=$(mnemex --agent impact SymbolName 2>/dev/null)
if [ -n "$IMPACT" ] && [ "$IMPACT" != "command not found" ]; then
echo "$IMPACT"
else
echo "Using fallback (direct callers only):"
mnemex --agent callers SymbolNamefi
Why This Matters:
Before reading any code files, get the structural overview:
# For a specific task, get focused repo map
mnemex --agent map "authentication flow"
# Output shows relevant symbols ranked by importance (PageRank):
# file: src/auth/AuthService.ts
# line: 15-89
# kind: class
# name: AuthService
# pagerank: 0.0921
# signature: class AuthService
# ---
# file: src/middleware/auth.ts
# ...
This tells you:
Once you know what to look for:
# Find exact location of a symbol
mnemex --agent symbol AuthService
# Output:
# file: src/auth/AuthService.ts
# line: 15-89
# kind: class
# name: AuthService
# signature: class AuthService implements IAuthProvider
# exported: true
# pagerank: 0.0921
# docstring: Handles user authentication and session management
Before modifying code, understand what depends on it:
# What calls AuthService? (impact of changes)
mnemex --agent callers AuthService
# Output:
# caller: LoginController.authenticate
# file: src/controllers/login.ts
# line: 34
# kind: call
# ---
# caller: SessionMiddleware.validate
# file: src/middleware/session.ts
# line: 12
# kind: call
# What does AuthService call? (its dependencies)
mnemex --agent callees AuthService
# Output:
# callee: Database.query
# file: src/db/database.ts
# line: 45
# kind: call
# ---
# callee: TokenManager.generate
# file: src/auth/tokens.ts
# line: 23
# kind: call
For complex modifications, get everything at once:
mnemex --agent context AuthService
# Output includes:
# [symbol]
# file: src/auth/AuthService.ts
# line: 15-89
# kind: class
# name: AuthService
# ...
# [callers]
# caller: LoginController.authenticate
# ...
# [callees]
# callee: Database.query
# ...
When you need actual code snippets:
# Semantic search
mnemex --agent search "password hashing"
# Search with repo map context (recommended for complex tasks)
mnemex --agent search "password hashing" --map```
---
## Advanced Tool Workflows
### Edit Tools Workflow
Use `edit_symbol` to modify a function or class body without knowing the exact line numbers.
**Decision tree:**
Need to modify code? ├─ Modifying a whole function/class/method body? → edit_symbol ├─ Modifying a few lines within a body (and you have line numbers)? → edit_lines ├─ Result is wrong? → restore_edit (then try again) └─ Renaming across codebase? → rename_symbol with dryRun=true first
**Workflow: Edit a symbol**
1. Call `symbol` to confirm the exact symbol name
2. Call `think` — IMPORTANT: structured reflection before any edit
3. Call `edit_symbol` with the symbol name and new body
4. If result is incorrect: call `restore_edit` immediately, then revise approach
**Anti-patterns:**
- DO NOT use Read + Edit tool to replace function bodies — prefer `edit_symbol` (it's symbol-name-based, not line-number-based, and survives concurrent edits)
- DO NOT call `edit_symbol` without calling `think` first — edits without reflection have higher failure rates
- DO NOT use `edit_lines` when you know the symbol name — line numbers go stale after any edit
**IMPORTANT: Line numbers go stale.** After any `edit_symbol` or `edit_lines` call, all previously-obtained line numbers are invalid. Re-query if needed.
### LSP Navigation Workflow
Use `define` and `hover` to get live, language-server-backed type information before editing.
**`hover` vs `symbol` docstring field:**
- `symbol` docstring: extracted from AST at index time — may be stale
- `hover`: queried from live LSP — always current, includes inferred types
**`define` vs `symbol`:**
- `symbol`: AST-indexed lookup, fast, works offline
- `define`: LSP textDocument/definition, handles overloaded names and generics correctly
**Workflow: Understand a symbol before editing**
1. Call `hover` on the symbol to get its current type signature
2. Call `define` if the symbol is overloaded or if `symbol` returned multiple matches
3. Proceed with edit using confirmed type information
**When to prefer LSP Navigation:**
- Overloaded function names in Java, C++, or TypeScript
- Generic types where you need the concrete instantiation
- After the index may be stale (check `index_status` first)
### Rename Workflow
`rename_symbol` uses LSP to rename a symbol consistently across the entire codebase.
**ALWAYS run with `dryRun=true` first** to see the full scope of changes before committing.
**Workflow:**
1. Call `symbol` to confirm the exact canonical name
2. Call `rename_symbol` with `dryRun=true` — review the change list
3. If scope looks correct: call `rename_symbol` without `dryRun` to apply
4. Verify with `symbol` on the new name
**Example (Scenario 3: Refactoring from codebase-detective)**:
Task: Rename DatabaseConnection to DatabasePool
Old approach (error-prone): mnemex callers DatabaseConnection → manual grep → edit each file
New approach (correct): rename_symbol("DatabaseConnection", "DatabasePool", dryRun=true) → Review: 47 files affected, 82 occurrences rename_symbol("DatabaseConnection", "DatabasePool") → Done. All callers, imports, type annotations updated.
**Anti-pattern:** DO NOT use `callers` + manual edit for rename operations. `rename_symbol` handles:
- String literals that match the name (configurable)
- Type annotations and generics
- Import statements
- Test files
### Memory Workflow
Use memory tools to persist investigation findings across sessions.
**Key naming convention**: `{project}/{topic}` format
- Example: `auth/architecture` — authentication module architecture notes
- Example: `payment/known-issues` — known bugs in payment flow
- Example: `global/code-style` — project-wide coding conventions
**Workflow: Write findings**
1. After completing an investigation, call `memory_write` with a descriptive key
2. Content: bullet-point summary (not full code — keep it < 500 chars)
3. Start new sessions with `memory_list` to see what's already known
**Workflow: Read findings**
1. Call `memory_list` at session start to see available notes
2. Call `memory_read` only when the key is relevant to current task
3. DO NOT read all memories — only read those relevant by key name
**Anti-patterns:**
- DO NOT write large code blocks to memory — write summaries and file:line references instead
- DO NOT call `memory_read` for every available key — infer relevance from the key name
- DO NOT `memory_delete` without user confirmation — deletion is irreversible
---
## Output Format
When using `--agent` flag, commands output machine-readable format:
file: src/core/store.ts line: 12-89 kind: class name: VectorStore ...
Records are separated by `---`. Each field is `key: value` on its own line.
---
## Command Reference
### mnemex map [query]
Get structural overview of the codebase. Optionally focused on a query.
```bash
# Full repo map (top symbols by PageRank)
mnemex --agent map
# Focused on specific task
mnemex --agent map "authentication"
# Limit tokens
mnemex --agent map "auth" --tokens 500```
**Output fields**: file, line, kind, name, signature, pagerank, exported
**When to use**: Always first - understand structure before reading code
### mnemex symbol <name>
Find a symbol by name. Disambiguates using PageRank and export status.
```bash
mnemex --agent symbol Indexermnemex --agent symbol "search" --file retriever # hint which file
Output fields: file, line, kind, name, signature, pagerank, exported, docstring
When to use: When you know the symbol name and need exact location
Find all symbols that call/reference the given symbol.
mnemex --agent callers AuthService```
**Output fields**: caller (name), file, line, kind (call/import/extends/etc)
**When to use**: Before modifying anything - know the impact radius
### mnemex callees <name>
Find all symbols that the given symbol calls/references.
```bash
mnemex --agent callees AuthService```
**Output fields**: callee (name), file, line, kind
**When to use**: To understand dependencies and trace data flow
### mnemex context <name>
Get full context: the symbol plus its callers and callees.
```bash
mnemex --agent context Indexermnemex --agent context Indexer --callers 10 --callees 20```
**Output sections**: [symbol], [callers], [callees]
**When to use**: For complex modifications requiring full awareness
### mnemex search <query>
Semantic search across the codebase.
```bash
mnemex --agent search "error handling"mnemex --agent search "error handling" --map # include repo map
mnemex --agent search "auth" -n 5 # limit results
Output fields: file, line, kind, name, score, content (truncated)
When to use: When you need actual code snippets (after mapping)
Find unused symbols in the codebase.
# Find all unused symbols
mnemex --agent dead-code
# Stricter threshold (only very low PageRank)
mnemex --agent dead-code --max-pagerank 0.005
# Include exported symbols (usually excluded)
mnemex --agent dead-code --include-exported```
**Algorithm:**
- Zero callers (nothing references the symbol)
- Low PageRank (< 0.001 default)
- Not exported (by default, exports may be used externally)
**Output fields**: file, line, kind, name, pagerank, last_caller_removed
**When to use**: Architecture cleanup, tech debt assessment, before major refactoring
**Empty Result Handling:**
```bash
RESULT=$(mnemex --agent dead-code )
if [ -z "$RESULT" ] || [ "$RESULT" = "No dead code found" ]; then
echo "Codebase is clean - no dead code detected!"
echo "This indicates good code hygiene."
else
echo "$RESULT"
fi
Static Analysis Limitations:
import()) may hide real callersFind high-importance code without test coverage.
# Find all test coverage gaps
mnemex --agent test-gaps
# Only critical gaps (high PageRank)
mnemex --agent test-gaps --min-pagerank 0.05```
**Algorithm:**
- High PageRank (> 0.01 default) - Important code
- Zero callers from test files (*.test.ts, *.spec.ts, *_test.go)
**Output fields**: file, line, kind, name, pagerank, production_callers, test_callers
**When to use**: Test coverage analysis, QA planning, identifying critical gaps
**Empty Result Handling:**
```bash
RESULT=$(mnemex --agent test-gaps )
if [ -z "$RESULT" ] || [ "$RESULT" = "No test gaps found" ]; then
echo "Excellent! All high-importance code has test coverage."
echo "Consider lowering --min-pagerank threshold for additional coverage."
else
echo "$RESULT"
fi
Static Analysis Limitations:
Analyze the impact of changing a symbol using BFS traversal.
# Get all transitive callers
mnemex --agent impact UserService
# Limit depth for large codebases
mnemex --agent impact UserService --max-depth 5```
**Algorithm:**
- BFS traversal from symbol to all transitive callers
- Groups results by depth level
- Shows file:line for each caller
**Output sections**: direct_callers, transitive_callers (with depth), grouped_by_file
**When to use**: Before ANY modification, refactoring planning, risk assessment
**Empty Result Handling:**
```bash
RESULT=$(mnemex --agent impact FunctionName )
if [ -z "$RESULT" ] || echo "$RESULT" | grep -q "No callers found"; then
echo "No callers found - this symbol appears unused or is an entry point."
echo "If unused, consider running: mnemex --agent dead-code "
echo "If entry point (API handler, main), this is expected."
else
echo "$RESULT"
fi
Static Analysis Limitations:
Claudemem v0.2.0+ supports LLM-enriched semantic search with specialized document types.
| Type | Purpose | Generated By |
|------|---------|--------------|
| symbol_summary | Function behavior, params, returns, side effects | LLM analysis |
| file_summary | File purpose, exports, architectural patterns | LLM analysis |
| idiom | Common patterns in codebase | Pattern detection |
| usage_example | How to use APIs | Documentation extraction |
| anti_pattern | What NOT to do | Static analysis + LLM |
| project_doc | Project-level documentation | README, CLAUDE.md |
For agent-optimized search with document type weighting:
# Navigation-focused search (prioritizes summaries)
mnemex --agent search "authentication" --use-case navigation
# Default search (balanced)
mnemex --agent search "authentication"```
**Navigation mode search weights:**
- `symbol_summary`: 1.5x (higher priority)
- `file_summary`: 1.3x (higher priority)
- `code_chunk`: 1.0x (normal)
- `idiom`: 1.2x (higher for pattern discovery)
### Symbol Summary Fields
```yaml
symbol: AuthService.authenticate
file: src/services/auth.ts
line: 45-89
behavior: "Validates user credentials and generates JWT token"
params:
- name: credentials
type: LoginCredentials
description: "Email and password from login form"
returns:
type: AuthResult
description: "JWT token and user profile on success, error on failure"
side_effects:
- "Updates user.lastLogin timestamp"
- "Logs authentication attempt"
- "May trigger rate limiting"
file: src/services/auth.ts
purpose: "Core authentication service handling login, logout, and session management"
exports:
- AuthService (class)
- authenticate (function)
- validateToken (function)
patterns:
- "Dependency Injection (constructor takes IUserRepository)"
- "Factory Pattern (createSession)"
- "Strategy Pattern (IAuthProvider interface)"
dependencies:
- bcrypt (password hashing)
- jsonwebtoken (JWT generation)
- UserRepository (user data access)
# Find function behavior without reading code
mnemex --agent search "processPayment behavior" --use-case navigation
# Output includes symbol_summary:
# symbol: PaymentService.processPayment
# behavior: "Charges customer card via Stripe and saves transaction"
# side_effects: ["Updates balance", "Sends receipt email", "Logs to audit"]
# Find file purposes for architecture understanding
mnemex --agent search "file:services purpose" --use-case navigation
# Find anti-patterns to avoid
mnemex --agent search "anti_pattern SQL"```
### Regenerating Enrichments
If codebase changes significantly:
```bash
# Re-index with LLM enrichment
mnemex index --enrich
# Or enrich specific files
mnemex enrich src/services/payment.ts
Standardized investigation patterns for common scenarios. All templates include error handling for empty results and version compatibility checks.
Trigger: "Why is X broken?", "Find bug", "Root cause"
# Step 1: Locate the symptom
SYMBOL=$(mnemex --agent symbol FunctionFromStackTrace )
if [ -z "$SYMBOL" ]; then
echo "Symbol not found - check spelling or run: mnemex --agent map 'related keywords' "
exit 1
fi
# Step 2: Get full context (callers + callees)
mnemex --agent context FunctionFromStackTrace
# Step 3: Trace backwards to find root cause
mnemex --agent callers suspectedSource
# Step 4: Check full impact of the bug (v0.4.0+)
IMPACT=$(mnemex --agent impact BuggyFunction 2>/dev/null)
if [ -n "$IMPACT" ]; then
echo "$IMPACT"
else
echo "Impact analysis requires mnemex v0.4.0+ or no callers found"
echo "Fallback: mnemex --agent callers BuggyFunction "
fi
# Step 5: Read identified file:line ranges
# Fix bug, verify callers still work
# Step 6: Document impacted code for testing
Output Template:
## Bug Investigation Report
**Symptom:** [Description]
**Root Cause:** [Location and explanation]
**Call Chain:** [How we got here]
**Impact Radius:** [What else is affected]
**Fix Applied:** [What was changed]
**Verification:** [Tests run, callers checked]
Trigger: "Add feature", "Implement X", "Extend functionality"
# Step 1: Map the feature area
MAP=$(mnemex --agent map "feature area keywords" )
if [ -z "$MAP" ]; then
echo "No matches found - try broader keywords"
fi
# Step 2: Identify extension points
mnemex --agent callees ExistingFeature
# Step 3: Get full context for modification point
mnemex --agent context ModificationPoint
# Step 4: Check existing patterns to follow
mnemex --agent search "similar pattern" --use-case navigation
# Step 5: Implement following existing patterns
# Step 6: Check test coverage gaps (v0.4.0+)
GAPS=$(mnemex --agent test-gaps 2>/dev/null)
if [ -n "$GAPS" ]; then
echo "Test gaps to address:"
echo "$GAPS"
else
echo "test-gaps requires v0.4.0+ or no gaps found"
fi
Output Template:
## Feature Implementation Plan
**Feature:** [Description]
**Extension Point:** [Where to add]
**Dependencies:** [What it needs]
**Pattern to Follow:** [Existing similar code]
**Test Requirements:** [Coverage needs]
Trigger: "Rename X", "Extract function", "Move code", "Refactor"
# Step 1: Find the symbol to refactor
SYMBOL=$(mnemex --agent symbol SymbolToRename )
if [ -z "$SYMBOL" ]; then
echo "Symbol not found - check exact name"
exit 1
fi
# Step 2: Get FULL impact (all transitive callers) (v0.4.0+)
IMPACT=$(mnemex --agent impact SymbolToRename 2>/dev/null)
if [ -n "$IMPACT" ]; then
echo "$IMPACT"
# (impact output includes grouped_by_file)
else
echo "Using fallback (direct callers only):"
mnemex --agent callers SymbolToRenamefi
# Step 3: Group by file for systematic updates
# Step 4: Update each caller location systematically
# Step 5: Verify all callers updated
mnemex --agent callers NewSymbolName
# Step 6: Run affected tests
Output Template:
## Refactoring Report
**Original:** [Old name/location]
**Target:** [New name/location]
**Direct Callers:** [Count]
**Transitive Callers:** [Count]
**Files Modified:** [List]
**Verification:** [All callers updated, tests pass]
Trigger: "How does X work?", "Explain architecture", "Onboarding"
# Step 1: Get full structural map
MAP=$(mnemex --agent map )
if [ -z "$MAP" ]; then
echo "Index may be empty - run: mnemex index"
exit 1
fi
echo "$MAP"
# Step 2: Identify architectural pillars (PageRank > 0.05)
# Document top 5 by PageRank
# Step 3: For each pillar, get full context
mnemex --agent context PillarSymbol
# Step 4: Trace major flows via callees
mnemex --agent callees EntryPoint
# Step 5: Identify dead code (cleanup opportunities) (v0.4.0+)
DEAD=$(mnemex --agent dead-code 2>/dev/null)
if [ -n "$DEAD" ]; then
echo "Dead code found:"
echo "$DEAD"
else
echo "No dead code found (or v0.4.0+ required)"
fi
# Step 6: Identify test gaps (risk areas) (v0.4.0+)
GAPS=$(mnemex --agent test-gaps 2>/dev/null)
if [ -n "$GAPS" ]; then
echo "Test gaps:"
echo "$GAPS"
else
echo "No test gaps found (or v0.4.0+ required)"
fi
Output Template:
## Architecture Report
**Core Abstractions (PageRank > 0.05):**
1. [Symbol] - [Role in system]
2. [Symbol] - [Role in system]
3. [Symbol] - [Role in system]
**Layer Structure:**
[Presentation Layer] | [Business Layer] | [Data Layer]
**Major Flows:**
- [Flow 1: Entry -> Processing -> Output]
- [Flow 2: Entry -> Processing -> Output]
**Health Indicators:**
- Dead Code: [Count] symbols
- Test Gaps: [Count] high-importance untested
- Tech Debt: [Summary]
Trigger: "Security review", "Audit authentication", "Check permissions"
# Step 1: Map security-related code
mnemex --agent map "auth permission security token"
# Step 2: Find authentication entry points
SYMBOL=$(mnemex --agent symbol authenticate )
if [ -z "$SYMBOL" ]; then
echo "No 'authenticate' symbol - try: login, verify, validate"
fi
mnemex --agent callers authenticate
# Step 3: Trace authentication flow
mnemex --agent callees authenticate
# Step 4: Check authorization patterns
mnemex --agent map "authorize permission check guard"
# Step 5: Find sensitive data handlers
mnemex --agent map "password hash token secret key"
# Step 6: Check for test coverage on security code (v0.4.0+)
GAPS=$(mnemex --agent test-gaps --min-pagerank 0.01 2>/dev/null)
if [ -n "$GAPS" ]; then
# Filter for security-related symbols
echo "$GAPS" | grep -E "(auth|login|password|token|permission|secret)"
fi
Output Template:
## Security Audit Report
**Authentication:**
- Entry Points: [List]
- Flow: [Description]
- Gaps: [Issues found]
**Authorization:**
- Permission Checks: [Where implemented]
- Coverage: [All routes covered?]
**Sensitive Data:**
- Password Handling: [How stored/compared]
- Token Management: [Generation/validation]
- Secrets: [How managed]
**Test Coverage:**
- Security Code Coverage: [X%]
- Critical Gaps: [List]
**Recommendations:**
1. [Priority 1 fix]
2. [Priority 2 fix]
Claudemem uses static AST analysis. Some patterns are not captured:
// NOT visible to static analysis
const module = await import(`./modules/${name}`);
Result: May show as "dead code" but is actually used dynamically. Action: Mark as "Potentially Dead - Manual Review"
// Exported for external use
export function publicAPI() { ... }
Result: May show 0 callers but used by other repositories.
Action: Use --include-exported carefully, or mark as "Externally Called - Manual Review Required"
// NOT visible to static analysis
const fn = obj[methodName]();
eval("functionName()");
Result: Callers not detected.
Action: Search codebase for eval, Object.keys, bracket notation.
// NOT visible as direct callers
emitter.on('event', handler);
document.addEventListener('click', onClick);
Result: handler and onClick may show 0 callers.
Action: Check for event registration patterns.
// Container registration hides relationships
container.register(IService, ServiceImpl);
Result: ServiceImpl may show 0 callers.
Action: Check DI container configuration.
Task: "Fix the null pointer exception in user authentication"
# Step 1: Get overview of auth-related code
mnemex --agent map "authentication null pointer"
# Step 2: Locate the specific symbol mentioned in error
mnemex --agent symbol authenticate
# Step 3: Check what calls it (to understand how it's used)
mnemex --agent callers authenticate
# Step 4: Read the actual code at the identified location
# Now you know exactly which file:line to read
Task: "Add rate limiting to the API endpoints"
# Step 1: Understand API structure
mnemex --agent map "API endpoints rate"
# Step 2: Find the main API handler
mnemex --agent symbol APIController
# Step 3: See what the API controller depends on
mnemex --agent callees APIController
# Step 4: Check if rate limiting already exists somewhere
mnemex --agent search "rate limit"
# Step 5: Get full context for the modification point
mnemex --agent context APIController```
### Scenario 3: Refactoring
**Task**: "Rename DatabaseConnection to DatabasePool"
```bash
# Step 1: Find the symbol
mnemex --agent symbol DatabaseConnection
# Step 2: Find ALL callers (these all need updating)
mnemex --agent callers DatabaseConnection
# Step 3: The output shows every file:line that references it
# Update each location systematically
Task: "How does the indexing pipeline work?"
# Step 1: Get high-level structure
mnemex --agent map "indexing pipeline"
# Step 2: Find the main entry point (highest PageRank)
mnemex --agent symbol Indexer
# Step 3: Trace the flow - what does Indexer call?
mnemex --agent callees Indexer
# Step 4: For each major callee, get its callees
mnemex --agent callees VectorStoremnemex --agent callees FileTracker
# Now you have the full pipeline traced
| Action | Token Cost | When to Use |
|--------|------------|-------------|
| map (focused) | ~500 | Always first - understand structure |
| symbol | ~50 | When you know the name |
| callers | ~100-500 | Before modifying anything |
| callees | ~100-500 | To understand dependencies |
| context | ~200-800 | For complex modifications |
| search | ~1000-3000 | When you need actual code |
| search --map | ~1500-4000 | For unfamiliar codebases |
Optimal order: map → symbol → callers/callees → search (only if needed)
This pattern typically uses 80% fewer tokens than blind exploration.
For maximum efficiency, follow this pattern:
1. RECEIVE TASK
↓
2. mnemex --agent map "<task keywords>" → Understand structure, identify key symbols
↓
3. mnemex --agent symbol <high-pagerank-symbol> → Get exact location
↓
4. mnemex --agent callers <symbol> (if modifying)
→ Know the impact radius
↓
5. mnemex --agent callees <symbol> (if needed)
→ Understand dependencies
↓
6. READ specific file:line ranges (not whole files)
↓
7. MAKE CHANGES with full awareness
↓
8. CHECK callers still work
PageRank measures how "central" a symbol is in the codebase:
| PageRank | Meaning | Action | |----------|---------|--------| | > 0.05 | Core abstraction | Understand this first - everything depends on it | | 0.01-0.05 | Important symbol | Key functionality, worth understanding | | 0.001-0.01 | Standard symbol | Normal code, read as needed | | < 0.001 | Utility/leaf | Helper functions, read only if directly relevant |
Why PageRank matters:
Claudemem provides more efficient alternatives to common search patterns:
| Instead of... | Try this | Benefit |
|---------------|----------|---------|
| cat src/core/*.ts \| head -1000 | mnemex --agent map "task" | Saves tokens, finds relevant files |
| grep -r "Database" src/ | mnemex --agent symbol Database | Semantic relationships, not just strings |
| Edit without caller check | mnemex --agent callers X first | Know what depends on your changes |
| Search immediately | map first, then search | Context improves search accuracy |
| Read every matching file | Focus on high-PageRank symbols | Core code first, utilities later |
| mnemex search "query" | mnemex --agent search "query" | Clean output without ASCII art |
map identifies relevant files before reading, avoiding wasted contextsymbol and callers understand code relationships, not just textcallers reveals dependencies before you modify codeResults are ranked by PageRank - most important symbols appear first. Using the complete output ensures you see all relevant results.
If output is too large, use built-in flags instead of truncating:
| Flag | Purpose | Example |
|------|---------|---------|
| --tokens N | Limit by token count | mnemex --agent map "query" --tokens 2000 |
| -n N | Limit result count | mnemex --agent search "auth" -n 10 |
| --page-size N | Pagination | mnemex --agent search "x" --page-size 20 |
| --max-depth N | Limit traversal | mnemex --agent context Func --max-depth 3 |
Tip: Piping to file preserves full output: mnemex --agent map "query" > /tmp/map.txt
| Instead of... | Try this | Why |
|--------------|----------|-----|
| Read files blindly | map first, then read specific lines | Ranked results, less tokens |
| grep -r "auth" | mnemex --agent symbol auth | Semantic understanding |
| Modify without callers | callers before any modification | Avoid breaking changes |
| Search immediately | map → symbol → search | Structural context first |
| cmd \| head | Use -n or --tokens flags | Output is pre-optimized |
┌─────────────────────────────────────────────────────────────────┐
│ CORRECT INVESTIGATION FLOW (v0.3.0) │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. mnemex --agent map "task" │
│ → Understand structure, find high-PageRank symbols │
│ │
│ 2. mnemex --agent symbol <name> │
│ → Get exact file:line location │
│ │
│ 3. mnemex --agent callers <name> │
│ → Know impact radius BEFORE modifying │
│ │
│ 4. mnemex --agent callees <name> │
│ → Understand dependencies │
│ │
│ 5. Read specific file:line ranges (NOT whole files) │
│ │
│ 6. Make changes with full awareness │
│ │
│ ⚠️ NEVER: Start with Read/Glob for semantic questions │
│ ⚠️ NEVER: Modify without checking callers │
│ ⚠️ NEVER: Search without mapping first │
│ │
└─────────────────────────────────────────────────────────────────┘
# Check if mnemex CLI is available
which mnemex || command -v mnemex
# Check version (must be 0.3.0+)
mnemex --version
# npm (recommended)
npm install -g claude-codemem
# Homebrew (macOS)
brew tap MadAppGang/claude-mem && brew install --cask mnemex
# Index current project
mnemex index
# Check status
mnemex --version && ls -la .mnemex/index.db 2>/dev/null
Claudemem v0.7.0+ includes automatic framework documentation fetching for your project dependencies. Documentation is indexed alongside your code, enabling unified semantic search across both.
# Core documentation commands
mnemex docs status # Show indexed libraries and cache state
mnemex docs fetch # Fetch docs for all detected dependencies
mnemex docs fetch react vue # Fetch specific libraries
mnemex docs providers # List available documentation providers
mnemex docs refresh # Force refresh all cached documentation
mnemex docs clear # Clear all documentation cache
mnemex docs clear react # Clear specific library cache
Claudemem uses a provider hierarchy with automatic fallback:
| Priority | Provider | Coverage | Requirements | |----------|----------|----------|--------------| | 1 (Best) | Context7 | 6000+ libraries with versioned code examples | API key (free tier available) | | 2 | llms.txt | Official AI-friendly docs from framework sites | Free, no key needed | | 3 | DevDocs | Consistent offline documentation, 100+ languages | Free, no key needed |
Claudemem automatically detects dependencies from:
| File | Ecosystem | Example |
|------|-----------|---------|
| package.json | npm/yarn | React, Vue, Express |
| requirements.txt | Python/pip | Django, FastAPI, Pandas |
| go.mod | Go | Gin, Echo, GORM |
| Cargo.toml | Rust | Tokio, Actix, Serde |
# Option 1: Run init (includes docs configuration)
mnemex init
# Option 2: Configure Context7 manually (optional, for best coverage)
export CONTEXT7_API_KEY=your_key
# Get free API key at: https://context7.com/dashboard
# Check current documentation status
mnemex docs status
# Output:
# 📚 Documentation Status
#
# Enabled: Yes
# Providers: Context7, llms.txt, DevDocs
# Libraries: 12 indexed
# Cache Age: 2h 15m
#
# Indexed Libraries:
# react (v18) via Context7 - 145 chunks
# typescript (v5) via Context7 - 89 chunks
# express (v4) via llms.txt - 34 chunks
# ...
# Fetch documentation for all project dependencies
mnemex docs fetch
# Output:
# 📚 Fetching Documentation
#
# [1/8] react... ✓ 145 chunks via Context7
# [2/8] typescript... ✓ 89 chunks via Context7
# [3/8] express... ✓ 34 chunks via llms.txt
# [4/8] lodash... ✓ 67 chunks via DevDocs
# ...
# Fetch specific library
mnemex docs fetch fastapi
# View available providers
mnemex docs providers
# Force refresh (clears cache, refetches)
mnemex docs refresh
After indexing documentation, mnemex search returns results from both your codebase and framework documentation:
mnemex --agent search "how to use React hooks"
# Output includes:
# --- Your Code ---
# file: src/components/UserProfile.tsx
# line: 12-45
# kind: function
# name: useUserProfile
# score: 0.89
# content: Custom hook for user profile management...
# ---
# --- React Documentation ---
# library: react
# section: Hooks Reference
# title: useEffect
# score: 0.87
# content: The useEffect Hook lets you perform side effects...
# ---
# library: react
# section: Hooks Reference
# title: useState
# score: 0.85
# content: useState is a Hook that lets you add state...
| Scenario | Command | Why |
|----------|---------|-----|
| New project setup | mnemex docs fetch | Index docs for all dependencies |
| Learning new library | mnemex docs fetch <library> | Get searchable reference |
| Updated dependencies | mnemex docs refresh | Refresh to get new versions |
| Check what's indexed | mnemex docs status | View cache state |
| Clear space | mnemex docs clear | Remove cached documentation |
Add documentation fetch to your investigation workflow:
# ENHANCED Investigation Workflow (v0.7.0+)
# Step 0: Ensure framework docs are available (one-time)
mnemex docs status || mnemex docs fetch
# Step 1: Map architecture (now includes library patterns)
mnemex --agent map "authentication"
# Step 2: Search both code AND framework docs
mnemex --agent search "JWT token validation"# Returns: your auth code + library docs on JWT handling
# Step 3: Understand how the library recommends usage
mnemex --agent search "react best practices hooks"# Returns: your patterns + React official guidance
The mnemex docs command requires v0.7.0+. Check your version:
mnemex --version
# Expected: 0.7.0 or higher
Note: If mnemex docs help returns "Unknown command", upgrade your mnemex installation.
Claudemem learns from your search patterns. After completing a task, report which search results were helpful to improve future searches.
| Feedback Type | Effect | Over Time | |---------------|--------|-----------| | Helpful | +10% boost | Files you consistently use rank higher | | Unhelpful | -10% demotion | Irrelevant results rank lower | | Document Type | Type weighting | Helpful types (e.g., symbol_summary) get priority |
# After using search results, report feedback
mnemex feedback --query "your original query" \
--helpful id1,id2 \
--unhelpful id3,id4
# Result IDs are shown in search output:
mnemex search "authentication" --agent# Output includes:
# id: abc123
# file: src/auth/middleware.ts
# ...
{
"tool": "report_search_feedback",
"arguments": {
"query": "authentication flow",
"allResultIds": ["id1", "id2", "id3"],
"helpfulIds": ["id1"],
"unhelpfulIds": ["id3"]
}
}
A result should be marked as helpful when:
A result should be marked as unhelpful when:
Do not track feedback for:
map command (structural overview, not semantic search)symbol command (exact lookup, not search)callers/callees commands (call graph, not search)search command results should have feedbackAdd feedback reporting to the end of each workflow template:
# Template 1: Bug Investigation (add at end)
# Step 7: Report feedback
if [ -n "$SEARCH_QUERY" ] && [ -n "$HELPFUL_IDS" ]; then
# Check if feedback is available (v0.8.0+)
if mnemex feedback --help 2>&1 | grep -qi "feedback"; then
timeout 5 mnemex feedback --query "$SEARCH_QUERY" \
--helpful "${HELPFUL_IDS}" \
--unhelpful "${UNHELPFUL_IDS}" 2>/dev/null || true
else
echo "Note: Search feedback requires mnemex v0.8.0+"
fi
fi
# Full investigation with feedback tracking
# 0. Check if feedback is available (v0.8.0+)
FEEDBACK_AVAILABLE=false
if mnemex feedback --help 2>&1 | grep -qi "feedback"; then
FEEDBACK_AVAILABLE=true
else
echo "Note: Search feedback requires mnemex v0.8.0+"
fi
# 1. Search and capture IDs
RESULTS=$(mnemex --agent search "payment processing" -n 10 )
ALL_IDS=$(echo "$RESULTS" | grep "^id:" | awk '{print $2}')
SEARCH_QUERY="payment processing"
# 2. Initialize tracking arrays
HELPFUL=()
UNHELPFUL=()
# 3. Process results (during investigation)
# When you read a result and it's useful:
HELPFUL+=("abc123")
# When you read a result and it's not relevant:
UNHELPFUL+=("def456")
# 4. Report feedback (at end of investigation)
if [ "$FEEDBACK_AVAILABLE" = true ] && ([ ${#HELPFUL[@]} -gt 0 ] || [ ${#UNHELPFUL[@]} -gt 0 ]); then
timeout 5 mnemex feedback \
--query "$SEARCH_QUERY" \
--helpful "$(IFS=,; echo "${HELPFUL[*]}")" \
--unhelpful "$(IFS=,; echo "${UNHELPFUL[*]}")" \
2>/dev/null || echo "Note: Feedback not sent (optional)"
fi
Add to the existing Quality Checklist:
search command)Before proceeding with investigation, verify the index is current:
# Count files modified since last index
STALE_COUNT=$(find . -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" -o -name "*.py" -o -name "*.go" -o -name "*.rs" \) \
-newer .mnemex/index.db 2>/dev/null | grep -v "node_modules" | grep -v ".git" | grep -v "dist" | grep -v "build" | wc -l)
STALE_COUNT=$((STALE_COUNT + 0)) # Normalize to integer
if [ "$STALE_COUNT" -gt 0 ]; then
# Get index time with explicit platform detection
if [[ "$OSTYPE" == "darwin"* ]]; then
INDEX_TIME=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M" .mnemex/index.db 2>/dev/null)
else
INDEX_TIME=$(stat -c "%y" .mnemex/index.db 2>/dev/null | cut -d'.' -f1)
fi
INDEX_TIME=${INDEX_TIME:-"unknown time"}
# Use AskUserQuestion to ask user how to proceed
# Options: [1] Reindex now (Recommended), [2] Proceed with stale index, [3] Cancel
fi
AskUserQuestion Template:
AskUserQuestion({
questions: [{
question: `${STALE_COUNT} files have been modified since the last index (${INDEX_TIME}). The mnemex index may be outdated, which could cause missing or incorrect results. How would you like to proceed?`,
header: "Index Freshness Warning",
multiSelect: false,
options: [
{
label: "Reindex now (Recommended)",
description: "Run mnemex index to update. Takes ~1-2 minutes."
},
{
label: "Proceed with stale index",
description: "Continue investigation. May miss recent code changes."
},
{
label: "Cancel investigation",
description: "I'll handle this manually."
}
]
}]
})
# map validation
RESULTS=$(mnemex --agent map "authentication" )
EXIT_CODE=$?
if [ "$EXIT_CODE" -ne 0 ]; then
echo "ERROR: mnemex command failed"
# Diagnose index health
DIAGNOSIS=$(mnemex --version && ls -la .mnemex/index.db 2>&1)
# Use AskUserQuestion
fi
if [ -z "$RESULTS" ]; then
echo "WARNING: No results found - may need reindex or different query"
# Use AskUserQuestion
fi
if ! echo "$RESULTS" | grep -qi "auth\|login\|user\|session"; then
echo "WARNING: Results may not be relevant to authentication query"
# Use AskUserQuestion
fi
# symbol validation
RESULTS=$(mnemex --agent symbol UserService )
if ! echo "$RESULTS" | grep -q "name: UserService"; then
echo "WARNING: UserService not found - check spelling or reindex"
# Use AskUserQuestion
fi
# search validation
RESULTS=$(mnemex --agent search "error handling" )
MATCH_COUNT=0
for kw in error handling catch try; do
if echo "$RESULTS" | grep -qi "$kw"; then
MATCH_COUNT=$((MATCH_COUNT + 1))
fi
done
if [ "$MATCH_COUNT" -lt 2 ]; then
echo "WARNING: Results may not be relevant to error handling query"
# Use AskUserQuestion
fi
If mnemex returns no results or the index isn't available:
mnemex status to verifymnemex index (~1-2 min)Native search tools (grep, Glob, find) are available when needed. They work well for:
| Feature | mnemex | grep/Glob | |---------|-----------|-----------| | Semantic understanding | ✓ | - | | Call graph analysis | ✓ | - | | PageRank ranking | ✓ | - | | Exact string match | ✓ | ✓ | | Works without index | - | ✓ |
Tip: After using native tools, consider running mnemex index to enable
semantic search for future investigations.
Before completing a mnemex workflow, ensure:
mnemex status)map to understand structure ⭐CRITICAL--agent for all commandscallers before modifying any symbolsearch command was used ⭐NEW in v0.8.0voyage/voyage-code-3 (best code understanding).mnemex/ directory--mcp flagmap, symbol, callers, callees, context commands--agent flag for clean, parseable outputdead-code, test-gaps, impact commands for code analysisdocs command for framework documentation fetchingMaintained by: Jack Rudenko @ MadAppGang Plugin: code-analysis v5.0.0 Last Updated: March 2026 (v5.0.0 - Absorbed code-search-selector and search-interceptor)
testing
A test skill for validation testing. Use when testing skill parsing and validation logic.
tools
--- name: bad-skill description: This skill has invalid YAML in frontmatter allowed-tools: [invalid, array, syntax prerequisites: not-an-array --- # Bad Skill This skill has malformed frontmatter that should fail parsing. The YAML has: - Unclosed array bracket - Wrong type for prerequisites (should be array, not string)
development
Sync model aliases from the curated Firebase database. Fetches default model assignments, short aliases, team compositions, and known model metadata from the claudish API. Run this to get fresh model recommendations.
tools
Release one or more Magus plugins to the distribution repos (magus, magus-alpha, magus-marketing). Handles version inference from git history, marketplace.json updates, tagging, and force-push to lean dist repos. Use whenever the user says "release kanban", "release the dev plugin", "cut a new version of gtd", "bump kanban to 1.7", or hands you a batch like "release kanban and gtd". Also use for multi-plugin releases and for checking what a release would contain before committing.