Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

context-daddy Documentation

Internal documentation for context-daddy development.

Contents

DocumentDescription
The Story So FarProject narrative, lessons learned, dragons
ArchitectureSystem architecture, components, data flow
TestingTest suite, CI workflows, guarantees
DevelopmentPlanned features, design decisions, history

The Story So Far

This page captures the evolving narrative of context-daddy - not just what it does, but why it exists and what we’ve learned building it.

The Vision

We started with a simple observation: Claude struggles with large codebases. It either drowns in context trying to understand everything at once, or makes blind guesses without sufficient understanding. There had to be a better way.

The solution: give Claude a structured way to explore code semantically. Instead of reading files randomly, it could query for symbols by name, understand the codebase structure through maps, and dive into specific implementations only when needed.

Evolution

v0.1-v0.3: The Naive Approach

Our first attempt was straightforward - use tree-sitter to parse code and generate repository maps. It worked fine for small projects but failed catastrophically on anything substantial. Memory would explode as we tried to parse everything simultaneously.

Lesson learned: You can’t just load an entire codebase into memory. Even with tree-sitter’s efficiency, large repos require incremental processing.

v0.4-v0.5: MCP Server Architecture

Static repository maps weren’t enough. Claude needed fast, targeted access to specific symbols. This led us to build an MCP server - a live query interface for code exploration rather than just generated static files.

Lesson learned: The real value isn’t in the map itself, but in the ability to query it dynamically.

v0.6-v0.8: Process Management Nightmares

This era was dominated by resource management issues:

  • Indexing processes hanging after Claude sessions ended
  • Memory leaks from multiple tree-sitter instances
  • Lock file conflicts between concurrent sessions

We went through multiple iterations:

  1. PreToolUse hooks - Spawned too many background processes
  2. Thread-based indexing - Hung tree-sitter froze entire MCP server
  3. Multiprocess architecture - Finally isolated indexing properly

Lesson learned: Process isolation is worth the complexity. A hung parser shouldn’t take down the whole system.

v0.9: Database Versioning

As the schema evolved, users hit compatibility issues between plugin versions. We added database versioning and learned that multiple Claude sessions can coexist with different plugin versions - we just need to handle schema mismatches gracefully.

Lesson learned: Schema versioning isn’t optional. Plan for it from the start.

v0.10: Documentation & Narrative

A philosophical shift: understanding codebases isn’t just about parsing syntax. It’s about capturing the stories, decisions, and hard-won insights that accumulate around projects.

Traditional documentation captures what code does. Narratives capture why it exists and what we’ve learned building it.

Lesson learned: Tribal knowledge is valuable and worth preserving systematically.

Dragons & Gotchas

Hard-won lessons that aren’t obvious from reading the code:

Hooks Autodiscovery

The hooks system is more fragile than it appears. Declaring hooks in both plugin.json and hooks/hooks.json causes validation failures. The fix: only use hooks/hooks.json - Claude Code autodiscovers them.

Tree-sitter Memory

Tree-sitter memory usage is unpredictable and can spike dramatically with certain file types or parsing errors. Our subprocess isolation helps, but resource limits are essential.

SQLite Concurrency

WAL mode saves us from many concurrency issues, but database migrations still require care. We moved away from process locks (which caused deadlocks) to graceful cleanup based on process detection.

MCP Server Lifecycle

The MCP server lifecycle is tightly coupled to Claude Code’s session management in ways that aren’t well-documented. We’ve reverse-engineered expected behaviors through trial and error - particularly around when servers start, stop, and restart.

Open Questions

Things we’re still figuring out:

  • Cache invalidation: The current mtime+hash approach works but feels heavyweight. Filesystem watching or git hooks might be more elegant.

  • Narrative maintenance: How do we keep tribal knowledge current without it becoming a maintenance burden? When should narratives be version-controlled?

  • FTS utilization: The full-text search infrastructure exists but we haven’t found the right UX patterns to make it genuinely useful in Claude’s workflow.

  • Validation: How do we measure whether narratives are actually useful? Technical metrics like indexing speed are easy; the value of tribal knowledge is harder to quantify.

Philosophy

A few principles that have emerged:

  1. Structure before detail - Help Claude understand the map before exploring the territory
  2. Fail gracefully - A hung process shouldn’t corrupt data or block the session
  3. Context is precious - Return markdown, not JSON; be concise, not comprehensive
  4. Stories matter - The “why” is often more valuable than the “what”

Architecture

Overview

context-daddy is a Claude Code plugin that helps AI assistants understand large codebases quickly and efficiently. It combines:

  • Tree-sitter parsing - Extract semantic symbols (functions, classes, methods) from source code
  • SQLite caching - Fast retrieval without re-parsing
  • MCP server - Expose tools for code exploration
  • Narrative documentation - Capture tribal knowledge that survives across sessions

The core philosophy: help Claude build understanding through structured symbol maps before diving into specific implementations.

System Architecture

flowchart LR
    CC[Claude Code] -->|hooks| Hooks[Hook Scripts]
    CC <-->|MCP| Server[MCP Server]

    Server -->|spawns| Indexer[Indexer]
    Server -->|queries| DB[(repo-map.db)]
    Indexer -->|writes| DB

    Hooks -->|updates| Narrative[narrative.md]

    classDef claude fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
    classDef component fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
    classDef storage fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue

    class CC claude
    class Hooks,Server,Indexer component
    class DB,Narrative storage

Core Components

MCP Server (servers/repo-map-server.py)

The MCP server provides tools for code exploration:

ToolPurpose
search_symbolsFind functions/classes by name pattern (glob wildcards)
get_symbol_contentGet source code of a specific symbol
get_file_symbolsList all symbols in a file
list_filesList indexed files with optional glob filter
reindex_repo_mapTrigger re-indexing
repo_map_statusCheck indexing status
md_outlineGet markdown document structure
md_get_sectionGet content under a heading

The server runs persistently during Claude sessions and handles concurrent requests while indexing runs in the background.

Indexing Pipeline (scripts/map.py)

The indexer uses tree-sitter to parse source files and extract:

  • Function/method signatures and docstrings
  • Class definitions and inheritance
  • Module-level constants and variables

Supported languages: Python, JavaScript/TypeScript, Rust, Go, C/C++, Java, Ruby, and more.

Process isolation: Indexing runs in a subprocess with resource limits:

  • Memory: 4GB virtual address space
  • CPU: 20 minutes timeout
  • Watchdog monitors for hung processes

Hook System

Hooks integrate with Claude Code’s lifecycle:

HookTriggerPurpose
SessionStartSession beginsLoad context, trigger indexing
StopSession endsUpdate narrative, capture learnings

Hooks are autodiscovered from hooks/hooks.json - they don’t need to be declared in plugin.json.

Narrative Documentation

The narrative system captures “tribal knowledge” - the stories, decisions, and insights that accumulate around codebases:

  • generate-narrative.py - Bootstrap narrative from git history and project structure
  • update-narrative.py - Revise narrative after development sessions

Output lives in .claude/narrative.md and provides context that survives across sessions.

Data Flow

sequenceDiagram
    participant CC as Claude Code
    participant Hook as Hook Script
    participant MCP as MCP Server
    participant Idx as Indexer
    participant DB as SQLite

    Note over CC,DB: Session Start
    CC->>Hook: SessionStart
    Hook->>MCP: Check status
    MCP->>DB: Read metadata
    alt Needs indexing
        MCP->>Idx: Spawn subprocess
        Idx->>DB: Write symbols (WAL)
    end
    Hook-->>CC: Context loaded

    Note over CC,DB: During Session
    CC->>MCP: search_symbols("*Handler")
    MCP->>DB: Query symbols table
    DB-->>MCP: Results
    MCP-->>CC: Formatted markdown

    Note over CC,DB: Session End
    CC->>Hook: Stop
    Hook->>Hook: Update narrative

Process Architecture

Why Multiprocess?

Tree-sitter is a native C extension that runs in-process. If parsing hangs (e.g., malformed file triggers infinite loop), the entire Python process freezes. Our solution:

flowchart LR
    subgraph MCP["MCP Server (always responsive)"]
        Handler["Tool handlers"]
        Watch["Watchdog thread"]
    end

    subgraph Sub["Indexer Subprocess"]
        TS["tree-sitter parsing"]
    end

    MCP -->|"spawns"| Sub
    Watch -->|"can SIGKILL"| Sub
    Sub -->|"writes"| DB[(SQLite WAL)]
    MCP <-->|"reads"| DB

    classDef server fill:#90EE90,stroke:#333,color:darkgreen
    classDef sub fill:#87CEEB,stroke:#333,color:darkblue

    class MCP server
    class Sub sub

Benefits:

  • MCP server stays responsive during indexing
  • Watchdog can kill hung indexer without affecting MCP
  • SQLite WAL handles concurrent read/write safely

Watchdog

The watchdog monitors indexing status:

  • Checks every 60 seconds
  • Detects indexing stuck >10 minutes
  • Sets status='failed' and can SIGKILL the subprocess
  • Safety check prevents hung process from overwriting database after intervention

Database Schema

-- Symbol definitions
CREATE TABLE symbols (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    kind TEXT NOT NULL,           -- 'function', 'class', 'method'
    signature TEXT,
    docstring TEXT,
    file_path TEXT NOT NULL,
    line_number INTEGER NOT NULL,
    end_line_number INTEGER,
    parent TEXT                   -- For methods: parent class name
);

-- Full-text search (partially implemented)
CREATE VIRTUAL TABLE code_text_fts USING fts5(
    file_path UNINDEXED,
    line_number UNINDEXED,
    element_type UNINDEXED,
    symbol_name UNINDEXED,
    content
);

-- Indexing metadata
CREATE TABLE metadata (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL
);
-- Keys: status, db_version, last_indexed, symbol_count

Design Decisions

Subprocess over threads

Problem: Hung tree-sitter parsing would freeze the entire MCP server.

Solution: Run indexing in a subprocess that can be killed independently.

WAL mode + single transaction

Problem: Crash during indexing could leave database in partial state.

Solution: All writes in a single transaction; crash = rollback to clean state.

Markdown over JSON

Problem: JSON responses consume context tokens inefficiently.

Solution: MCP tools return formatted markdown that’s human-readable and compact.

Hooks autodiscovery

Problem: Declaring hooks in both plugin.json and hooks/hooks.json caused validation errors.

Solution: Hooks are autodiscovered from hooks/hooks.json only. Don’t declare them in plugin.json.

Narrative documentation

Problem: Traditional docs capture what code does, not why or what was learned building it.

Solution: Generate and evolve “tribal knowledge” narratives that capture project stories, gotchas, and evolving understanding.

Testing

Running Tests

# Run all unit tests
uv run pytest tests/

# Run specific test file
uv run pytest tests/test_plugin_config.py

# Run plugin config validation (standalone)
uv run tests/test_plugin_config.py

Test Files

FilePurpose
tests/test_plugin_config.pyPlugin configuration validation (7 tests)
tests/test_mcp_tools.pyMCP tool functionality
tests/test_list_files.pyFile listing with glob patterns

CI Workflows

WorkflowTriggerPurpose
ci.ymlpush, PRStructure validation, script tests
test-hooks.ymlpush to mainE2E hook execution
e2e-test.ymlmanualFull E2E testing with Claude
pages.ymlpush to mainDeploy documentation
preview-docs.ymlPRDocumentation preview

Note: E2E tests require ANTHROPIC_API_KEY secret.

Plugin Configuration Tests

test_plugin_config.py validates:

  1. Required fields - plugin.json has name, version, description, author, keywords, repository
  2. Hooks discovery - hooks/hooks.json exists (autodiscovered by Claude Code)
  3. Hook types - All hook types are valid (SessionStart, PreCompact, Stop, etc.)
  4. Script existence - All referenced scripts in hooks.json exist
  5. Version format - Version follows semver (X.Y.Z)
  6. MCP servers - Referenced server scripts exist
  7. Version consistency - plugin.json and marketplace.json versions match

E2E Hook Tests

.github/workflows/test-hooks.yml tests:

  • SessionStart hook - Creates .claude directory and manifest
  • PreCompact + Stop hooks - Verifies compaction flow via turn limits
  • Artifact verification - Checks repo-map.db creation and MCP logs

Test Guarantees

Transaction Safety

  • All database writes in single BEGIN IMMEDIATE / COMMIT block
  • WAL mode enabled for crash safety
  • Atomic rename only after successful commit
  • Rollback on exception (no partial state)

Watchdog

  • Detects indexing hung >10 minutes
  • Sets status=‘failed’ with error message
  • Prevents hung process from overwriting after intervention
  • Runs on server startup and every 60 seconds

Data Integrity

  • Safety check before rename prevents watchdog race condition
  • Concurrent reads during indexing handled by SQLite WAL
  • Recovery from failed/crashed indexing supported

Development

Future plans, design decisions, and development history.

Planned Features

String Literals and Comments Indexing

Status: Planned

Extend repo-map indexing to capture string literals and comments, enabling concept searches without grep.

Use Cases:

  • Find error messages: search_strings("connection failed")
  • Find TODOs: search_comments(tags="TODO")
  • Find API endpoints: search_strings("/api/users")

Schema Extensions:

CREATE TABLE string_literals (
    id INTEGER PRIMARY KEY,
    content TEXT NOT NULL,
    file_path TEXT NOT NULL,
    line_number INTEGER NOT NULL,
    context TEXT,
    kind TEXT  -- single, double, triple, f-string, raw
);

CREATE TABLE comments (
    id INTEGER PRIMARY KEY,
    content TEXT NOT NULL,
    file_path TEXT NOT NULL,
    line_number INTEGER NOT NULL,
    kind TEXT,  -- line, block, docstring
    tags TEXT   -- TODO, FIXME, NOTE, etc.
);

New MCP Tools:

  • search_strings(pattern, file?) - Find string literals
  • search_comments(pattern?, tags?, file?) - Find comments
  • get_todos() / get_fixmes() - Convenience tools

Full-Text Search (FTS)

Status: Partially Implemented

The FTS5 table schema exists but is not yet populated or exposed via MCP tools.

What’s done:

  • FTS5 virtual table created in schema (code_text_fts)
  • Table structure supports comments, docstrings, and string literals

What’s remaining:

  • Populate FTS table during indexing (extract strings/comments from tree-sitter AST)
  • Add search_text() MCP tool
  • Wire up to existing indexing pipeline

Schema (already in place):

CREATE VIRTUAL TABLE code_text_fts USING fts5(
    file_path UNINDEXED,
    line_number UNINDEXED,
    element_type UNINDEXED,  -- 'comment', 'docstring', 'string_literal'
    symbol_name UNINDEXED,
    content,
    tokenize='unicode61 remove_diacritics 2'
);

Expected performance: FTS5 queries <50ms vs grep 100-500ms (10-20x faster).

Other Ideas

  • Multi-Repository Support - Track symbols across related repos
  • Symbol References - Call graph: where symbols are used, not just defined
  • Import/Include Tracking - Index dependencies
  • AI-Powered Similar Code - Embeddings for semantic search

Completed Features

v0.10.x - Documentation & CI

  • mdbook documentation with GitHub Pages
  • PR preview workflow
  • Mermaid diagrams in architecture docs

v0.9.x - Plugin Stability

  • Database versioning for schema compatibility
  • Plugin configuration validation tests
  • E2E hook testing in CI

v0.8.0 - Multiprocess Architecture

Changed from thread-based to subprocess-based indexing.

Why: Hung tree-sitter parsing would freeze the entire MCP server.

Solution:

  • do_index() spawns subprocess: uv run scripts/generate-repo-map.py
  • Watchdog can SIGKILL hung subprocess without affecting MCP server
  • SQLite WAL handles concurrent read (MCP) / write (subprocess)

Resource Limits:

  • Memory: 4GB virtual address space
  • CPU: 20 minutes timeout
  • Watchdog checks every 60 seconds

v0.7.x - Indexing Status & Watchdog

Added metadata table to track indexing status and detect hung processes.

Metadata keys: status, db_version, last_indexed, symbol_count

Watchdog:

  • Detects indexing stuck >10 minutes
  • Sets status='failed' with error message
  • Safety check prevents hung process from overwriting after watchdog intervention