---
name: add-feature-discovery
description: Use when analyzing codebase for a specific feature - creates/updates discovery.md with technical analysis, patterns, files mapping and caches for future sessions
---

# Feature Discovery

Skill for technical codebase analysis focused on a specific feature. Persists analysis in `discovery.md` for reuse across sessions.

**Principle:** Analyze once, use always. Cache per feature.

---

## When to Use

- New feature without `discovery.md` → full analysis
- `discovery.md` exists but empty → full analysis
- `discovery.md` exists and filled → read cache, complement if needed
- Significant codebase changes → update affected sections

### When NOT to Use

- Global project analysis (use `add-architecture-discovery` instead)
- Post-implementation review of finished work (use `add-code-review`)
- Hotfix triage where root-cause investigation is needed (use `add-investigation`)

---

## Workflow

**REQUIRED:** Apply before writing:
- `token-efficiency` — minified JSON, tables, no decoration
- `documentation-style/cache` — Read → Preserve → Complement → Metadata

### Phase 1: Check Cache

```bash
cat docs/features/[FEATURE_ID]/discovery.md
```

|State|Action|
|---|---|
|Filled and recent|Use as context, skip to Phase 4|
|Empty/template|Phase 2 (full analysis)|
|Outdated|Phase 2 focused on changes|

### Phase 1.5: Past Features Discovery

**Goal:** Identify features with direct or indirect relation to the current feature.

**EXECUTE as a separate subagent [read-only, light] BEFORE Phase 2.**

**Cache:** IF `past-features.md` exists AND `metadata.updated` = today → reuse, skip Phase 1.5.

**Required input:**
- `RECENT_CHANGELOGS` (output of `init.sh` or `status.sh`)
- `about.md` of the current feature

**Process:**
```
1. Extract keywords from about.md (domain, entities, actions)
2. For each feature in RECENT_CHANGELOGS:
   a. Read the "## Quick Ref" section of changelog.md (if it exists) → match by domain, keywords, touched
   b. IF Quick Ref does not exist: read first 30 lines of changelog.md as fallback
3. For each match found:
   a. Read the full iterations.jsonl of the feature
   b. Read the about.md of the feature (scope, requirements)
   c. Classify the relation: extends | depends | conflicts | shares-pattern | shares-domain
4. Generate past-features.md
```

**Match criteria (in order of relevance):**
| Criterion | Weight |
|-----------|--------|
| Same domain (Quick Ref `domain`) | High |
| Files in common (Quick Ref `touched`) | High |
| Keywords in common (Quick Ref `keywords`) | Medium |
| Patterns in common (Quick Ref `patterns`) | Medium |
| Same module/package | Low |

**Output:** `docs/features/${FEATURE_ID}/past-features.md`

**past-features.md format:**
```markdown
# Past Features Analysis: [Feature Name]

## Matches

### F[XXXX]-[name] ([relation-type])
- **Domain:** [domain1, domain2]
- **Shared files:** `src/path/file.ts`
- **Patterns used:** [pattern1, pattern2]
- **Key decisions:** [most relevant decision]
- **Iterations summary:** N iterations, N pivots
- **Relevance:** [why it matters for the current feature]

## No Match
- F[XXXX]-[name] — [reason in 1 line]

## Metadata
{"updated":"YYYY-MM-DD","feature":"F[XXXX]-[name]","matches":N,"total_analyzed":N,"by":"past-features-agent"}
```

---

### Phase 2: Focused Analysis

**Goal:** Analyze ONLY what is relevant to the feature.

**EXECUTE as a separate subagent [read-write, standard] AFTER Phase 1.5.**

**BEFORE analyzing the codebase:**
```
1. Read docs/features/${FEATURE_ID}/past-features.md (generated by Phase 1.5)
2. Use as context:
   - Files already touched by related features → prioritize in search
   - Patterns used → follow the same ones
   - Past decisions → do not contradict
   - Potential conflicts → map them
3. Include "Related Features" section in discovery.md
```

```
1. Read about.md → understand requirements
2. Identify domain/area affected
3. Search related files (Glob/Grep)
4. Identify existing similar patterns
5. Map dependencies
```

**What to analyze:**

{"analysisAreas":{"Entities":"Models/entities related to the domain","Patterns":"Similar features as reference","Infrastructure":"Existing services, repositories, controllers","Frontend":"Related components, hooks, stores","Integrations":"External APIs, webhooks, events"}}

### Phase 3: Structure Findings

**Template discovery.md (Business Style):**

```markdown
# Discovery: [Feature]

## Summary
{"patterns":["main pattern"],"files_create":N,"files_modify":N,"deps":["critical dep"],"complexity":"low|medium|high","risks":["main risk"]}

---

## Technical Context

### Relevant Stack
- **Backend:** [specific technologies]
- **Frontend:** [specific technologies]
- **Infra:** [if applicable]

### Identified Patterns
- **[Pattern]:** used in [location] — [how to apply here]

---

## Codebase Analysis

### Related Files
- `path/file.ts` — [purpose, ~10 words]

### Similar Features
- **[Feature X]:** [what to reuse] — `path/`

---

## File Mapping

### Create
- `path/new-file.ts` — [purpose]

### Modify
- `path/existing.ts` — [what changes]

---

## Prerequisites Analysis (CRITICAL)

**Goal:** Identify WHAT MUST EXIST for the feature to work.

**For EACH requirement in about.md, analyze across all prerequisite types:**

| Type | Requirement | Prerequisite | Exists? | Action |
|------|-------------|--------------|---------|--------|
| Data/Model | RF01 | Field X on entity Y | ✅/❌ | Create if ❌ |
| Flow | RF01 | Endpoint to assign X | ✅/❌ | Create if ❌ |
| Integration | RF01 | External API Y | ✅/❌ | Configure if ❌ |
| Existing Data | RF01 | Records with field X | ✅/❌ | Migrate if ❌ |

**Rule:** If any prerequisite is ❌, the feature CANNOT be considered complete without implementing it first.

---

## Delivery Completeness

**Central question:** With this scope, can the end user USE the functionality?

### Functional Delivery Validation

| Validated in Questionnaire | Required Layer | In Scope? | User can use? |
|----------------------------|----------------|-----------|---------------|
| [validated item] | Frontend/Backend/DB | ✅/❌ | ✅/❌ |

**Failure examples:**
- Validated "checkbox" but excluded frontend → ❌ User can't use
- Validated "type choice" but excluded frontend → ❌ User can't use
- Backend only without UI → ❌ Feature unusable (except for pure APIs)

**If "User can use?" = ❌ → Scope INCOMPLETE. Add the missing layer.**

---

## Dependencies

### Internal
- `@package/module` — [what to use]

### External
- `package@version` — [purpose]

---

## Technical Assumptions

- **[Assumption]:** [impact if incorrect]

---

## Identified Risks

- **[Risk]:** [mitigation]

---

## Planning Summary

[3-5 lines: complexity, attention points, critical dependencies]

---

## Updates
[{"date":"YYYY-MM-DD","change":"short description"}]

---

## Metadata
{"updated":"YYYY-MM-DD","sessions":N,"by":"[subagent]"}
```

**Always update `## Summary` and `## Updates` when there are changes.**

### Phase 4: Persist/Update

**If creating:** Write full discovery.md with metadata

**If updating:**
1. Preserve valid existing information
2. Complement with new findings
3. Increment `sessions` in metadata
4. Update `updated` date

---

## Checklist

- [ ] Read about.md to understand requirements?
- [ ] Checked existing discovery.md?
- [ ] Checked existing past-features.md (cache check)?
- [ ] Phase 1.5 executed with RECENT_CHANGELOGS?
- [ ] past-features.md generated with matches + no-matches + metadata?
- [ ] Read past-features.md BEFORE analyzing codebase?
- [ ] Identified similar features and reused patterns?
- [ ] "Related Features" section included in discovery.md (with table + `<!-- refs: ... -->`)?
- [ ] Mapped files to create/modify with concrete, verifiable paths?
- [ ] Analyzed prerequisites for EACH requirement (no assumptions, verified)?
- [ ] Missing prerequisites are in scope of the feature?
- [ ] Validated Delivery Completeness — can the user USE the feature with this scope? (CRITICAL)
- [ ] Focused only on the relevant domain (not entire codebase)?
- [ ] Preserved valid existing info (no overwrite, no redundant files)?
- [ ] Listed dependencies, documented assumptions and risks?
- [ ] Updated metadata at the end?
