---
name: scorpio-feature-plan
description: Investigate the codebase to design a feature implementation - find integration points, identify patterns to follow, and design the approach. Outputs a design document plus TASK-PLAN-HANDOFF.json for scorpio-task-plan. Use after scorpio-feature-intake (`scorpio-feature-intake`) or when you have clear feature requirements.
---

# Feature Plan Design (alias: Feature Architect)

A systematic methodology for designing feature implementations within an existing codebase. This skill bridges feature requirements to actionable development tasks by deeply understanding the existing system.

> **Model role — plan.** This skill runs the pipeline's **plan** phase, so it targets the configured `{models.plan}` (model + optional `effort`) when `scorpio.config.json` sets it — falling back to `{models.default}` → the harness's main-session model. Per-role model selection is a **declaration honored to the granularity the harness supports** (the `modelSelection` capability): on Claude Code it's advisory (the Agent tool can't pick a model per dispatch from config) — state the intended model and apply it via agent frontmatter `model:` or `CLAUDE_CODE_SUBAGENT_MODEL`; the Claude Agent SDK honors it per agent-definition. See [docs/CONFIG.md](../../docs/CONFIG.md#per-role-models).

## Prerequisites

Before designing, you need either:
- A feature brief from **scorpio-feature-intake** (`scorpio-feature-intake`), OR
- Clear requirements with: what it does, who uses it, where it lives, and constraints

If requirements are unclear, use **scorpio-feature-intake** first.

## Input

**Read the feature brief from `{docs.planning}/FEATURE-BRIEF.md`** (or `{docs.planning}/FEATURE-BRIEF-*.md` if multiple exist) — this file is produced by scorpio-feature-intake (`scorpio-feature-intake`) and contains the what, who, where, how, and constraints gathered from the user. This is your primary input. If this file doesn't exist, check the conversation context for a feature brief. If neither source has structured requirements, stop and report that the interview output is missing — do NOT infer or fabricate requirements.

## Architecture Phases

```
Phase 1: Explore      → Understand existing codebase patterns
Phase 2: Locate       → Find integration points
Phase 3: Design       → Plan the implementation approach
Phase 4: Validate     → Check for conflicts and edge cases
Phase 5: Generate     → Create implementation tasks
```

## Phase 1: Explore

Understand the existing codebase architecture and patterns before designing.

**If a Project Context document exists** (from **scorpio-project-map**), read `docs/PROJECT-CONTEXT.md` first — it provides structure, stack, architecture, and conventions. Then focus exploration on feature-specific questions (similar features, specific integration areas). This avoids redundant codebase mapping.

**If no Project Context document exists**, either run **scorpio-project-map** first, or perform manual exploration:

### Exploration Goals

| Goal | Questions to Answer |
|------|---------------------|
| **Architecture** | How is the codebase structured? What patterns are used? |
| **Similar features** | What existing features are most similar? How were they built? |
| **Conventions** | What naming, file organization, and code style conventions exist? |
| **Tech stack** | What frameworks, libraries, and tools are in use? |

### Exploration Strategy

Use Task agents with Explore subagent for broad understanding:
```
"How is the codebase organized? What are the main architectural patterns?"
"Find existing features similar to [feature description]"
"What conventions are used for [API routes / React components / etc.]?"
```

### Document Your Understanding

```markdown
## Codebase Analysis

### Architecture Overview
- **Pattern**: [MVC / Clean Architecture / Feature-based / etc.]
- **Frontend**: [React + Redux / Vue + Pinia / etc.]
- **Backend**: [Express routes → Services → Storage / FastAPI routers → services / Rails controllers → models / etc.]
- **Database**: [PostgreSQL + Drizzle ORM / Postgres + SQLAlchemy / MySQL + ActiveRecord / etc.]

### Relevant Existing Features
- `[feature]` in `path/to/code` - [why it's relevant]
- `[feature]` in `path/to/code` - [why it's relevant]

### Key Conventions
- Routes: [pattern, e.g., "kebab-case files in server/routes/"]
- Components: [pattern, e.g., "PascalCase in client/src/components/"]
- Services: [pattern, e.g., "one service per domain in server/services/"]
- Tests: [pattern, e.g., "co-located .test.ts files"]
```

## Phase 2: Locate

Find specific integration points for the new feature.

### Integration Point Types

| Type | What to Find | Example |
|------|--------------|---------|
| **Entry point** | Where the feature is triggered | Button click, route hit, scheduled job |
| **Data access** | How data is read/written | Existing queries, storage methods |
| **UI placement** | Where UI components go | Existing page, new route, modal |
| **Shared code** | Utilities, types, services to reuse | Auth middleware, validation helpers |

### Locate Commands

Search for specific patterns:
```
Grep: "export function" in server/services/ - find service methods
Grep: "router.post" - find API route patterns
Glob: "**/components/**/*.tsx" - find component structure
```

Read similar implementations:
```
Read the episode download feature implementation
Read how the existing export functionality works
```

### Document Integration Points

```markdown
## Integration Points

### UI Entry Point
- **Location**: `client/src/pages/EpisodePage.tsx:145`
- **Pattern**: Add button next to existing `<DownloadButton />`
- **Component to create**: `<ShareButton />`

### API Endpoint
- **Location**: New route in `server/routes/episodes.ts`
- **Pattern**: Follow existing `GET /episodes/:id` structure
- **Endpoint**: `GET /episodes/:id/share-link`

### Data Access
- **Existing**: `storage.getEpisode(id)` returns episode data
- **New needed**: None - can use existing query

### Shared Code to Reuse
- `client/src/components/Button.tsx` - base button component
- `server/middleware/validate.ts` - request validation
- `shared/types.ts` - Episode type definition
```

## Phase 3: Design

Design the implementation approach based on exploration and integration points.

### Design Document Format

```markdown
## Implementation Design: [Feature Name]

### Overview
[2-3 sentences describing the technical approach]

### Architecture Diagram
```
[User Action] → [UI Component] → [API Call] → [Service] → [Response]
     │              │                │            │
     └──────────────┴────────────────┴────────────┴── [Existing code to use]
```

### Component Design

#### [Component/Layer 1]
- **File**: `path/to/new/file.ts`
- **Responsibility**: [What it does]
- **Interfaces with**: [What it calls/uses]
- **Pattern**: [Following pattern from X]

#### [Component/Layer 2]
...

### Data Flow
1. User clicks share button on episode page
2. ShareButton component calls `api.getShareLink(episodeId)`
3. API route `/episodes/:id/share-link` validates request
4. Route calls `episodeService.generateShareLink(id)`
5. Service returns shareable URL
6. UI displays share modal with link and Twitter button

### API Contract
```typescript
// GET /api/episodes/:id/share-link
// Response:
{
  url: string;           // Shareable URL
  title: string;         // Episode title for social sharing
  description: string;   // Episode description snippet
}
```

### State Management
- **Local state**: Modal open/closed, copy success feedback
- **No global state needed**: Feature is self-contained

### Error Handling
- Invalid episode ID → 404 response → "Episode not found" message
- Network error → Retry option in UI

### Edge Cases
- Episode is private → Return 403, show "Cannot share private episodes"
- Very long title → Truncate for Twitter (280 char limit)
```

## Phase 4: Validate

Check the design for potential issues before generating tasks.

### Validation Checklist

| Check | Question |
|-------|----------|
| **Conflicts** | Does this conflict with existing features or planned work? |
| **Performance** | Will this impact performance? Need caching, pagination, async? |
| **Security** | Any auth, authorization, or data exposure concerns? |
| **Testing** | Is this design testable? What's the test strategy? |
| **Migration** | Any data migration or backwards compatibility needs? |
| **Dependencies** | New dependencies required? Team approval needed? |

### Document Concerns

```markdown
## Design Validation

### Potential Issues
- [ ] **None identified** OR
- [ ] **[Issue]**: [Description and mitigation]

### Performance Considerations
- [Any performance notes]

### Security Review
- [Any security considerations]

### Test Strategy
- **Unit tests**: Service methods, utility functions
- **Integration tests**: API endpoint with test database
- **Component tests**: ShareButton renders, handles states
- **E2E tests**: Full share flow (optional - depends on criticality)
```

## Phase 5: Generate Handoff

Produce a structured handoff for **scorpio-task-plan** — do NOT write task files directly.

### Handoff Output

Write `{docs.planning}/TASK-PLAN-HANDOFF.json` with this schema:

```json
{
  "source_skill": "scorpio-feature-plan",
  "source_artifact": "{docs.planning}/IMPLEMENTATION-DESIGN-<feature>.md",
  "feature_name": "<Feature Name>",
  "scope_summary": "<2-3 sentence overview>",
  "slices": [
    {
      "title": "<slice title>",
      "type": "Feature|Chore|Test",
      "estimate": "XS|S|M",
      "description": "<what this slice does>",
      "files_to_modify": ["path/to/file.ts"],
      "integration_points": ["path/to/existing.ts"],
      "acceptance_criteria": ["criterion 1", "criterion 2"],
      "depends_on": []
    }
  ],
  "constraints": ["max 5 files per task", "L/XL slices must be split"],
  "test_strategy": {
    "unit": "<what to unit test>",
    "integration": "<what to integration test>",
    "manual": "<manual verification steps>"
  }
}
```

### Slice Sizing Guidance

Each slice becomes one task. To ensure reliable subagent execution:
- **Max 5 files to modify per slice.** If more are needed, split the slice.
- **List specific files** — this helps the downstream scorpio-task-plan produce focused tasks.
- L/XL slices **must** be split. No exceptions.

### Also Write Design Artifact

Write `{docs.planning}/IMPLEMENTATION-DESIGN-<feature>.md` with architecture summary, component design, data flow, API contracts, and validation results from Phases 1-4.

## Output Artifacts

Feature Architect produces these artifacts:

### 1. Implementation Design Document
`{docs.planning}/IMPLEMENTATION-DESIGN-<feature>.md` — architecture, component design, data flow, API contracts.

### 2. Task Plan Handoff
`{docs.planning}/TASK-PLAN-HANDOFF.json` — structured handoff consumed by **scorpio-task-plan** to generate task files.

**Important**: This skill does NOT write task files or task index files. Task file creation is exclusively owned by **scorpio-task-plan**.

## Quick Design Mode

For small, straightforward features, compress Phases 1-4 and still produce the handoff JSON:

```markdown
## Quick Design: [Feature Name]

### Integration Point
- Add to: `path/to/file.ts:line`
- Pattern: Follow `similar/feature.ts`

### Changes Needed
1. [File]: [Change]
2. [File]: [Change]
3. [File]: [Change]
```

Then write `TASK-PLAN-HANDOFF.json` with a single slice.

## What NOT To Do

- ❌ Design without exploring the codebase first
- ❌ Ignore existing patterns and conventions
- ❌ Write task files directly (use handoff JSON instead)
- ❌ Over-engineer simple features
- ❌ Under-specify integration points
- ❌ Skip the test strategy
- ❌ Omit the handoff JSON output

## Handling Complexity

If the feature is too complex for a single design:

1. **Split into sub-features**: Create separate feature briefs
2. **Spike first**: Create a spike task to research unknowns
3. **Incremental delivery**: Design MVP version, plan enhancements

```markdown
## Complexity Assessment

**Feature complexity**: High
**Recommendation**: Split into phases

### Phase 1 (MVP)
- Basic share link (copy only)
- Tasks: FEAT-001, FEAT-002

### Phase 2 (Enhancement)
- Social media integration
- Tasks: FEAT-003, FEAT-004

### Phase 3 (Polish)
- Analytics, URL shortening
- Tasks: FEAT-005, FEAT-006
```

## Skill Chain

This skill is part of the feature development workflow:

1. **scorpio-feature-intake** (`scorpio-feature-intake`) → Gather feature requirements
2. **scorpio-feature-plan** (`scorpio-feature-plan`) → Design implementation + handoff JSON (you are here)
3. **scorpio-task-plan** (`scorpio-task-plan`) → Generate task files from handoff
4. **scorpio-execute** (`scorpio-execute`) → Execute tasks in focused subagent sessions (max 3 per session)
5. **scorpio-qa** (`scorpio-qa`) → Per-task code review and acceptance criteria validation
6. **task-review-final** (`scorpio-qa-final`) → Final-pass review: integration, UI, cross-task concerns
7. **task-triage-findings** (`scorpio-qa-rework`) → Triage findings, generate rework tasks, approve or loop back to step 4

## Next Steps

After producing design + handoff JSON:

1. Run **scorpio-task-plan** to generate task files from `TASK-PLAN-HANDOFF.json`
2. Review task files with the user if needed
3. Use **scorpio-execute** to execute each task in dependency order
4. Use **task-review-final** to validate code changes and UI behavior
5. Use **task-triage-findings** to triage findings and generate rework tasks if needed
6. Repeat steps 3-5 for rework until all tasks pass
7. Demo to stakeholders if applicable
