Your codebase's context needs a responsible adult. Fast code exploration, living project narratives, and tribal knowledge that survives across sessions.

version
0.20.0
GitHub stars
8

Install

/plugin install context-daddy@chipflow-context-daddy

Run it inside Claude Code after adding the marketplace with /plugin marketplace add ChipFlow/context-daddy.

Contents

Discovered from source

Skills 1

Context Tools for Claude Code

This skill provides intelligent context management for large codebases through:

  • Repository Mapping: Parses Python, Rust, and C++ code to extract classes, functions, and methods
  • Duplicate Detection: Identifies similar code patterns using fuzzy matching
  • MCP Symbol Server: Enables fast symbol search via search_symbols and get_file_symbols tools
  • Automatic Indexing: Background incremental updates as files change

Using MCP Tools - PRIMARY CODE EXPLORATION METHOD

⚡ DECISION TREE - Ask yourself BEFORE using Grep/Search/Bash:

Am I searching for code symbols (functions, classes, enums, structs, types)?
├─ YES → Use MCP tools (search_symbols / get_symbol_content / get_file_symbols)
│         Example: Finding "enum InstructionData" → search_symbols("InstructionData")
│         Example: Finding "Phi" variant → get_symbol_content("InstructionData")
│
└─ NO → Am I searching for text/comments/strings/config values?
          └─ YES → Use Grep/Search
                   Example: Finding string literals, documentation, JSON values

CRITICAL: Use repo-map tools as your FIRST approach when you need to:

  • Find a function/class/method by name or pattern → search_symbols
  • Understand how to use a function (parameters, return type) → search_symbols or get_symbol_content
  • Get the source code of a specific function/class → get_symbol_content
  • See all code in a file → get_file_symbols
  • Discover what functionality exists in the codebase → search_symbols with patterns

Do NOT use Grep or Bash for these tasks - the repo-map tools are:

  • Faster (pre-indexed SQLite database)
  • More accurate (AST-parsed, not regex)
  • More informative (includes signatures, docstrings, line ranges)

When to use Grep instead:

  • Searching for string literals, comments, or arbitrary text
  • Searching in non-code files (markdown, config, etc.)
  • Cross-file text pattern searches

Tool availability check: Before attempting to use MCP tools (mcp__plugin_context-daddy_repo-map__*), check if .claude/repo-map.db exists:

  • If YES: Try the MCP tool. If it fails (not available), use sqlite3 fallback.
  • If NO: The project hasn't been indexed yet. Either wait for indexing or run /context-daddy:repo-map to generate it.

Fallback order:

  1. Try MCP tool first
  2. If tool not found, use sqlite3 fallback to still answer the question
  3. Explain that session needs restart to load MCP server for future use

Real-World Usage Examples

Example 1: User asks "Can we compare against OSDI?"

Inefficient approach (DON'T DO THIS):

grep -r "setup_model\|setup_instance" jax_spice/devices/*.py

Problems: Slow, error-prone pattern matching, gets interrupted on large codebases.

Efficient approach (DO THIS):

mcp__plugin_context-daddy_repo-map__search_symbols
pattern: "setup_*"

Result: Instant list of all setup_model, setup_instance, etc. with locations and signatures.

Example 2: User asks "How does the config loader work?"

Inefficient approach (DON'T DO THIS):

find . -name "*.py" -exec grep -l "class.*Config" {} \;

Efficient approach (DO THIS):

mcp__plugin_context-daddy_repo-map__search_symbols
pattern: "*Config*"
kind: "class"

Then get the source:

mcp__plugin_context-daddy_repo-map__get_symbol_content
name: "ConfigLoader"

Example 3: User asks "What functions are in utils.py?"

Inefficient approach (DON'T DO THIS):

grep "^def " src/utils.py

Efficient approach (DO THIS):

mcp__plugin_context-daddy_repo-map__get_file_symbols
file: "src/utils.py"

Result: Complete list of all functions/classes with signatures and docstrings.

Example 4: Finding Rust enum variants (Real user case)

User needs to check if it's Phi or PhiNode in enum InstructionData.

Inefficient approach (DON'T DO THIS):

grep -n "enum InstructionData" openvaf-py/vendor/OpenVAF/openvaf/mir/src
grep -n "Phi" openvaf-py/vendor/OpenVAF/openvaf/mir/src/instructions.rs

Problems: Multiple searches, manual parsing, easy to miss correct variant.

Efficient approach (DO THIS):

mcp__plugin_context-daddy_repo-map__search_symbols
pattern: "InstructionData"

mcp__plugin_context-daddy_repo-map__get_symbol_content
name: "InstructionData"

Result: Complete enum with all variants visible, including PhiNode(_).

First Time Setup

IMPORTANT: If the user has just installed this plugin:

"I see you've installed the context-daddy plugin. The MCP server should auto-configure on restart. After restarting Claude Code, run /mcp to verify the repo-map server is loaded.

If it doesn't load automatically, let me know and I can help troubleshoot using /context-daddy:setup-mcp."

The MCP server auto-configures from the plugin manifest. Only if auto-config fails should you run /context-daddy:setup-mcp for troubleshooting.

Included Components

Hooks

  • SessionStart: Generates project manifest and displays status
  • PreCompact: Refreshes context before compaction
  • SessionEnd: Cleanup operations

Note: Indexing is now handled by the MCP server itself (no PreToolUse hook needed).

MCP Server (repo-map)

Database Schema (.claude/repo-map.db):

symbols table columns:
- name (TEXT): Symbol name (function/class/method name)
- kind (TEXT): "function", "class", or "method"
- signature (TEXT): Full function/method signature with parameters and type hints
  Examples:
  - "extract_symbols_from_python(file_path: Path, relative_to: Path) -> list[Symbol]"
  - "analyze_files(files: list[Path], extractor, language: str, root: Path)"
- docstring (TEXT): First line of docstring or full docstring
- file_path (TEXT): Relative path from project root
- line_number (INTEGER): Start line (1-indexed)
- end_line_number (INTEGER): End line (1-indexed)
- parent (TEXT): For methods, the class name

metadata table (v0.7.0+):
- key (TEXT PRIMARY KEY): Metadata key
- value (TEXT): Metadata value
Keys:
- 'status': 'idle' | 'indexing' | 'completed' | 'failed'
- 'index_start_time': ISO8601 timestamp when indexing started
- 'last_indexed': ISO8601 timestamp when last completed
- 'symbol_count': Total symbols indexed (string)
- 'error_message': Error message if status='failed'

Indexing Status and Auto-Wait (v0.7.0+):

  • The MCP server tracks indexing status in the metadata table
  • Tools automatically wait (up to 60s) if indexing is in progress
  • Watchdog: Detects hung indexing (>10 minutes) and resets status to 'failed'
  • First Use: On first use in a new codebase, indexing starts automatically
  • Behavior: Most tools wait for completion, repo_map_status does not (use to check progress)

Available MCP Tools:

  • mcp__plugin_context-daddy_repo-map__search_symbols - Search symbols by pattern (supports glob wildcards)
    • Returns: name, kind, signature, file_path, line_number, docstring, parent
    • AUTO-WAIT: If indexing is in progress, automatically waits up to 60s for completion
  • mcp__plugin_context-daddy_repo-map__get_file_symbols - Get all symbols in a specific file
    • Returns: All symbols with full metadata
    • AUTO-WAIT: If indexing is in progress, automatically waits up to 60s for completion
  • mcp__plugin_context-daddy_repo-map__get_symbol_content - Get full source code of a symbol by exact name
    • Returns: symbol metadata + content (source code text) + location
    • AUTO-WAIT: If indexing is in progress, automatically waits up to 60s for completion
  • mcp__plugin_context-daddy_repo-map__list_files - List all indexed files, optionally filtered by glob pattern
    • Returns: list of file paths matching pattern (e.g., ".va", "psp103", "**/devices/")
    • MUCH faster than find/ls - queries pre-built index instead of filesystem traversal
    • AUTO-WAIT: If indexing is in progress, automatically waits up to 60s for completion
  • mcp__plugin_context-daddy_repo-map__reindex_repo_map - Trigger manual reindex
    • Does NOT auto-wait (use to force reindex)
  • mcp__plugin_context-daddy_repo-map__repo_map_status - Check indexing status and staleness
    • Returns: index_status (idle/indexing/completed/failed), symbol_count, last_indexed, indexing_duration_seconds
    • Does NOT auto-wait (use to check status)
  • mcp__plugin_context-daddy_repo-map__wait_for_index - Explicitly wait for indexing to complete
    • Takes: timeout_seconds (default: 60)
    • Returns: success (bool), message (str)
    • Use when you want to wait longer than the default 60s auto-wait timeout

Fallback when MCP tools unavailable: Use sqlite3 directly on .claude/repo-map.db:

# Search symbols
sqlite3 .claude/repo-map.db "SELECT name, kind, signature, file_path, line_number FROM symbols WHERE name LIKE 'pattern%' LIMIT 20"

# Get symbol with source
sqlite3 .claude/repo-map.db "SELECT * FROM symbols WHERE name = 'function_name'"
# Then read file_path lines line_number to end_line_number

Slash Commands

  • /context-daddy:repo-map - Regenerate repository map
  • /context-daddy:manifest - Refresh project manifest
  • /context-daddy:learnings - Manage project learnings
  • /context-daddy:status - Show plugin status

Language Support

LanguageParserFile Extensions
PythonAST.py
Rusttree-sitter-rust.rs
C++tree-sitter-cpp.cpp, .cc, .cxx, .hpp, .h, .hxx

Commands 16

Clash Summary

Show a summary of potential naming clashes detected in the codebase with analysis.

python3 << 'PYSCRIPT'
import re
import json
from pathlib import Path

repo_map = Path(".claude/repo-map.md")
if not repo_map.exists():
    print("No repo map found. Run /repo-map first.")
    exit(0)

content = repo_map.read_text()

# Parse similar classes (multi-line format)
# Format: - **Name1** (file1.py)\n  ↔ **Name2** (file2.py)\n  Reason: ...
similar_classes = []
class_pattern = re.compile(
    r'- \*\*([^*]+)\*\* \(([^)]+)\)\n\s+↔ \*\*([^*]+)\*\* \(([^)]+)\)\n\s+Reason: ([^\n]+)',
    re.MULTILINE
)
class_section = re.search(r'## ⚠️ Potentially Similar Classes.*?(?=\n## |\Z)', content, re.DOTALL)
if class_section:
    for match in class_pattern.finditer(class_section.group(0)):
        similar_classes.append({
            'name1': match.group(1), 'loc1': match.group(2),
            'name2': match.group(3), 'loc2': match.group(4),
            'reason': match.group(5)
        })

# Parse similar functions (multi-line format)
similar_functions = []
func_section = re.search(r'## ⚠️ Potentially Similar Functions.*?(?=\n## |\Z)', content, re.DOTALL)
if func_section:
    for match in class_pattern.finditer(func_section.group(0)):
        similar_functions.append({
            'name1': match.group(1), 'loc1': match.group(2),
            'name2': match.group(3), 'loc2': match.group(4),
            'reason': match.group(5)
        })

total = len(similar_classes) + len(similar_functions)
if total == 0:
    print("No naming clashes detected in this codebase.")
    exit(0)

print(f"{total} potential naming clash(es) detected\n")

# Output detailed clash info for Claude to analyze
if similar_classes:
    print(f"=== Similar Classes ({len(similar_classes)}) ===\n")
    for c in similar_classes:
        print(f"  {c['name1']} ({c['loc1']})")
        print(f"    <-> {c['name2']} ({c['loc2']})")
        print(f"    Reason: {c['reason']}")
        print()

if similar_functions:
    print(f"=== Similar Functions ({len(similar_functions)}) ===\n")
    for f in similar_functions:
        print(f"  {f['name1']} ({f['loc1']})")
        print(f"    <-> {f['name2']} ({f['loc2']})")
        print(f"    Reason: {f['reason']}")
        print()

print("---")
print("Run /resolve-clashes to review and resolve interactively.")
PYSCRIPT

After running this command:

  1. Review the clashes listed above
  2. Analyze each clash to determine if it's:
    • Intentional: Different purposes (e.g., Setup vs Result, strategy patterns, test utilities)
    • Candidate for consolidation: True duplicates that could be merged
    • Naming issue: Similar names that could be made more distinct
  3. Suggest specific resolutions for clashes that appear problematic
  4. Use /resolve-clashes to interactively resolve them

Debug Plugin Status

Run this to diagnose plugin issues:

echo "=== Context Tools Debug ==="
echo ""

# Check .claude directory
CLAUDE_DIR="${PWD}/.claude"
echo "Project .claude dir: ${CLAUDE_DIR}"
if [[ -d "${CLAUDE_DIR}" ]]; then
    echo "  EXISTS"
    ls -la "${CLAUDE_DIR}/" 2>/dev/null || echo "  (empty)"
else
    echo "  DOES NOT EXIST"
fi
echo ""

# Check repo map
REPO_MAP="${CLAUDE_DIR}/repo-map.md"
if [[ -f "${REPO_MAP}" ]]; then
    SYMBOL_COUNT=$(grep -c "^\*\*" "${REPO_MAP}" 2>/dev/null || echo "0")
    echo "Repo map: EXISTS (${SYMBOL_COUNT} symbols)"
    echo "  Modified: $(stat -f '%Sm' "${REPO_MAP}" 2>/dev/null || stat -c '%y' "${REPO_MAP}" 2>/dev/null || echo 'unknown')"
else
    echo "Repo map: DOES NOT EXIST"
fi
echo ""

# Check progress file
PROGRESS="${CLAUDE_DIR}/repo-map-progress.json"
if [[ -f "${PROGRESS}" ]]; then
    echo "Progress file: EXISTS"
    cat "${PROGRESS}" | python3 -m json.tool 2>/dev/null || cat "${PROGRESS}"
else
    echo "Progress file: DOES NOT EXIST"
fi
echo ""

# Check lock file
LOCK="${CLAUDE_DIR}/repo-map-cache.lock"
if [[ -f "${LOCK}" ]]; then
    echo "Lock file: EXISTS (indexing in progress)"
    cat "${LOCK}"
else
    echo "Lock file: does not exist (not currently indexing)"
fi
echo ""

# Check cache
CACHE="${CLAUDE_DIR}/repo-map-cache.json"
if [[ -f "${CACHE}" ]]; then
    FILE_COUNT=$(python3 -c "import json; print(len(json.load(open('${CACHE}')).get('files', {})))" 2>/dev/null || echo "?")
    echo "Cache: EXISTS (${FILE_COUNT} files cached)"
else
    echo "Cache: DOES NOT EXIST"
fi
echo ""

# Check manifest
MANIFEST="${CLAUDE_DIR}/project-manifest.json"
if [[ -f "${MANIFEST}" ]]; then
    echo "Manifest: EXISTS"
    python3 -c "import json; m=json.load(open('${MANIFEST}')); print(f\"  Project: {m.get('project_name', '?')}\")" 2>/dev/null || true
else
    echo "Manifest: DOES NOT EXIST"
fi
echo ""

echo "=== Debug Complete ==="

This will show all the plugin state files and their contents.

Complete Current Goal Step

Quick step completion for the active goal.

IMPORTANT: This is an executable skill

When invoked, execute the steps below. Don't just explain - DO it.

Step 1: Show Current Goal

Use the goal_show MCP tool:

goal_show()

If no current goal is set, tell the user and suggest /context-daddy:goal to select one.

Step 2: Identify Current Step

Find the step marked with ← current in the output. Note its step ID and description.

Step 3: Confirm and Complete

Tell the user which step will be marked complete and ask for confirmation.

If confirmed, use the goal_update_step MCP tool:

goal_update_step(id="<goal-id>", step="<step-id>", complete=true)

Step 4: Optionally Add a Learning

Ask if there's anything worth recording about this step (approaches tried, gotchas):

goal_add_learning(id="<goal-id>", text="LEARNING_TEXT")

Step 5: Show Updated State

Use goal_show() to display the updated goal.

Summarize: what was completed and what the next step is.

Focus on a Goal Step

Set which step you're actively working on for the current goal.

IMPORTANT: This is an executable skill

When invoked, execute the steps below. Don't just explain - DO it.

Step 1: Show Current Goal

Use the goal_show MCP tool to display the current goal with its plan steps:

goal_show()

If no current goal is set, tell the user and suggest /context-daddy:goal to select one.

Step 2: Show Numbered Steps

Parse the plan steps from the output and display them clearly with their step IDs:

1. [define-plan] Define plan steps
2. [add-src-location] Add source location to ABC network nodes  <- current
3. [test-annotations] Write annotation tests

Step 3: Ask Which Step to Focus On

Ask the user which step they want to focus on. They can specify by:

  • Step ID (e.g., add-src-location)
  • Step number (e.g., 2)

Default to the next incomplete step if user doesn't specify.

Step 4: Set Focus

Use the goal_focus MCP tool:

goal_focus(step="<step-id>")

Step 5: Confirm

Show the updated focus:

  • Which step is now focused
  • Step position (e.g., "step 2/5")
  • The step description

Tell the user that this step will appear in their session context going forward.

Create New Goal

Guided creation of a cross-session goal that persists across sessions.

IMPORTANT: This is an executable skill

When invoked, execute the steps below. Don't just explain - DO it.

Step 1: Gather Info

Ask the user for:

  1. Title (short, descriptive): e.g., "Add source annotation tracking"
  2. Objective (1-3 sentences): What does success look like?

If the user provided these with the command (e.g., /context-daddy:goal-new "Add auth" "Implement OAuth2 login flow"), skip the questions.

Step 2: Create the Goal

Use the goal_create MCP tool:

goal_create(title="TITLE", objective="OBJECTIVE")

Note the goal ID and slug from the response.

Step 3: Add Plan Steps

Ask the user for their plan steps. If they have a rough plan, help refine it into discrete, checkable steps.

For each step, use the goal_add_step MCP tool:

goal_add_step(id="<goal-id>", description="Step description")

The first step created replaces the default "Define plan steps" placeholder.

You can specify a custom step ID with step_id or insert at a position with after:

goal_add_step(id="<goal-id>", description="Step description", step_id="custom-id", after="previous-step-id")

Step 4: Link Related Projects (Optional)

If the goal spans multiple projects, ask which other projects are involved:

goal_link_project(id="<goal-id>", path="/path/to/other-project", role="dependency")

Step 5: Confirm

Show the final goal using goal_show(id="<goal-id>").

Tell the user:

  • The goal is now active and will appear in future sessions
  • Use /context-daddy:goal-focus to set which step to work on
  • Use /context-daddy:goal-done to mark steps complete
  • Use /context-daddy:goal to manage goals

Goal Management

Manage cross-session goals that persist across sessions and projects.

IMPORTANT: This is an executable skill

When invoked, execute the steps below. Don't just explain - DO it.

Step 1: Show Current State

Use the goal_list MCP tool to see goals for the current project:

goal_list()

And show the current goal details:

goal_show()

If no current goal is set, note that and continue to Step 2.

Step 2: Offer Actions

Based on the output, offer the user these options:

  • Switch goal: If multiple goals exist, ask which to activate

    • Use the goal_switch MCP tool with the goal's UUID or slug
  • Show all goals (including other projects):

    • Use goal_list(all=true)
  • Create new goal: Point them to /context-daddy:goal-new

  • Focus on a step: Point them to /context-daddy:goal-focus

  • Complete current step: Point them to /context-daddy:goal-done

  • Archive a goal (mark as finished/abandoned):

    • Use goal_archive(id="<goal-id>")
  • Unset current goal (stop tracking without archiving):

    • Use goal_unset()
  • Reorder plan steps: To move steps around:

    1. Use goal_show() to see current plan
    2. Read the goal file directly (path shown in output, e.g. ~/.claude/goals/<id>.md)
    3. Rearrange the - [ ] [step-id] Description lines in the ## Plan section
    4. Write the file back. Steps are identified by [step-id], not position, so reordering is safe.
    5. Use goal_focus(step="<step-id>") to set the current step if needed
  • Remove a plan step: Edit the goal file directly and delete the line

Step 3: Execute User Choice

Run the appropriate MCP tool based on the user's selection.

After any change, show the updated state using goal_show().

MCP Tools vs Grep - When to Use What

The context-tools plugin provides fast MCP tools for code symbol lookups using a pre-built SQLite index. Use these instead of grep when searching for functions, classes, or methods.

Quick Reference

✅ Use MCP Tools When:

  • Finding functions/classes by name: search_symbols with patterns like setup_*, *Handler, Config*
  • Listing what's in a file: get_file_symbols shows all functions/classes without reading the file
  • Getting function source: get_symbol_content retrieves the full source by name
  • Exploring unfamiliar codebases: Much faster than grep for discovering structure

❌ Use Grep When:

  • Searching for arbitrary text or comments
  • Finding string literals or configuration values
  • Searching in non-code files (markdown, JSON, etc.)

Real-World Example

Scenario: User asks "Can we compare our generated code against OSDI?"

Inefficient approach (using grep):

grep -r "setup_model\|setup_instance" jax_spice/devices/*.py
# Problems:
# - Slow on large codebases
# - Pattern matching with wildcards is error-prone
# - Doesn't show function signatures
# - Gets interrupted easily

Efficient approach (using MCP tools):

mcp__plugin_context-tools_repo-map__search_symbols
pattern: "setup_*"
# Result: Instant list of all matching functions with file locations

mcp__plugin_context-tools_repo-map__get_symbol_content
name: "setup_model"
# Result: Full function source code without knowing which file

Example 2: Finding Rust enum variants (Real user interaction)

Scenario: Need to find the correct variant name for enum InstructionData (e.g., is it Phi or PhiNode?)

Inefficient approach (using grep):

grep -n "enum InstructionData" openvaf-py/vendor/OpenVAF/openvaf/mir/src
grep -n "Phi" openvaf-py/vendor/OpenVAF/openvaf/mir/src/instructions.rs | head -10
# Problems:
# - Multiple searches needed
# - Have to manually parse enum definition
# - Easy to miss the correct variant name

Efficient approach (using MCP tools):

mcp__plugin_context-tools_repo-map__search_symbols
pattern: "InstructionData"
# Result: Finds the enum definition location instantly

mcp__plugin_context-tools_repo-map__get_symbol_content
name: "InstructionData"
# Result: Complete enum definition showing all variants including PhiNode(_)

Benefits: One search, complete enum definition, see all variants at once.

Example 3: Finding files in directory structure (Real user interaction)

Scenario: Need to find PSP103 or BSIM4 models in vendor directory

Inefficient approach (using find/ls):

find vendor/OpenVAF/integration_tests -name "*.va" | grep -E "(psp103|bsim4)"
ls -la openvaf-py/vendor/OpenVAF/
ls -la vendor/
ls -la vendor/VACASK/devices/
ls -la vendor/VACASK/devices/psp103v4/
# Problems:
# - Trial and error with directory paths
# - Multiple ls commands to explore structure
# - Slow on large directory trees

Efficient approach (using MCP tools):

mcp__plugin_context-tools_repo-map__list_files
pattern: "*psp103*"
# Result: Instant list of all PSP103-related files

mcp__plugin_context-tools_repo-map__list_files
pattern: "*.va"
# Result: All Verilog-A model files

Benefits: One query, instant results, no trial-and-error with paths.

Available MCP Tools

Search for symbols by pattern:

mcp__plugin_context-tools_repo-map__search_symbols
pattern: "get_*"          # Functions starting with "get_"
pattern: "*Handler"       # Classes ending with "Handler"
pattern: "*config*"       # Anything containing "config"

List all symbols in a file:

mcp__plugin_context-tools_repo-map__get_file_symbols
file: "src/models/user.py"

Get source code by exact name:

mcp__plugin_context-tools_repo-map__get_symbol_content
name: "UserModel"         # Class name
name: "process_data"      # Function name
name: "User.save"         # Method name

List indexed files (discover file structure):

mcp__plugin_context-tools_repo-map__list_files
# List all indexed files

mcp__plugin_context-tools_repo-map__list_files
pattern: "*.va"           # All Verilog-A files
pattern: "*psp103*"       # PSP103 model files
pattern: "**/devices/*"   # All files under devices/

Check index status:

mcp__plugin_context-tools_repo-map__repo_map_status

Manually reindex:

mcp__plugin_context-tools_repo-map__reindex_repo_map

Performance

MCP tools use a pre-built SQLite index:

  • 10-100x faster than grep for symbol lookups
  • Works instantly even on massive codebases
  • No risk of interruption from large result sets

Multi-Project Support (v0.8.0+)

MCP tools automatically adapt to your current directory:

cd /path/to/project-A
# MCP tools query project-A's index

cd /path/to/project-B
# MCP tools now query project-B's index (no restart needed!)

Each project maintains its own .claude/repo-map.db index.

Cross-Session Goals (v0.14.0+)

Track multi-session, multi-project objectives that persist across sessions.

Commands:

  • /context-daddy:goal - List, switch, or archive goals
  • /context-daddy:goal-new - Create a new goal with guided setup
  • /context-daddy:goal-done - Complete the current step and advance
  • /context-daddy:goal-focus - Set which step you're working on

MCP Tools (v0.14.1+):

Goals are managed via MCP tools (no Bash noise). All tools are under mcp__plugin_context-daddy_goals__:

ToolPurpose
goal_createCreate a new goal
goal_listList goals (optionally all projects)
goal_showShow goal details
goal_switchSet active goal
goal_unsetRemove current goal marker
goal_focusSet focused step by step ID
goal_update_stepComplete or advance steps
goal_add_learningRecord an insight
goal_add_stepInsert a plan step
goal_link_projectLink a project to a goal
goal_archiveArchive a finished goal

Key concepts (v0.14.1):

  • Slugs: Goals have human-readable slugs (e.g., goal-tracking-functionality) auto-generated from the title. Use slugs or UUIDs interchangeably.
  • Step IDs: Each plan step has a text ID (e.g., [fix-review]) auto-generated from the description. Steps are referenced by ID, not position number.
  • Focus: Set which step you're working on with goal_focus. This appears in session context, subagent context, and status messages.
  • Project-scoped context: Session startup shows the active goal, focused step, recent activity filtered to the current project, and recent learnings.

How it works:

  • Goals are stored globally in ~/.claude/goals/ (survive across projects)
  • Each project has an index (.claude/active-goals.json) for fast startup
  • The active goal appears in session startup, post-compaction context, and subagent context
  • Commits are automatically tracked in the active goal's Recent Activity
  • PostToolUse hook shows updated status after goal changes

CLI (direct script usage):

uv run scripts/goals.py create "Title" "Objective"
uv run scripts/goals.py list [--all]
uv run scripts/goals.py show [<id-or-slug>]
uv run scripts/goals.py switch <id-or-slug>
uv run scripts/goals.py focus <step-id> [goal-id]
uv run scripts/goals.py update-step <id> <step-id> --complete
uv run scripts/goals.py add-learning <id> "text"
uv run scripts/goals.py add-step <id> "description" [--id custom-id] [--after step-id]
uv run scripts/goals.py archive <id>
uv run scripts/goals.py sync
uv run scripts/goals.py migrate  # Upgrade v1 goals to v2 format
uv run scripts/goals.py context  # Show project-scoped context as JSON

Troubleshooting

If MCP tools aren't working:

  1. Check if index exists: ls -la .claude/repo-map.db
  2. Check status: /context-tools:status or use repo_map_status tool
  3. Manually reindex: /context-tools:repo-map or use reindex_repo_map tool
  4. After plugin updates: Restart Claude Code session (Ctrl+C, then claude continue)

Manage Project Learnings

Record important discoveries and learnings for this project that should persist across sessions.

Check existing learnings

Project learnings are stored in .claude/learnings.md (create if it doesn't exist).

Global learnings (across all projects) are stored in ~/.claude/learnings.md.

Add a new learning

When you discover something important about this project (an optimization approach, a tricky pattern, a gotcha), record it in .claude/learnings.md with this format:

## [Topic]: Brief title

**Context**: When/where this applies
**Discovery**: What was learned
**Solution/Pattern**: How to handle it

Example learning entry

## Database: Connection pooling optimization

**Context**: High-traffic API endpoints with PostgreSQL
**Discovery**: Default pool size of 5 was causing connection exhaustion under load
**Solution/Pattern**: Increase pool size to 20, add connection timeout of 30s, implement retry logic with exponential backoff

Learnings help Claude remember important project-specific knowledge across sessions.

Regenerate Repository Map

Regenerate the repo map for this project to understand the code structure, find similar classes/functions, and identify documentation gaps.

Run this command to regenerate:

# Kill ALL repo-map processes for this project
PROJECT_PATH="${PWD}"
echo "Checking for existing repo-map processes..."
PIDS=$(pgrep -f "map.py.*${PROJECT_PATH}" 2>/dev/null || true)
if [[ -n "${PIDS}" ]]; then
    echo "Stopping existing processes: ${PIDS}"
    echo "${PIDS}" | xargs kill 2>/dev/null || true
    sleep 1
    # Force kill any remaining
    PIDS=$(pgrep -f "map.py.*${PROJECT_PATH}" 2>/dev/null || true)
    if [[ -n "${PIDS}" ]]; then
        echo "${PIDS}" | xargs kill -9 2>/dev/null || true
    fi
fi

# Run any cache format migrations (clears cache if incompatible version)
python3 -c "
import json
from pathlib import Path

CURRENT_VERSION = 2  # Must match CACHE_VERSION in map.py

cache_path = Path('.claude/repo-map-cache.json')
if cache_path.exists():
    try:
        data = json.loads(cache_path.read_text())
        version = data.get('version', 0)
        if version != CURRENT_VERSION:
            print(f'Cache version {version} != {CURRENT_VERSION}, clearing...')
            cache_path.unlink()
    except (json.JSONDecodeError, KeyError):
        print('Corrupt cache, clearing...')
        cache_path.unlink()
" 2>/dev/null

# Run in foreground with live output
echo "Regenerating repo map..."
uv run ${CLAUDE_PLUGIN_ROOT}/scripts/map.py 2>&1

# Show summary with clash count
if [[ -f .claude/repo-map.md ]]; then
    CLASH_COUNT=$(grep -c "^- \*\*" .claude/repo-map.md 2>/dev/null | head -1 || echo "0")
    if [[ "${CLASH_COUNT}" -gt 0 ]]; then
        echo ""
        echo "${CLASH_COUNT} potential naming clash(es) detected."
        echo "Run /clash-summary for overview or /resolve-clashes to review interactively."
    fi
fi

After running, review the output for:

  • Similar classes: May indicate overlapping responsibilities or duplicate implementations (same-language only)
  • Similar functions: May be candidates for consolidation (same-language only)
  • Undocumented code: Opportunities to improve codebase understanding

Note: Cross-language similarities (e.g., Python and Rust) are not flagged as they're typically intentional (bindings, ports).

If clashes are detected, use /clash-summary for an overview or /resolve-clashes to review and resolve them interactively.

Generate README from Narrative

Generate or update the project README based on the narrative document.

Prerequisites

You need a narrative first. If .claude/narrative.md doesn't exist:

/context-daddy:story

Generating README

uv run ${CLAUDE_PLUGIN_ROOT}/scripts/readme.py

This creates a README with:

  • What/Why - Quick pitch from narrative summary
  • Quick Start - Minimal install/run commands
  • Features - From narrative
  • How It Works - Architecture in plain language
  • The Journey - Story from narrative (no version numbers)
  • Dragons & Open Questions - Warnings and uncertainties

Updating Existing README

To update while preserving project-specific content:

uv run ${CLAUDE_PLUGIN_ROOT}/scripts/readme.py --update

Dry Run

Preview without saving:

uv run ${CLAUDE_PLUGIN_ROOT}/scripts/readme.py --dry-run

Structure

The generated README follows this order:

  1. What/Why/Quick Start - People want to use it first
  2. Features/Commands/How It Works - Reference material
  3. --- (separator) - Backstory below
  4. Journey/Dragons/Questions - For the curious

This structure prioritizes action over story while still capturing the narrative.

Update Project Narrative

Update the project's living narrative based on git history and session learnings.

IMPORTANT: This is an executable skill

When invoked, you MUST execute the update process below. Don't just explain it - DO it.

Step 1: Check Prerequisites

Verify the narrative exists:

ls -la .claude/narrative.md

If the file doesn't exist, tell the user to run /context-daddy:story first and stop.

Step 2: Gather Context

Build a session summary from TWO sources:

A. Your Session Understanding

Reflect on what you know from the current session:

  • What tasks did we work on?
  • What decisions were made?
  • What did we learn or discover?
  • Any gotchas or dragons encountered?
  • Did focus shift during the session?

B. User Input (Optional)

If the user provided a summary with the command (e.g., /context-daddy:refresh "we fixed the auth bug"), incorporate that.

If you're unsure about key context, ask:

Is there anything specific from this session I should include in the narrative update?

Step 3: Run the Update Script

Execute with --git-history flag to include recent commits, plus your session context:

uv run ${CLAUDE_PLUGIN_ROOT}/scripts/update-narrative.py --git-history "SESSION_CONTEXT_HERE"

Replace SESSION_CONTEXT_HERE with a concise summary combining:

  • Your understanding from the session (Step 2A)
  • Any user-provided context (Step 2B)

Example:

uv run ${CLAUDE_PLUGIN_ROOT}/scripts/update-narrative.py --git-history "Made refresh skill executable, added CI workflow for narrative freshness. Key insight: skills need to be prescriptive not just documentation."

The --git-history flag automatically extracts commits since the last narrative update.

If the script fails (e.g., missing ANTHROPIC_API_KEY), fall back to Step 4.

Step 4: Manual Fallback (only if script fails)

If the automated script isn't available:

  1. Get git history since last update:

    git log --oneline $(git log -1 --format=%H -- .claude/narrative.md)..HEAD
    
  2. Read .claude/narrative.md

  3. Revise it based on:

    • The git commits (what changed)
    • Your session understanding (why it changed, what we learned)
  4. Write the updated content back

CRITICAL RULES for manual update:

  • REVISE existing sections - don't append to end
  • Keep the SAME structure (Summary, Current Foci, How It Works, The Story So Far, Dragons & Gotchas, Open Questions)
  • Maintain "we" voice throughout
  • Be concise - integrate, don't bloat

Section guidance:

  • Current Foci: Update if focus shifted. Remove completed, add new.
  • The Story So Far: Only add for significant epochs.
  • Dragons & Gotchas: Add discoveries, remove fixed ones.
  • Open Questions: Remove answered, add new.

LENGTH LIMITS (auto-truncated when injected):

  • Summary: ~2-3 sentences, under 300 chars
  • Current Foci: 2-4 bullets, under 400 chars
  • Dragons: Key warnings, under 300 chars

Footer: Update the _Generated: line at the bottom with current date and session ID (from $CLAUDE_SESSION_ID env var or "unknown").

Step 5: Confirm Success

After the update completes, tell the user:

  • Narrative has been updated
  • Brief summary of what changed

When to Skip

If the session was just exploration/reading with no significant learnings, it's OK to skip. Tell the user:

"Nothing significant to update - narrative is still current."

Resolve Naming Clashes

Interactively review and resolve naming clashes in the codebase.

First, get the list of clashes:

python3 << 'PYSCRIPT'
import json
import re
from pathlib import Path

repo_map = Path(".claude/repo-map.md")
config_path = Path(".claude/clash-config.json")

# Load existing config
config = {"ignoredPairs": [], "ignoredDirs": [], "ignoredPatterns": []}
if config_path.exists():
    try:
        config = json.loads(config_path.read_text())
    except:
        pass

if not repo_map.exists():
    print(json.dumps({"error": "No repo map found. Run /repo-map first."}))
    exit(0)

content = repo_map.read_text()
clashes = []

# Parse clashes (multi-line format)
# Format: - **Name1** (file1.py)\n  ↔ **Name2** (file2.py)\n  Reason: ...
clash_pattern = re.compile(
    r'- \*\*([^*]+)\*\* \(([^)]+)\)\n\s+↔ \*\*([^*]+)\*\* \(([^)]+)\)\n\s+Reason: ([^\n]+)',
    re.MULTILINE
)

# Parse similar classes
class_section = re.search(r'## ⚠️ Potentially Similar Classes.*?(?=\n## |\Z)', content, re.DOTALL)
if class_section:
    for match in clash_pattern.finditer(class_section.group(0)):
        clashes.append({
            'type': 'class',
            'name1': match.group(1), 'loc1': match.group(2),
            'name2': match.group(3), 'loc2': match.group(4),
            'reason': match.group(5)
        })

# Parse similar functions
func_section = re.search(r'## ⚠️ Potentially Similar Functions.*?(?=\n## |\Z)', content, re.DOTALL)
if func_section:
    for match in clash_pattern.finditer(func_section.group(0)):
        clashes.append({
            'type': 'function',
            'name1': match.group(1), 'loc1': match.group(2),
            'name2': match.group(3), 'loc2': match.group(4),
            'reason': match.group(5)
        })

# Filter out already-ignored clashes
def is_ignored(clash):
    pair_key = tuple(sorted([f"{clash['loc1']}::{clash['name1']}", f"{clash['loc2']}::{clash['name2']}"]))
    if list(pair_key) in config.get("ignoredPairs", []):
        return True
    for d in config.get("ignoredDirs", []):
        if clash['loc1'].startswith(d) or clash['loc2'].startswith(d):
            return True
    return False

unresolved = [c for c in clashes if not is_ignored(c)]

print(json.dumps({
    "total": len(clashes),
    "resolved": len(clashes) - len(unresolved),
    "unresolved": len(unresolved),
    "clashes": unresolved[:20],  # Show first 20
    "config": config
}, indent=2))
PYSCRIPT

After getting the clashes, present them to the user one at a time using AskUserQuestion with these options:

For each clash, show:

  • The two symbols and their locations
  • The reason they were flagged (similar names, similar docstrings)

Resolution options:

  1. Ignore this pair - Add to ignoredPairs in clash-config.json
  2. Ignore directory - Add the common parent directory to ignoredDirs
  3. Rename symbol - Help user rename one of the symbols
  4. Skip for now - Move to next clash without action

To save an ignore decision:

python3 << 'PYSCRIPT'
import json
from pathlib import Path

config_path = Path(".claude/clash-config.json")
config = {"ignoredPairs": [], "ignoredDirs": [], "ignoredPatterns": []}
if config_path.exists():
    try:
        config = json.loads(config_path.read_text())
    except:
        pass

# Add ignore - replace IGNORE_TYPE and IGNORE_VALUE
# For pairs: config["ignoredPairs"].append(["loc1::name1", "loc2::name2"])
# For dirs: config["ignoredDirs"].append("path/to/dir")

config_path.write_text(json.dumps(config, indent=2))
print("Configuration saved.")
PYSCRIPT

Regenerate Project Manifest

Regenerate the project manifest to refresh understanding of this project's structure, build system, and entry points.

Run this command:

uv run ${CLAUDE_PLUGIN_ROOT}/scripts/scan.py

The manifest captures:

  • Languages detected in the project
  • Build system and commands (npm, uv, pdm, cargo, cmake, etc.)
  • Entry points (main scripts, CLI tools)
  • Git activity summary

The manifest is saved to .claude/project-manifest.json.

MCP Server Troubleshooting

Note: The MCP server should auto-configure when you install the plugin and restart Claude Code. This guide is only needed if auto-configuration fails.

Check if Already Configured

First, verify the server isn't already running:

claude mcp list

If you see repo-map: ... - ✓ Connected, it's already working! No action needed.

Manual Configuration (If Auto-Config Failed)

If the server isn't listed or shows an error, configure it manually:

  1. Get the plugin version:
PLUGIN_VERSION=$(python3 -c "import json; print(json.load(open('${HOME}/.claude/plugins/cache/chipflow-context-tools/context-tools/.claude-plugin/plugin.json'))['version'])")
  1. Add the MCP server:
claude mcp add --scope user --transport stdio repo-map \
  --env PROJECT_ROOT='${PWD}' \
  -- uv run "${HOME}/.claude/plugins/cache/chipflow-context-tools/context-tools/${PLUGIN_VERSION}/servers/repo-map-server.py"
  1. Verify it's configured:
claude mcp list

You should see: repo-map: ... - ✓ Connected

After Setup

Restart Claude Code for the MCP server to load.

After restart, the MCP tools will be available in all projects. The server automatically:

  • Indexes your codebase on first use
  • Monitors for file changes and reindexes
  • Stores symbols in .claude/repo-map.db

Troubleshooting

If claude mcp list shows an error:

  • Check that uv is installed: uv --version
  • Verify the plugin is installed: claude plugin list
  • Check the plugin cache path exists: ls ~/.claude/plugins/cache/chipflow-context-tools/context-tools/

To Remove

claude mcp remove repo-map

Check Indexing Status

Check the current status of repo map generation.

Status Information

PROJECT_ROOT="${PWD}"
CLAUDE_DIR="${PROJECT_ROOT}/.claude"
REPO_MAP="${CLAUDE_DIR}/repo-map.md"
PROGRESS_FILE="${CLAUDE_DIR}/repo-map-progress.json"

# Check if repo-map process is running (use pgrep, not lock file)
is_running() {
    pgrep -f "generate-repo-map.py.*${PROJECT_ROOT}" >/dev/null 2>&1
}

echo "=== Repo Map Status ==="

if [[ -f "${REPO_MAP}" ]]; then
    SYMBOL_COUNT=$(grep -c "^\*\*" "${REPO_MAP}" 2>/dev/null || echo "0")
    echo "Status: Complete"
    echo "Symbols: ${SYMBOL_COUNT}"

    if [[ -f "${PROGRESS_FILE}" ]]; then
        python3 -c "
import json
import time
with open('${PROGRESS_FILE}') as f:
    p = json.load(f)
ts = p.get('timestamp', 0)
if ts > 0:
    age = time.time() - ts
    if age < 60:
        print(f'Last updated: {int(age)}s ago')
    elif age < 3600:
        print(f'Last updated: {int(age/60)}m ago')
    else:
        print(f'Last updated: {int(age/3600)}h ago')
print(f'Files: {p.get(\"files_total\", \"?\")} ({p.get(\"files_cached\", 0)} cached)')
" 2>/dev/null || true
    fi

    if is_running; then
        echo ""
        echo "⏳ Update in progress..."
    fi
elif is_running; then
    echo "Status: Building..."

    if [[ -f "${PROGRESS_FILE}" ]]; then
        python3 -c "
import json
with open('${PROGRESS_FILE}') as f:
    p = json.load(f)
status = p.get('status', 'unknown')
parsed = p.get('files_parsed', 0)
to_parse = p.get('files_to_parse', 0)
total = p.get('files_total', 0)
cached = p.get('files_cached', 0)
symbols = p.get('symbols_found', 0)

print(f'Total files: {total}')
print(f'Cached: {cached}')
if to_parse > 0:
    pct = int(parsed / to_parse * 100)
    print(f'Parsing: {parsed}/{to_parse} ({pct}%)')
if symbols > 0:
    print(f'Symbols found: {symbols}')
" 2>/dev/null || echo "Progress data not available yet"
    else
        echo "Starting up..."
    fi

    echo ""
    echo "The repo map is building in the background."
    echo "It will be available once indexing completes."
else
    echo "Status: Not started"
    echo ""
    echo "Run /context-tools:repo-map to generate the repo map"
fi

echo "======================="

The repo map indexes all Python, C++, and Rust code in your project to help Claude understand the codebase structure and detect potential duplicates.

Generate Project Narrative

Generate a living narrative document for this codebase from git history.

Step 1: Extract Git Data

Run the extraction script:

uv run ${CLAUDE_PLUGIN_ROOT}/scripts/story.py --extract-only

This saves git history data to .claude/narrative-data.json.

Step 2: Generate Narrative

Read the extracted data:

Read .claude/narrative-data.json

Then generate a narrative document with EXACTLY this structure and write it to .claude/narrative.md:

# Project Narrative: [project_name]

## Summary
<!-- 2-3 sentences. The elevator pitch. What is this and why does it matter? -->

## Current Foci
<!-- What we're actively working on NOW. Based on recent commits, what are the 2-4 active areas? -->

- **[Focus area]**: Brief description of what and why

## How It Works
<!-- Current architecture/structure. Main subsystems and their roles. Keep concise but useful. -->

## The Story So Far
<!-- Narrative of how we got here. Identify major phases/epochs. Not a list of commits, but the STORY. -->

## Dragons & Gotchas
<!-- Warnings for future-us. Fragile areas, non-obvious behavior, things that bit us. -->

## Open Questions
<!-- Things we're still figuring out. Uncertainties. Technical debt we're aware of. -->

---
_Generated: [DATE] | Session: [SESSION_ID from narrative-data.json]_

Critical rules for generation:

  • Write in "we" voice throughout - this is OUR project, OUR narrative
  • Be opinionated - include hunches and intuitions, not just facts
  • This is NOT a changelog - it's a story that helps understand WHY things are the way they are
  • Look at commit patterns, file churn, and major changes to identify epochs and focus areas
  • High-churn files often indicate pain points (dragons)

LENGTH LIMITS (sections are auto-truncated when injected into context):

  • Summary: ~2-3 sentences, under 300 characters
  • Current Foci: 2-4 bullet points, under 400 characters total
  • Dragons & Gotchas: Key warnings only, under 300 characters
  • Keep it punchy - this gets injected on every session start

When to Use

  • First time: Bootstrap the narrative for a codebase
  • Fresh start: If the narrative has drifted too far from reality
  • New team member: Help them understand the project story

For ongoing updates after sessions, use /context-daddy:refresh instead.

MCP servers 2

Sponsors

Details

Marketplace
ChipFlow/context-daddy
Author
Robert Taylor
Category
Community
License
MIT
Keywords
context, narrative, repo-map, tribal-knowledge, documentation