New advertisers: 50% off your first month with code FIRSTMONTHSee slots

Deep code investigation plugin that wraps claudemem for AST-based search and architecture analysis.

version
3.2.2
GitHub stars
289
View on GitHub

What it does

  • Adds /analyze, /help, and /setup commands, a codebase-detective agent, and eight detective skills
  • Covers architecture mapping via PageRank, semantic search, caller and callee analysis, and parallel multi-agent investigation
  • Enforces claudemem-first searching by intercepting Bash, Glob, Grep, and Read calls through hooks, with auto-reindexing at session start
  • Designed for developers who need to understand unfamiliar codebases or audit system design before modifying code

Deep code investigation with claudemem. v3.2.2: Updated for claudish v4.5.1 (--agent flag removed). v3.0.0: ENRICHMENT MODE.

Add marketplace

/plugin marketplace add MadAppGang/claude-code

Run it inside Claude Code once, then install the plugin below.

Install

/plugin install code-analysis@mag-claude-plugins

Run it inside Claude Code after adding the marketplace.

Files

Discovered from source

Architect Detective Skill

This skill uses claudemem's AST structural analysis for architecture investigation.

Why Claudemem Works Better for Architecture

TaskclaudememNative Tools
Find core abstractionsmap with PageRank rankingRead all files
Identify design patternsStructural symbol graphGrep patterns
Map dependenciescallers/callees chainsManual tracing
Find architectural pillarsHigh-PageRank symbolsUnknown

Primary commands:

  • claudemem --agent map "query" - Architecture overview with PageRank
  • claudemem --agent symbol <name> - Exact file:line locations

Architect Detective Skill

Version: 3.3.0 Role: Software Architect Purpose: Deep architectural investigation using AST structural analysis with PageRank and dead-code detection

Role Context

You are investigating this codebase as a Software Architect. Your focus is on:

  • System boundaries - Where modules, services, and layers begin and end
  • Design patterns - Architectural patterns used (MVC, Clean Architecture, DDD, etc.)
  • Dependency flow - How components depend on each other
  • Abstraction layers - Interfaces, contracts, and abstractions
  • Core abstractions - High-PageRank symbols that everything depends on

Why map is Perfect for Architecture

The map command with PageRank shows you:

  • High-PageRank symbols = Core abstractions everything depends on
  • Symbol kinds = classes, interfaces, functions organized by type
  • File distribution = Where architectural layers live
  • Dependency centrality = Which code is most connected

Architect-Focused Commands (v0.3.0)

Architecture Discovery (use map)

# Get high-level architecture overview
claudemem --agent map "architecture layers"
# Find core abstractions (highest PageRank)
claudemem --agent map  # Full map, sorted by importance

# Map specific architectural concerns
claudemem --agent map "service layer business logic"claudemem --agent map "repository data access"claudemem --agent map "controller API endpoints"claudemem --agent map "middleware request handling"```

### Layer Boundary Discovery

```bash
# Find interfaces/contracts (architectural boundaries)
claudemem --agent map "interface contract abstract"
# Find dependency injection points
claudemem --agent map "inject provider module"
# Find configuration/bootstrap
claudemem --agent map "config bootstrap initialize"```

### Pattern Discovery

```bash
# Find factory patterns
claudemem --agent map "factory create builder"
# Find repository patterns
claudemem --agent map "repository persist query"
# Find event-driven patterns
claudemem --agent map "event emit subscribe handler"```

### Dependency Analysis

```bash
# For a core abstraction, see what depends on it
claudemem --agent callers CoreService
# See what the abstraction depends on
claudemem --agent callees CoreService
# Get full dependency context
claudemem --agent context CoreService```

### Dead Code Detection (v0.4.0+ Required)

```bash
# Find unused symbols for cleanup
claudemem --agent dead-code
# Only truly dead code (very low PageRank)
claudemem --agent dead-code --max-pagerank 0.005```

**Architectural insight**: Dead code indicates:
- Failed features that were never removed
- Over-engineering (abstractions nobody uses)
- Potential tech debt cleanup opportunities

High PageRank + dead = Something broke recently (investigate!)
Low PageRank + dead = Safe to remove

**Handling Results:**
```bash
DEAD_CODE=$(claudemem --agent dead-code)
if [ -z "$DEAD_CODE" ]; then
  echo "No dead code found - architecture is well-maintained"
else
  # Categorize by risk
  HIGH_PAGERANK=$(echo "$DEAD_CODE" | awk '$5 > 0.01')
  LOW_PAGERANK=$(echo "$DEAD_CODE" | awk '$5 <= 0.01')

  if [ -n "$HIGH_PAGERANK" ]; then
    echo "WARNING: High-PageRank dead code found (possible broken references)"
    echo "$HIGH_PAGERANK"
  fi

  if [ -n "$LOW_PAGERANK" ]; then
    echo "Cleanup candidates (low PageRank):"
    echo "$LOW_PAGERANK"
  fi
fi

Limitations Note: Results labeled "Potentially Dead" require manual verification for:

  • Dynamically imported modules
  • Reflection-accessed code
  • External API consumers

PHASE 0: MANDATORY SETUP

Step 1: Verify claudemem v0.3.0

which claudemem && claudemem --version
# Must be 0.3.0+

Step 2: If Not Installed → STOP

Use AskUserQuestion (see ultrathink-detective for template)

Step 3: Check Index Status

# Check claudemem installation and index
claudemem --version && ls -la .claudemem/index.db 2>/dev/null

Step 3.5: Check Index Freshness

Before proceeding with investigation, verify the index is current:

# First check if index exists
if [ ! -d ".claudemem" ] || [ ! -f ".claudemem/index.db" ]; then
  # Use AskUserQuestion to prompt for index creation
  # Options: [1] Create index now (Recommended), [2] Cancel investigation
  exit 1
fi

# 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 .claudemem/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" .claudemem/index.db 2>/dev/null)
  else
    INDEX_TIME=$(stat -c "%y" .claudemem/index.db 2>/dev/null | cut -d'.' -f1)
  fi
  INDEX_TIME=${INDEX_TIME:-"unknown time"}

  # Get sample of stale files
  STALE_SAMPLE=$(find . -type f \( -name "*.ts" -o -name "*.tsx" \) \
    -newer .claudemem/index.db 2>/dev/null | grep -v "node_modules" | grep -v ".git" | head -5)

  # Use AskUserQuestion (see template in ultrathink-detective)
fi

Step 4: Index if Needed

claudemem index

Workflow: Architecture Analysis (v0.3.0)

Phase 1: Map the Landscape

# Get structural overview with PageRank
claudemem --agent map
# Focus on high-PageRank symbols (> 0.01) - these are architectural pillars

Phase 2: Identify Layers

# Map each layer
claudemem --agent map "controller handler endpoint"  # Presentation
claudemem --agent map "service business logic"       # Business
claudemem --agent map "repository database query"    # Data

Phase 3: Trace Dependencies

# For each high-PageRank symbol, understand its role
claudemem --agent symbol UserServiceclaudemem --agent callers UserService  # Who depends on it?
claudemem --agent callees UserService  # What does it depend on?

Phase 4: Identify Boundaries

# Find interfaces (architectural contracts)
claudemem --agent map "interface abstract"
# Check how implementations connect
claudemem --agent callers IUserRepository```

### Phase 5: Cleanup Opportunities (v0.4.0+ Required)

```bash
# Find dead code
DEAD_CODE=$(claudemem --agent dead-code)

if [ -z "$DEAD_CODE" ]; then
  echo "No cleanup needed - codebase is well-maintained"
else
  # For each dead symbol:
  # - Check PageRank (low = utility, high = broken)
  # - Verify not used externally (see limitations)
  # - Add to cleanup backlog

  echo "Review each item for static analysis limitations:"
  echo "- Dynamic imports may hide real usage"
  echo "- External callers not visible to static analysis"
fi

Output Format: Architecture Report

1. Architecture Overview

┌─────────────────────────────────────────────────────────┐
│                 ARCHITECTURE ANALYSIS                    │
├─────────────────────────────────────────────────────────┤
│  Pattern: Clean Architecture / Layered                  │
│  Core Abstractions (PageRank > 0.05):                   │
│    - UserService (0.092) - Central business logic       │
│    - Database (0.078) - Data access foundation          │
│    - AuthMiddleware (0.056) - Security boundary         │
│  Search Method: claudemem v0.3.0 (AST + PageRank)       │
└─────────────────────────────────────────────────────────┘

2. Layer Map

┌─────────────────────────────────────────────────────────┐
│                    LAYER STRUCTURE                       │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  PRESENTATION (src/controllers/, src/routes/)            │
│    └── UserController (0.034)                           │
│    └── AuthController (0.028)                           │
│            ↓                                             │
│  BUSINESS (src/services/)                               │
│    └── UserService (0.092) ⭐HIGH PAGERANK              │
│    └── AuthService (0.067)                              │
│            ↓                                             │
│  DATA (src/repositories/)                               │
│    └── UserRepository (0.045)                           │
│    └── Database (0.078) ⭐HIGH PAGERANK                 │
│                                                          │
└─────────────────────────────────────────────────────────┘

3. Dependency Flow

Entry → Controller → Service → Repository → Database
                  ↘ Middleware (cross-cutting)

PageRank for Architecture

PageRankArchitectural RoleAction
> 0.05Core abstractionThis IS the architecture - understand first
0.01-0.05Important componentKey building block, affects many things
0.001-0.01Standard componentNormal code, not architecturally significant
< 0.001Leaf/utilityImplementation detail, skip for arch analysis

Result Validation Pattern

After EVERY claudemem command, validate results:

Map Command Validation

After map commands, validate architectural symbols were found:

RESULTS=$(claudemem --agent map "service layer business logic")
EXIT_CODE=$?

# Check for failure
if [ "$EXIT_CODE" -ne 0 ]; then
  DIAGNOSIS=$(claudemem status 2>&1)
  # Use AskUserQuestion
fi

# Check for empty results
if [ -z "$RESULTS" ]; then
  echo "WARNING: No symbols found - may be wrong query or index issue"
  # Use AskUserQuestion: Reindex, Different query, or Cancel
fi

# Check for high-PageRank symbols (> 0.01)
HIGH_PR=$(echo "$RESULTS" | grep "pagerank:" | awk -F': ' '{if ($2 > 0.01) print}' | wc -l)

if [ "$HIGH_PR" -eq 0 ]; then
  # No architectural symbols found - may be wrong query or index issue
  # Use AskUserQuestion: Reindex, Broaden query, or Cancel
fi

Symbol Validation

SYMBOL=$(claudemem --agent symbol ArchitecturalComponent)

if [ -z "$SYMBOL" ] || echo "$SYMBOL" | grep -qi "not found\|error"; then
  # Component doesn't exist or index issue
  # Use AskUserQuestion
fi

FALLBACK PROTOCOL

CRITICAL: Never use grep/find/Glob without explicit user approval.

If claudemem fails or returns irrelevant results:

  1. STOP - Do not silently switch tools
  2. DIAGNOSE - Run claudemem status
  3. REPORT - Tell user what happened
  4. ASK - Use AskUserQuestion for next steps
// Fallback options (in order of preference)
AskUserQuestion({
  questions: [{
    question: "claudemem map returned no architectural symbols or failed. How should I proceed?",
    header: "Architecture Discovery Issue",
    multiSelect: false,
    options: [
      { label: "Reindex codebase", description: "Run claudemem index (~1-2 min)" },
      { label: "Try broader query", description: "Use different architectural terms" },
      { label: "Use grep (not recommended)", description: "Traditional search - loses PageRank ranking" },
      { label: "Cancel", description: "Stop investigation" }
    ]
  }]
})

See ultrathink-detective skill for complete Fallback Protocol documentation.


Anti-Patterns

Anti-PatternWhy WrongCorrect Approach
grep -r "class"No ranking, no structureclaudemem --agent map
Read all filesToken wasteFocus on high-PageRank symbols
Skip map commandMiss architectureALWAYS start with map
Ignore PageRankMiss core abstractionsHigh PageRank = important
cmd | head/tailHides high-PageRank symbolsUse full output or --tokens

Output Truncation Warning

╔══════════════════════════════════════════════════════════════════════════════╗ ║ ║ ║ ❌ Anti-Pattern 7: Truncating Claudemem Output ║ ║ ║ ║ FORBIDDEN (any form of output truncation): ║ ║ → BAD: claudemem --agent map "query" | head -80 ║ ║ → BAD: claudemem --agent callers X | tail -50 ║ ║ → BAD: claudemem --agent search "x" | grep -m 10 "y" ║ ║ → BAD: claudemem --agent map "q" | awk 'NR <= 50' ║ ║ → BAD: claudemem --agent callers X | sed '50q' ║ ║ → BAD: claudemem --agent search "x" | sort | head -20 ║ ║ → BAD: claudemem --agent map "q" | grep "pattern" | head -20 ║ ║ ║ ║ CORRECT (use full output or built-in limits): ║ ║ → GOOD: claudemem --agent map "query" ║ ║ → GOOD: claudemem --agent search "x" -n 10 ║ ║ → GOOD: claudemem --agent map "q" --tokens 2000 ║ ║ → GOOD: claudemem --agent search "x" --page-size 20 --page 1 ║ ║ → GOOD: claudemem --agent context Func --max-depth 3 ║ ║ ║ ║ WHY: Output is pre-optimized; truncation hides critical results ║ ║ ║ ╚══════════════════════════════════════════════════════════════════════════════╝


Feedback Reporting (v0.8.0+)

After completing investigation, report search feedback to improve future results.

When to Report

Report feedback ONLY if you used the search command during investigation:

Result TypeMark AsReason
Read and usedHelpfulContributed to investigation
Read but irrelevantUnhelpfulFalse positive
Skipped after previewUnhelpfulNot relevant to query
Never read(Don't track)Can't evaluate

Feedback Pattern

# Track during investigation
SEARCH_QUERY="your original query"
HELPFUL_IDS=""
UNHELPFUL_IDS=""

# When reading a helpful result
HELPFUL_IDS="$HELPFUL_IDS,$result_id"

# When reading an unhelpful result
UNHELPFUL_IDS="$UNHELPFUL_IDS,$result_id"

# Report at end of investigation (v0.8.0+ only)
if claudemem feedback --help 2>&1 | grep -qi "feedback"; then
  timeout 5 claudemem feedback \
    --query "$SEARCH_QUERY" \
    --helpful "${HELPFUL_IDS#,}" \
    --unhelpful "${UNHELPFUL_IDS#,}" 2>/dev/null || true
fi

Output Update

Include in investigation report:

Search Feedback: [X helpful, Y unhelpful] - Submitted (v0.8.0+)

Notes

  • map is your primary tool - It shows architecture through PageRank
  • High-PageRank symbols ARE the architecture - they're what everything depends on
  • Use callers to see what depends on a component (impact of changes)
  • Use callees to see what a component depends on (its requirements)
  • Works best with TypeScript, Go, Python, Rust codebases

Maintained by: MadAppGang Plugin: code-analysis v2.7.0 Last Updated: December 2025 (v3.3.0 - Cross-platform compatibility, inline templates, improved validation)

Readme

Shared Resources

This directory contains resources shared across all Claude Code plugins.

Purpose

Centralized management of common resources to ensure consistency and reduce duplication.

Architecture

shared/                                    ← SOURCE OF TRUTH (edit here)
├── recommended-models.md                  ← Model recommendations
├── QUICK_REFERENCE_SPEC.md                ← Quick reference spec
├── README.md                              ← This file
└── skills/                                ← Shared skills
    └── claudish-usage/                    ← Claudish usage skill
        └── SKILL.md                       ← AUTO-DISTRIBUTED

scripts/
└── sync-shared.ts                         ← Distribution script (recursive)

plugins/
├── frontend/
│   ├── recommended-models.md              ← AUTO-COPIED
│   ├── QUICK_REFERENCE_SPEC.md            ← AUTO-COPIED
│   ├── README.md                          ← AUTO-COPIED
│   └── skills/                            ← AUTO-CREATED
│       └── claudish-usage/                ← AUTO-CREATED
│           └── SKILL.md                   ← AUTO-COPIED
├── bun/
│   ├── recommended-models.md              ← AUTO-COPIED
│   ├── QUICK_REFERENCE_SPEC.md            ← AUTO-COPIED
│   ├── README.md                          ← AUTO-COPIED
│   └── skills/                            ← AUTO-CREATED
│       └── claudish-usage/                ← AUTO-CREATED
│           └── SKILL.md                   ← AUTO-COPIED
└── code-analysis/
    ├── recommended-models.md              ← AUTO-COPIED
    ├── QUICK_REFERENCE_SPEC.md            ← AUTO-COPIED
    ├── README.md                          ← AUTO-COPIED
    └── skills/                            ← AUTO-CREATED
        └── claudish-usage/                ← AUTO-CREATED
            └── SKILL.md                   ← AUTO-COPIED

How It Works

1. Edit Source Files

All shared resources are stored in shared/ directory. This is the ONLY place you should edit these files.

Example:

# Edit the source
vim shared/recommended-models.md

2. Sync to Plugins

Run the sync script to copy resources to all plugins:

# Sync all shared resources
bun run sync-shared

# Or use the short alias
bun run sync

3. Automatic Distribution

The sync script copies each file from shared/ to all plugin directories:

  • shared/recommended-models.md → plugins/frontend/recommended-models.md
  • shared/recommended-models.md → plugins/bun/recommended-models.md
  • shared/recommended-models.md → plugins/code-analysis/recommended-models.md

4. Plugin Usage

Commands and agents read the synced files using plugin-relative paths:

For flat files:

Read file: ${CLAUDE_PLUGIN_ROOT}/recommended-models.md

For skills:

Read file: ${CLAUDE_PLUGIN_ROOT}/skills/claudish-usage/SKILL.md

This ensures each plugin always has access to the latest recommendations and shared skills.

Shared Skills

What are Shared Skills?

Shared skills are reusable knowledge modules that are distributed across all plugins. They provide:

  • ✅ Consistent guidance across plugins
  • ✅ Centralized knowledge management
  • ✅ Automatic updates when skills are improved
  • ✅ Reduced duplication

Current Shared Skills

  1. claudish-usage (skills/claudish-usage/SKILL.md)
    • How to use Claudish CLI with OpenRouter models
    • File-based sub-agent patterns
    • Model selection and cost tracking
    • Best practices for AI agents

Adding New Shared Skills

  1. Create skill directory: shared/skills/skill-name/
  2. Add SKILL.md file with YAML frontmatter:
    ---
    name: skill-name
    description: Clear description of what the skill does and when to use it
    ---
    
  3. Write skill content (instructions, examples, best practices)
  4. Run bun run sync-shared
  5. Skill is automatically distributed to all plugins and discovered by Claude

Using Shared Skills in Commands/Agents

Skills are automatically discovered - Claude loads them based on the task at hand.

Skills must have YAML frontmatter with name and description:

---
name: claudish-usage
description: Guide for using Claudish CLI to run Claude Code with OpenRouter models. Use when working with external AI models, multi-model workflows, or cost optimization.
---

How it works:

  1. Startup: Skill metadata (name + description) loaded into system prompt (~100 tokens/skill)
  2. Task matching: When user request matches description, Claude automatically reads SKILL.md via bash
  3. Progressive loading: Claude only loads relevant skills, avoiding context pollution

You do NOT need to:

  • ❌ Manually read skill files with Read tool
  • ❌ Reference skills in agent/command prompts
  • ❌ Load skills into context explicitly

Claude automatically uses skills when:

  • ✅ Task matches the skill's description
  • ✅ User mentions keywords from description (e.g., "Claudish", "OpenRouter", "Grok")
  • ✅ Workflow requires skill's capabilities

Example: User asks "use Grok to implement feature X"

  1. Claude recognizes "Grok" matches claudish-usage skill description
  2. Automatically reads skills/claudish-usage/SKILL.md via bash
  3. Uses skill guidance to complete the task

Only reference skills explicitly if:

  • You need to pass skill content to a sub-agent that doesn't have skill access
  • You're building a tool that needs to extract skill metadata
  • You're debugging or testing skill content

Maintaining Shared Resources

Adding New Shared Files

  1. Create the file in shared/ directory (or subdirectory)
  2. Run bun run sync-shared
  3. File is automatically copied to all plugins (preserving directory structure)
  4. Update plugin commands/agents to use the new file

Updating Existing Files

  1. Edit the file in shared/ directory (NOT in plugin directories)
  2. Run bun run sync-shared
  3. Updates are automatically distributed to all plugins

Adding New Plugins

  1. Add plugin name to PLUGIN_NAMES array in scripts/sync-shared.ts
  2. Run bun run sync-shared
  3. All shared resources are copied to the new plugin

File Format Standards

Markdown Files

Shared markdown files should be:

  • AI-native (no JSON parsing required)
  • Human-readable
  • Well-structured with clear headings
  • Include rich context and explanations
  • Use consistent formatting

Example: Model Recommendations

### Model Name (⭐ RECOMMENDED)
- **Provider:** provider-name
- **OpenRouter ID:** `provider/model-id`
- **Best For:** use cases
- **Trade-offs:** considerations

Best Practices

DO:

✅ Edit files in shared/ directory only ✅ Run sync script after every change ✅ Use descriptive file names ✅ Include version and last-updated metadata in files ✅ Add comments explaining the purpose of each file

DON'T:

❌ Edit files in plugin directories directly (changes will be overwritten) ❌ Commit plugin copies to git (they're auto-generated) ❌ Skip running sync script after changes ❌ Use complex file formats that require parsing

Future Extensibility

This pattern can be extended to other shared resources:

Current Shared Resources:

  • ✅ Skills - Reusable knowledge modules (skills/claudish-usage/)
  • ✅ Model Recommendations - OpenRouter model data (recommended-models.md)
  • ✅ Quick Reference - Spec templates (QUICK_REFERENCE_SPEC.md)

Future Shared Resources:

  • API Schema Templates - Standard OpenAPI schemas (schemas/)
  • Best Practices Snippets - Common code patterns (snippets/)
  • Configuration Templates - Standard configs (templates/)
  • Testing Patterns - Standard test structures (patterns/)
  • Documentation Templates - Standard doc formats (docs/)

To add a new shared resource:

  1. Create file/directory in shared/
  2. Run bun run sync-shared (handles subdirectories automatically)
  3. Update plugin files to reference it using ${CLAUDE_PLUGIN_ROOT}/path/to/file
  4. Document in this README

Troubleshooting

Sync Script Fails

Problem: ❌ Shared directory not found Solution: Ensure you're running from repository root

Problem: ✗ Failed to copy to plugin Solution: Check plugin directory exists and is writable

Plugin Files Out of Sync

Problem: Plugin has old version of shared file Solution: Run bun run sync-shared to update

Changes Not Appearing

Problem: Edited plugin file directly Solution: Edit shared/ file instead, then run sync

Questions?

See main documentation:

Contact: Jack Rudenko (i@madappgang.com)

Details

Marketplace
MadAppGang/claude-code
Source
plugins/code-analysis
Author
Jack Rudenko
Category
Development
Keywords
code-analysis, codebase, investigation, detective, architecture, patterns, debugging, code-navigation, semantic-search, claudemem, enrichment
Listed since
Apr 6, 2026

More from MadAppGang/claude-code

All 9

Similar to code-analysis

More Developer Tools