---
name: architecture-planning
description: Plan and document software architecture decisions. Use when designing systems, choosing between architectural approaches, refactoring modules, evaluating coupling patterns, or recording decisions in ADRs. Combines C4 model visualization, Architecture Decision Records, deep-module refactoring (Ousterhout), and Rumelt strategy structure. Use alongside codebase-analysis and pm-planning skills.
---

# Architecture Planning: Design Before You Build

Apply structured architectural thinking before implementing anything significant. The three non-negotiables: (1) understand what exists before proposing changes, (2) record every significant decision as an ADR, (3) design for depth not breadth.

---

## Part 1: Architecture Mapping (C4 Model)

Visualize the system at the right level of abstraction before planning changes.

### Four levels (use the right one for your audience)

**Level 1 — System Context** (zoom out, 1 diagram)
Who uses the system? What external systems does it depend on?
```
[User] → [This System] → [External API]
                       → [Database]
                       → [Message Queue]
```

**Level 2 — Container** (zoom in, 1 diagram)
What are the deployable units? How do they communicate?
```
[Web App] → [API Server] → [PostgreSQL]
                         → [Redis Cache]
                         → [Worker Process]
```

**Level 3 — Component** (zoom in more, per-container)
What are the major logical components inside a container?
- Use only when a container is complex enough to need it

**Level 4 — Code** (zoom in furthest, per-component)
Classes, interfaces, functions — only when truly needed for communication

### C4 rules
- Every element needs: name, type, technology, one-line description
- Limit diagrams to 20 elements maximum (beyond that, split or zoom out)
- Show relationships as one-directional arrows with a verb label
- Write diagrams as Mermaid in `docs/architecture/`

### Mermaid template (Level 2 container)
```mermaid
graph LR
    user[User\nWeb Browser] -->|HTTPS| api[API Server\nGo/gin]
    api -->|SQL| db[(PostgreSQL\nData store)]
    api -->|pub/sub| queue[RabbitMQ\nEvent bus]
    queue -->|consume| worker[Worker\nGo service]
    worker -->|SQL| db
```

---

## Part 2: Architecture Decision Records (ADRs)

Every significant architectural decision gets an ADR. "Significant" means: choosing a framework, data store, deployment approach, inter-service protocol, auth mechanism, or any decision you might second-guess in six months.

### When to write an ADR
- Choosing between two significant alternatives
- Deciding "we won't do X even though it seems obvious"
- Any decision you wouldn't want to re-debate in three months
- Any decision a new engineer would be confused by

### ADR format (Michael Nygard + ECC extensions)

Store in `docs/adr/ADR-NNNN-title-slug.md`:

```markdown
# ADR-NNNN: [Decision Title]

**Date**: YYYY-MM-DD
**Status**: proposed | accepted | deprecated | superseded by ADR-NNNN

## Context

[2-5 sentences: the situation, constraints, forces at play. What made this a decision worth recording?]

## Decision

[1-3 sentences: what are we doing?]

## Alternatives Considered

### Alternative: [Name]
- **Pros**: ...
- **Cons**: ...
- **Why not**: [specific reason rejected]

## Consequences

**Positive**: what gets easier
**Negative**: what gets harder or is sacrificed
**Risks**: what could go wrong and how we'll mitigate
```

### ADR anti-patterns
- Don't record trivial decisions ("we used a for-loop")
- Don't write ADRs without alternatives considered — it's just a log entry
- Don't let ADRs get stale — update status when superseded
- Don't duplicate what's already in DECISIONS.md — keep them in sync (sf uses DECISIONS.md; ADRs go in docs/adr/ for human navigation)

---

## Part 3: Deep vs Shallow Modules (Ousterhout)

Before refactoring or adding abstractions, evaluate whether modules are deep or shallow.

**Deep module:** small interface, large implementation
- Interface complexity << implementation complexity
- Easy to test at the boundary
- AI-navigable (fewer entry points to understand)
- Example: `os.File` — simple open/read/write/close hides massive OS complexity

**Shallow module:** interface almost as complex as implementation
- Provides little abstraction value
- Forces callers to know too much
- Example: a "wrapper" that just delegates every method with no added logic

### Detecting shallow modules
```bash
# Find files with many exported symbols but little internal logic
rg "^func |^type |^var |^const " --count | sort -t: -k2 -nr | head -20

# Find files where the interface is large relative to implementation
wc -l *.go | sort -n  # small files that are heavily imported = shallow
```

### Refactoring to depth — parallel design process

When you've identified a shallow module or coupling problem:

1. **Write the constraint spec** — what must any new interface do? What dependencies does it have?
2. **Design 3+ radically different interfaces** (can be sub-agents in parallel):
   - Agent 1: "Minimize interface — aim for 1-3 entry points max"
   - Agent 2: "Maximize flexibility — support many use cases"
   - Agent 3: "Optimize for the most common caller — make the default trivial"
3. **Compare designs** — show trade-offs for each
4. **Pick or hybrid** — be opinionated; the goal is a strong recommendation, not a menu
5. **Document as ADR** — record what was chosen and why alternatives were rejected

### Dependency categories (what's being hidden)

| Category | Description | Design implication |
|---|---|---|
| **I/O** | File, network, database | Inject interface, mock in tests |
| **State** | In-memory, cache | Pass explicitly or use value objects |
| **Cross-cutting** | Logging, metrics, auth | Pass as context/middleware, not global |
| **Domain logic** | Business rules | Keep pure; no I/O dependencies |

---

## Part 4: Architectural Integrity Checks

Run these before approving any milestone plan:

**Coupling check**
```bash
# Detect potential circular imports (Go)
go build ./... 2>&1 | grep "import cycle"

# Find most-depended-on files (high coupling risk)
rg "import|require|from" --count | sort -t: -k2 -rn | head -20
```

**Boundary violations**
- Does any module import from a module it shouldn't know about?
- Does any layer (e.g. HTTP handler) contain business logic?
- Does any data store module leak implementation details to callers?

**Abstraction level consistency**
- Is this module operating at a consistent level of abstraction throughout?
- Are there places where high-level flow is mixed with low-level implementation detail?

**Testability**
- Can this component be tested without starting the database?
- Can this component be tested without real network calls?
- Can this component be tested without the full application running?
- If the answer is "no" to any: it has a hidden dependency that needs to be injected

---

## Part 5: Architecture Memory in `.sf/`

After any architecture analysis or significant decision, update:

**`.sf/CODEBASE-ANALYSIS.md`** (from codebase-analysis skill)
- Architecture map (C4 Level 1-2 in text)
- Module coupling findings

**`.sf/DECISIONS.md`** (via `save_decision` tool)
- All significant architectural decisions
- Automatically regenerated by the tool

**`docs/adr/`** (human-readable ADR trail)
- Detailed decision records with alternatives
- Links from DECISIONS.md entries

**`.sf/PM-STRATEGY.md`** (from pm-planning skill)
- Guiding Policies section: architectural principles that constrain future decisions

These four files together give any future agent (or engineer) a complete architectural picture without rereading the full codebase.

---

## Sources

- [softaworks/agent-toolkit](https://github.com/softaworks/agent-toolkit) — C4 architecture skill
- [affaan-m/everything-claude-code](https://github.com/affaan-m/everything-claude-code) — ADR skill (Michael Nygard format)
- [mattpocock/skills](https://github.com/mattpocock/skills) — improve-codebase-architecture, parallel interface design
- [trailofbits/skills](https://github.com/trailofbits/skills) — audit-context-building, phase structure
- John Ousterhout, *A Philosophy of Software Design* — deep vs shallow modules
- Richard Rumelt, *Good Strategy/Bad Strategy* — diagnosis and guiding policies
- Simon Brown — C4 model for visualizing software architecture
