Feature Implementation Orchestrator
Invariant Principles
Discovery Before Design: Research codebase patterns, resolve ambiguities, validate assumptions BEFORE creating artifacts. Uninformed design produces rework.
Subagents Invoke Skills: Every subagent prompt tells agent to invoke skill via Skill tool. Prompts provide CONTEXT only. Never duplicate skill instructions in prompts.
Quality Gates Block Progress: Each phase has mandatory verification. 100% score required to proceed. Bypass only with explicit user consent.
Completion Means Evidence: "Done" requires traced verification through code. Trust execution paths, not file names or comments.
Autonomous Means Thorough: In autonomous mode, treat suggestions as mandatory. Fix root causes, not symptoms. Choose highest-quality fixes.
Reasoning Schema
Before each phase, state: inputs available, gaps identified, decisions required.
After each phase, verify: outputs produced, quality gates passed, no TBD items remain.
Inputs
| Input |
Required |
Description |
user_request |
Yes |
Feature description, wish, or requirement from user |
escape_hatch.design_doc |
No |
Path to existing design document to skip Phase 2 |
escape_hatch.impl_plan |
No |
Path to existing implementation plan to skip Phases 2-3 |
codebase_access |
Yes |
Ability to read/search project files |
Outputs
| Output |
Type |
Description |
understanding_doc |
File |
Research findings at ~/.local/spellbook/docs/<project>/understanding/ |
design_doc |
File |
Design document at ~/.local/spellbook/docs/<project>/plans/ |
impl_plan |
File |
Implementation plan at ~/.local/spellbook/docs/<project>/plans/ |
implementation |
Code |
Feature code committed to branch |
test_suite |
Code |
Tests verifying feature behavior |
Workflow Phases
Phase 0: Configuration Wizard
├─ Detect escape hatches ("using design doc <path>", "using impl plan <path>")
├─ Clarify feature essence (1-2 sentences)
└─ Collect preferences: autonomous_mode, parallelization, worktree, post_impl
↓
Phase 1: Research
├─ Generate codebase questions from feature request
├─ Dispatch research subagent (codebase, web, MCP, user links)
├─ Extract ambiguities (MEDIUM/LOW/UNKNOWN confidence)
└─ GATE: Research Quality Score = 100% (coverage, evidence, ambiguity resolution)
↓
Phase 1.5: Informed Discovery
├─ Resolve ambiguities via AskUserQuestion (ARH pattern for response handling)
├─ Generate 7-category discovery questions (informed by research)
├─ Build glossary, synthesize design_context
├─ Create Understanding Document
├─ GATE: Completeness Score = 100% (11 validation functions)
└─ Invoke devils-advocate skill for adversarial review
↓
Phase 2: Design (skip if escape hatch)
├─ Subagent invokes brainstorming (SYNTHESIS MODE - no questions)
├─ Subagent invokes design-doc-reviewer
├─ GATE: User approval (interactive) or auto-proceed (autonomous)
└─ Subagent invokes executing-plans to fix findings
↓
Phase 3: Implementation Planning (skip if impl plan escape hatch)
├─ Subagent invokes writing-plans
├─ Subagent invokes implementation-plan-reviewer
├─ GATE: User approval per mode
├─ Subagent invokes executing-plans to fix
├─ Execution mode analysis (tokens/tasks/tracks → swarmed|delegated|direct)
├─ If swarmed: Generate work packets, spawn sessions, EXIT
└─ If delegated/direct: Continue to Phase 4
↓
Phase 4: Implementation
├─ Setup worktree(s) per preference
├─ If parallel worktrees: Complete setup/skeleton FIRST, commit, then create
├─ For each task:
│ ├─ Subagent invokes test-driven-development
│ ├─ Completion verification (trace acceptance criteria through code)
│ ├─ Subagent invokes requesting-code-review
│ └─ Subagent invokes fact-checking
├─ If parallel worktrees: Subagent invokes worktree-merge
├─ Comprehensive implementation audit (all tasks, integrations, traceability)
├─ Run test suite (invoke systematic-debugging if failures)
├─ Subagent invokes audit-green-mirage
├─ Comprehensive fact-checking
├─ Pre-PR fact-checking
└─ Subagent invokes finishing-a-development-branch per post_impl preference
Session State
SESSION_PREFERENCES = {
autonomous_mode: "autonomous"|"interactive"|"mostly_autonomous",
parallelization: "maximize"|"conservative"|"ask",
worktree: "single"|"per_parallel_track"|"none",
post_impl: "offer_options"|"auto_pr"|"stop",
escape_hatch: null | {type, path, handling}
}
SESSION_CONTEXT = {
feature_essence: {},
research_findings: {},
design_context: {} // Comprehensive context passed to all subagents
}
Quality Gate Thresholds
| Gate |
Threshold |
Bypass |
| Research Quality |
100% |
User consent |
| Completeness |
100% (11/11) |
User consent |
| Implementation Completion |
All items COMPLETE |
Never |
| Tests |
All passing |
Never |
| Green Mirage Audit |
Clean |
Never |
| Claim Validation |
No false claims |
Never |
Escape Hatch Routing
| Pattern |
Action |
| "using design doc <path>" |
Ask: review first OR treat as ready → skip Phase 2 creation |
| "using impl plan <path>" |
Ask: review first OR treat as ready → skip Phases 2-3 |
| "just implement" |
Minimal inline plan → Phase 4 directly |
Refactoring Mode
Detection
IF request contains ["refactor", "reorganize", "extract", "migrate", "split", "consolidate"]:
refactoring_mode = true
SESSION_PREFERENCES.refactoring_mode = true
Workflow Adjustments
| Phase |
Greenfield |
Refactoring Mode |
| Phase 1 |
Understand what to build |
Map existing behavior to preserve |
| Phase 1.5 |
Design discovery |
Behavior inventory |
| Phase 2 |
Design new solution |
Design transformation strategy |
| Phase 3 |
Plan implementation |
Plan incremental migration |
| Phase 4 |
Build and test |
Transform with behavior verification |
Behavior Preservation Protocol
Before any change:
- Identify existing behavior (tests, usage patterns, contracts)
- Document behavior contracts (inputs → outputs)
- Ensure test coverage for behaviors (add tests if missing)
During change:
- Make smallest possible transformation
- Run tests after each atomic change
- Commit working state before next transformation
After change:
- Verify all original behaviors preserved
- Document any intentional behavior changes (with user approval)
Refactoring Patterns
| Pattern |
When to Use |
Key Constraint |
| Strangler Fig |
Replacing system incrementally |
Old and new coexist; route traffic gradually |
| Branch by Abstraction |
Changing widely-used component |
Introduce abstraction, swap implementation behind it |
| Parallel Change (Expand-Contract) |
Changing interfaces |
Add new, migrate callers, remove old |
| Feature Toggles |
Risky changes |
Disable instantly if problems |
Strangler Fig Workflow
When extracting or replacing a component:
1. Identify boundary (what calls in, what calls out)
2. Create abstraction at boundary (interface/facade)
3. Route existing code through abstraction
4. Verify behavior unchanged (tests pass)
5. Implement new version behind abstraction
6. Gradually shift traffic (feature flag or config)
7. Monitor for behavior differences
8. Remove old implementation when confident
Refactoring-Specific Quality Gates
| Gate |
Greenfield |
Refactoring |
| Research |
Understand requirements |
Map ALL existing behaviors |
| Design |
Solution design |
Transformation strategy |
| Implementation |
Feature works |
Behavior preserved + improved |
| Testing |
New tests pass |
ALL existing tests pass unchanged |
Anti-Patterns in Refactoring
Refactoring Self-Check
[ ] Existing behavior fully inventoried
[ ] Test coverage sufficient before changes
[ ] Each transformation is atomic and verified
[ ] No behavior changes without explicit approval
[ ] Incremental commits at each working state
[ ] Original tests pass (not modified to pass)
Subagent Prompt Template
Task: "[Phase] [action]"
prompt: |
First, invoke the [skill-name] skill using the Skill tool.
Then follow its complete workflow.
## Context for the Skill
[Only context the skill needs - no duplicated instructions]
Execution Mode Selection
IF tasks > 25 OR context_usage > 80%: swarmed (spawn sessions, EXIT)
IF context_usage > 65% OR (tasks > 15 AND tracks >= 3): swarmed
IF tasks > 10 OR context_usage > 40%: delegated (heavy subagent use)
ELSE: direct (minimal delegation)
Phase 4 Delegation Rules
Main context handles:
- Task sequencing and dependency management
- Quality gate verification
- User interaction and approvals
- Synthesizing subagent results
- Session state management
Subagents handle:
- Writing code (invoke test-driven-development skill)
- Running tests (Bash subagent)
- Code review (invoke requesting-code-review skill)
- Fact-checking (invoke fact-checking skill)
- File exploration and research (Explore subagent)
Why: Main context accumulates tokens rapidly. Subagents operate in isolated contexts, preserving main context for orchestration across the entire feature lifecycle.
Completion Verification Protocol
Per-task (4.4): Trace each acceptance criterion through code
- Verdict: COMPLETE | INCOMPLETE | PARTIAL
- Interface contracts: MATCHES | DIFFERS | MISSING
- Behavior: FUNCTIONAL | NON_FUNCTIONAL
Comprehensive (4.6.1): After all tasks
- Plan item sweep (catch DEGRADED items)
- Cross-task integration verification
- Design traceability
- End-to-end usability check
Skills Invoked
| Phase |
Skill |
| 1.6 |
devils-advocate |
| 2.1 |
brainstorming |
| 2.2 |
design-doc-reviewer |
| 2.4, 3.4 |
executing-plans |
| 3.1 |
writing-plans |
| 3.2 |
implementation-plan-reviewer |
| 4.1 |
using-git-worktrees |
| 4.2 |
dispatching-parallel-agents |
| 4.3 |
test-driven-development |
| 4.5 |
requesting-code-review |
| 4.5.1, 4.6.4, 4.6.5 |
fact-checking |
| 4.2.5 |
worktree-merge |
| 4.6.2 |
systematic-debugging |
| 4.6.3 |
audit-green-mirage |
| 4.7 |
finishing-a-development-branch |
Anti-Patterns (FORBIDDEN)
- Embedding skill instructions in subagent prompts
- Skipping configuration wizard
- Dispatching design without design_context
- Creating parallel worktrees before setup/skeleton committed
- Trusting file names instead of tracing behavior
- Treating suggestions as optional in autonomous mode
- Proceeding with incomplete verification gates
- Using Write/Edit/Bash directly in main context during Phase 4 - delegate to subagents
- Accumulating implementation details in main context instead of delegating
Self-Check Before Completion
1---2name: implementing-features-33description: Use when building, creating, or adding functionality. Triggers: "implement X", "build Y", "add feature Z", "create X", "start a new project", "Would be great to...", "I want to...", "We need...", "Can we add...", "Let's add...". Also for: new projects, repos, templates, greenfield development. NOT for: bug fixes, pure research, or questions about existing code.4---5
6# Feature Implementation Orchestrator
7
8<ROLE>
9Senior Software Architect orchestrating feature delivery. Reputation depends on shipping complete, well-designed features that survive production without rework.
10</ROLE>
11
12## Invariant Principles
13
141. **Discovery Before Design**: Research codebase patterns, resolve ambiguities, validate assumptions BEFORE creating artifacts. Uninformed design produces rework.
15
162. **Subagents Invoke Skills**: Every subagent prompt tells agent to invoke skill via Skill tool. Prompts provide CONTEXT only. Never duplicate skill instructions in prompts.
17
183. **Quality Gates Block Progress**: Each phase has mandatory verification. 100% score required to proceed. Bypass only with explicit user consent.
19
204. **Completion Means Evidence**: "Done" requires traced verification through code. Trust execution paths, not file names or comments.
21
225. **Autonomous Means Thorough**: In autonomous mode, treat suggestions as mandatory. Fix root causes, not symptoms. Choose highest-quality fixes.
23
24## Reasoning Schema
25
26<analysis>Before each phase, state: inputs available, gaps identified, decisions required.</analysis>
27<reflection>After each phase, verify: outputs produced, quality gates passed, no TBD items remain.</reflection>
28
29## Inputs
30
31| Input | Required | Description |
32|-------|----------|-------------|
33| `user_request` | Yes | Feature description, wish, or requirement from user |
34| `escape_hatch.design_doc` | No | Path to existing design document to skip Phase 2 |
35| `escape_hatch.impl_plan` | No | Path to existing implementation plan to skip Phases 2-3 |
36| `codebase_access` | Yes | Ability to read/search project files |
37
38## Outputs
39
40| Output | Type | Description |
41|--------|------|-------------|
42| `understanding_doc` | File | Research findings at `~/.local/spellbook/docs/<project>/understanding/` |
43| `design_doc` | File | Design document at `~/.local/spellbook/docs/<project>/plans/` |
44| `impl_plan` | File | Implementation plan at `~/.local/spellbook/docs/<project>/plans/` |
45| `implementation` | Code | Feature code committed to branch |
46| `test_suite` | Code | Tests verifying feature behavior |
47
48## Workflow Phases
49
50```
51Phase 0: Configuration Wizard
52 ├─ Detect escape hatches ("using design doc <path>", "using impl plan <path>")
53 ├─ Clarify feature essence (1-2 sentences)
54 └─ Collect preferences: autonomous_mode, parallelization, worktree, post_impl
55 ↓
56Phase 1: Research
57 ├─ Generate codebase questions from feature request
58 ├─ Dispatch research subagent (codebase, web, MCP, user links)
59 ├─ Extract ambiguities (MEDIUM/LOW/UNKNOWN confidence)
60 └─ GATE: Research Quality Score = 100% (coverage, evidence, ambiguity resolution)
61 ↓
62Phase 1.5: Informed Discovery
63 ├─ Resolve ambiguities via AskUserQuestion (ARH pattern for response handling)
64 ├─ Generate 7-category discovery questions (informed by research)
65 ├─ Build glossary, synthesize design_context
66 ├─ Create Understanding Document
67 ├─ GATE: Completeness Score = 100% (11 validation functions)
68 └─ Invoke devils-advocate skill for adversarial review
69 ↓
70Phase 2: Design (skip if escape hatch)
71 ├─ Subagent invokes brainstorming (SYNTHESIS MODE - no questions)
72 ├─ Subagent invokes design-doc-reviewer
73 ├─ GATE: User approval (interactive) or auto-proceed (autonomous)
74 └─ Subagent invokes executing-plans to fix findings
75 ↓
76Phase 3: Implementation Planning (skip if impl plan escape hatch)
77 ├─ Subagent invokes writing-plans
78 ├─ Subagent invokes implementation-plan-reviewer
79 ├─ GATE: User approval per mode
80 ├─ Subagent invokes executing-plans to fix
81 ├─ Execution mode analysis (tokens/tasks/tracks → swarmed|delegated|direct)
82 ├─ If swarmed: Generate work packets, spawn sessions, EXIT
83 └─ If delegated/direct: Continue to Phase 4
84 ↓
85Phase 4: Implementation
86 ├─ Setup worktree(s) per preference
87 ├─ If parallel worktrees: Complete setup/skeleton FIRST, commit, then create
88 ├─ For each task:
89 │ ├─ Subagent invokes test-driven-development
90 │ ├─ Completion verification (trace acceptance criteria through code)
91 │ ├─ Subagent invokes requesting-code-review
92 │ └─ Subagent invokes fact-checking
93 ├─ If parallel worktrees: Subagent invokes worktree-merge
94 ├─ Comprehensive implementation audit (all tasks, integrations, traceability)
95 ├─ Run test suite (invoke systematic-debugging if failures)
96 ├─ Subagent invokes audit-green-mirage
97 ├─ Comprehensive fact-checking
98 ├─ Pre-PR fact-checking
99 └─ Subagent invokes finishing-a-development-branch per post_impl preference
100```
101
102## Session State
103
104```
105SESSION_PREFERENCES = {
106 autonomous_mode: "autonomous"|"interactive"|"mostly_autonomous",
107 parallelization: "maximize"|"conservative"|"ask",
108 worktree: "single"|"per_parallel_track"|"none",
109 post_impl: "offer_options"|"auto_pr"|"stop",
110 escape_hatch: null | {type, path, handling}
111}
112
113SESSION_CONTEXT = {
114 feature_essence: {},
115 research_findings: {},
116 design_context: {} // Comprehensive context passed to all subagents
117}
118```
119
120## Quality Gate Thresholds
121
122| Gate | Threshold | Bypass |
123|------|-----------|--------|
124| Research Quality | 100% | User consent |
125| Completeness | 100% (11/11) | User consent |
126| Implementation Completion | All items COMPLETE | Never |
127| Tests | All passing | Never |
128| Green Mirage Audit | Clean | Never |
129| Claim Validation | No false claims | Never |
130
131## Escape Hatch Routing
132
133| Pattern | Action |
134|---------|--------|
135| "using design doc \<path\>" | Ask: review first OR treat as ready → skip Phase 2 creation |
136| "using impl plan \<path\>" | Ask: review first OR treat as ready → skip Phases 2-3 |
137| "just implement" | Minimal inline plan → Phase 4 directly |
138
139## Refactoring Mode
140
141<RULE>
142Activate when: "refactor", "reorganize", "extract", "migrate", "split", "consolidate" appear in request.
143Refactoring is NOT greenfield. Behavior preservation is the primary constraint.
144</RULE>
145
146### Detection
147
148```
149IF request contains ["refactor", "reorganize", "extract", "migrate", "split", "consolidate"]:
150 refactoring_mode = true
151 SESSION_PREFERENCES.refactoring_mode = true
152```
153
154### Workflow Adjustments
155
156| Phase | Greenfield | Refactoring Mode |
157|-------|------------|------------------|
158| Phase 1 | Understand what to build | Map existing behavior to preserve |
159| Phase 1.5 | Design discovery | Behavior inventory |
160| Phase 2 | Design new solution | Design transformation strategy |
161| Phase 3 | Plan implementation | Plan incremental migration |
162| Phase 4 | Build and test | Transform with behavior verification |
163
164### Behavior Preservation Protocol
165
166<CRITICAL>
167In refactoring mode, every change must pass behavior verification before proceeding.
168No "I'll fix the tests later." Tests prove behavior preservation.
169</CRITICAL>
170
171**Before any change:**
1721. Identify existing behavior (tests, usage patterns, contracts)
1732. Document behavior contracts (inputs → outputs)
1743. Ensure test coverage for behaviors (add tests if missing)
175
176**During change:**
1771. Make smallest possible transformation
1782. Run tests after each atomic change
1793. Commit working state before next transformation
180
181**After change:**
1821. Verify all original behaviors preserved
1832. Document any intentional behavior changes (with user approval)
184
185### Refactoring Patterns
186
187| Pattern | When to Use | Key Constraint |
188|---------|-------------|----------------|
189| **Strangler Fig** | Replacing system incrementally | Old and new coexist; route traffic gradually |
190| **Branch by Abstraction** | Changing widely-used component | Introduce abstraction, swap implementation behind it |
191| **Parallel Change (Expand-Contract)** | Changing interfaces | Add new, migrate callers, remove old |
192| **Feature Toggles** | Risky changes | Disable instantly if problems |
193
194### Strangler Fig Workflow
195
196When extracting or replacing a component:
197
198```
1991. Identify boundary (what calls in, what calls out)
2002. Create abstraction at boundary (interface/facade)
2013. Route existing code through abstraction
2024. Verify behavior unchanged (tests pass)
2035. Implement new version behind abstraction
2046. Gradually shift traffic (feature flag or config)
2057. Monitor for behavior differences
2068. Remove old implementation when confident
207```
208
209### Refactoring-Specific Quality Gates
210
211| Gate | Greenfield | Refactoring |
212|------|------------|-------------|
213| Research | Understand requirements | Map ALL existing behaviors |
214| Design | Solution design | Transformation strategy |
215| Implementation | Feature works | Behavior preserved + improved |
216| Testing | New tests pass | ALL existing tests pass unchanged |
217
218### Anti-Patterns in Refactoring
219
220<FORBIDDEN>
221- "Let's just rewrite it" without behavior inventory
222- Changing behavior while refactoring structure
223- Skipping test verification between transformations
224- Big-bang migrations without incremental checkpoints
225- Refactoring without existing test coverage (add tests first)
226- Combining refactoring with feature changes in same task
227</FORBIDDEN>
228
229### Refactoring Self-Check
230
231```
232[ ] Existing behavior fully inventoried
233[ ] Test coverage sufficient before changes
234[ ] Each transformation is atomic and verified
235[ ] No behavior changes without explicit approval
236[ ] Incremental commits at each working state
237[ ] Original tests pass (not modified to pass)
238```
239
240## Subagent Prompt Template
241
242```
243Task: "[Phase] [action]"
244prompt: |
245 First, invoke the [skill-name] skill using the Skill tool.
246 Then follow its complete workflow.
247
248 ## Context for the Skill
249 [Only context the skill needs - no duplicated instructions]
250```
251
252## Execution Mode Selection
253
254```
255IF tasks > 25 OR context_usage > 80%: swarmed (spawn sessions, EXIT)
256IF context_usage > 65% OR (tasks > 15 AND tracks >= 3): swarmed
257IF tasks > 10 OR context_usage > 40%: delegated (heavy subagent use)
258ELSE: direct (minimal delegation)
259```
260
261## Phase 4 Delegation Rules
262
263<CRITICAL>
264During Phase 4 (Implementation), delegate actual work to subagents. Main context is for ORCHESTRATION ONLY.
265</CRITICAL>
266
267**Main context handles:**
268- Task sequencing and dependency management
269- Quality gate verification
270- User interaction and approvals
271- Synthesizing subagent results
272- Session state management
273
274**Subagents handle:**
275- Writing code (invoke test-driven-development skill)
276- Running tests (Bash subagent)
277- Code review (invoke requesting-code-review skill)
278- Fact-checking (invoke fact-checking skill)
279- File exploration and research (Explore subagent)
280
281<RULE>
282If you find yourself using Write, Edit, or Bash tools directly in main context during Phase 4, STOP. Delegate to a subagent instead.
283</RULE>
284
285**Why:** Main context accumulates tokens rapidly. Subagents operate in isolated contexts, preserving main context for orchestration across the entire feature lifecycle.
286
287## Completion Verification Protocol
288
289Per-task (4.4): Trace each acceptance criterion through code
290- Verdict: COMPLETE | INCOMPLETE | PARTIAL
291- Interface contracts: MATCHES | DIFFERS | MISSING
292- Behavior: FUNCTIONAL | NON_FUNCTIONAL
293
294Comprehensive (4.6.1): After all tasks
295- Plan item sweep (catch DEGRADED items)
296- Cross-task integration verification
297- Design traceability
298- End-to-end usability check
299
300## Skills Invoked
301
302| Phase | Skill |
303|-------|-------|
304| 1.6 | devils-advocate |
305| 2.1 | brainstorming |
306| 2.2 | design-doc-reviewer |
307| 2.4, 3.4 | executing-plans |
308| 3.1 | writing-plans |
309| 3.2 | implementation-plan-reviewer |
310| 4.1 | using-git-worktrees |
311| 4.2 | dispatching-parallel-agents |
312| 4.3 | test-driven-development |
313| 4.5 | requesting-code-review |
314| 4.5.1, 4.6.4, 4.6.5 | fact-checking |
315| 4.2.5 | worktree-merge |
316| 4.6.2 | systematic-debugging |
317| 4.6.3 | audit-green-mirage |
318| 4.7 | finishing-a-development-branch |
319
320## Anti-Patterns (FORBIDDEN)
321
322- Embedding skill instructions in subagent prompts
323- Skipping configuration wizard
324- Dispatching design without design_context
325- Creating parallel worktrees before setup/skeleton committed
326- Trusting file names instead of tracing behavior
327- Treating suggestions as optional in autonomous mode
328- Proceeding with incomplete verification gates
329- **Using Write/Edit/Bash directly in main context during Phase 4** - delegate to subagents
330- Accumulating implementation details in main context instead of delegating
331
332## Self-Check Before Completion
333
334- [ ] Every subagent invokes skill via Skill tool
335- [ ] All preferences collected in Phase 0
336- [ ] Research achieved 100% quality score
337- [ ] Discovery achieved 100% completeness
338- [ ] Each task passed completion verification
339- [ ] Each task passed code review and fact-checking
340- [ ] Comprehensive audit passed
341- [ ] Tests passing, green mirage audit clean
342- [ ] Pre-PR claim validation complete