Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:37:27 +08:00
commit 37774aa937
131 changed files with 31137 additions and 0 deletions

View File

@@ -0,0 +1,456 @@
---
name: ln-220-story-coordinator
description: CREATE/REPLAN Stories for Epic (5-10 Stories). Delegates ln-221-standards-researcher for standards research. Decompose-First Pattern. Auto-discovers team/Epic.
---
# Story Coordinator
Universal Story management coordinator that delegates CREATE/REPLAN operations to specialized workers after building IDEAL Story plan.
## When to Use This Skill
Use when:
- Decompose Epic to User Stories (5-10 Stories covering Epic scope)
- Update existing Stories when Epic requirements change
- Rebalance Story scopes within Epic
- Add new Stories to existing Epic structure
## Core Pattern: Decompose-First
**Key principle:** Build IDEAL Story plan FIRST, THEN check existing Stories to determine mode:
- **No existing Stories** → CREATE MODE (delegate to ln-222-story-creator)
- **Has existing Stories** → REPLAN MODE (delegate to ln-223-story-replanner)
**Rationale:** Ensures consistent Story decomposition based on current Epic requirements, independent of existing Story structure (may be outdated).
## Story Numbering Convention
**Rule:** Stories start from Story 1 (US001), NO Story 0 reserved.
**Rationale:**
- Epic 0 = Infrastructure **Epic** (group of 5-10 Stories like any other Epic)
- Stories within Epic 0 numbered normally: US001, US002, ... US010
- No reserved Story 0 (unlike Epics, Stories don't need infrastructure placeholder)
**Numbering within Epic:**
- Epic 0: Infrastructure → US001-US010 (logging, monitoring, CI/CD Stories)
- Epic 1: User Management → US011-US020 (registration, login, profile Stories)
- Epic 2: Product Catalog → US021-US030 (product list, search, details Stories)
**Next Story Number:** Incremented sequentially across ALL Epics (read from kanban_board.md Epic Story Counters table)
## How It Works
### Phase 1: Context Assembly
**Objective:** Gather context for Story planning (Epic details, planning questions, frontend context, fallback docs, user input)
**Step 1: Discovery (Automated)**
Auto-discovers from `docs/tasks/kanban_board.md`:
1. **Team ID:** Reads Linear Configuration table
2. **Epic:** Parses Epic number from request → Validates in Linear → Loads Epic description
- **User format:** "Epic N" (Linear Project number, e.g., "Epic 7: OAuth Authentication")
- **Query:** `get_project(query="Epic N")` → Fetch full Epic document
- **Extract:** Goal, Scope In/Out, Success Criteria, Technical Notes (Standards Research if Epic created by ln-210 v7.0.0+)
- **Note:** Epic N = Linear Project number (global), NOT initiative-internal index (Epic 0-N)
3. **Next Story Number:** Reads Epic Story Counters table → Gets next sequential number
**Step 2: Extract Planning Information (Automated)**
Parses Epic structure for Story planning questions:
| Question | Extraction Source |
|----------|-------------------|
| **Q1 - User/Persona** | Epic Goal ("Enable [persona]...") + Scope In (user roles) |
| **Q2 - What they want** | Epic Scope In (capabilities) + functional requirements |
| **Q3 - Why it matters** | Epic Success Criteria (metrics) + Goal (business value) |
| **Q4 - Which Epic** | Already from Step 1 |
| **Q5 - Main AC** | Derive from Epic Scope In features → testable scenarios |
| **Q6 - Application type** | Epic Technical Notes (UI/API mentioned) → Default: API |
**Step 3: Frontend Research (Optional)**
**Trigger:** If Q2 (capabilities) OR Q5 (AC) missing after Step 2
**Process:**
1. Scan HTML files: `Glob` `**/*.html`, `src/**/*.html`
2. Extract:
- Forms → AC scenarios (e.g., `<form id="login">` → "Given valid credentials, When submit, Then login success")
- Buttons/Actions → capabilities (e.g., `<button id="register">` → "User registration")
- Validation rules → edge case AC (e.g., `minlength="8"` → "Given password <8 chars, Then error")
3. Combine with Epic context, deduplicate, prioritize Epic AC if conflict
**Fallback:** If no HTML → Skip to Step 4
**Step 4: Fallback Search Chain**
**Objective:** Fill missing Q1-Q6 BEFORE asking user.
For each question with no answer from Step 2-3:
| Question | Fallback Search |
|----------|-----------------|
| **Q1 (User/Persona)** | Search `requirements.md` for "User personas", "Actors" → Default "User" if not found |
| **Q3 (Why it matters)** | Search `requirements.md` for "Business objectives", "Goals" → Infer from Epic Success Criteria |
| **Q6 (Application type)** | Search `tech_stack.md` for "Frontend", "Backend", "API" → Default "API" |
**Skip:** Q2, Q5 (Epic + HTML are sources of truth), Q4 (already known)
**Step 5: User Input (Only if Missing)**
**If still missing after Step 2 + 3 + 4:**
- Show extracted: "From Epic: [Epic info]. From HTML: [HTML info]. From fallback: [fallback info]"
- Ask user to confirm or provide remaining missing details
**If all questions answered from Epic OR HTML OR fallback:** Skip user prompts, proceed to Phase 2
**Output:** Complete context (Epic details, next Story number, Q1-Q6 answers)
---
### Phase 2: Standards Research (Delegated)
**Objective:** Research industry standards/patterns BEFORE Story generation to ensure implementation follows best practices.
**Why:** Prevents outdated patterns or RFC violations (e.g., OAuth without PKCE).
**Process:**
1. **Parse Epic for domain keywords:** Extract domain from Epic goal/Scope In (authentication, rate limiting, payments)
2. **Delegate to ln-221-standards-researcher:**
- Call `Skill(skill: "ln-221-standards-researcher", epic_description="[Epic full description]", story_domain="[domain]")`
- Wait for Standards Research (Markdown string)
3. **Store:** Cache for Phase 5a/5b (workers insert in Story Technical Notes)
**Output:** Standards Research stored for ALL Stories in Epic
**Skip conditions:**
- Epic has NO standards in Technical Notes
- Story domain is trivial CRUD
- Epic says "research not needed"
**Time-box:** 15-20 minutes (handled by ln-221)
**Note:** Research done ONCE per Epic, results reused for all Stories (5-10 Stories benefit from single research)
---
### Phase 3: Planning
**Objective:** Build IDEAL Story plan, determine execution mode
**Story Grouping Guidelines:**
Each Story = ONE vertical slice of user capability (end-to-end: UI → API → Service → DB).
**✅ GOOD Story Grouping (1 Story = 1 user journey):**
- ✅ "User registration" (form → validation → API → database → email)
- ✅ "Password reset" (request link → verify token → set password → update DB)
- ✅ "Product search" (input → filter/sort → API → DB query → display)
**❌ BAD Story Grouping (horizontal slices):**
- ❌ "Create user table" (database only, no user value → Task, not Story)
- ❌ "User registration API endpoint" (API layer only, not vertical)
- ❌ "Registration UI form" (frontend only, not vertical)
**Rule:** 1 Story = 1 user capability = 3-5 AC = 6-20 hours = 10-28 tests
**Build IDEAL Plan (Automated):**
1. **Analyze Epic Scope:** Review features in Epic Scope In, identify user capabilities
2. **Determine Story Count:**
- Simple Epic (1-3 features): 3-5 Stories
- Medium Epic (4-7 features): 6-8 Stories
- Complex Epic (8+ features): 8-10 Stories
- **Max 10 Stories per Epic**
3. **Story Size Guidelines:**
| Criterion | Min | Max | Under-decomposed | Over-decomposed |
|-----------|-----|-----|------------------|-----------------|
| **AC** | 3 | 5 | >5 AC (split) | <3 AC (merge) |
| **Duration** | 6h | 20h | >20h (split) | <6h (merge) |
| **Tests** | 10 | 28 | >28 tests (split) | <10 tests (merge) |
**Over-decomposition indicators:**
- ❌ <3 AC, <6 hours, <10 tests
- ❌ Purely technical (no user value)
- ❌ Title starts with "Add", "Create", "Update" (likely Task)
- ❌ Crosses only 1-2 layers (not vertical)
4. **Build IDEAL Plan "in mind":**
- Each Story: persona + capability + business value
- Each Story: 3-5 testable AC (Given-When-Then)
- Stories ordered by dependency
- Each Story: Test Strategy (Risk-Based: 2-5 E2E, 3-8 Integration, 5-15 Unit, 10-28 total)
- Each Story: Technical Notes (architecture, integrations, **Standards Research from Phase 2**, guide links)
**INVEST Checklist:**
| Criterion | Check | ✅ GOOD | ❌ BAD |
|-----------|-------|---------|--------|
| **Independent** | Can develop/deploy without blocking others | "Request OAuth token" (independent) | "Validate token" depends on "Request token" (merge or ensure API contract) |
| **Negotiable** | AC focus on WHAT, not HOW | "User gets valid token" (what) | "Use authlib 1.3.0, store in Redis" (how) |
| **Valuable** | Clear business value | "User refreshes expired token to maintain session" | "Add token_refresh table" (no user value) |
| **Estimable** | Can estimate 6-20h | Clear scope, known patterns, researched standards | "Implement authentication" (too vague) |
| **Small** | Fits 1-2 sprints | 3-5 AC, 6-20h, 10-28 tests | "Full OAuth flow" (>5 AC, >20h) |
| **Testable** | AC measurable | "Given valid refresh token, Then receive token <200ms" | "Token refresh should be fast" (not measurable) |
**Output:** IDEAL Story plan (5-10 Stories) with titles, statements, core AC, ordering
---
### Phase 4: Check Existing & Detect Mode
**Objective:** Determine execution mode based on existing Stories AND user intent
**Process:**
Query Linear for existing Stories in Epic:
```
list_issues(project=Epic.id, label="user-story")
```
**Mode Detection:**
1. **Analyze user request** for keywords:
- ADD keywords: "add story", "one more story", "additional story", "append"
- REPLAN keywords: "update plan", "revise", "requirements changed", "replan stories"
2. **Decision matrix:**
| Condition | Mode | Delegate To |
|-----------|------|-------------|
| Count = 0 | **CREATE** | Phase 5a: ln-222-story-creator |
| Count ≥ 1 AND ADD keywords | **ADD** | Phase 5c: ln-222-story-creator (appendMode) |
| Count ≥ 1 AND REPLAN keywords | **REPLAN** | Phase 5b: ln-223-story-replanner |
| Count ≥ 1 AND ambiguous | **ASK USER** | "Add new Story or revise the plan?" |
**Important:** Orchestrator loads metadata ONLY (ID, title, status). Workers load FULL descriptions (token efficiency).
**Output:** Execution mode determined + existingCount for workers
---
### Phase 5a: Delegate CREATE (No Existing Stories)
**Trigger:** Epic has no Stories yet (first decomposition)
**Delegation:**
Call ln-222-story-creator via Skill tool:
```javascript
Skill(
skill: "ln-222-story-creator",
epicData: {id, title, description},
idealPlan: [ /* 5-10 Stories from Phase 3 */ ],
standardsResearch: "Standards Research from Phase 2",
teamId: "team-id",
autoApprove: false // or true for automation
)
```
**Worker handles:**
- Generate Story documents (8 sections, insert Standards Research)
- Validate INVEST criteria
- Show preview
- User confirmation (if autoApprove=false)
- Create in Linear (project=Epic, labels=user-story, state=Backlog)
- Update kanban_board.md (Epic Grouping Algorithm)
**Output:** Created Story URLs + summary from worker
---
### Phase 5b: Delegate REPLAN (Existing Stories Found)
**Trigger:** Epic already has Stories (requirements changed)
**Delegation:**
Call ln-223-story-replanner via Skill tool:
```javascript
Skill(
skill: "ln-223-story-replanner",
epicData: {id, title, description},
idealPlan: [ /* 5-10 Stories from Phase 3 */ ],
standardsResearch: "Standards Research from Phase 2",
existingCount: N,
teamId: "team-id",
autoApprove: false // or true for automation
)
```
**Worker handles:**
- Load existing Stories (Progressive Loading: ONE BY ONE for token efficiency)
- Compare IDEAL vs existing (KEEP/UPDATE/OBSOLETE/CREATE operations)
- Show replan summary with diffs (AC, Standards Research, Technical Notes)
- User confirmation (if autoApprove=false)
- Execute operations (respecting status constraints: Backlog/Todo only, warnings for In Progress/Review/Done)
- Update kanban_board.md (add NEW Stories only via Epic Grouping Algorithm)
**Output:** Operation results + warnings + affected Story URLs from worker
---
### Phase 5c: Delegate ADD (Append to Existing Stories)
**Trigger:** Epic has Stories, user wants to ADD more (not replan existing)
**Delegation:**
Call ln-222-story-creator via Skill tool with appendMode:
```javascript
Skill(
skill: "ln-222-story-creator",
appendMode: true, // ADD to existing, don't replace
epicData: {id, title, description},
newStoryDescription: userRequestedStory, // Single Story from user request
standardsResearch: "Standards Research from Phase 2",
teamId: "team-id",
autoApprove: false
)
```
**Key differences from CREATE MODE:**
- `appendMode: true` → Skip full IDEAL plan, create only requested Story
- `newStoryDescription` → User's specific request (e.g., "add authorization Story")
- Does NOT require Phase 3 IDEAL plan for all Stories
- Preserves existing Stories without comparison
**Worker handles:**
- Research standards for NEW Story only
- Generate Story document (8 sections)
- Validate INVEST criteria
- Create in Linear (append to existing)
- Update kanban_board.md
**Output:** Created Story URL + summary from worker
---
## Integration with Ecosystem
**Calls:**
- **ln-221-standards-researcher** (Phase 2) - research standards/patterns for Epic
- **ln-222-story-creator** (Phase 5a, 5c) - CREATE and ADD worker
- **ln-223-story-replanner** (Phase 5b) - REPLAN worker
**Called by:**
- **ln-200-scope-decomposer** (Phase 3) - automated full decomposition (scope → Epics → Stories)
- **Manual** - user invokes for Epic Story creation/replanning
**Upstream:**
- **ln-210-epic-coordinator** - creates Epics (prerequisite for Story creation)
**Downstream:**
- **ln-310-story-decomposer** - creates implementation tasks for each Story
- **ln-320-story-validator** - validates Story structure/content
- **ln-330-story-executor** - orchestrates task execution for Story
---
## Definition of Done
**✅ Phase 1: Context Assembly Complete:**
- [ ] Team ID, Epic number, Next Story Number loaded from kanban_board.md
- [ ] Q1-Q6 extracted from Epic (Step 2)
- [ ] Frontend Research attempted if Q2/Q5 missing (Step 3)
- [ ] Fallback Search attempted for missing info (Step 4)
- [ ] User input requested if still missing (Step 5)
- [ ] Complete Story planning context assembled
**✅ Phase 2: Standards Research Complete:**
- [ ] Epic parsed for domain keywords
- [ ] ln-221-standards-researcher invoked with Epic description + Story domain
- [ ] Standards Research cached for workers
- [ ] OR Phase 2 skipped (trivial CRUD, no standards, explicit skip)
**✅ Phase 3: Planning Complete:**
- [ ] Epic Scope analyzed
- [ ] Optimal Story count determined (5-10 Stories)
- [ ] IDEAL Story plan created (titles, statements, core AC, ordering)
- [ ] Story Grouping Guidelines validated (vertical slicing)
- [ ] INVEST checklist validated for all Stories
**✅ Phase 4: Check Existing Complete:**
- [ ] Queried Linear for existing Stories (count only)
- [ ] Execution mode determined (CREATE or REPLAN)
**✅ Phase 5: Delegation Complete:**
- [ ] Called ln-222-story-creator (Phase 5a) OR ln-223-story-replanner (Phase 5b) via Skill tool
- [ ] Passed epicData, idealPlan, standardsResearch, teamId, autoApprove
- [ ] Received output from worker (Story URLs + summary + next steps)
---
## Example Usage
**CREATE MODE (First Time):**
```
"Create stories for Epic 7: OAuth Authentication"
```
**Process:**
1. Phase 1: Context Assembly → Discovery (Team "API", Epic 7, US004), Extract (Persona: API client, Value: secure API access), Frontend Research (HTML login/register forms → AC), Fallback Search (requirements.md for personas)
2. Phase 2: Standards Research → Epic mentions "OAuth 2.0", delegate ln-221 → Standards Research with RFC 6749, patterns
3. Phase 3: Planning → Build IDEAL (5 Stories: "Register client", "Request token", "Validate token", "Refresh token", "Revoke token")
4. Phase 4: Check Existing → Count = 0 → CREATE MODE
5. Phase 5a: Delegate CREATE → Call ln-222-story-creator → US004-US008 created with Standards Research
**REPLAN MODE (Requirements Changed):**
```
"Replan stories for Epic 7 - removed custom token formats, added scope management"
```
**Process:**
1. Phase 1: Context Assembly → Discovery (Team "API", Epic 7, has US004-US008), Extract (Removed custom formats, added scopes)
2. Phase 2: Standards Research → Epic mentions "OAuth 2.0 scopes", delegate ln-221 → Updated Standards Research with RFC 6749 Section 3.3
3. Phase 3: Planning → Build IDEAL (5 Stories: "Register client", "Request token", "Validate token", "Refresh token", "Manage scopes")
4. Phase 4: Check Existing → Count = 5 → REPLAN MODE
5. Phase 5b: Delegate REPLAN → Call ln-223-story-replanner → KEEP 4, UPDATE Technical Notes (scope research), OBSOLETE US008, CREATE US009
---
## Best Practices
**Story Content:**
- **Research-First:** Always perform Phase 2 research (standards/patterns) before Story generation
- **Story level:** STANDARDS/PATTERNS (OAuth RFC 6749, middleware pattern)
- **Task level:** LIBRARIES (authlib vs oauthlib) - delegated by ln-310
- **Business-oriented Stories:** Each Story = USER JOURNEY (what user does, what they get), NOT technical tasks
- ✅ GOOD: "As API client, I want to refresh expired token, so that I maintain session without re-authentication"
- ❌ BAD: "Create token refresh endpoint in API" (Task, not Story)
- **Vertical Slicing:** Each Story delivers end-to-end functionality (UI → API → Service → DB)
- **One capability per Story:** Clear, focused persona + capability + value
- **Testable AC:** Given-When-Then, 3-5 AC, specific criteria ("<200ms" not "fast")
- **Test Strategy:** Risk-Based Testing (2-5 E2E, 3-8 Integration, 5-15 Unit, 10-28 total)
- **Standards Research:** Include Phase 2 research in ALL Story Technical Notes
**Story Decomposition:**
- **Decompose-First:** Build IDEAL plan before checking existing - prevents anchoring to suboptimal structure
- **INVEST validation:** Validate every Story against INVEST criteria
- **Size enforcement:** 3-5 AC, 6-20 hours, 10-28 tests
- **Avoid over-decomposition:** <3 AC, <6 hours, <10 tests → Merge Stories
**User Interaction:**
- **Epic extraction:** Try to extract all planning info from Epic in Phase 1 Step 2 before asking user
- **Frontend Research:** HTML forms/validation → AC scenarios (Phase 1 Step 3)
- **Fallback search:** requirements.md, tech_stack.md if Epic incomplete (Phase 1 Step 4)
- **Only ask user for missing info** after Epic extraction AND frontend AND fallback search fail
**Delegation:**
- **Orchestrator loads metadata only:** ID, title, status (~50 tokens per Story)
- **Workers load full descriptions:** 8 sections (~5,000 tokens per Story)
- **Token efficiency:** 10 Stories × 50 tokens = 500 tokens (orchestrator) vs 10 Stories × 5,000 tokens = 50,000 tokens (workers load when needed)
---
**Version:** 4.0.0 (BREAKING: Decomposed to Orchestrator-Worker pattern. Phase 4a/4b removed, replaced with Phase 5a/5b delegation to ln-222-story-creator/ln-223-story-replanner. Orchestrator loads metadata only, workers load full descriptions for token efficiency. Progressive Loading now handled by ln-223-story-replanner, not orchestrator. Story execution logic moved to workers, orchestrator focuses on context assembly, standards research, planning, mode determination, delegation.)
**Last Updated:** 2025-11-20

View File

@@ -0,0 +1,170 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ln-220-story-coordinator Workflow</title>
<link rel="stylesheet" href="../shared/css/diagram.css">
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<script>
mermaid.initialize({
startOnLoad: true,
theme: 'base',
themeVariables: {
primaryColor: '#4A90E2',
primaryTextColor: '#fff',
primaryBorderColor: '#2E5C8A',
lineColor: '#5C6BC0',
secondaryColor: '#7E57C2',
tertiaryColor: '#26A69A'
}
});
</script>
</head>
<body>
<div class="container">
<h1>ln-220-story-coordinator: Story Coordinator</h1>
<div class="diagram-section">
<h2>Workflow Diagram</h2>
<div class="mermaid">
graph TD
Start([Input: Epic Number]) --> Phase1[Phase 1: Context Assembly]
Phase1 --> Step1Discovery[Step 1: Discovery<br/>Team ID, Epic, Story Number]
Step1Discovery --> Step2Extract[Step 2: Extract Planning Info<br/>Q1-Q6 from Epic]
Step2Extract --> CheckQ2Q5{Q2 or Q5<br/>missing?}
CheckQ2Q5 -->|Yes| Step3HTML[Step 3: Frontend Research<br/>Scan HTML for AC/capabilities]
CheckQ2Q5 -->|No| Step4Fallback
Step3HTML --> Step4Fallback[Step 4: Fallback Search<br/>requirements.md, tech_stack.md]
Step4Fallback --> CheckMissing{Still<br/>missing?}
CheckMissing -->|Yes| Step5User[Step 5: User Input<br/>Ask for remaining info]
CheckMissing -->|No| Phase2
Step5User --> Phase2[Phase 2: Standards Research]
Phase2 --> ParseDomains[Parse Epic for domain keywords<br/>standards mentions]
ParseDomains --> SkipResearch{Standards<br/>mentioned?}
SkipResearch -->|No| EmptyResearch[Empty Standards Research]
SkipResearch -->|Yes| DelegateLN221[DELEGATE: ln-221-standards-researcher<br/>epic_description, story_domain]
DelegateLN221 --> WaitResearch[Wait for Standards Research]
WaitResearch --> CacheResearch[Cache Standards Research<br/>for workers Phase 5a/5b]
EmptyResearch --> Phase3[Phase 3: Planning]
CacheResearch --> Phase3
Phase3 --> BuildIDEAL[Build IDEAL Plan "in mind"<br/>Analyze Scope, 5-10 Stories<br/>Vertical Slicing, INVEST Checklist]
BuildIDEAL --> Phase4[Phase 4: Check Existing]
Phase4 --> QueryLinear[Query Linear for existing Stories<br/>list_issues project=Epic label=user-story<br/>Metadata ONLY ID, title, status]
QueryLinear --> CountCheck{Count = 0?}
CountCheck -->|Yes| Phase5a[Phase 5a: Delegate CREATE]
CountCheck -->|No| Phase5b[Phase 5b: Delegate REPLAN]
Phase5a --> DelegateLN222[DELEGATE: ln-222-story-creator<br/>epicData, idealPlan<br/>standardsResearch, teamId<br/>autoApprove]
DelegateLN222 --> WaitCREATE[Wait for worker output:<br/>Created Story URLs<br/>Summary + Next Steps]
WaitCREATE --> End([Done])
Phase5b --> DelegateLN223[DELEGATE: ln-223-story-replanner<br/>epicData, idealPlan<br/>standardsResearch, existingCount<br/>teamId, autoApprove]
DelegateLN223 --> WaitREPLAN[Wait for worker output:<br/>Operation results<br/>Warnings + URLs + Next Steps]
WaitREPLAN --> End
style Start fill:#4A90E2,stroke:#2E5C8A,color:#fff
style End fill:#26A69A,stroke:#1B5E20,color:#fff
style Phase1 fill:#7E57C2,stroke:#4A148C,color:#fff
style Phase2 fill:#7E57C2,stroke:#4A148C,color:#fff
style Phase3 fill:#7E57C2,stroke:#4A148C,color:#fff
style Phase4 fill:#7E57C2,stroke:#4A148C,color:#fff
style Phase5a fill:#26A69A,stroke:#1B5E20,color:#fff
style Phase5b fill:#FF9800,stroke:#E65100,color:#fff
style CountCheck fill:#FF9800,stroke:#E65100,color:#fff
style SkipResearch fill:#FF9800,stroke:#E65100,color:#fff
style CheckQ2Q5 fill:#FF9800,stroke:#E65100,color:#fff
style CheckMissing fill:#FF9800,stroke:#E65100,color:#fff
style DelegateLN221 fill:#FFC107,stroke:#F57C00,color:#000
style DelegateLN222 fill:#FFC107,stroke:#F57C00,color:#000
style DelegateLN223 fill:#FFC107,stroke:#F57C00,color:#000
style WaitResearch fill:#FFC107,stroke:#F57C00,color:#000
style WaitCREATE fill:#FFC107,stroke:#F57C00,color:#000
style WaitREPLAN fill:#FFC107,stroke:#F57C00,color:#000
</div>
</div>
<div class="info-section">
<h2>Key Information</h2>
<ul>
<li><strong>Type:</strong> Domain Coordinator (L2)</li>
<li><strong>Phases:</strong> 5 phases (Context Assembly → Standards Research → Planning → Check Existing → Delegate)</li>
<li><strong>Pattern:</strong> Decompose-First (build IDEAL → check existing → CREATE/REPLAN)</li>
<li><strong>Delegates to:</strong> ln-221-standards-researcher (Phase 2), ln-222-story-creator (Phase 5a), ln-223-story-replanner (Phase 5b)</li>
<li><strong>Output:</strong> Worker output (5-10 Stories with Standards Research in Technical Notes)</li>
<li><strong>Modes:</strong> Phase 5a: Delegate CREATE (no existing) / Phase 5b: Delegate REPLAN (KEEP/UPDATE/OBSOLETE/CREATE)</li>
<li><strong>Version:</strong> 4.0.0 (BREAKING - Orchestrator-Worker pattern, Phase 5a/5b delegation)</li>
</ul>
</div>
<div class="delegation-section">
<h2>Delegation Flow</h2>
<ul>
<li><strong>Phase 2:</strong> ln-221-standards-researcher v2.0.0
<ul>
<li><strong>Input:</strong> Epic description + Story domain</li>
<li><strong>Output:</strong> Standards Research (RFCs, industry standards, architectural patterns)</li>
<li><strong>Time-box:</strong> 15-20 minutes</li>
</ul>
</li>
<li><strong>Phase 5a:</strong> ln-222-story-creator v1.0.0
<ul>
<li><strong>Input:</strong> epicData, idealPlan, standardsResearch, teamId, autoApprove</li>
<li><strong>Output:</strong> Created Story URLs + summary + next steps</li>
<li><strong>Handles:</strong> Generate documents, validate INVEST, create in Linear, update kanban</li>
</ul>
</li>
<li><strong>Phase 5b:</strong> ln-223-story-replanner v1.0.0
<ul>
<li><strong>Input:</strong> epicData, idealPlan, standardsResearch, existingCount, teamId, autoApprove</li>
<li><strong>Output:</strong> Operation results + warnings + affected URLs + next steps</li>
<li><strong>Handles:</strong> Load existing (Progressive Loading), compare, show diffs, execute operations, update kanban</li>
</ul>
</li>
</ul>
</div>
<div class="notes-section">
<h2>Important Notes</h2>
<ul>
<li><strong>Phase 1 (5 Steps):</strong> Context Assembly with Sequential Numbering
<ul>
<li>Step 1: Discovery (Team ID, Epic, Next Story Number from kanban_board.md)</li>
<li>Step 2: Extract Planning Info (Q1-Q6 from Epic Goal, Scope In/Out, Success Criteria)</li>
<li>Step 3: Frontend Research (Optional - scan HTML for AC/capabilities if Q2/Q5 missing)</li>
<li>Step 4: Fallback Search (requirements.md, tech_stack.md for missing Q1/Q3/Q6)</li>
<li>Step 5: User Input (Only if still missing after Step 2-4)</li>
</ul>
</li>
<li><strong>Phase 2:</strong> Standards Research - delegates to ln-221, caches for workers. Focus: RFCs, architectural patterns (NOT libraries)</li>
<li><strong>Phase 3:</strong> Planning - ALWAYS build IDEAL plan FIRST (5-10 vertical Stories), INVEST checklist. Story Grouping: 1 Story = 1 vertical slice (UI → API → DB)</li>
<li><strong>Phase 4:</strong> Check Existing - query Linear for metadata ONLY (ID, title, status ~50 tokens/Story). Workers load FULL descriptions (~5,000 tokens/Story) for token efficiency</li>
<li><strong>Phase 5a:</strong> Delegate CREATE - ln-222-story-creator handles document generation, INVEST validation, Linear creation, kanban update</li>
<li><strong>Phase 5b:</strong> Delegate REPLAN - ln-223-story-replanner handles Progressive Loading (ONE BY ONE), comparison, diffs (AC, Standards Research), Story Split/Merge warnings, operations execution</li>
<li><strong>Token Efficiency:</strong> Coordinator loads metadata only (~500 tokens for 10 Stories), workers load full descriptions when needed (~50,000 tokens)</li>
<li><strong>Story Numbering:</strong> No Story 0 reserved (Stories start from US001). Epic 0 = Infrastructure Epic (contains US001-US010)</li>
<li><strong>Epic Numbering:</strong> Epic N = Linear Project number (global), NOT initiative-internal index (Epic 0-N)</li>
</ul>
</div>
<div class="changes-section">
<h2>Changes in v4.0.0 (BREAKING)</h2>
<ul>
<li><strong>Orchestrator-Worker Pattern:</strong> Decomposed to coordinator + 2 workers (ln-222, ln-223)</li>
<li><strong>Phase 4a/4b Removed:</strong> Replaced with Phase 5a/5b delegation</li>
<li><strong>Coordinator loads metadata only:</strong> ID, title, status (~50 tokens/Story)</li>
<li><strong>Workers load full descriptions:</strong> 8 sections (~5,000 tokens/Story)</li>
<li><strong>Progressive Loading:</strong> Now handled by ln-223-story-replanner, not coordinator</li>
<li><strong>Story execution logic:</strong> Moved to workers (ln-222, ln-223)</li>
<li><strong>Coordinator focuses on:</strong> Context assembly, standards research, planning, mode determination, delegation</li>
<li><strong>Token Efficiency:</strong> 10 Stories: 500 tokens (coordinator) vs 50,000 tokens (workers load when needed)</li>
</ul>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,506 @@
# Story Replan Algorithm
Detailed documentation of the Story comparison and operation determination logic used in ln-220-story-coordinator REPLAN MODE.
## Overview
When ln-220-story-coordinator is invoked on an Epic that already has Stories, it enters REPLAN MODE. This algorithm determines how to reconcile the IDEAL Story plan (built from current Epic requirements) with existing Stories in Linear.
**Key Principle:** Decompose-First Pattern ensures we always build the IDEAL plan based on current Epic state BEFORE checking existing Stories, preventing "anchoring bias" to potentially outdated Story structure.
## Algorithm Steps
### Step 1: Match by Goal
**Objective:** Identify which existing Stories correspond to which Stories in IDEAL plan.
**Matching Criteria (Fuzzy Match):**
1. **Story Title Similarity:**
- Extract keywords from both titles
- Calculate similarity score (Levenshtein distance or keyword overlap)
- Match threshold: >70% similarity
2. **Persona Match:**
- Extract persona from Story Statement ("As a [persona]")
- Exact match required (e.g., "API client" matches "API client")
3. **Capability Match:**
- Extract capability from Story Statement ("I want [capability]")
- Fuzzy match on action verbs + objects
- Match threshold: >60% similarity
- Example: "register OAuth client" matches "create OAuth registration"
**Matching Process:**
```
For each Story in IDEAL plan:
For each existing Story:
Calculate similarity_score = (
0.4 * title_similarity +
0.3 * persona_match +
0.3 * capability_similarity
)
If similarity_score > 0.7:
Mark as MATCHED
```
**Output:**
- Matched pairs: (IDEAL Story, Existing Story)
- Unmatched IDEAL Stories → Candidates for CREATE
- Unmatched existing Stories → Candidates for OBSOLETE
### Step 2: Determine Operations
For each matched pair and unmatched Story, determine the appropriate operation.
#### KEEP Operation
**Criteria** (ALL must be true):
- ✅ Story exists in IDEAL plan (matched)
- ✅ Story Statement unchanged (persona + capability + value)
- ✅ AC unchanged (same Given-When-Then scenarios)
- ✅ Technical Notes still valid (no new integrations/patterns)
- ✅ Status: Any except Done or Canceled
**Action:** None (no Linear API calls)
**Example:**
```
IDEAL:
Title: US004: Register OAuth client
Persona: API client
Capability: Register new OAuth application
AC: [3 scenarios unchanged]
Existing:
Title: US004: Register OAuth client
Status: Todo
[Same Story Statement, AC, Technical Notes]
→ KEEP (no changes needed)
```
#### UPDATE Operation
**Criteria** (ANY must be true):
- ⚠️ AC changed (new AC added, existing modified, AC removed)
- ⚠️ Story Statement refined (same capability, clearer phrasing)
- ⚠️ Technical Notes changed (new guide links, integration approach)
- ⚠️ Test Strategy changed (different E2E/Integration/Unit distribution)
**Constraints:**
- Status: Backlog or Todo ONLY
- If In Progress/To Review/Done → Show warning, no auto-update
**Action:** `update_issue(id, description=new_description)`
**Example:**
```
IDEAL:
Title: US006: Validate access token
AC:
- Given token with valid signature, When validated, Then return claims
- Given token with invalid signature, When validated, Then reject
- Given expired token, When validated, Then return specific error ← NEW
Existing:
Title: US006: Validate access token
Status: Todo
AC: [Only first 2 scenarios]
→ UPDATE (new AC scenario added)
```
#### OBSOLETE Operation
**Criteria:**
- ❌ Story NOT in IDEAL plan (no match found)
- ❌ Feature removed from Epic Scope
- ❌ Capability no longer needed
**Constraints:**
- Status: Backlog or Todo ONLY
- If In Progress → Show warning "Story in progress, manual review needed"
- If To Review → Show warning "Story under review, manual review needed"
- If Done → Show warning "Story completed, cannot cancel - will remain in Epic"
**Action:** `update_issue(id, state="Canceled")`
**Rationale:** Use Canceled state (not deletion) to preserve history and reference.
**Example:**
```
Existing:
Title: US008: Custom token formats
Status: Todo
[Feature removed from Epic Scope]
IDEAL plan:
[No matching Story - custom formats feature removed]
→ OBSOLETE (cancel Story in Linear)
```
#### CREATE Operation
**Criteria:**
- Story in IDEAL plan (no match in existing)
- New capability added to Epic
- New user need identified
**Action:** `create_issue()` (same as CREATE MODE)
**Example:**
```
IDEAL:
Title: US009: Manage token scopes
Persona: API client
Capability: Define access scopes for tokens
[New Epic requirement]
Existing Stories:
[No matching Story - new capability]
→ CREATE (create new Story in Linear)
```
### Step 3: Handle Edge Cases
#### Case 1: Story In Progress with Changes
**Situation:** IDEAL plan shows AC changes for Story currently In Progress
**Resolution:**
- Do NOT auto-update (developers actively working on it)
- Show warning: "⚠️ US006 (In Progress): AC changed but cannot auto-update - manual review needed"
- Include diff in warning (show before/after AC)
- Recommend: Manual review after current work completes
**Example:**
```
IDEAL:
US006: New AC added (token expiry validation)
Existing:
US006: Status = In Progress (developer working on it)
→ WARNING (show diff, no auto-update)
```
#### Case 2: Story Done with Scope Changes
**Situation:** IDEAL plan shows Story should be removed, but it's already Done
**Resolution:**
- Do NOT cancel (work already completed and delivered)
- Show warning: "⚠️ US008 (Done): Feature removed from Epic scope, but Story already completed - will remain in Epic"
- Recommend: Keep for historical reference, do not revert
**Example:**
```
IDEAL:
[US008 not in plan - feature removed]
Existing:
US008: Status = Done
→ WARNING (cannot cancel Done Story)
```
#### Case 3: Multiple Matches (Ambiguous)
**Situation:** One IDEAL Story matches multiple existing Stories (similarity_score > 0.7 for multiple)
**Resolution:**
- Pick highest similarity_score match
- For other existing Stories → Mark as OBSOLETE candidates
- Show warning: "⚠️ Ambiguous match: US007 matches both 'Token refresh' and 'Token renewal' - selected 'Token refresh' (85% match)"
#### Case 4: No Matches (Complete Redesign)
**Situation:** Epic requirements completely changed, no existing Stories match IDEAL plan
**Resolution:**
- All existing Stories → OBSOLETE (if Backlog/Todo) or WARNING (if In Progress/Done)
- All IDEAL Stories → CREATE
- Show summary: "Complete Epic redesign detected: 5 Stories to obsolete, 7 new Stories to create"
- Require explicit user confirmation
#### Case 5: Story Split (1 → 2)
**Situation:** One existing Story matches 2 IDEAL Stories (capability split into smaller Stories)
**Resolution:**
- First IDEAL Story → UPDATE existing Story
- Second IDEAL Story → CREATE new Story
- Show explanation: "US004 'User authentication' split into US004 'Login' (update existing) and US009 'Password reset' (create new)"
#### Case 6: Story Merge (2 → 1)
**Situation:** Two existing Stories match 1 IDEAL Story (capabilities merged)
**Resolution:**
- Primary existing Story (higher similarity) → UPDATE
- Secondary existing Story → OBSOLETE
- Show explanation: "US004 'Login' and US005 'Session management' merged into US004 'User authentication' (update US004, obsolete US005)"
## Best Practices
### 1. Always Show Diffs
For UPDATE operations, show before/after comparison:
```
US006: Validate access token
Changes:
📋 Acceptance Criteria:
+ Given expired token, When validated, Then return specific error code
+ Given token from revoked client, When validated, Then reject
📝 Technical Notes:
+ Add guide link: Token Validation Best Practices
```
### 2. Group Operations by Type
Present operations in consistent order:
1. ✅ KEEP: N stories (list titles)
2. 🔧 UPDATE: M stories (show diffs)
3. ❌ OBSOLETE: K stories (show reasoning)
4. CREATE: L stories (show new capabilities)
5. ⚠️ WARNINGS: Edge cases requiring manual review
### 3. Preserve Story Continuity
- Keep existing Story IDs when updating (don't create new + delete old)
- Maintain Story numbering sequence (US004, US005, US006...)
- Update Epic Story Counters only for CREATE operations
### 4. Respect Status Transitions
Linear workflow:
```
Backlog → Todo → In Progress → To Review → Done
└─→ Canceled (OBSOLETE only)
```
**Safe to auto-update:** Backlog, Todo
**Warnings only:** In Progress, To Review, Done
### 5. Require User Confirmation
**Always** show complete summary before executing:
- Total operation count
- All diffs for UPDATE operations
- All warnings for edge cases
- Estimated impact (Stories affected)
**Never** execute operations without explicit "confirm" from user.
## Implementation Checklist
Before implementing replan in ln-220-story-coordinator, verify:
**✅ Data Loading:**
- [ ] Fetch all existing Stories from Epic: `list_issues(project=Epic.id, label="user-story")`
- [ ] Load FULL descriptions (all 8 sections) for each Story
- [ ] Note Story status (Backlog/Todo/In Progress/To Review/Done)
**✅ IDEAL Plan Building:**
- [ ] Build IDEAL plan from Epic Scope (Phase 4)
- [ ] IDEAL plan has 5-10 Stories
- [ ] Each IDEAL Story has: title, persona, capability, value, AC (3-5), Technical Notes
**✅ Matching:**
- [ ] Implement fuzzy matching (title + persona + capability)
- [ ] Similarity threshold: >70%
- [ ] Handle ambiguous matches (multiple existing match one IDEAL)
**✅ Operation Determination:**
- [ ] Implement KEEP logic (all unchanged)
- [ ] Implement UPDATE logic (AC/Tech changed, status=Backlog/Todo only)
- [ ] Implement OBSOLETE logic (not in IDEAL, status=Backlog/Todo only, use state="Canceled")
- [ ] Implement CREATE logic (new in IDEAL, no existing match)
**✅ Edge Cases:**
- [ ] Handle In Progress Stories with changes (warning, no auto-update)
- [ ] Handle Done Stories removed from Epic (warning, no cancel)
- [ ] Handle ambiguous matches (pick highest score, warn)
- [ ] Handle Story splits (UPDATE + CREATE)
- [ ] Handle Story merges (UPDATE + OBSOLETE)
**✅ User Experience:**
- [ ] Show grouped operations (KEEP/UPDATE/OBSOLETE/CREATE)
- [ ] Show diffs for UPDATE operations
- [ ] Show warnings with explanations
- [ ] Require explicit "confirm" before execution
- [ ] Show progress during execution ("Updating US006...")
- [ ] Show final summary (operations executed + warnings)
**✅ Linear API:**
- [ ] Use `update_issue(id, description)` for UPDATE
- [ ] Use `update_issue(id, state="Canceled")` for OBSOLETE
- [ ] Use `create_issue()` for CREATE
- [ ] Handle API errors gracefully
**✅ kanban_board.md:**
- [ ] Remove Canceled Stories from all sections
- [ ] Update modified Stories (keep in current section)
- [ ] Add new Stories to "### Backlog"
- [ ] Update Epic Story Counters (Last Story, Next Story)
## Scenarios
### Scenario 1: Minor AC Refinement
**Context:** Epic 7 OAuth Authentication, existing 5 Stories, refined AC for 2 Stories
**IDEAL Plan (5 Stories):**
- US004: Register OAuth client (unchanged)
- US005: Request access token (AC refined: add token expiry)
- US006: Validate token (AC refined: add signature validation details)
- US007: Refresh expired token (unchanged)
- US008: Revoke token (unchanged)
**Existing Stories (5 Stories):**
- US004: Register OAuth client (Backlog)
- US005: Request access token (Todo)
- US006: Validate token (In Progress)
- US007: Refresh expired token (Todo)
- US008: Revoke token (Backlog)
**Operations:**
- ✅ KEEP: US004, US007, US008 (3 Stories unchanged)
- 🔧 UPDATE: US005 (AC refined, status=Todo, safe to update)
- ⚠️ WARNING: US006 (AC refined, but status=In Progress, cannot auto-update)
**Summary:**
```
✅ KEEP: 3 stories unchanged
🔧 UPDATE: 1 story (US005)
⚠️ Manual Review Needed: 1 story
- US006 (In Progress): AC changed - review manually after current work completes
Operations: 1 update, 0 obsolete, 0 create
```
### Scenario 2: Feature Removed
**Context:** Epic 7, "Custom token formats" feature removed from scope
**IDEAL Plan (4 Stories):**
- US004: Register OAuth client
- US005: Request access token
- US006: Validate token
- US007: Refresh expired token
**Existing Stories (5 Stories):**
- US004: Register OAuth client (Todo)
- US005: Request access token (Todo)
- US006: Validate token (Done)
- US007: Refresh expired token (Todo)
- US008: Custom token formats (Todo)
**Operations:**
- ✅ KEEP: US004, US005, US006, US007 (4 Stories unchanged)
- ❌ OBSOLETE: US008 (feature removed, status=Todo, safe to cancel)
**Summary:**
```
✅ KEEP: 4 stories unchanged
❌ OBSOLETE: 1 story (US008 - Custom token formats)
Operations: 0 update, 1 obsolete, 0 create
```
### Scenario 3: New Feature Added
**Context:** Epic 7, "Token scope management" feature added to scope
**IDEAL Plan (6 Stories):**
- US004: Register OAuth client (unchanged)
- US005: Request access token (unchanged)
- US006: Validate token (unchanged)
- US007: Refresh expired token (unchanged)
- US008: Revoke token (unchanged)
- US009: Manage token scopes (NEW)
**Existing Stories (5 Stories):**
- US004: Register OAuth client (Backlog)
- US005: Request access token (Todo)
- US006: Validate token (Todo)
- US007: Refresh expired token (Todo)
- US008: Revoke token (Backlog)
**Operations:**
- ✅ KEEP: US004, US005, US006, US007, US008 (5 Stories unchanged)
- CREATE: US009 (new capability added)
**Summary:**
```
✅ KEEP: 5 stories unchanged
CREATE: 1 new story (US009 - Manage token scopes)
Operations: 0 update, 0 obsolete, 1 create
```
### Scenario 4: Complete Epic Redesign
**Context:** Epic 7 scope completely changed from "OAuth Authentication" to "API Key Authentication"
**IDEAL Plan (4 Stories):**
- US009: Generate API key (NEW)
- US010: Validate API key (NEW)
- US011: Rotate API key (NEW)
- US012: Revoke API key (NEW)
**Existing Stories (5 Stories):**
- US004: Register OAuth client (Todo)
- US005: Request access token (Todo)
- US006: Validate token (In Progress)
- US007: Refresh expired token (Done)
- US008: Revoke token (Todo)
**Operations:**
- ❌ OBSOLETE: US004, US005, US008 (3 Stories, status=Todo, safe to cancel)
- ⚠️ WARNING: US006 (In Progress, cannot auto-cancel)
- ⚠️ WARNING: US007 (Done, cannot cancel)
- CREATE: US009, US010, US011, US012 (4 new Stories)
**Summary:**
```
Complete Epic redesign detected
❌ OBSOLETE: 3 stories (OAuth features removed)
⚠️ Manual Review Needed: 2 stories
- US006 (In Progress): Feature removed but work in progress - review manually
- US007 (Done): Feature removed but Story completed - will remain for historical reference
CREATE: 4 new stories (API Key features)
Operations: 0 update, 3 obsolete, 4 create
⚠️ High impact - requires manual review of in-progress work
```
### Scenario 5: Story Split
**Context:** Epic 7, "User authentication" Story too large, split into "Login" and "Password reset"
**IDEAL Plan (6 Stories):**
- US004: Register OAuth client (unchanged)
- US005: User login (SPLIT from US006)
- US006: Request access token (unchanged from old US007)
- US007: Password reset (SPLIT from old US006)
- US008: Validate token (unchanged from old US008)
- US009: Refresh token (unchanged from old US009)
**Existing Stories (5 Stories):**
- US004: Register OAuth client (Todo)
- US006: User authentication (Todo, covers both login + password reset)
- US007: Request access token (Todo)
- US008: Validate token (Todo)
- US009: Refresh token (Todo)
**Operations:**
- ✅ KEEP: US004, US007, US008, US009 (4 Stories unchanged)
- 🔧 UPDATE: US006 → "User login" (narrow scope to just login)
- CREATE: US007 (new) → "Password reset" (split from US006)
**Summary:**
```
✅ KEEP: 4 stories unchanged
🔧 UPDATE: 1 story (US006 scope narrowed to "User login")
CREATE: 1 new story (US007 - Password reset, split from US006)
Note: Story split detected - US006 "User authentication" → US006 "User login" + US007 "Password reset"
Operations: 1 update, 0 obsolete, 1 create
```
---
**Version:** 1.0.0 (Story replan algorithm with Epic extraction)
**Last Updated:** 2025-11-10