---
name: codebase-analysis
description: Deep, structured codebase analysis before planning or implementing anything. Use at the start of any autonomous session, research phase, or when analyzing an unfamiliar codebase. Produces a reliable mental model — architecture map, technical debt inventory, test coverage gaps, and struggling moments — that feeds directly into milestone planning. Based on Trail of Bits audit-context-building, Anthropic tech-debt, and Addy Osmani code-review frameworks.
---

# Codebase Analysis: Build Understanding Before Planning

Produce a deep, evidence-based understanding of the codebase before any planning or implementation. This skill prevents the most common autonomous agent failure: planning based on assumptions rather than what's actually in the code.

**Core principle:** Slow is fast. Every hour of thorough analysis prevents days of building the wrong thing.

---

## Phase 1: Orientation (Bottom-Up Mapping)

Start with a minimal structural map. Do NOT assume behavior from file names alone.

```
rg --files | head -100          # what's here
find . -name "*.go" -o -name "*.ts" -o -name "*.rs" | head -50
ls -la                          # top-level structure
cat go.mod / package.json / Cargo.toml   # dependencies and version
git log --oneline -20           # recent history
git log --all --oneline --stat --since="30 days ago" | head -50  # recent churn
```

Build a preliminary map:
1. **Modules / packages** — major units of organization
2. **Entry points** — main(), HTTP handlers, CLI commands, exported APIs
3. **Actors** — who calls what (users, crons, external services, other services)
4. **Storage** — databases, files, caches, queues touched
5. **External dependencies** — APIs, third-party services called
6. **Build / test / deploy** — how it's built, how tests run, how it's deployed

Do NOT proceed to Phase 2 until this map exists in writing.

---

## Phase 2: Ultra-Granular Function Analysis

For every non-trivial function on the critical path, apply full micro-analysis.

### Per-function checklist

For each function:

**Purpose** — why it exists, its role in the system

**Inputs & Assumptions**
- Parameters and their types
- Implicit inputs: global state, environment variables, context
- Preconditions: what must be true for this to work?
- What happens if a precondition is violated?

**Outputs & Effects**
- Return value and its meaning
- State/storage mutations
- Side effects: logs, metrics, events emitted, external calls

**Invariants** (≥3 per function)
- What is always true before this runs?
- What is always true after this runs?
- What must never happen inside this function?

**Assumptions** (≥3 per function)
- What does this code assume about its callers?
- What does it assume about external systems?
- What would break if these assumptions were wrong?

**Risk considerations** (≥3 per function)
- What happens under concurrent access?
- What happens if an external call fails partway through?
- What input values would cause unexpected behavior?

### Anti-rationalization rules (from Trail of Bits)

| Temptation | Why it's wrong | Required action |
|---|---|---|
| "I get the gist" | Gist-level misses edge cases | Line-by-line anyway |
| "This function is simple" | Simple functions compose into complex bugs | Apply analysis anyway |
| "I'll remember this invariant" | You won't — context degrades | Write it down |
| "External call is probably fine" | External = adversarial until proven | Trace the full call chain |
| "I can skip this helper" | Helpers carry assumptions that propagate | Trace it |
| "This is taking too long" | Rushed context = wrong plans | Slow is fast |

---

## Phase 3: Technical Debt Inventory

Scan for struggling moments encoded in the codebase. Classify by type and score with priority formula.

### Six debt categories (from Anthropic tech-debt skill)

| Type | What to scan for | Risk if ignored |
|---|---|---|
| **Code debt** | `TODO/FIXME/HACK/XXX`, duplicated logic, magic numbers, functions >50 lines, cyclomatic complexity >10 | Bugs, slow feature work |
| **Architecture debt** | God objects, circular dependencies, wrong data store (file used as DB), tight coupling across boundaries | Scaling limits, impossible to test |
| **Test debt** | Missing test files on critical paths, `// TODO test this`, test files with only happy paths, no integration tests | Regressions ship undetected |
| **Dependency debt** | `go.sum`/`package-lock.json` outdated packages, CVE-flagged versions, unmaintained libraries (last commit >2 years) | Security vulnerabilities |
| **Documentation debt** | Missing README, no runbook, tribal knowledge in comments, outdated architecture docs | Onboarding failure, incident recovery pain |
| **Infrastructure debt** | No metrics, no structured logging, manual deploy steps, no health checks, no graceful shutdown | Silent failures, 3am incidents |

### Priority formula

```
Priority = (Impact + Risk) × (6 - Effort)

Impact: 1-5  (how much does it slow development?)
Risk:   1-5  (what happens if we don't fix it? data loss=5, UX glitch=1)
Effort: 1-5  (how hard? hours=1, months=5)
```

High-priority items (score >20) are milestone candidates. Low-priority items (score <10) are lead bullets.

---

## Phase 4: Test Coverage Analysis

Run the test suite. Measure. Don't assume.

```bash
go test ./... -cover 2>&1 | tee test-output.txt
cargo test 2>&1 | tee test-output.txt
npm test -- --coverage 2>&1 | tee test-output.txt
pytest --cov=. --cov-report=term-missing 2>&1 | tee test-output.txt
```

Identify:
- **Critical paths with zero test coverage** — cannonball debt
- **Flaky tests** (tests that sometimes fail) — reliability debt
- **Happy-path-only tests** (no error cases, no edge cases) — false confidence
- **Missing integration tests** — components tested in isolation but never together
- **Test files that mock everything** — tests that don't catch real failures

---

## Phase 5: Code Quality Scan (5-axis review, from Addy Osmani)

Apply to the most-changed files (`git log --stat` to find them):

**1. Correctness**
- Edge cases handled? (null, empty, boundary values)
- Error paths handled beyond happy path?
- Off-by-one errors, race conditions, state inconsistencies?

**2. Readability & Simplicity**
- Names descriptive and consistent?
- Control flow straightforward (no nested ternaries, deep callbacks)?
- Could this be done in 10x fewer lines? (1000 lines where 100 suffice is a failure)
- Are abstractions earning their complexity? (don't generalize until 3rd use case)
- Dead code: no-op variables, backwards-compat shims, `// removed` comments?

**3. Architecture**
- Clean module boundaries?
- Circular dependencies? (`rg "import.*moduleA" moduleA/` to detect)
- Code duplication that should be shared?
- Dependencies flowing in the right direction?
- **Deep vs shallow modules?** (Ousterhout: shallow = interface as complex as implementation = bad)

**4. Security**
- User input validated at boundaries?
- Secrets out of code and logs?
- Auth checked where needed?
- SQL parameterized?
- External data treated as untrusted?

**5. Performance**
- N+1 query patterns?
- Unbounded loops or unconstrained fetches?
- Blocking operations that should be async?
- Missing pagination on list endpoints?

---

## Output: Codebase Analysis Report

Write findings to `.sf/CODEBASE-ANALYSIS.md`:

```markdown
# Codebase Analysis

_Date: YYYY-MM-DD | Analyzed by: <unit-type>_

## Architecture Map
<!-- Module diagram, entry points, actors, storage, external deps -->

## Critical Path Summary
<!-- The 3-5 most important flows in the system -->

## Technical Debt Inventory
| Item | Type | Impact | Risk | Effort | Score | Milestone candidate? |
|---|---|---|---|---|---|---|

## Test Coverage Gaps
<!-- Critical paths with no tests, flaky tests, false-confidence tests -->

## Code Quality Findings
<!-- Top issues by 5-axis review, with file:line references -->

## Struggling Moments
<!-- TODO/FIXME/HACK count by file, most critical entries verbatim -->

## Diagnosis
<!-- One paragraph: what is the core challenge this codebase faces? -->
```

This file feeds directly into PM-STRATEGY.md (opportunity map) and milestone CONTEXT.md (diagnosis section). Write it before planning any milestones.

---

## Sources

- [trailofbits/skills](https://github.com/trailofbits/skills) — audit-context-building, ultra-granular analysis phases
- [anthropics/knowledge-work-plugins](https://github.com/anthropics/knowledge-work-plugins) — tech-debt categories and priority formula
- [addyosmani/agent-skills](https://github.com/addyosmani/agent-skills) — five-axis code review framework
- [OthmanAdi/codebase-knowledge-builder](https://github.com/OthmanAdi/codebase-knowledge-builder) — four-phase methodology
- John Ousterhout, *A Philosophy of Software Design* — deep vs shallow modules
