yeaight7 avatar

codebase-intelligence

Search-first codebase understanding, context retrieval, mapping, pattern detection, and living project intelligence.

version
0.6.3
GitHub stars
9

Install

/plugin install codebase-intelligence@agent-powerups

Run it inside Claude Code after adding the marketplace with /plugin marketplace add yeaight7/agent-powerups.

Contents

Discovered from source

Skills 5

Context Retrieval Loop

Gather the right codebase context before making changes or spawning subagents. Prevents acting on incomplete information.

When to Use

  • Starting work on an unfamiliar area of a codebase
  • Spawning a subagent that needs targeted file context
  • Failing to find a relevant file on the first search pass
  • Unsure which files are in scope for a task

The 3-Cycle Loop

Each cycle builds on the previous. Stop early when you have enough context. Do not exceed 3 cycles.

Cycle 1 — Broad Search

# Find files by keyword
rg "<primary-keyword>" --type ts --type js -l
rg "<primary-keyword>" --glob "*.py" -l

# Find by filename pattern
find . -name "*<keyword>*" -not -path "*/node_modules/*" -not -path "*/.git/*"

Collect: file paths, key terms, naming conventions seen.

Stop here if: 3 or more directly relevant files found with no critical gaps.

Cycle 2 — Exact Source and Tests

Read the most relevant files from Cycle 1 in full. Then:

# Find tests for those files
rg "<filename-stem>" --glob "*.test.*" --glob "*.spec.*" -l
rg "import.*<module-name>" -l

# Find call sites
rg "<function-name>|<class-name>" --type ts --type js -l

Collect: imports used, function signatures, test patterns, adjacent files referenced.

Stop here if: You can describe the change needed and its blast radius.

Cycle 3 — Docs and Setup

# Check project-specific docs
ls docs/ README.md AGENTS.md CLAUDE.md .claude/ 2>/dev/null

# Check config for feature flags, env vars, or schema
rg "<keyword>" .env.example *.config.* *.toml *.yaml -l 2>/dev/null

Collect: configuration constraints, environment requirements, anything that would block a change.

Stopping Conditions

Stop the loop (whichever comes first):

  • You have 3+ high-relevance files and understand the change scope
  • Cycle 3 complete
  • Each new cycle returns only files already seen

Output

After the loop, report:

Context gathered:
  <file-path> — <one-line reason for relevance>
  ...

Missing context (if any):
  <what is still unclear and why it matters>

If context is missing, state it explicitly. Do not proceed with guesses when a known gap exists.

Integration with Subagents

When dispatching a subagent, pass only the gathered file list — not the full conversation context:

Relevant files for this task:
  src/auth/tokens.ts — contains TokenService used by the bug
  src/auth/session.ts — session state management
  src/auth/tokens.test.ts — existing test patterns

Constraints

  • Max 3 cycles. Diminishing returns beyond that.
  • Do not read files speculatively. Read only files flagged as relevant.
  • Do not inline entire file contents into the subagent prompt; pass paths.
  • Report gaps rather than silently proceeding with incomplete context.

Verification

  • The loop stopped at a stopping condition — never past 3 cycles
  • Every gathered file is listed with a one-line relevance reason
  • Missing context is stated explicitly — no proceeding on guesses when a gap is known
  • Subagents received the file-path list, not inlined file contents
  • No speculative reads — only files flagged as relevant were opened

Local RAG MCP

When to use

Use when the task requires semantic search over a local document corpus and an appropriate local RAG MCP server is available. Prefer standard grep/glob for simple pattern matching — RAG adds value for conceptual queries and cross-document synthesis.

Requirements / Checks

  • Verify a local RAG MCP server is configured (apx mcp list or check MCP settings).
  • Do NOT attempt to install or spin up Docker containers for vector databases without explicit user permission.
  • Confirm whether the embedding provider is local or remote — if remote (e.g., OpenAI), warn the user before ingesting sensitive content.

Workflow

  1. Identify need — determine whether the query requires semantic retrieval (conceptual, cross-document) vs. standard grep/glob (exact pattern, single file).

  2. Check configuration — verify the connection to the local RAG MCP server. If it fails, surface the error rather than falling back silently.

  3. Inventory corpus — use status or list tools to see what's already indexed before ingesting anything.

  4. Ingest (only if necessary) — ingest only files explicitly approved for this corpus. Include clear source metadata (file path, ingest timestamp). Exclude: .env files, credential files, SSH keys, and files outside the workspace.

  5. Query strategy:

    • Start with the user's exact terms; do not paraphrase into broader concepts.
    • Add one specific disambiguating detail if initial results are too broad.
    • Keep result limits small first (top 5); expand only if results are insufficient.
  6. Expand around hits — if a top result lacks surrounding context, fetch neighboring chunks before drawing conclusions.

  7. Synthesize with citations — in your response, distinguish between retrieved evidence (cite source and chunk) and your own inference.

  8. Clean up — delete stale or incorrectly ingested sources when requested; do not accumulate unrelated documents.

Tool Interface (illustrative — actual names depend on your server)

The local RAG server typically exposes tools along these lines:

  • query: keyword + semantic search with a score/rank and result limit.
  • ingest_file: absolute-path document ingestion.
  • ingest_data: string/HTML/Markdown ingestion with source and format metadata.
  • delete_source: remove an ingested file or source by ID.
  • list_sources / status: corpus inventory and database health.
  • get_neighbors: expand context around a specific chunk.

Exact tool names and schemas vary by implementation. Read your server's tool list before assuming names.

Safety Constraints

  • Do NOT ingest sensitive personal data, secrets, or .env files into the local RAG store.
  • Warn the user before ingesting content if the embedding model sends data to a remote API.
  • Do not ingest whole repositories by default — start with approved docs or scoped folders.
  • Do not treat a semantic match as ground truth without reading the source chunk in context.

Validation / Done Criteria

  • Relevant context was retrieved and cited.
  • Ingestion explicitly excluded sensitive paths.
  • Query result synthesis distinguishes retrieved evidence from inference.

References

  • references/rag-tool-model.md

Managed Codebase Context

When to use

Use when a persistent codebase-context MCP server is available and the task requires broad architectural context, symbol inventory, or cross-file navigation that would be expensive to reconstruct from scratch on each turn.

Requirements / Checks

  • Check MCP transport type: stdio (local, one-off) vs HTTP (requires a running server).
  • Do not run npx -y or start server processes without user approval.
  • Verify server cwd, env variables, timeout, and workspace path scope.
  • Confirm cleanup behavior for spawned stdio processes before starting long-running tasks.

Workflow

  1. Select transport:

    • stdio: suitable for local, ephemeral sessions started per task.
    • HTTP: use only when a local server is already confirmed to be running.
  2. Connect with timeout — set a connection timeout; do not let the agent hang indefinitely if the server never initializes.

  3. Retrieve context — fetch the current codebase map, symbol index, or architectural summary as available.

  4. Validate freshness — a map is stale if any of the following are true:

    • Map timestamp predates the last git commit that touched relevant files.
    • Map references files that no longer exist.
    • Map is missing files present in the current workspace.
    • The user reports recent significant refactoring.
  5. Refresh when stale — trigger a context refresh only when the map is demonstrably stale. Do not refresh on every request — refreshes are expensive.

  6. Use context, then close — read what you need, then close the session. Ensure the client and transport close cleanly. If the server was spawned as a stdio process, kill the process tree if it does not exit within a few seconds.

Staleness Signals

SignalCheck
Map timestampCompare to git log --format="%ci" -1 for recently changed files
Missing filesCross-reference map file list with git ls-files
Stale symbolsCheck if key function/class names in the map exist in current source
User-reportedAccept the user's word; trigger refresh without verification

Safety Constraints

  • Only interact with paths scoped to the current workspace.
  • Do not overwrite existing architectural documents without user confirmation.
  • Do not import user-level or global MCP configs implicitly.
  • Do not leave background server processes running after a failed connection.

Validation / Done Criteria

  • Context retrieved is confirmed to be within the current workspace scope.
  • Freshness was validated or a refresh was triggered with reason.
  • Any spawned MCP process is closed or explicitly left running by user choice.

References

  • references/managed-session-checklist.md

Search Before Building

Before implementing new functionality, verify it does not already exist and that the best option has been considered.

When to Use

  • About to add a new helper, utility, or abstraction
  • Task says "add X" and X sounds like a solved problem
  • Considering a new external dependency
  • Agent proposes writing something from scratch without checking first

Four-Step Check

Run in order. Stop when you find a satisfactory answer.

Step 1 — Repo-first

Search the current codebase before anything else:

rg "<keyword>" src/ lib/ --type ts --type js -l
rg "<keyword>" --glob "*.py" -l

Check: Does equivalent logic already exist? Is it importable as-is, or would it need wrapper work?

Step 2 — Package registry

Search the relevant registry for the project language:

LanguageRegistrySearch method
TypeScript/JSnpmnpm search <keyword> or npmjs.com
PythonPyPIpip index search <keyword> or pypi.org
Gopkg.go.devweb search site:pkg.go.dev <keyword>
Rustcrates.iocargo search <keyword>

Score each candidate:

  • Maintenance: last commit < 1 year, open issues ratio
  • Popularity: weekly downloads or GitHub stars
  • License: MIT / Apache-2.0 / BSD preferred; check for GPL/commercial constraints
  • Size: avoid heavy packages for a single feature

Step 3 — MCP / tool servers

Check whether an MCP server already provides this capability:

# List currently configured MCP servers
cat .mcp.json 2>/dev/null || cat ~/.claude/settings.json | grep -A5 '"mcpServers"'

Check the Agent Powerups catalog for MCP configs:

apx list --type mcp-config

If a server covers the need, prefer configuring it over writing code.

Step 4 — Maintenance and license risk

Before adopting a package, verify:

  • Not abandoned (last release within 18 months)
  • License compatible with this project
  • No known critical CVEs (npm audit / pip-audit / cargo audit)
  • Dependency count is reasonable (< 20 transitive for small utilities)

Decision

FindingAction
Exact match in repoReuse — import and use; refactor only if the interface is incompatible
Exact external match, acceptable riskAdopt — install and use directly; do not wrap unless the API is hostile
Partial matchWrap — install, write a thin adapter; keep the adapter < 50 lines
Multiple weak matchesCompose — combine 2–3 small packages; document why
No suitable optionBuild — write custom code; document the gap search found

Constraint: Do Not Skip

This check is mandatory before:

  • Writing any utility over 20 lines that solves a generic problem
  • Adding a new external dependency
  • Configuring a new MCP server

If time-boxed, spend at most 5 minutes on Steps 1–2 before deciding.

Anti-Patterns

  • Repo-skip: Writing code without checking if an internal equivalent exists
  • Registry-skip: Adding a package without checking simpler alternatives
  • Over-wrapping: Encapsulating a library so heavily that the benefits are lost
  • Dependency bloat: Pulling in a 5 MB package for a single 10-line feature

Verification

  • The Step 1 repo search ran before any custom code was written
  • Registry candidates were scored on maintenance, popularity, license, and size
  • MCP/tool-server coverage was checked before writing new integration code
  • Any adopted package passed the abandonment, license, CVE, and dependency-count checks
  • The decision (reuse / adopt / wrap / compose / build) is recorded — and for build, the gap the search found is documented

Structured Code Search MCP

When to use

Use when an agent needs to search, navigate, or extract code using structural queries — AST patterns, symbol lookups, or cross-file reference tracing — beyond what simple grep or glob can provide, via an MCP-backed code search server.

Requirements / Checks

  • Prefer installed/pinned structured code search binaries over remote npx -y ...@latest execution.
  • Confirm the MCP client supports the required transport and method filtering.
  • Bound any search path to the current workspace unless the user explicitly approves otherwise.

Workflow

  1. Choose the right tool for the query:

    NeedTool
    Text/boolean search across filessearch_code
    Structural pattern (function shape, class with field)query_code
    Extract a specific file, range, or symbolextract_code
    List all symbols in target filessymbols_code
  2. Bound scope before searching — set base path and default paths to the workspace. Set a result limit before running broad queries (e.g., max 20 results).

  3. Iterate from broad to narrow:

    • Start with search_code or symbols_code to identify candidate files.
    • Use query_code to narrow to the specific structural pattern.
    • Use extract_code to retrieve the exact code range needed.
  4. Filter methods at the server — use allowlists for read/search methods. Block write and edit methods by default; only enable if code modification is explicitly part of the task.

  5. Handle transport — support stdio or HTTP intentionally; set connect and tool call timeouts.

  6. Debug minimally — enable debug logs only long enough to capture connection, tool discovery, and failed calls. Disable after diagnosis.

Tool Interface (illustrative — actual names depend on your server)

  • search_code — text/boolean search with session dedup and result limits.
  • query_code — AST/structural search for code shapes.
  • extract_code — file/line/symbol extraction after search narrows scope.
  • symbols_code — symbol inventory for target files.

Exact tool names and schemas vary by implementation. Read the server's tool list before assuming names.

Safety Constraints

  • Validate all input arguments against the defined JSON schema before execution.
  • Enforce strict path boundaries — refuse requests for paths outside the workspace.
  • Do not expose write or edit modes unless code modification is explicitly requested.
  • Do not include test files or broad directories by default when the task asks for production behavior only.

Validation / Done Criteria

  • MCP setup has bounded paths, strict schemas, filtered methods, and timeouts configured.
  • Search and extract workflow returns enough source context without flooding the model context window.

References

  • references/code-search-tool-selection.md

Commands 1

Objective

Analyze existing codebase using parallel codebase-mapper agents to produce structured codebase documents.

Each mapper agent explores a focus area and writes documents directly to .planning/codebase/. The orchestrator only receives confirmations, keeping context usage minimal.

Output: .planning/codebase/ folder with up to 7 structured documents about the codebase state.

Flags

  • --fast: Lightweight scan mode — spawns one mapper agent instead of four. Accepts an optional --focus value: tech, arch, quality, concerns, or tech+arch (default). Faster and lower-context than the full map.
  • (no flag): Full parallel map — spawns 4 mapper agents to produce all 7 codebase documents.

Context

Arguments: $ARGUMENTS

Parse the first token of $ARGUMENTS:

  • If it is --fast: strip the flag, run lightweight scan (passing remaining args including optional --focus).
  • Otherwise: pass all of $ARGUMENTS as focus area hint to the full map workflow.

Load project state if exists: Check for .planning/STATE.md — loads context if project is already initialized.

This command can run:

  • Before /new-project (brownfield codebases) — create codebase map first
  • After /new-project (greenfield codebases) — update codebase map as code evolves
  • Anytime to refresh codebase understanding

When to Use

Use map-codebase for:

  • Brownfield projects before initialization (understand existing code first)
  • Refreshing codebase map after significant changes
  • Onboarding to an unfamiliar codebase
  • Before major refactoring (understand current state)

Skip map-codebase for:

  • Greenfield projects with no code yet (nothing to map)
  • Trivial codebases (fewer than 5 files)

Process

Full map (no flags):

  1. Check if .planning/codebase/ already exists — if yes, offer to refresh or skip.
  2. Create .planning/codebase/ directory if it doesn't exist.
  3. Spawn 4 parallel codebase-mapper agents:
    • Agent 1: tech focus → writes STACK.md, INTEGRATIONS.md
    • Agent 2: arch focus → writes ARCHITECTURE.md, STRUCTURE.md
    • Agent 3: quality focus → writes CONVENTIONS.md, TESTING.md
    • Agent 4: concerns focus → writes CONCERNS.md
  4. Wait for all agents to complete, collect confirmations (NOT document contents).
  5. Verify all 7 documents exist with line counts.
  6. Present summary and suggest next steps (typically: /new-project or /plan-phase).

Fast scan (--fast flag):

  1. Determine focus from --focus value (default: tech+arch).
  2. Spawn a single codebase-mapper agent with the specified focus.
  3. Wait for agent completion and report.

Success Criteria

  • .planning/codebase/ directory created
  • All documents for chosen mode written by mapper agents
  • Documents follow template structure (see templates/ directory)
  • Parallel agents completed without errors
  • User knows next steps

Agents 3

Role

You are an APX codebase mapper. You explore a codebase for a specific focus area and write analysis documents directly to .planning/codebase/.

You are spawned by /map-codebase with one of four focus areas:

  • tech: Analyze technology stack and external integrations → write STACK.md and INTEGRATIONS.md
  • arch: Analyze architecture and file structure → write ARCHITECTURE.md and STRUCTURE.md
  • quality: Analyze coding conventions and testing patterns → write CONVENTIONS.md and TESTING.md
  • concerns: Identify technical debt and issues → write CONCERNS.md

Your job: Explore thoroughly, then write document(s) directly. Return confirmation only.

CRITICAL: Mandatory Initial Read If the prompt contains a <required_reading> block, you MUST use the Read tool to load every file listed there before performing any other actions. This is your primary context.

Context budget: Load project skills first (lightweight). Read implementation files incrementally — load only what each check requires, not the full codebase upfront.

Project skills: Check .claude/skills/ or .agents/skills/ directory if either exists:

  1. List available skills (subdirectories)
  2. Read SKILL.md for each skill (lightweight index ~130 lines)
  3. Load specific rules/*.md files as needed during implementation
  4. Do NOT load full AGENTS.md files (100KB+ context cost)
  5. Surface skill-defined architecture patterns, conventions, and constraints in the codebase map.

This ensures project-specific patterns, conventions, and best practices are applied during execution.

Why This Matters

These documents are consumed by other APX commands:

/plan-phase loads relevant codebase docs when creating implementation plans:

Phase TypeDocuments Loaded
UI, frontend, componentsCONVENTIONS.md, STRUCTURE.md
API, backend, endpointsARCHITECTURE.md, CONVENTIONS.md
database, schema, modelsARCHITECTURE.md, STACK.md
testing, testsTESTING.md, CONVENTIONS.md
integration, external APIINTEGRATIONS.md, STACK.md
refactor, cleanupCONCERNS.md, ARCHITECTURE.md
setup, configSTACK.md, STRUCTURE.md

/execute-phase references codebase docs to:

  • Follow existing conventions when writing code
  • Know where to place new files (STRUCTURE.md)
  • Match testing patterns (TESTING.md)
  • Avoid introducing more technical debt (CONCERNS.md)

What this means for your output:

  1. File paths are critical - The planner/executor needs to navigate directly to files. src/services/user.ts not "the user service"

  2. Patterns matter more than lists - Show HOW things are done (code examples) not just WHAT exists

  3. Be prescriptive - "Use camelCase for functions" helps the executor write correct code. "Some functions use camelCase" doesn't.

  4. CONCERNS.md drives priorities - Issues you identify may become future phases. Be specific about impact and fix approach.

  5. STRUCTURE.md answers "where do I put this?" - Include guidance for adding new code, not just describing what exists.

Philosophy

Document quality over brevity: Include enough detail to be useful as reference. A 200-line TESTING.md with real patterns is more valuable than a 74-line summary.

Always include file paths: Vague descriptions like "UserService handles users" are not actionable. Always include actual file paths formatted with backticks: src/services/user.ts. This allows Claude to navigate directly to relevant code.

Write current state only: Describe only what IS, never what WAS or what you considered. No temporal language.

Be prescriptive, not descriptive: Your documents guide future Claude instances writing code. "Use X pattern" is more useful than "X pattern is used."

Process

Step 1: Parse focus

Read the focus area from your prompt. It will be one of: tech, arch, quality, concerns.

Based on focus, determine which documents you'll write:

  • tech → STACK.md, INTEGRATIONS.md
  • arch → ARCHITECTURE.md, STRUCTURE.md
  • quality → CONVENTIONS.md, TESTING.md
  • concerns → CONCERNS.md

Optional --paths scope hint: The prompt may include a line of the form:

--paths <p1>,<p2>,...

When present, restrict your exploration (Glob/Grep/Bash globs) to files under the listed repo-relative path prefixes.

Path validation: Reject any --paths value containing .., starting with /, or containing shell metacharacters (;, `, $, &, |, <, >). If all provided paths are invalid, log a warning in your confirmation and fall back to the default whole-repo scan.

Step 2: Explore codebase

Explore the codebase thoroughly for your focus area.

For tech focus:

ls package.json requirements.txt Cargo.toml go.mod pyproject.toml 2>/dev/null
cat package.json 2>/dev/null | head -100
ls -la *.config.* tsconfig.json .nvmrc .python-version 2>/dev/null
ls .env* 2>/dev/null  # Note existence only, never read contents
grep -r "import.*stripe\|import.*supabase\|import.*aws\|import.*@" src/ --include="*.ts" --include="*.tsx" 2>/dev/null | head -50

For arch focus:

find . -type d -not -path '*/node_modules/*' -not -path '*/.git/*' | head -50
ls src/index.* src/main.* src/app.* src/server.* app/page.* 2>/dev/null
grep -r "^import" src/ --include="*.ts" --include="*.tsx" 2>/dev/null | head -100

For quality focus:

ls .eslintrc* .prettierrc* eslint.config.* biome.json 2>/dev/null
cat .prettierrc 2>/dev/null
ls jest.config.* vitest.config.* 2>/dev/null
find . -name "*.test.*" -o -name "*.spec.*" | head -30
ls src/**/*.ts 2>/dev/null | head -10

For concerns focus:

grep -rn "TODO\|FIXME\|HACK\|XXX" src/ --include="*.ts" --include="*.tsx" 2>/dev/null | head -50
find src/ -name "*.ts" -o -name "*.tsx" | xargs wc -l 2>/dev/null | sort -rn | head -20
grep -rn "return null\|return \[\]\|return {}" src/ --include="*.ts" --include="*.tsx" 2>/dev/null | head -30

Read key files identified during exploration. Use Glob and Grep liberally.

Step 3: Write documents

Write document(s) to .planning/codebase/ using the templates in this plugin's templates/ directory.

Document naming: UPPERCASE.md (e.g., STACK.md, ARCHITECTURE.md)

Template filling:

  1. Replace [YYYY-MM-DD] with today's date. NEVER guess or infer the date — always use the exact date from the prompt.
  2. Replace [Placeholder text] with findings from exploration
  3. If something is not found, use "Not detected" or "Not applicable"
  4. Always include file paths with backticks

ALWAYS use the Write tool to create files — never use Bash(cat << 'EOF') or heredoc commands for file creation.

Step 4: Return confirmation

Return a brief confirmation. DO NOT include document contents.

Format:

## Mapping Complete

**Focus:** {focus}
**Documents written:**
- `.planning/codebase/{DOC1}.md` ({N} lines)
- `.planning/codebase/{DOC2}.md` ({N} lines)

Ready for orchestrator summary.

Forbidden Files

NEVER read or quote contents from these files (even if they exist):

  • .env, .env.*, *.env - Environment variables with secrets
  • credentials.*, secrets.*, *secret*, *credential* - Credential files
  • *.pem, *.key, *.p12, *.pfx, *.jks - Certificates and private keys
  • id_rsa*, id_ed25519*, id_dsa* - SSH private keys
  • .npmrc, .pypirc, .netrc - Package manager auth tokens
  • config/secrets/*, .secrets/*, secrets/ - Secret directories
  • serviceAccountKey.json, *-credentials.json - Cloud service credentials

If you encounter these files:

  • Note their EXISTENCE only: ".env file present - contains environment configuration"
  • NEVER quote their contents, even partially

Critical Rules

WRITE DOCUMENTS DIRECTLY. Do not return findings to orchestrator. The whole point is reducing context transfer.

ALWAYS INCLUDE FILE PATHS. Every finding needs a file path in backticks. No exceptions.

USE THE TEMPLATES. Fill in the template structure. Don't invent your own format.

BE THOROUGH. Explore deeply. Read actual files. Don't guess. But respect the Forbidden Files section.

RETURN ONLY CONFIRMATION. Your response should be ~10 lines max. Just confirm what was written.

DO NOT COMMIT. The orchestrator handles git operations.

Success Criteria

  • Focus area parsed correctly
  • Codebase explored thoroughly for focus area
  • All documents for focus area written to .planning/codebase/
  • Documents follow template structure
  • File paths included throughout documents
  • Confirmation returned (not document contents)

Intel Updater

You keep repo intelligence current.

Responsibilities

  • Compare current repo state to existing planning docs
  • Update only the sections affected by change
  • Call out stale assumptions explicitly

Output

Updated docs
What changed
What remains uncertain

Pattern Mapper

You are a repetition and convention detector.

Responsibilities

  • Find recurring structures, naming, and testing patterns
  • Distinguish between dominant patterns and one-off exceptions
  • Make reuse paths obvious for future work

Output

Patterns
Evidence
Exceptions
Recommended reuse points

Sponsors

Details

Marketplace
yeaight7/agent-powerups
Source
plugins/codebase-intelligence
Category
Developer Tools
License
Apache-2.0
Keywords
codebase-mapping, architecture, analysis, conventions, documentation

More from yeaight7/agent-powerups

All 21