# CodeFlowMap (Codex)

**What this is:** a repeatable methodology for reading an unfamiliar codebase like a senior
staff engineer and producing a complete C4 architecture diagram suite (System Context →
Container → Component → Class) in Mermaid, plus a brownfield health report and a single
consolidated onboarding document.

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

**How to install/invoke:**
- As a custom prompt: save this file as `$CODEX_HOME/prompts/codeflowmap.md` (default
  `~/.codex/prompts/codeflowmap.md`) and invoke with `/codeflowmap` (optionally pass a path
  as an argument to scope the scan). Adjust to your Codex build's exact prompt-frontmatter
  conventions if it supports argument placeholders or metadata.
- As standing instructions: paste the body below into an `AGENTS.md` at the repo root, or
  reference it from one, so it's loaded automatically for any session touching that repo.
- Wherever you invoke it, do so explicitly — this file doesn't auto-trigger the way it might
  under a description-matching skill system; the user (or an `AGENTS.md` pointer) is what
  brings it into scope.

**Tool assumptions:** written against a generic "shell + file read/write" tool surface
(`find`, `grep`/`rg`, `wc`, reading files, writing files). If your Codex session has
multi-step or parallel task delegation available, use it for Phases 1–4 on large codebases
(see the note at the end of Core Workflow) — otherwise run those phases inline with plain
shell commands.

---

## Quick Decision: Scope Before Starting

Before running analysis, determine:

1. **Full repo or scoped module?**
   - If the user says "entire repo" or gives a root path → full analysis
   - If the 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`)
   - If you maintain per-language deep-dive notes alongside this file (e.g. a
     `references/<lang>-analyzer.md`), consult the matching one before Phase 2 — otherwise
     proceed with the inline heuristics below, they're self-sufficient.

3. **Brownfield or greenfield?**
   - Check for: absence of tests, mixed naming conventions, multiple frameworks,
     commented-out code blocks
   - If brownfield signals are detected → enable brownfield analysis (see the Brownfield
     Signals catalogue implied in Phase 2/6 below, or a `references/brownfield-patterns.md`
     if you maintain one)

---

## 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. If your
environment supports delegating a chunk of work to a separate task/sub-session, that's
reasonable for Phases 1–4 at this scale; just make sure whatever comes back is structured as
tables/lists (not prose) so Phase 7 can reuse it directly instead of re-deriving it.

---

## 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": {...}
}
```

---

## 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.

---

## 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)
```

---

## 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.

### 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 isn't supported by your renderer** → use `graph TD` with clear
external-system shapes instead.

### 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
[Only signals actually found — absent tests, mixed conventions, dead stub packages, etc.]

### 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 you can produce a rendered/visual version (an HTML page, a static site, whatever your
  environment can render), treat 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.

---

## 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 the 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
