codebase-health

codebase-health is a command for coding agents from oalders/kitchen-sink. It costs 17 tokens per session (3,513 once invoked), scanned A, original, MIT.

A health check for a codebase, meaning the collection of source files that make up a project. It examines organization, unused code, duplication, dependencies, and how easily an AI coding tool can find relevant information.

In plain words
What is it for?
Use it periodically or before a major release to inspect the whole project or a selected folder and receive metrics, severity categories, and recommendations.
Why use it?
It reveals clutter, repeated code, hard-to-find files, and dependency problems that can make maintenance and AI-assisted work less reliable.

Command

Part of the kitchen-sink plugin — 9 skills, 20 commands, 12 hooks shipped together

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add commands/oalders/kitchen-sink/codebase-health
Clone the repo
git clone --depth 1 https://github.com/oalders/kitchen-sink

Or install kitchen-sink, the plugin that ships this one along with the rest of its 9 skills, 20 commands, 12 hooks.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for codebase-health

README.md
[![agentmods](https://agentmods.dev/badge/commands/oalders/kitchen-sink/codebase-health.svg)](https://agentmods.dev/commands/oalders/kitchen-sink/codebase-health)
Your own site
<a href="https://agentmods.dev/commands/oalders/kitchen-sink/codebase-health"><img src="https://agentmods.dev/badge/commands/oalders/kitchen-sink/codebase-health.svg" alt="Measured on agentmods" height="20"></a>
Per session 17 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 3,513 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00017 $0.03513
Opus 5 $0.00009 $0.01757
Sonnet 5 $0.00003 $0.00703
Haiku 4.5 $0.00002 $0.00351

Measured 4d ago against content hash fb0d174e5988, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

codebase-health scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

commands/codebase-health.md · 456 lines

How it starts

The opening of the file, as written. The whole thing — 456 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Codebase Health Check

Overview

Automated analysis of codebase organization optimized for AI consumption. Checks for: (1) Dead code and token waste, (2) Discoverability issues, (3) Code duplication, (4) Dependency health.

When to Use

Run periodically (monthly or before major releases) to ensure codebase remains AI-friendly.

Steps

1. Determine Scope

Check conversation context first. If not specified:

# Analyze entire codebase
pwd

# Or specific subdirectory
ls -d specific/path

2. Invoke Codebase Health Analyzer

Task(general-purpose):
  description: Analyze codebase health for AI optimization
  model: "sonnet"

  prompt:
    # Codebase Health Analyzer

    You are a codebase health expert analyzing code organization for AI consumption.

    **Your task:**
    1. Systematically check for AI optimization issues
    2. Apply comprehensive checklist
    3. Provide quantitative metrics
    4. Categorize issues by severity
    5. Generate actionable recommendations

    ## What to Analyze

    Codebase: [PATH]

    Focus areas: Token efficiency, discoverability, code quality, dependency health

    ## Comprehensive Checklist

    **CRITICAL: Check EVERY category systematically with specific examples.**

    ### 1. Dead Code Analysis (Token Waste)

    **Unused Imports:**
    - Import statements that are never used in code
    - **Go**: Skip entirely (goimports handles this better)
    - **JavaScript**: Check if ESLint configured, otherwise search for unused imports
    - **Python**: Check for unused import statements
    - **TypeScript**: Check if project has linter configured
    - Focus on languages without automated import management
    - Report: file:line with import statement, or "skipped (project uses goimports/ESLint)"

    **Unused Functions:**
    - Find unexported/private functions with no callers
    - Go: `grep -r "^func [a-z]" | check for references`
    - JavaScript: Functions defined but never called
    - Report: file:line with function name and size

    **Orphaned Files:**
    - Files that nothing imports/requires
    - Build dependency graph, find disconnected nodes
    - Exclude: _test files, main packages, scripts

    **Commented-Out Code:**
    - Large blocks of commented code (>10 lines)
    - `git log` can recover - no need to keep in codebase
    - Report: file:line with size of block

    **Dead Branches:**
    - `if false`, unreachable code after return
    - Conditions that can never be true

    **Metrics to Report:**
    ```
    Dead Code Summary:
    - Unused imports: X files, Y import statements (or "skipped - Go project with goimports")
    - Unused functions: X functions, ~Y total lines
    - Orphaned files: X files
    - Commented code blocks: X blocks, ~Y lines
    - Estimated token savings: ~Z tokens
    ```

    ### 2. File Size & Organization (Token Efficiency)

    **Large Files:**
    - Error: >1000 lines (should be split)
    - Warning: 500-1000 lines (consider splitting)
    - Report top 10 largest files with line counts

    **Monolithic Files:**
    - Single file containing unrelated functionality
    - Example: web.go with 50+ handler functions
    - Check if file contains multiple domain concepts

    **Deep Nesting:**
    - Error: >5 levels deep
    - Warning: 4-5 levels deep
    - Report deepest paths with depth count
    - Example: `src/app/features/user/components/profile/details/forms/edit/fields/name.tsx` (10 levels)

    **Vendor/Dependencies:**
    - Check if vendor/ or node_modules/ is tracked in git
    - Report size if present
    - Recommend .gitignore and AI ignore patterns

    **Metrics to Report:**
    ```
    File Organization:
    - Files >1000 lines: X files (list top 5)
    - Files 500-1000 lines: Y files
    - Deepest path: X levels (path)
    - Vendor directory size: X MB (if tracked)
    ```

    ### 3. Discoverability Issues (AI Can't Find Things)

    **Generic Naming:**
    - Flag: utils, helpers, common, misc, handler, service (without context)
    - Flag: data, types, constants (too broad)
    - Example: ❌ `utils.go` → ✅ `date-utils.go`
    - Report: file count and specific examples

    **Missing Documentation:**
    - Package-level: directories without README.md
    - File-level: files without top-comment explaining purpose
    - Check major packages (>5 files in directory)
    - Report: directories needing READMEs, files needing doc comments

    **Unclear Package Structure:**
    - Directories with >20 files but no README
    - Directories with unclear purpose (mixed concerns)
    - Report: packages needing structure documentation

    **Hidden Functionality:**
    - Important logic in >500-line functions
    - Functions that should be extracted and named
    - Report: functions >100 lines that could be split

    **Metrics to Report:**
    ```
    Discoverability:
    - Generic filenames: X files
    - Packages without README: X directories
    - Files without documentation: X files
    - Large functions (>100 lines): X functions
    ```

    ### 4. Code Duplication (AI Confusion)

    **Template/View Duplication:**
    - Nearly identical templates differing only in URLs
    - Example: pagination-*.gohtml files 95% identical
    - Use diff or similarity analysis

    **Function-Level Duplication:**
    - Similar function signatures across files
    - Copy-pasted logic with minor variations
    - Example: `validateUserInput` in 3 different packages
    - Report: function pairs with >80% similarity

    **Pattern Inconsistency:**
    - Same operation implemented different ways
    - Example: Some handlers use middleware for auth, others inline
    - Example: Error handling varies (some use helper, some don't)
    - Report: inconsistent patterns with examples

    **Metrics to Report:**
    ```
    Code Duplication:
    - Duplicate templates: X sets of Y files each
    - Duplicate functions: X function pairs
    - Inconsistent patterns: X categories
    - Estimated duplication: ~Y lines
    ```

    ### 5. Dependency Health (Import Graph Analysis)

    **Circular Dependencies:**
    - Package A imports B, B imports A
    - Prevents clean mental model
    - **REQUIRED**: Run `go mod graph | grep -E "^(.+) \1$"` or equivalent
    - JavaScript: Use `npx madge --circular src/`
    - Report: cycles with package names or "0 circular dependencies found"

    **Unused Exports:**
    - Exported functions/types never imported elsewhere
    - Should be unexported (private)
    - **REQUIRED**: Build import graph, check each exported symbol
    - Go: Grep for `^func [A-Z]`, `^type [A-Z]`, cross-reference imports
    - Report: count and examples or "all exports used"

    **Orphaned Modules:**
    - Entire packages/modules that nothing imports
    - May be leftover from refactoring
    - **REQUIRED**: Build dependency tree, find disconnected packages
    - Exclude: main packages, _test.go files, cmd/* binaries
    - Report: package names or "no orphaned packages"

    **Deep Dependency Chains:**
    - A → B → C → D → E (too deep)
    - Warning: >4 levels deep
    - Makes changes risky (cascading failures)

    **Metrics to Report:**
    ```
    Dependency Health:
    - Circular dependencies: X cycles
    - Unused exports: Y symbols
    - Orphaned packages: Z packages
    - Deepest dependency chain: N levels
    ```

    ### 6. Naming Convention Consistency

    **Mixed Conventions:**
    - camelCase and snake_case in same directory
    - PascalCase and lowercase mixed
    - Inconsistent file naming (admin-events.go vs admin_users.go)

    **Check by Language:**
    - Go: Should be camelCase for vars, PascalCase for exports
    - JavaScript: camelCase for files and vars
    - Python: snake_case for everything
    - Files: kebab-case or snake_case consistently

    **Metrics to Report:**
    ```
    Naming Conventions:
    - Files with mixed case: X files
    - Directories with inconsistent naming: Y dirs
    - Top violators: (list files)
    ```

    ### 7. Configuration & Documentation

    **Multiple CLAUDE.md Files:**
    - Should be single source of truth
    - Check for contradictions between files
    - Report: locations and recommendation

    **CLAUDE.md Completeness:**
    - Does it cover: testing, structure, patterns?
    - Are worktrees documented?
    - Are ignore patterns specified?

    **Architecture Documentation:**
    - Is there docs/ARCHITECTURE.md or equivalent?
    - High-level system overview for AI context

    **Metrics to Report:**
    ```
    Documentation:
    - CLAUDE.md files: X locations
    - Missing sections: Y items
    - Architecture docs: Present/Missing
    ```

    ## Output Format

    ### Executive Summary

    **Overall Health Score:** X/100

    **Top 3 Issues:**
    1. [Issue] - [Impact] - [Files affected]
    2. [Issue] - [Impact] - [Files affected]
    3. [Issue] - [Impact] - [Files affected]

    **Estimated Token Savings:** ~X tokens per typical operation if recommendations applied

    ### Critical Issues (Must Fix)

    #### 1. [Issue Name] - [Category]
    - **Impact**: How this affects AI and humans
    - **Locations**: file:line references (top 5 examples)
    - **Count**: X occurrences, Y lines affected
    - **Fix**: Specific actionable steps
    - **Estimated Savings**: ~X tokens

    #### 2. [Next critical issue...]

    ### Important Issues (Should Fix Soon)

    #### 1. [Issue Name] - [Category]
    - **Impact**: [Description]
    - **Locations**: [Examples]
    - **Fix**: [Steps]

    ### Minor Issues (Nice to Have)

    #### 1. [Issue Name] - [Category]
    - **Impact**: [Description]
    - **Fix**: [Steps]

    ### Quantitative Metrics

    ```
    Codebase Statistics:
    ├─ Total Files: X
    ├─ Total Lines: Y
    ├─ Average File Size: Z lines
    ├─ Largest File: A lines (path)
    ├─ Deepest Nesting: B levels (path)
    │
    ├─ Dead Code:
    │  ├─ Unused imports: X
    │  ├─ Unused functions: Y (~Z lines)
    │  └─ Orphaned files: N
    │
    ├─ Duplication:
    │  ├─ Duplicate templates: X sets
    │  ├─ Duplicate functions: Y pairs
    │  └─ Estimated duplicate lines: ~Z
    │
    ├─ Discoverability:
    │  ├─ Generic names: X files
    │  ├─ Missing READMEs: Y packages
    │  └─ Undocumented files: Z
    │
    └─ Dependencies:
       ├─ Circular deps: X cycles
       ├─ Unused exports: Y
       └─ Orphaned packages: Z
    ```

    ### Recommendations by Priority

    **Immediate Actions** (High ROI, Low Effort):
    1. Remove unused imports (automated)
    2. Delete commented-out code blocks
    3. Add README to top 3 packages
    4. Consolidate duplicate templates

    **Short Term** (This Sprint):
    5. Split monolithic files (>1000 lines)
    6. Fix circular dependencies
    7. Consolidate CLAUDE.md files
    8. Document common patterns

    **Medium Term** (Next Month):
    9. Refactor deep directory nesting
    10. Standardize naming conventions
    11. Extract hidden functionality
    12. Create architecture docs

    **Long Term** (Nice to Have):
    13. Remove orphaned packages
    14. Flatten dependency chains
    15. Automate health checks in CI

    ### Health Score Breakdown

    **Token Efficiency:** X/25
    - Dead code cleanup potential: Y points
    - File size optimization: Z points

    **Discoverability:** X/25
    - Naming quality: Y points
    - Documentation completeness: Z points

    **Code Quality:** X/25
    - Duplication level: Y points
    - Consistency: Z points

    **Dependency Health:** X/25
    - Import graph cleanliness: Y points
    - Module organization: Z points

    ## Critical Rules for Analyzer

    **DO:**
    - Check EVERY category systematically
    - Provide specific file:line examples
    - Give quantitative metrics (counts, sizes, percentages)
    - Estimate token savings for each recommendation
    - Prioritize by impact × effort

    **DON'T:**
    - Skip categories because "codebase looks clean"
    - Give vague advice ("improve organization")
    - Ignore small issues (they compound)
    - Recommend changes without specific examples
    - Assume patterns are consistent without checking

    ## Example Issue Format

    ```
    #### Critical

Read the full file on GitHub · 456 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 456 lines · 17 tokens per session scan A fb0d174e5988

Subscribe to this mod's changes

codebase-health is a command published in the GitHub repository oalders/kitchen-sink (4 stars, last pushed 4d ago), licensed MIT. It adds 17 tokens to every session and 3,513 once invoked, about $0.0001 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.