# architecture-spec

Adopt this skill: https://proskills.md/skills/documentation/comsky-remy-skill-recipes-skills-architecture-spec

Page: https://proskills.md/skills/documentation/comsky-remy-skill-recipes-skills-architecture-spec
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/architecture-spec/SKILL.md
size: 8329
sha: 4d41ef63c2148a094bfe6710dca8c80fd669b76d
upstream: https://github.com/comsky/remy-skill-recipes/blob/main/skills/architecture-spec/SKILL.md

```text
---
name: architecture-spec
description: >
  Generate architecture and design documents for implemented code changes
  with risk-based depth selection. Automatically evaluates risk signals,
  layer spread, and change magnitude to choose documentation level (A/B/C).
  Use after completing a feature, before merging a PR that touches multiple
  layers or sensitive areas (auth, infra, migrations, payments), or when an
  implemented change needs a design record or ADR.
license: MIT
metadata:
  compatibility: Claude Code, Cursor
  type: execution
  category: documentation
  maturity: draft
  estimated_time: 10 min
---

# Skill: Architecture Spec (Post-Implementation)

**Type:** Execution

## Purpose

Given implemented changes (diff / changed files), generate an
architecture/design document with appropriate depth.

The depth is selected automatically based on:

- Risk signals
- Layer spread
- Change magnitude
- Sensitive areas (auth, infra, migration, etc.)

---

## When to Use

- After completing a feature or significant code change
- Before merging a PR that touches multiple layers or sensitive areas
- When stakeholders need a design record for changes already implemented
- After a hotfix or incident-driven change that requires documentation

---

## When NOT to Use

- During initial design/planning (use a design doc skill instead)
- Documentation-only or comment-only changes
- Auto-generated code changes (lock files, migration snapshots)
- Trivial single-file changes with no risk signals (e.g., typo fix)

---

## Inputs Required

Do not run this skill without:

- [ ] changed_files (list of modified files)
- [ ] diff_summary (LOC count or file count)
- [ ] feature_name (short name for the change)

Optional but recommended:

- [ ] diff_snippets (key portions of the diff)
- [ ] repo_context (architecture overview, dependency map)

Without asking the user (unless unavailable), gather these inputs directly from the repository.

---

## Output Format

1. Risk Evaluation Summary (score breakdown, selected level)
2. Architecture/Design Document (level-appropriate Markdown)
3. ADR section (Level C only)
4. Notion page URL (if Notion integration available)

---

## Procedure

### Step 1 — Evaluate Risk

→ Detailed scoring criteria: [subskills/diff-risk-evaluator.md](subskills/diff-risk-evaluator.md)
  (load only if the summary below is insufficient for scoring)

Analyze changed files and calculate a deterministic risk score across three dimensions:

| Dimension | What it measures |
|---|---|
| Path-Based Risk | Sensitive area keywords in file paths (+3 to +4 per match) |
| Layer Spread | Number of architectural layers touched (+1 to +5) |
| Change Magnitude | Lines of code changed (+1 to +6) |

`total_score = path_score + layer_score + magnitude_score`

### Step 2 — Select Documentation Level

| Total Score | Level |
|---|---|
| 0–6 | A (Lightweight) |
| 7–13 | B (Standard) |
| 14+ | C (Architecture-Level) |

**Hard Rules:**

- Auth + multi-layer → minimum B
- Infra change → minimum B
- Migration + medium change → minimum B
- Financial impact → C
- Global middleware + high magnitude → C

If unsure, prefer B over A.

### Step 3 — Generate Document

→ Load and follow [subskills/notion-spec-generator.md](subskills/notion-spec-generator.md)
  at this point (not before).

Generate a Notion-ready Markdown document for the selected level:

- **Level A** — Overview, What Changed, Simple Flow, Decisions, Test Notes
- **Level B** — Level A + Architecture, Sequence Diagram, API Spec, Edge Cases, Security Notes, Operational Notes, Future Improvements
- **Level C** — Level B + Threat Model, Failure Flow, Rollback Plan, Observability Plan, ADR-style Decisions

For Level C only, additionally load and follow
[subskills/adr-generator.md](subskills/adr-generator.md) to produce
a formal ADR section. Do NOT load this subskill for Level A or B.

All levels must include: Title, Metadata table, TL;DR, Changed files summary.

### Step 4 — Publish to Notion (Optional)

> **ACTIVATION:** This step runs only if Notion MCP integration is
> available and the user requests publishing. If skipped, do NOT load
> the subskill file.

→ Load and follow [subskills/notion-page-publisher.md](subskills/notion-page-publisher.md)
  only when this step is activated.

If Notion MCP integration is available, persist the generated spec to Notion:

- Create or update a page in the target database
- Map properties (Level, Risk Score, Feature, Status)
- For Level C, attach ADR as a child page or appended section
- If a Draft page with the same feature name exists, update instead of creating a new one
- Return the Notion page URL

---

## Quality Bar

The document must answer:

- What changed?
- Why?
- How does it work?
- Where can it fail?
- How is it monitored?
- How do we roll back?
- Is the document visually scannable? (emoji headings, tables, diagrams, dividers)

---

## Guardrails

- Deterministic scoring first; keyword detection only nudges the level.
- Never under-document security or financial changes.
- Prefer a safer (higher) level if signals are incomplete.
- Do not invent architecture details not present in the code.
- Explicitly state assumptions when context is incomplete.
- If inputs are insufficient to evaluate risk, ask for clarification before proceeding.
- Do not skip the risk evaluation step and jump directly to document generation.

---

## Failure Patterns

Common bad outputs:

- Selecting Level A for multi-layer changes that touch auth or infra
- Generating a document without running the risk scoring procedure
- Producing generic architecture descriptions not tied to the actual diff
- Missing the ADR section for Level C changes
- Inflating risk scores by double-counting the same file in multiple categories
- Skipping the Quality Bar questions (especially "Where can it fail?" and "How do we roll back?")

---

## Example 1 (Minimal Context)

**Input:**

feature_name: "Add rate limiting to public API"
changed_files: `middleware/rate-limiter.ts`, `config/rate-limit.ts`, `routes/api.ts`
diff_summary: 120 LOC

**Output:**

1. Risk Evaluation:
   - Path score: +3 (middleware) + +3 (config) = 6
   - Layer spread: +3 (2 layers: middleware, routes)
   - Magnitude: +1 (<150 LOC)
   - Total: 10 → **Level B**
2. Document: Standard spec with Overview, Architecture (middleware chain diagram), Sequence Diagram (request → rate check → pass/reject), API Spec (429 response), Edge Cases (distributed rate limiting gaps), Security Notes (bypass vectors), Operational Notes (Redis dependency)

---

## Example 2 (Realistic Scenario)

**Input:**

feature_name: "Migrate user auth from session to JWT"
changed_files: `auth/jwt-provider.ts`, `auth/session-provider.ts` (deleted), `middleware/auth.ts`, `config/auth.ts`, `migrations/20250220_drop_sessions.sql`, `routes/login.ts`, `routes/logout.ts`, `services/user.ts`, `tests/auth.test.ts`
diff_summary: 850 LOC

**Output:**

1. Risk Evaluation:
   - Path score: +4 (auth) + +3 (middleware) + +3 (config) + +3 (migration) = 13
   - Layer spread: +5 (4+ layers: auth, middleware, config, routes, services)
   - Magnitude: +4 (500–1500 LOC)
   - Total: 22 → **Level C**
   - Hard rule applied: Auth + multi-layer → minimum B (already exceeded)
2. Document: Full architecture spec with Threat Model (token theft, replay attacks), Failure Flow (JWT validation failure paths), Rollback Plan (session table restoration, dual-auth transition period), Observability Plan (auth failure rate metric, token expiry distribution)
3. ADR: "Migrate from server-side sessions to JWT" — options considered (session + Redis vs JWT vs JWT + refresh token), decision rationale, consequences (stateless scaling benefit vs token revocation complexity)

---

## Notes

**FAST MODE** (only if explicitly requested):

- Always use Level A regardless of risk score
- Skip Step 4 (Notion publish)
- Risk evaluation still runs for the metadata record

---

This skill delegates detailed work to four subskills:

- **diff-risk-evaluator** — risk scoring only (no document generation)
- **notion-spec-generator** — Markdown document generation per level
- **adr-generator** — ADR section for Level C changes
- **notion-page-publisher** — Persist spec to Notion (optional, requires Notion MCP)
```

## File: skills/architecture-spec/README.md
size: 1110
sha: e78f3449ed48b2f85ce897ac34b9a9a34daa63f1
upstream: https://github.com/comsky/remy-skill-recipes/blob/main/skills/architecture-spec/README.md

```text
# Architecture Spec (Post-Implementation)

Automatically generate a structured architecture/design document
based on implemented code changes.

This skill:

- Analyzes Git diff / changed files
- Evaluates risk and blast radius
- Selects documentation depth (A/B/C)
- Generates a Notion-ready Markdown spec
- Includes diagrams (Mermaid), tables, decisions, and operational notes

---

## Why

Documentation depth should scale with:

- Risk
- Security impact
- Infra impact
- Blast radius

This skill ensures consistency without CI enforcement.

---

## Output Levels

- A — Lightweight
- B — Standard
- C — Architecture-Level

The level is selected automatically.

---

## Structure

- [SKILL.md](SKILL.md) — Main skill (entry point)
- [subskills/diff-risk-evaluator.md](subskills/diff-risk-evaluator.md) — Risk scoring
- [subskills/notion-spec-generator.md](subskills/notion-spec-generator.md) — Document generation
- [subskills/adr-generator.md](subskills/adr-generator.md) — ADR section (Level C)
- [subskills/notion-page-publisher.md](subskills/notion-page-publisher.md) — Publish to Notion
```

## File: skills/architecture-spec/README.ko.md
size: 1304
sha: 881bf0cd1466e34fe144a4ff79a6dccfd80047ae
upstream: https://github.com/comsky/remy-skill-recipes/blob/main/skills/architecture-spec/README.ko.md

```text
# Architecture Spec (구현 후 설계 문서)

구현 완료된 코드 변경사항을 기반으로
구조화된 아키텍처/설계 문서를 자동 생성합니다.

이 스킬은:

- Git diff / 변경된 파일을 분석
- 리스크와 영향 범위를 평가
- 문서화 깊이를 자동 선택 (A/B/C)
- Notion-ready Markdown 사양서를 생성
- 다이어그램 (Mermaid), 테이블, 설계 결정, 운영 참고사항 포함

---

## 왜 필요한가

문서화 깊이는 다음에 비례해야 합니다:

- 리스크
- 보안 영향
- 인프라 영향
- 영향 범위 (blast radius)

이 스킬은 CI 강제 없이도 일관된 문서화를 보장합니다.

---

## 출력 레벨

- A — 경량 (Lightweight)
- B — 표준 (Standard)
- C — 아키텍처 수준 (Architecture-Level)

리스크 점수에 따라 레벨이 자동으로 선택됩니다.

---

## 구조

- [SKILL.md](SKILL.md) — 메인 스킬 (진입점)
- [subskills/diff-risk-evaluator.md](subskills/diff-risk-evaluator.md) — 리스크 점수 산정
- [subskills/notion-spec-generator.md](subskills/notion-spec-generator.md) — 문서 생성
- [subskills/adr-generator.md](subskills/adr-generator.md) — ADR 섹션 (Level C)
- [subskills/notion-page-publisher.md](subskills/notion-page-publisher.md) — Notion 게시
```

## File: skills/architecture-spec/subskills/adr-generator.md
size: 3344
sha: 158d125037a5943e2f4580b2671584513824545d
upstream: https://github.com/comsky/remy-skill-recipes/blob/main/skills/architecture-spec/subskills/adr-generator.md

```text
# Subskill: ADR Generator

**Parent:** [SKILL.md](../SKILL.md)  
**Role:** ADR section generation (Level C only)

---

## Purpose

Generate an Architecture Decision Record (ADR) for high-impact changes
(typically Level C).

---

## When to Use

- Security/auth changes
- Infra changes
- Schema migrations
- Global behavior changes
- Financial-impact logic

---

## Inputs

- feature_name (required)
- decision context from the diff (required)
- risk_summary from diff-risk-evaluator (required)
- repo_context (optional)

---

## ADR Template

### ADR: \<Decision Title\>

**Status:** Proposed / Accepted / Superseded

**Context:**
Describe the problem, constraints, and forces.

**Options Considered:**

| Option | Description | Pros | Cons |
|---|---|---|---|
| A | ... | ... | ... |
| B | ... | ... | ... |

**Decision:**
State the selected option clearly.

**Consequences:**

| Type | Impact |
|---|---|
| Technical | ... |
| Operational | ... |
| Security | ... |
| Long-term | ... |

**Rollback Considerations:**

- Can this be reverted?
- Data impact?
- Migration strategy?

---

## Guardrails

- Always present at least 2 realistic options (do not fabricate a strawman option just to fill the table).
- Consequences must cover all four types (Technical, Operational, Security, Long-term); write "N/A" if truly not applicable.
- Do not recommend an option without explicit justification tied to the project context.

---

## Failure Patterns

- Listing only one option and presenting it as a "decision" (no real trade-off analysis)
- Omitting rollback considerations for irreversible changes (e.g., schema migrations)
- Generic consequences not tied to the actual change (e.g., "may cause issues" without specifics)

---

## Example

**Input:**

feature_name: "Migrate user auth from session to JWT"
decision context: Replacing server-side session store with stateless JWT tokens.
risk_summary: Level C, auth + migration + multi-layer.

**Output:**

### ADR: Migrate authentication from server-side sessions to JWT

**Status:** Proposed

**Context:**
Current session-based auth requires Redis for session storage, adding operational complexity and a single point of failure. The team wants stateless auth to simplify horizontal scaling.

**Options Considered:**

| Option | Description | Pros | Cons |
|---|---|---|---|
| A | Keep sessions + Redis | No migration risk, proven | Redis SPOF, session affinity needed |
| B | JWT (access only) | Stateless, simple | No revocation without blacklist |
| C | JWT + refresh token | Stateless + revocation via refresh rotation | Higher implementation complexity |

**Decision:**
Option C — JWT with refresh token rotation. Provides stateless scaling while maintaining revocation capability through refresh token rotation.

**Consequences:**

| Type | Impact |
|---|---|
| Technical | New token refresh endpoint, refresh token storage in DB |
| Operational | Remove Redis dependency, add token expiry monitoring |
| Security | Short-lived access tokens (15min), refresh rotation mitigates theft |
| Long-term | Enables multi-service auth without shared session store |

**Rollback Considerations:**

- Revert requires restoring session table and Redis config
- Existing JWTs will be invalid after rollback; force re-login required
- Run dual-auth (session + JWT) for 1 sprint before full cutover
```

## File: skills/architecture-spec/subskills/diff-risk-evaluator.md
size: 3133
sha: 57cdbf0f3faf3a5d614d70e6f1a2d5a1a7daf728
upstream: https://github.com/comsky/remy-skill-recipes/blob/main/skills/architecture-spec/subskills/diff-risk-evaluator.md

````text
# Subskill: Diff Risk Evaluator

**Parent:** [SKILL.md](../SKILL.md)  
**Role:** Risk scoring (Step 1 of parent skill)

---

## Purpose

Analyze changed files / diff summary and calculate a deterministic risk
score.

This subskill does NOT generate documentation. It only returns:

- risk signals (matched patterns)
- total score (numeric)
- recommended documentation level (A/B/C)

---

## Inputs

- changed_files (required)
- diff_summary — LOC or file count (required)
- diff_snippets (optional)

---

## Output Format

Return a structured risk summary:

```
Path Score:      +N  (matched: <patterns>)
Layer Score:     +N  (<count> layers)
Magnitude Score: +N  (<LOC> LOC)
Total Score:     N
Level:           A / B / C
Hard Override:   <applied rule or "none">
```

---

## Step 1 — Path-Based Risk Detection

| Pattern | Score |
|---|---|
| /auth/, security, rbac | +4 |
| migration, schema | +3 |
| /infra/, terraform | +4 |
| k8s, Dockerfile | +3 |
| /integrations/, oauth, oidc | +3 |
| middleware, global | +3 |
| config, .env | +3 |
| payment, billing | +4 |

Match each changed file path against these patterns. Sum all unique matches
(do not double-count the same file if it matches multiple patterns in the
same row).

---

## Step 2 — Layer Spread

| Layers Touched | Score |
|---|---|
| 1 | +1 |
| 2–3 | +3 |
| 4+ | +5 |

Layers are architectural boundaries (e.g., routes, middleware, services,
repositories, config, infra). Test files do not count as a separate layer.

---

## Step 3 — Change Magnitude

| LOC Changed | Score |
|---|---|
| <150 | +1 |
| 150–500 | +2 |
| 500–1500 | +4 |
| 1500+ | +6 |

Fallback: file-count based estimation (1 file ≈ 50 LOC).

---

## Step 4 — Total Score

`total_score = path_score + layer_score + magnitude_score`

---

## Level Mapping

| Score | Level |
|---|---|
| 0–6 | A |
| 7–13 | B |
| 14+ | C |

---

## Hard Overrides

These rules override the calculated level:

- Auth + multi-layer → minimum B
- Infra change → minimum B
- Migration + medium magnitude → minimum B
- Financial impact → C
- Global middleware + high magnitude → C

---

## Guardrails

- Do not double-count the same file across multiple risk patterns.
- Use only deterministic path matching; do not infer risk from file content unless diff_snippets are provided.
- If LOC and file count are both unavailable, ask for clarification rather than guessing.

---

## Failure Patterns

- Double-counting a file that matches both "config" and ".env" patterns, inflating the score
- Treating test files as production layer spread (tests should not count as a separate architectural layer)
- Ignoring hard overrides after calculating the total score

---

## Example

**Input:**

changed_files: `auth/jwt.ts`, `middleware/auth.ts`, `config/auth.ts`, `routes/login.ts`
diff_summary: 200 LOC

**Output:**

```
Path Score:      +10 (matched: auth +4, middleware +3, config +3)
Layer Score:     +5  (4 layers: auth, middleware, config, routes)
Magnitude Score: +2  (200 LOC)
Total Score:     17
Level:           C
Hard Override:   Auth + multi-layer → minimum B (already exceeded)
```
````

## File: skills/architecture-spec/subskills/notion-page-publisher.md
size: 2287
sha: fe9e3aadec5ae36b027b44dc65872557ca088bdd
upstream: https://github.com/comsky/remy-skill-recipes/blob/main/skills/architecture-spec/subskills/notion-page-publisher.md

```text
# Subskill: Notion Page Publisher

**Parent:** [SKILL.md](../SKILL.md)  
**Role:** Notion publishing (Step 4 of parent skill)

---

## Purpose

Persist the generated architecture spec into Notion.

This subskill assumes Notion MCP integration is available.

---

## Inputs

- title
- content_markdown
- database_id
- level (A/B/C)
- feature_name
- risk_score
- tags (optional)

---

## Step 1 — Determine Parent

If database_id provided:
→ create page inside database

Else:
→ create page under default "Architecture Specs" parent page

---

## Step 2 — Map Properties

Example property mapping:

| Property   | Value        |
| ---------- | ------------ |
| Name       | title        |
| Level      | A/B/C        |
| Status     | Draft        |
| Risk Score | number       |
| Feature    | feature_name |
| Created At | now()        |

---

## Step 3 — Create Page

Use:

notion.create_page({
parent: { database_id },
properties: { ... },
children: markdown_to_blocks(content_markdown)
})

---

## Step 4 — ADR Handling

If level == C:

- Append ADR section to same page
  OR
- Create child page under spec

---

## Behavior

- If page already exists (same feature name, Draft status):
  → update instead of create
- Always return Notion URL

---

## Guardrails

- Do not create a page if content_markdown is empty or only whitespace.
- If Notion MCP is unavailable, skip publishing and return a warning instead of failing.
- Always verify database_id exists before attempting page creation.
- Do not overwrite pages in non-Draft status without explicit confirmation.

---

## Failure Patterns

- Creating a duplicate page instead of updating an existing Draft with the same feature name
- Silently failing when Notion MCP is unavailable instead of reporting the issue
- Publishing with missing required properties (Level, Risk Score) causing incomplete Notion entries

---

## Example

**Input:**

title: "Add rate limiting to public API — Technical Spec"
content_markdown: (generated Level B spec)
database_id: "abc123"
level: B
feature_name: "Add rate limiting to public API"
risk_score: 10

**Output:**

Notion page created: https://notion.so/add-rate-limiting-spec-xyz789
Properties: Level=B, Status=Draft, Risk Score=10, Feature="Add rate limiting to public API"
```

## File: skills/architecture-spec/subskills/notion-spec-generator.md
size: 10990
sha: 164a4624236626ae7539c236d93029c775698551
upstream: https://github.com/comsky/remy-skill-recipes/blob/main/skills/architecture-spec/subskills/notion-spec-generator.md

````text
# Subskill: Notion Spec Generator

**Parent:** [SKILL.md](../SKILL.md)  
**Role:** Document generation (Step 3 of parent skill)

---

## Purpose

Generate a structured Notion-ready Markdown document based on selected
documentation level (A/B/C).

---

## Visual Formatting Rules

Every generated document MUST follow these rules to ensure visual scannability:

### Section Headers

Use `##` headings with an emoji prefix for every major section:

| Emoji | Section |
|---|---|
| 📖 | Overview |
| 🔄 | What Changed |
| 🏗 | Architecture |
| 🔀 | Sequence Diagram |
| 🔌 | API Spec |
| ⚖️ | Decisions & Trade-offs |
| ⚠️ | Edge Cases |
| 🔒 | Security Notes |
| 🛠 | Operational Notes |
| 🔮 | Future Improvements |
| 🛡 | Threat Model |
| 💥 | Failure Flow |
| ⏪ | Rollback Plan |
| 📡 | Observability Plan |
| 🧪 | Test Notes |

### Dividers

Insert `---` between every major section for clear visual separation.

### Tables

Use tables (not prose) whenever data has 2+ comparable attributes:

- API endpoints → Method / Path / Request / Response / Status Codes
- Edge cases → Scenario / Impact / Mitigation
- Decisions → Option / Pros / Cons
- Changed files → File / Change / Layer

### Mermaid Diagrams

Minimum diagram count per level:

| Level | Min Diagrams | Required Types |
|---|---|---|
| A | 1 | flowchart |
| B | 2 | flowchart + sequenceDiagram |
| C | 3 | flowchart + sequenceDiagram + failure flow |

Diagrams must reflect actual components from the changed files, never generic placeholders.

### Callouts

Use blockquotes (`>`) to highlight critical warnings, constraints, or assumptions:

> ⚠️ **Note:** This middleware must be applied before auth to prevent...

### Risk Badges

Use emoji badges for risk/status indicators:

| Badge | Meaning |
|---|---|
| 🟢 | Low risk (Level A, score 0–6) |
| 🟡 | Medium risk (Level B, score 7–13) |
| 🔴 | High risk (Level C, score 14+) |

---

## Inputs

- feature_name (required)
- selected_level — A/B/C (required)
- risk_summary from diff-risk-evaluator (required)
- changed_files (required)
- repo_context (optional)

---

> **READING RULE:** This subskill contains templates for all three
> levels (A, B, C). Read only the Common Header section and the
> section matching the selected level. Skip the other level templates
> to conserve context.

## Common Header (All Levels)

Every document must begin with the following structure:

```
# 📋 <Feature Name> — Technical Spec

| Field         | Value                |
| ------------- | -------------------- |
| 📝 Author     | (auto)               |
| 📅 Date       | YYYY-MM-DD           |
| 📊 Level      | A / B / C            |
| 🎯 Risk Score | N (🟢 / 🟡 / 🔴)    |
| 📌 Status     | Draft                |

> **TL;DR:** 2–3 sentence summary of the change.

---

## 📁 Changed Files

| File         | Change                                 | Layer      |
| ------------ | -------------------------------------- | ---------- |
| path/to/file | New / Modified / Deleted — description | Layer name |
```

---

## Level A — Lightweight

Sections (min 1 Mermaid diagram):

```
## 📖 Overview
Brief description of the change and its purpose.

---

## 🔄 What Changed
Bullet list of key changes with context.

---

## 🔀 Simple Flow
```mermaid
flowchart LR
  ComponentA --> ComponentB
  ComponentB --> ComponentC
```

---

## ⚖️ Decisions
| Decision | Rationale |
|---|---|
| ... | ... |

---

## 🧪 Test Notes
- [ ] Unit tests added/updated
- [ ] Integration tests covering ...
- [ ] Manual test scenarios: ...
```

---

## Level B — Standard

Sections (min 2 Mermaid diagrams):

```
## 📖 Overview
Description of the change, motivation, and scope.

---

## 🏗 Architecture
Component relationships and data flow.

```mermaid
flowchart TD
  ComponentA --> ComponentB
  ComponentB --> ComponentC
  ComponentC --> ExternalService
```

---

## 🔀 Sequence Diagram
```mermaid
sequenceDiagram
  Actor->>ServiceA: Request
  ServiceA->>ServiceB: Process
  ServiceB-->>ServiceA: Response
  ServiceA-->>Actor: Result
```

---

## 🔌 API Spec
| Method | Path | Request | Response | Status Codes |
|---|---|---|---|---|
| POST | /api/... | `{ ... }` | `{ ... }` | 200, 400, 429 |

---

## ⚖️ Decisions & Trade-offs
| Option | Pros | Cons |
|---|---|---|
| A — ... | ... | ... |
| B — ... | ... | ... |

> **Selected:** Option X because ...

---

## ⚠️ Edge Cases
| Scenario | Impact | Mitigation |
|---|---|---|
| ... | ... | ... |

---

## 🔒 Security Notes
- [ ] Authentication: ...
- [ ] Authorization: ...
- [ ] Input validation: ...
- [ ] Rate limiting: ...

---

## 🛠 Operational Notes
| Item | Detail |
|---|---|
| Dependencies | ... |
| Env Variables | ... |
| Monitoring | ... |
| Alerts | ... |

---

## 🔮 Future Improvements
- ...
- ...
```

---

## Level C — Architecture-Level

Includes all Level B sections plus (min 3 Mermaid diagrams):

```
## 🛡 Threat Model
| Threat | Vector | Likelihood | Impact | Mitigation |
|---|---|---|---|---|
| ... | ... | 🟡 Medium | 🔴 High | ... |

---

## 💥 Failure Flow
```mermaid
flowchart TD
  Request --> Validation
  Validation -->|Invalid| ErrorResponse
  Validation -->|Valid| Processing
  Processing -->|Timeout| Retry
  Retry -->|Max retries| Fallback
  Fallback --> DegradedResponse
```

---

## ⏪ Rollback Plan
| Step | Action | Verification |
|---|---|---|
| 1 | ... | ... |
| 2 | ... | ... |

> ⚠️ **Data impact:** describe any irreversible data changes.

---

## 📡 Observability Plan
| Signal | Metric / Log | Alert Threshold |
|---|---|---|
| ... | ... | ... |

---

## 📝 ADR
→ Generated by the parent skill via adr-generator.md — do not load separately.
```

---

## Guardrails

- Mermaid diagrams must reflect actual components from the changed files, not generic placeholders.
- The metadata table must include the risk score and selected level for traceability.
- Do not add sections beyond the level specification (e.g., no Threat Model in Level A).
- Every section heading must use the designated emoji prefix from the Visual Formatting Rules.
- Use tables instead of prose for any data with 2+ comparable attributes.
- Meet the minimum Mermaid diagram count for the selected level (A: 1, B: 2, C: 3).
- Insert `---` dividers between every major section.

---

## Failure Patterns

- Using the example Mermaid diagrams from this template verbatim instead of building diagrams from the actual code
- Generating a Level B document when Level A was selected (over-documenting)
- Omitting the TL;DR or metadata table from the common header
- Writing vague "Overview" sections that don't reference the actual change
- Generating flat text-only sections without tables or diagrams where structured data exists
- Omitting emoji prefixes from section headings
- Using only one Mermaid diagram when the level requires more
- Missing `---` dividers between sections, producing a wall of text

---

## Example

**Input:**

feature_name: "Add rate limiting to public API"
selected_level: B
risk_summary: Path +6, Layer +3, Magnitude +1, Total 10
changed_files: `middleware/rate-limiter.ts`, `config/rate-limit.ts`, `routes/api.ts`

**Output:**

# 📋 Add rate limiting to public API — Technical Spec

| Field | Value |
|---|---|
| 📝 Author | (auto) |
| 📅 Date | 2025-02-20 |
| 📊 Level | B (Standard) |
| 🎯 Risk Score | 10 🟡 |
| 📌 Status | Draft |

> **TL;DR:** Added token-bucket rate limiting middleware to all public API routes. Configurable via environment variables. Returns 429 when limit exceeded.

---

## 📁 Changed Files

| File | Change | Layer |
|---|---|---|
| middleware/rate-limiter.ts | New — token bucket implementation | Middleware |
| config/rate-limit.ts | New — rate limit configuration | Config |
| routes/api.ts | Modified — apply rate limiter middleware | Routes |

---

## 📖 Overview

Token-bucket rate limiter applied to all `/api/v1/*` routes. Each client is identified by API key (or IP for unauthenticated requests). The bucket refills at a configurable rate and rejects requests with HTTP 429 when depleted.

---

## 🏗 Architecture

```mermaid
flowchart LR
  Client --> AuthMiddleware
  AuthMiddleware --> RateLimiter
  RateLimiter --> TokenBucket[(Token Bucket)]
  RateLimiter -->|Pass| RouteHandler
  RateLimiter -->|Reject| Response429[429 Response]
```

---

## 🔀 Sequence Diagram

```mermaid
sequenceDiagram
  Client->>AuthMiddleware: Request + API Key
  AuthMiddleware->>RateLimiter: Authenticated request
  RateLimiter->>TokenBucket: consume(clientId)
  alt Under limit
    TokenBucket-->>RateLimiter: remaining: N
    RateLimiter->>Handler: Forward request
    Handler-->>Client: 200 OK
  else Over limit
    TokenBucket-->>RateLimiter: remaining: 0
    RateLimiter-->>Client: 429 Too Many Requests
  end
```

---

## 🔌 API Spec

| Method | Path | Request | Response | Status Codes |
|---|---|---|---|---|
| ANY | /api/v1/* | — | — | 200, 429 |

Response headers added:

| Header | Value |
|---|---|
| X-RateLimit-Limit | Max requests per window |
| X-RateLimit-Remaining | Remaining tokens |
| X-RateLimit-Reset | Seconds until bucket refill |

---

## ⚖️ Decisions & Trade-offs

| Option | Pros | Cons |
|---|---|---|
| A — Fixed window counter | Simple, low memory | Burst at window boundary |
| B — Token bucket | Smooth rate, burst-tolerant | Slightly more complex |
| C — Sliding window log | Most accurate | High memory per client |

> **Selected:** Option B (Token bucket) — balances accuracy with resource efficiency. Allows short bursts while maintaining a steady average rate.

---

## ⚠️ Edge Cases

| Scenario | Impact | Mitigation |
|---|---|---|
| Distributed deployment (multi-instance) | Each instance has its own bucket → effective limit multiplied | Use shared Redis store for token state |
| Clock skew between instances | Inconsistent refill timing | Use Redis TTL-based expiry instead of local clock |
| API key rotation mid-window | New key gets fresh bucket | Acceptable — does not bypass intent of rate limiting |

---

## 🔒 Security Notes

- [x] Rate limiter applied before route handlers (cannot bypass)
- [x] IP-based fallback for unauthenticated requests (prevents anonymous abuse)
- [ ] Consider stricter limits for sensitive endpoints (login, password reset)
- [ ] Verify rate limit headers do not leak internal architecture info

---

## 🛠 Operational Notes

| Item | Detail |
|---|---|
| Dependencies | Redis (optional, for distributed mode) |
| Env Variables | `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_SEC`, `RATE_LIMIT_STORE` |
| Monitoring | Track `rate_limit.rejected` counter metric |
| Alerts | Alert if rejection rate > 20% sustained for 5 min |

---

## 🔮 Future Improvements

- Per-endpoint configurable limits (e.g., stricter for auth routes)
- Tiered rate limits based on subscription plan
- WebSocket connection rate limiting
````
