codeflowmap · git:20260813.e67a4f0 · 2026-08-13 · sha256 5bd53a79e8cd0650

codeflowmap git:20260813.e67a4f0A

Immutable. This exact content is served forever at /api/v1/blob/5bd53a79e8cd0650.

---
name: codeflowmap
description: >
  Analyzes any codebase and generates a full C4 architecture diagram suite (L1 to L4) in Mermaid syntax.
  Use this skill whenever the user asks to: understand a codebase, generate architecture diagrams, map a repo,
  document a brownfield system, find duplicates or dead code, analyze module structure, produce C4 diagrams,
  or onboard onto an unfamiliar project. Triggers on phrases like "map this codebase", "generate diagrams",
  "understand this repo", "what does this code do", "document the architecture", "find duplicates",
  "analyze this project". Supports Python, TypeScript, GoLang, and Java. Applies Feynman first-principles
  analysis — builds understanding from atomic units upward before generating any diagram.
---

# CodeFlowMap

A skill that reads any codebase like a Senior Staff Engineer and produces a complete C4 diagram suite —
from System Context down to Class level — along with brownfield health observations.

**Supports:** Python · TypeScript · GoLang · Java
**Output:** Four Mermaid diagrams + Architectural Health Report + a single consolidated Onboarding Report

---

## Quick Decision: Scope Before Starting

Before running analysis, determine:

1. **Full repo or scoped module?**
   - If user says "entire repo" or gives a root path → full analysis
   - If user scopes to a folder/module → scope `SCAN_ROOT` to that path

2. **What language(s)?**
   - Auto-detect from file extensions (`.py`, `.ts`, `.go`, `.java`)
   - Read the relevant language sub-agent from `agents/`

3. **Brownfield or greenfield?**
   - Check for: absence of tests, mixed naming conventions, multiple frameworks, commented-out code blocks
   - If brownfield signals detected → enable brownfield analysis (see `references/brownfield-patterns.md`)

---

## Core Workflow

Run these 7 phases in sequence. Each phase feeds the next.

```
Phase 1: FOUNDATION SCAN      → atomic units inventory
Phase 2: CONNECTION MAP        → dependency graph
Phase 3: PATTERN RECOGNITION   → layers, modules, design patterns
Phase 4: FLOW TRACE            → entry-to-exit request/event flows
Phase 5: DIAGRAM GENERATION    → all 4 C4 levels in Mermaid
Phase 6: HEALTH REPORT         → brownfield findings, duplicates, risks
Phase 7: ONBOARDING REPORT     → single consolidated doc for new developers
```

For large codebases (>500 files), Phases 1–4 generate a lot of raw material (entry-point
tables, domain/package inventories, external-dependency lists, design-pattern findings,
duplicate/migration findings, one fully-traced flow). Keep that material in a structured
form as you go — it becomes the body of Phase 7, not just the health report. Delegating
Phases 1–4 to a background/subagent research pass is reasonable at this scale; just make
sure its findings come back as tables/lists (not prose) so Phase 7 can reuse them directly
instead of re-deriving them.

---

## Phase 1 — Foundation Scan (Feynman Layer 1)

> "If you can't explain it simply, you don't understand it well enough." — Feynman

Start at the atomic level. Understand each unit completely before connecting them.

**What to collect:**

```
FOUNDATION INVENTORY
├── Entry points       (main, bootstrap, CLI, server start, exported index)
├── Config files       (env, yaml, toml, json config — not lock files)
├── Build artifacts    (Dockerfile, Makefile, pyproject.toml, pom.xml, go.mod)
└── Directory tree     (2-level deep structure)
```

**Language-specific entry point heuristics:**

| Language   | Entry Point Signals |
|------------|-------------------|
| Python     | `if __name__ == "__main__"`, `app = FastAPI()`, `app = Flask(__name__)`, `def main()` in root |
| TypeScript | `app.listen(`, `server.listen(`, `bootstrap()`, `main()` in `index.ts` / `server.ts` |
| GoLang     | `func main()` in `main.go`, `http.ListenAndServe(` |
| Java       | `@SpringBootApplication`, `public static void main(`, `@QuarkusMain` |

**Skip always:**
`node_modules/`, `.git/`, `__pycache__/`, `dist/`, `build/`, `target/`, `vendor/`,
`*.lock`, `*.min.js`, `*.generated.*`, migration files

**Output of Phase 1:**
```
{
  "language": "...",
  "framework": "...",
  "runtime_context": "web_server | cli | library | microservice | monorepo",
  "entry_points": [...],
  "config_files": [...],
  "total_files": N,
  "directory_tree": {...}
}
```

→ Read the matching language agent from `agents/` before Phase 2.

---

## Phase 2 — Connection Map (Feynman Layer 2)

Map how atomic units connect. Build the dependency graph bottom-up.

**What to extract per file:**
- Imports / requires / includes
- Function/method calls to other modules
- Interface implementations and class inheritance
- Data flow: what goes in, what comes out

**Produce:**
```
CONNECTION MAP
├── Internal imports graph    (which modules import which)
├── External dependencies     (third-party libs, their purpose)
├── Circular dependencies     (flag these — brownfield risk)
└── Orphan files              (files with no imports and not imported anywhere)
```

**Circular dependency detection:** If module A imports B and B imports A (directly or transitively) → flag in health report.

**Orphan file detection:** Files that are never imported and don't contain entry points = dead code candidates.

→ Read `references/brownfield-patterns.md` for full brownfield signal catalogue.

---

## Phase 3 — Pattern Recognition (Feynman Layer 3)

With the connection map built, identify emergent structure.

**Layer identification heuristics:**

| Pattern | Layer Assignment |
|---------|-----------------|
| Route handlers, HTTP decorators, REST annotations | API / Presentation Layer |
| Business rules, use cases, orchestration logic | Business Logic / Application Layer |
| DB queries, ORM models, file I/O | Data / Persistence Layer |
| Queue consumers/producers, external API clients | Infrastructure / Adapter Layer |
| Shared utilities, helpers, constants | Cross-cutting / Shared |

**Design pattern recognition:**

```
Check for:
□ Repository pattern   — class with find/save/delete methods wrapping DB
□ Service layer        — class orchestrating multiple repositories
□ Factory pattern      — static create() or build() methods
□ Singleton            — module-level instance, __instance checks
□ Observer/EventEmit   — event emitter registrations, pub/sub
□ Decorator/Middleware — function wrapping another function
□ Strategy pattern     — interface with multiple concrete implementations
□ Adapter pattern      — wrapping third-party client behind interface
```

**Duplicate detection:**

```
Check for:
□ Near-identical function signatures in different modules
□ Repeated business logic (same validation, same transformation)
□ Multiple implementations of the same interface doing the same thing
□ Copy-paste error handling blocks
□ Duplicate data models (same entity defined in 2+ places)
```

→ Read `references/c4-levels.md` to understand what each diagram level should capture.

---

## Phase 4 — Flow Trace (Feynman Layer 4)

Trace 2-3 representative flows end-to-end through the system.

**For each flow:**
1. Pick a user-facing action (e.g., "user submits an order", "CLI runs with --input flag")
2. Follow it from entry point → through each layer → to external system and back
3. Note synchronous vs asynchronous handoffs
4. Identify where errors are handled (or not handled)

**Output:**
```
FLOW SUMMARY
├── Flow 1: [name]  →  EntryPoint → LayerA → LayerB → ExternalSystem
├── Flow 2: [name]  →  ...
└── Error paths: where and how failures propagate
```

This flow summary becomes the edge labels in the component diagram.

---

## Phase 5 — Diagram Generation

Generate all four C4 levels. Read `references/mermaid-syntax.md` for exact syntax rules.

### L1 — System Context Diagram

Shows the system as a black box and its users/external systems.

```mermaid
C4Context
  title System Context — [System Name]
  Person(user, "End User", "...")
  System(sys, "[System Name]", "...")
  System_Ext(ext1, "External System", "...")
  Rel(user, sys, "Uses")
  Rel(sys, ext1, "Calls via HTTP")
```

**If C4Context syntax not supported** → use `graph TD` with clear external system shapes.

### L2 — Container Diagram

Shows deployable units: web app, API server, database, queue, cache.

```mermaid
C4Container
  title Container Diagram — [System Name]
  Person(user, "End User")
  Container(api, "API Server", "Python/FastAPI", "Handles requests")
  ContainerDb(db, "Database", "PostgreSQL", "Stores data")
  Rel(user, api, "HTTPS")
  Rel(api, db, "SQL")
```

### L3 — Component Diagram

Shows internal components within the main container. Uses `graph TD`.

Rules:
- `subgraph` blocks per layer
- Labeled edges with interaction type
- External systems as distinct terminal nodes
- Entry points clearly marked with `:::entry` or `[🚀 EntryPoint]`

### L4 — Class Diagram

Shows classes, interfaces, fields, methods, relationships. Uses `classDiagram`.

Rules:
- `<<stereotypes>>` on every class/interface
- Field visibility: `+` public, `-` private, `#` protected
- All 5 relationship types used where appropriate
- Multiplicity on associations
- Only architecturally significant methods (skip trivial getters/setters)

---

## Phase 6 — Health Report

Produce an `ARCHITECTURAL_HEALTH.md` with these sections:

```markdown
## Architectural Health Report

### Codebase Summary
[2-4 sentences: what it does, architecture style, stack]

### C4 Diagram Index
| Level | File | Description |
|-------|------|-------------|

### Brownfield Signals
[From brownfield-patterns.md catalogue — only signals actually found]

### Duplicate & Redundancy Findings
[List any duplicate logic, models, or patterns found in Phase 3]

### Circular Dependencies
[List any cycles found in Phase 2]

### Dead Code Candidates
[Orphan files found in Phase 2]

### Staff Engineer Observations
[5-10 bullet observations: coupling risks, missing abstractions, patterns worth preserving, technical debt hotspots]

### Recommended Next Steps
[3-5 actionable improvements, ordered by impact]
```

---

## Phase 7 — Onboarding Report

Always produce a single consolidated `ONBOARDING_REPORT.md`, whether or not the user asked
for one by name — the four diagrams and the health report are working artifacts, but a new
developer wants one document to read top-to-bottom. This is the primary deliverable; the
`.mmd` files and `ARCHITECTURAL_HEALTH.md` back it, they don't replace it.

**Rules:**
- **Self-contained.** Reproduce all four diagrams verbatim as fenced ` ```mermaid ` blocks
  inline (not links to the `.mmd` files) so the document renders fully on its own — link to
  the `.mmd` files too, as a secondary reference, but the diagrams themselves must be inline.
- **Reuse, don't re-derive.** Every table/finding already produced in Phases 1–6 (entry
  points, domain/package inventory, external dependencies, design patterns, duplicate/
  migration findings, the flow trace, health findings) gets folded in here. Do not re-scan
  the codebase for this phase.
- **Onboarding-shaped structure**, roughly in this order: what the system is (1 paragraph) →
  L1 → L2 → L3 → L4 with the traced flow narrated as numbered steps → domain/package map →
  full entry-point catalogue → design patterns → migration/duplication status → health
  signals & next steps → a closing **"Where do I start?"** cheat sheet mapping common tasks
  ("add an endpoint to domain X", "change how Y is indexed") to the file/package to open
  first. The cheat sheet is the one section with no equivalent earlier in the workflow —
  don't skip it, it's what makes the report an onboarding tool rather than a dump of the
  other five files.
- **Numbered flow steps are earned, not decorative** — only number the request/event trace
  from Phase 4 (it's a real sequence); don't add numbering elsewhere just for structure.
- Write it to `codeflowmap_output/ONBOARDING_REPORT.md`.
- If the user has (or would benefit from) a visual, rendered version — ask, or default to
  producing one when the surrounding tooling supports rendering a page — build it as a second
  pass over the same content, not a redesign: same section order, same tables, diagrams
  rendered natively. Treat it as a reference document (dense tables, code identifiers, a
  scannable structure) rather than a marketing page — this is a utilitarian deliverable, so
  keep polish proportionate: real typographic hierarchy and a considered palette grounded in
  the subject, not a heavy hero treatment.

---

## Output File Structure

```
codeflowmap_output/
├── L1_system_context.mmd
├── L2_container.mmd
├── L3_component.mmd
├── L4_class.mmd
├── ARCHITECTURAL_HEALTH.md
└── ONBOARDING_REPORT.md      ← primary deliverable: consolidated, diagrams inline
```

All `.mmd` files include a comment header:
```
%% CodeFlowMap — [Level Name]
%% Repository: [path]
%% Language: [lang] | Framework: [framework]
%% Generated: [timestamp]
```

---

## Behavioral Constraints

- **Never fabricate** — only diagram what is actually in the code
- **Feynman check** — if you cannot explain what a module does in one sentence, re-read it before diagramming it
- **Brownfield first** — in brownfield systems, surface health issues even if not asked
- **Scope respect** — if user scoped to a module, L1/L2 show the broader system context but L3/L4 focus on the scoped module
- **Large codebase** — if >500 files, prioritize breadth at L1/L2/L3 and depth at L4 for the core domain only
- **Auto-generated files** — skip them (migrations, protobuf generated, compiled output)
- **Always ship the consolidated report** — `ONBOARDING_REPORT.md` (Phase 7) is not optional
  scope creep; the four `.mmd` files and the health report alone are not a finished onboarding
  deliverable

---

## Reference Files

Read these as needed during execution:

| File | When to Read |
|------|-------------|
| `agents/python-analyzer.md` | Detected Python codebase |
| `agents/typescript-analyzer.md` | Detected TypeScript/JavaScript codebase |
| `agents/golang-analyzer.md` | Detected Go codebase |
| `agents/java-analyzer.md` | Detected Java codebase |
| `references/c4-levels.md` | Before Phase 5 — diagram generation |
| `references/mermaid-syntax.md` | During Phase 5 — syntax rules per diagram type |
| `references/brownfield-patterns.md` | When brownfield signals detected in Phase 1 |

**If these files aren't present** in this skill's directory (they're optional deep-dive
references, not requirements), proceed anyway using the heuristics already given inline in
this file — the entry-point signal table (Phase 1), the layer/pattern/duplicate checklists
(Phase 3), and the Mermaid syntax templates (Phase 5) are self-sufficient on their own.