---
name: spec-writer
source: botcore
description: >
  Write high-quality technical specifications for AI agent implementation.
  Use when creating specs, writing technical plans, or following SDD methodology.
version: "2.2.0"
triggers:
  - write spec
  - create specification
  - technical plan
  - spec-driven development
  - SDD
  - SPEC.md
  - feature specification
---

# Spec Writer

Expert guidance for writing specifications that AI agents can reliably implement.

## Capabilities

1. **Clarify** — Resolve ambiguity before writing
2. **Specify** — Transform proposals into structured specs
3. **Plan** — Map requirements to architecture
4. **Tasks** — Break into atomic, executable work items

## Quick Reference

```
Intent → Clarify → Specify → Plan → Tasks → Implement
```

**Inputs:** `PROPOSAL.md`, `REVIEW.md`, `SPEC_CONTEXT.md`  
**Output:** `SPEC.md`

## Routing Logic

| Request Type | Load Reference |
|--------------|----------------|
| Clarification, ambiguity resolution | [references/clarify.md](references/clarify.md) |
| Spec structure, templates | [references/spec-template.md](references/spec-template.md) |
| Technical planning, architecture | [references/plan-template.md](references/plan-template.md) |
| Task breakdown, waves | [references/task-template.md](references/task-template.md) |
| Quality gates, anti-patterns | [references/quality-gates.md](references/quality-gates.md) |

## Core Principles

### 1. "Code in English Before Code"

Write precise specifications before any implementation.

### 2. No Fuzzy Words

Avoid: "fast", "secure", "scalable", "handle gracefully"
Use: "< 200ms response", "OAuth2 + JWT", "100K concurrent users"

### 3. RFC 2119 Keywords

| Word | Meaning |
|------|---------|
| MUST | Absolute requirement |
| SHOULD | Recommended, exceptions possible |
| MAY | Optional |

### 4. Constitutional Compliance

Always check `AGENTS.md` and project rules before specifying.

## Spec Content Boundaries

Specs define **WHAT** and **WHY**, not **HOW**. Code written in markdown has no type checking, no tests, no IDE support — it's the worst of both worlds.

### ✅ INCLUDE in Specs

| Content | Example |
|---------|---------|
| **Interfaces/Contracts** | `interface AuthAdapter { getSession(): Promise<Session \| null> }` |
| **API Signatures** | Function names, params, return types (no bodies) |
| **Architecture Diagrams** | Mermaid diagrams showing data flow |
| **Narrative Strategy** | "Use provider factory pattern to support multiple auth backends" |
| **Acceptance Criteria** | "User can sign in with Google in < 3 clicks" |
| **Error Codes/States** | `AUTH_EXPIRED`, `INVALID_TOKEN`, `NETWORK_ERROR` |
| **Configuration Schema** | What config options exist, not how they're parsed |

### ❌ EXCLUDE from Specs

| Content | Why |
|---------|-----|
| **Full Implementations** | No type checking, creates unbounded review loops |
| **Test Code** | Tests belong in test files with actual assertions |
| **Edge Case Handlers** | Let implementation discover these |
| **Internal Helper Functions** | Implementation detail |
| **Boilerplate** | Imports, React state, cleanup logic |
| **Copy-Paste Code Blocks** | If it looks ready to run, it shouldn't be in a spec |

### The 50-Line Rule

If any code block exceeds ~50 lines, it's probably implementation disguised as specification. Extract to interface + narrative.

**Anti-pattern:**
```markdown
## AuthProvider Implementation
\`\`\`typescript
// 200 lines of React component with hooks, effects, error boundaries...
\`\`\`
```

**Better:**
```markdown
## AuthProvider Contract
- MUST wrap app and provide `useSession()` hook
- MUST handle loading/error/authenticated states
- SHOULD memoize context value to prevent re-renders

\`\`\`typescript
interface AuthProviderProps { children: ReactNode; adapter: AuthAdapter; }
type AuthState = { status: 'loading' } | { status: 'error'; error: Error } | { status: 'authenticated'; session: Session };
\`\`\`
```

### Prefer Mermaid Diagrams

Mermaid diagrams pack high information density and are ideal for spec context-setting:

| Diagram Type | Best For |
|--------------|----------|
| `graph TD` | Data flow, component relationships |
| `sequenceDiagram` | API calls, auth flows, multi-step processes |
| `classDiagram` | Type hierarchies, interface relationships |
| `stateDiagram-v2` | State machines, status transitions |

**Example:**
```markdown
## Session State Flow

\`\`\`mermaid
stateDiagram-v2
    [*] --> Loading
    Loading --> Authenticated: token valid
    Loading --> Unauthenticated: no token
    Authenticated --> Refreshing: token expiring
    Refreshing --> Authenticated: refresh success
    Refreshing --> Unauthenticated: refresh failed
\`\`\`
```

A single diagram often replaces 50+ lines of prose.

## Agent-Efficient Formats

Specs are consumed by AI agents, not just humans. Optimize for low tokens + explicit relationships.

### ✅ High-Density Formats

| Format | Tokens | Why Agent-Friendly |
|--------|--------|-------------------|
| **Mermaid diagrams** | ~50 | Explicit relationships, parseable structure |
| **TypeScript interfaces** | ~30 | Literal contracts, no inference needed |
| **Tables** | ~40 | Explicit column → row mapping |
| **Checklists** | ~20 | Binary pass/fail, scannable |
| **ASCII trees** | ~30 | Parseable hierarchy |
| **Error code tables** | ~40 | Code → Message → Fix mapping |

### ❌ Anti-Patterns (Token-Heavy, Inference-Heavy)

| Pattern | Problem | Fix |
|---------|---------|-----|
| **Hedging prose** | "typically", "might", "could" require inference | Use MUST/SHOULD/MAY |
| **Narrative flow** | Buries relationships in sentences | Extract to table or diagram |
| **Implicit context** | "as mentioned above" — agent may lack "above" | Repeat or link explicitly |
| **Long paragraphs** | High tokens, low density | Break into bullets or table |
| **Examples without contracts** | Agent may over-fit to example | Lead with interface, example follows |

### Token Efficiency Comparison

```
Prose (200 tokens):
"The session sync component should typically use BroadcastChannel 
when it's available, which is the case in Chrome 54 and later, 
Firefox 38 and later, and Safari 15.4 and later. When BroadcastChannel
is not available, it should fall back to using localStorage events..."

Table (40 tokens):
| Browser | BroadcastChannel | Fallback |
|---------|------------------|----------|
| Chrome 54+ | ✅ | N/A |
| Firefox 38+ | ✅ | N/A |
| Safari 15.4+ | ✅ | N/A |
| Older | ❌ | localStorage events |
```

Same information, 5x fewer tokens, zero ambiguity.

## Spec Quality Checklist

- [ ] Every requirement uses MUST/SHOULD/MAY
- [ ] No code blocks exceed 50 lines
- [ ] Interfaces only — no implementation bodies
- [ ] Architecture shown via Mermaid diagram(s)
- [ ] Tables used for mappings (not prose paragraphs)
- [ ] No hedging words ("typically", "might", "could")
- [ ] All metrics are quantifiable
- [ ] Edge cases and error states documented
- [ ] Success criteria are testable
- [ ] Rollback plan exists

## When to Escalate

- **Conflicting requirements** — Stakeholders disagree
- **Missing domain knowledge** — Spec requires expertise not available
- **Scope creep** — Requirements expanding beyond original proposal
