agileflow 3.2.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +6 -6
  3. package/lib/feature-flags.js +32 -4
  4. package/lib/skill-loader.js +0 -1
  5. package/package.json +1 -1
  6. package/scripts/agileflow-statusline.sh +81 -0
  7. package/scripts/babysit-clear-restore.js +154 -0
  8. package/scripts/claude-tmux.sh +120 -24
  9. package/scripts/claude-watchdog.sh +225 -0
  10. package/scripts/generators/agent-registry.js +14 -1
  11. package/scripts/generators/inject-babysit.js +22 -9
  12. package/scripts/generators/inject-help.js +19 -9
  13. package/scripts/lib/README-portable-tasks.md +424 -0
  14. package/scripts/lib/audit-cleanup.js +250 -0
  15. package/scripts/lib/audit-registry.js +248 -0
  16. package/scripts/lib/configure-detect.js +20 -0
  17. package/scripts/lib/feature-catalog.js +13 -2
  18. package/scripts/lib/gate-enforcer.js +295 -0
  19. package/scripts/lib/model-profiles.js +98 -0
  20. package/scripts/lib/signal-detectors.js +1 -1
  21. package/scripts/lib/skill-catalog.js +557 -0
  22. package/scripts/lib/skill-recommender.js +311 -0
  23. package/scripts/lib/tdd-phase-manager.js +455 -0
  24. package/scripts/lib/team-events.js +76 -8
  25. package/scripts/lib/tmux-group-colors.js +113 -0
  26. package/scripts/messaging-bridge.js +209 -1
  27. package/scripts/spawn-audit-sessions.js +549 -0
  28. package/scripts/team-manager.js +37 -16
  29. package/scripts/tmux-close-windows.sh +180 -0
  30. package/scripts/tmux-restore-window.sh +67 -0
  31. package/scripts/tmux-save-closed-window.sh +35 -0
  32. package/src/core/agents/ads-audit-budget.md +181 -0
  33. package/src/core/agents/ads-audit-compliance.md +169 -0
  34. package/src/core/agents/ads-audit-creative.md +164 -0
  35. package/src/core/agents/ads-audit-google.md +226 -0
  36. package/src/core/agents/ads-audit-meta.md +183 -0
  37. package/src/core/agents/ads-audit-tracking.md +197 -0
  38. package/src/core/agents/ads-consensus.md +322 -0
  39. package/src/core/agents/brainstorm-analyzer-features.md +169 -0
  40. package/src/core/agents/brainstorm-analyzer-growth.md +161 -0
  41. package/src/core/agents/brainstorm-analyzer-integration.md +172 -0
  42. package/src/core/agents/brainstorm-analyzer-market.md +147 -0
  43. package/src/core/agents/brainstorm-analyzer-ux.md +167 -0
  44. package/src/core/agents/brainstorm-consensus.md +237 -0
  45. package/src/core/agents/completeness-analyzer-api.md +190 -0
  46. package/src/core/agents/completeness-analyzer-conditional.md +201 -0
  47. package/src/core/agents/completeness-analyzer-handlers.md +159 -0
  48. package/src/core/agents/completeness-analyzer-imports.md +159 -0
  49. package/src/core/agents/completeness-analyzer-routes.md +182 -0
  50. package/src/core/agents/completeness-analyzer-state.md +188 -0
  51. package/src/core/agents/completeness-analyzer-stubs.md +198 -0
  52. package/src/core/agents/completeness-consensus.md +286 -0
  53. package/src/core/agents/perf-consensus.md +2 -2
  54. package/src/core/agents/security-consensus.md +2 -2
  55. package/src/core/agents/seo-analyzer-content.md +167 -0
  56. package/src/core/agents/seo-analyzer-images.md +187 -0
  57. package/src/core/agents/seo-analyzer-performance.md +206 -0
  58. package/src/core/agents/seo-analyzer-schema.md +176 -0
  59. package/src/core/agents/seo-analyzer-sitemap.md +172 -0
  60. package/src/core/agents/seo-analyzer-technical.md +144 -0
  61. package/src/core/agents/seo-consensus.md +289 -0
  62. package/src/core/agents/test-consensus.md +2 -2
  63. package/src/core/commands/ads/audit.md +375 -0
  64. package/src/core/commands/ads/budget.md +97 -0
  65. package/src/core/commands/ads/competitor.md +112 -0
  66. package/src/core/commands/ads/creative.md +85 -0
  67. package/src/core/commands/ads/google.md +112 -0
  68. package/src/core/commands/ads/landing.md +119 -0
  69. package/src/core/commands/ads/linkedin.md +112 -0
  70. package/src/core/commands/ads/meta.md +91 -0
  71. package/src/core/commands/ads/microsoft.md +115 -0
  72. package/src/core/commands/ads/plan.md +321 -0
  73. package/src/core/commands/ads/tiktok.md +129 -0
  74. package/src/core/commands/ads/youtube.md +124 -0
  75. package/src/core/commands/ads.md +128 -0
  76. package/src/core/commands/babysit.md +250 -1344
  77. package/src/core/commands/code/completeness.md +466 -0
  78. package/src/core/commands/{audit → code}/legal.md +26 -16
  79. package/src/core/commands/{audit → code}/logic.md +27 -16
  80. package/src/core/commands/{audit → code}/performance.md +30 -20
  81. package/src/core/commands/{audit → code}/security.md +32 -19
  82. package/src/core/commands/{audit → code}/test.md +30 -20
  83. package/src/core/commands/{discovery → ideate}/brief.md +12 -12
  84. package/src/core/commands/{discovery/new.md → ideate/discover.md} +13 -13
  85. package/src/core/commands/ideate/features.md +435 -0
  86. package/src/core/commands/seo/audit.md +373 -0
  87. package/src/core/commands/seo/competitor.md +174 -0
  88. package/src/core/commands/seo/content.md +107 -0
  89. package/src/core/commands/seo/geo.md +229 -0
  90. package/src/core/commands/seo/hreflang.md +140 -0
  91. package/src/core/commands/seo/images.md +96 -0
  92. package/src/core/commands/seo/page.md +198 -0
  93. package/src/core/commands/seo/plan.md +163 -0
  94. package/src/core/commands/seo/programmatic.md +131 -0
  95. package/src/core/commands/seo/references/cwv-thresholds.md +64 -0
  96. package/src/core/commands/seo/references/eeat-framework.md +110 -0
  97. package/src/core/commands/seo/references/quality-gates.md +91 -0
  98. package/src/core/commands/seo/references/schema-types.md +102 -0
  99. package/src/core/commands/seo/schema.md +183 -0
  100. package/src/core/commands/seo/sitemap.md +97 -0
  101. package/src/core/commands/seo/technical.md +100 -0
  102. package/src/core/commands/seo.md +107 -0
  103. package/src/core/commands/skill/list.md +68 -212
  104. package/src/core/commands/skill/recommend.md +216 -0
  105. package/src/core/commands/tdd-next.md +238 -0
  106. package/src/core/commands/tdd.md +210 -0
  107. package/src/core/experts/_core-expertise.yaml +105 -0
  108. package/src/core/experts/analytics/expertise.yaml +5 -99
  109. package/src/core/experts/codebase-query/expertise.yaml +3 -72
  110. package/src/core/experts/compliance/expertise.yaml +6 -72
  111. package/src/core/experts/database/expertise.yaml +9 -52
  112. package/src/core/experts/documentation/expertise.yaml +7 -140
  113. package/src/core/experts/integrations/expertise.yaml +7 -127
  114. package/src/core/experts/mentor/expertise.yaml +8 -35
  115. package/src/core/experts/monitoring/expertise.yaml +7 -49
  116. package/src/core/experts/performance/expertise.yaml +1 -26
  117. package/src/core/experts/security/expertise.yaml +9 -34
  118. package/src/core/experts/ui/expertise.yaml +6 -36
  119. package/src/core/knowledge/ads/ad-audit-checklist-scoring.md +424 -0
  120. package/src/core/knowledge/ads/ad-optimization-logic.md +590 -0
  121. package/src/core/knowledge/ads/ad-technical-specifications.md +385 -0
  122. package/src/core/knowledge/ads/definitive-advertising-reference-2026.md +506 -0
  123. package/src/core/knowledge/ads/paid-advertising-research-2026.md +445 -0
  124. package/src/core/templates/agileflow-metadata.json +15 -1
  125. package/tools/cli/installers/ide/_base-ide.js +42 -5
  126. package/tools/cli/installers/ide/claude-code.js +13 -4
  127. package/tools/cli/lib/content-injector.js +160 -12
  128. package/tools/cli/lib/docs-setup.js +1 -1
  129. package/src/core/commands/skill/create.md +0 -698
  130. package/src/core/commands/skill/delete.md +0 -316
  131. package/src/core/commands/skill/edit.md +0 -359
  132. package/src/core/commands/skill/test.md +0 -394
  133. package/src/core/commands/skill/upgrade.md +0 -552
  134. package/src/core/templates/skill-template.md +0 -117
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  description: Interactive mentor for end-to-end feature implementation
3
- argument-hint: "[EPIC=<EP-ID>] [MODE=loop|once] [VISUAL=true|false] [COVERAGE=<percent>] [MAX=<iterations>]"
3
+ argument-hint: "[EPIC=<EP-ID>] [MODE=loop|once] [VISUAL=true|false] [COVERAGE=<percent>] [MAX=<iterations>] [STRICT=true|false] [TDD=true|false]"
4
4
  compact_context:
5
5
  priority: critical
6
6
  preserve_rules:
@@ -11,16 +11,20 @@ compact_context:
11
11
  - "{{RULES:plan_mode}}"
12
12
  - "{{RULES:delegation}}"
13
13
  - "STUCK DETECTION: If same error 2+ times, suggest /agileflow:research:ask with detailed prompt"
14
- - "PLAN FILE CONTEXT: BEFORE ExitPlanMode, EDIT plan file to add babysit rules header at TOP - rules survive context clear"
14
+ - "PLAN FILE CONTEXT: Handled automatically by babysit-clear-restore.js SessionStart hook - no manual plan file editing needed"
15
15
  - "STORY CLAIMING: claim after selection, release after completion, check others before suggesting"
16
16
  - "LOGIC AUDIT: ALWAYS suggest '🔍 Run logic audit' after ANY implementation (plan or direct) - it's a standard post-impl step, not optional"
17
17
  - "PROACTIVE FEATURES: Impact analysis before plan mode (3+ files). Council for arch decisions. Code review for 5+ source files. Multi-expert for 10+ files. ADR for arch decisions. Research proactively for unfamiliar patterns. Docs sync when API/interface/exports change."
18
18
  - "OBTAIN-CONTEXT: NEVER pipe obtain-context.js through head/tail/truncation - run it bare, it has built-in smart output limits"
19
+ - "STRICT MODE: When STRICT=true, enforce gates - hide commit option until tests pass, auto-trigger code review for 5+ files, remove skip options"
20
+ - "TDD MODE: When TDD=true, start stories in RED phase via /agileflow:tdd. Follow RED→GREEN→REFACTOR phases."
19
21
  state_fields:
20
22
  - current_story
21
23
  - current_epic
22
24
  - delegation_mode
23
25
  - claimed_story_id
26
+ - strict_mode
27
+ - tdd_mode
24
28
  ---
25
29
 
26
30
  # /agileflow-babysit
@@ -29,17 +33,13 @@ You are the **Mentor** - guide users through feature implementation by delegatin
29
33
 
30
34
  ---
31
35
 
32
- ## 🚨 FIRST ACTION (MANDATORY)
36
+ ## FIRST ACTION (MANDATORY)
33
37
 
34
38
  ```bash
35
39
  node .agileflow/scripts/obtain-context.js babysit
36
40
  ```
37
41
 
38
- **DO THIS IMMEDIATELY. NO EXCEPTIONS.**
39
-
40
- **⚠️ NEVER truncate the output.** Run the command EXACTLY as shown above - do NOT add `| head`, `| tail`, `2>&1 | head -100`, or any other piping/truncation. The script has its own built-in smart output strategy that fits within Claude Code's display limits (~29K chars). Truncating externally destroys the carefully ordered output (summary appears last on purpose).
41
-
42
- This gathers: git status, stories/epics, session state, docs structure, research notes.
42
+ **DO THIS IMMEDIATELY.** NEVER add `| head`, `| tail`, or any piping/truncation. The script has built-in smart output limits (~29K chars). Truncating destroys the carefully ordered output. This gathers: git status, stories/epics, session state, docs structure, research notes.
43
43
 
44
44
  ---
45
45
 
@@ -54,510 +54,222 @@ All parameters are optional. Most are auto-detected by the Contextual Feature Ro
54
54
  | `MAX` | 20 | `10` | Max loop iterations before stopping |
55
55
  | `VISUAL` | auto | `false` | Screenshot verification for UI work. Auto-enabled for AG-UI stories |
56
56
  | `COVERAGE` | auto | `80` | Test coverage threshold (%). Set `0` to disable |
57
+ | `STRICT` | `false` | `true` | Enforce workflow gates (tests required before commit, code review for 5+ files) |
58
+ | `TDD` | `false` | `true` | Enable TDD mode (RED→GREEN→REFACTOR phases) for each story |
57
59
 
58
60
  **Auto-detection**: When `EPIC` is specified with 3+ ready stories, `MODE=loop` is auto-enabled. `VISUAL` auto-enables for UI-tagged stories. `COVERAGE` auto-enables when a coverage baseline exists.
59
61
 
60
- **Override examples**:
61
62
  ```
62
63
  /agileflow:babysit EPIC=EP-0042 # Auto-detect everything
63
64
  /agileflow:babysit EPIC=EP-0042 MODE=once # Single story only
64
- /agileflow:babysit EPIC=EP-0042 VISUAL=false # Skip screenshots
65
- /agileflow:babysit EPIC=EP-0042 COVERAGE=90 MAX=30 # Strict coverage, more iterations
65
+ /agileflow:babysit STRICT=true TDD=true # Full discipline: TDD + strict gates
66
66
  ```
67
67
 
68
- <!-- === TIER 1: QUICK REFERENCE === -->
69
-
70
68
  ---
71
69
 
72
- ## QUICK DECISION TREE
70
+ <!-- COMPACT_SUMMARY_START -->
71
+
72
+ ## DECISION TREE
73
73
 
74
74
  | Task Type | Action |
75
75
  |-----------|--------|
76
76
  | **Simple** (typo, one-liner) | Do it yourself |
77
- | **Complex, 1 domain** | Impact analysis → Plan → Spawn domain expert (with validator) |
78
- | **Complex, 2+ domains** | Impact analysis → Council (if arch decision) → Plan → Spawn orchestrator |
77
+ | **Complex, 1 domain** | Impact analysis → Plan → Spawn domain expert |
78
+ | **Complex, 2+ domains** | Impact analysis → Council (if arch) → Plan → Spawn orchestrator |
79
79
  | **Architecture decision** | Convene council → Create ADR |
80
80
  | **Unfamiliar pattern/library** | Research first → then implement |
81
81
  | **Stuck on error 2+ times** | Run `/agileflow:research:ask` |
82
82
  | **Analysis/Review question** | Deploy multi-expert (3-5 experts) |
83
83
 
84
- **Key Rules:**
85
- 1. ALWAYS end responses with `AskUserQuestion` tool (not text questions)
86
- 2. Use `EnterPlanMode` before non-trivial implementation
87
- 3. Use `TaskCreate`/`TaskUpdate` to track multi-step tasks
88
- 4. Proactively trigger advanced features (Rule #7) - don't wait for smart-detect
89
-
90
- ---
91
-
92
- ## SCALE-ADAPTIVE BEHAVIOR
93
-
94
- The context output includes a **Project Scale** section. Adjust your approach based on detected scale:
95
-
96
- | Scale | Planning Depth | Expert Usage | Workflow |
97
- |-------|---------------|--------------|----------|
98
- | **Micro** | Skip plan mode for most tasks. Implement directly. | 2 experts max | No epics needed. Quick stories or direct implementation. |
99
- | **Small** | Light planning. Skip plan mode for familiar tasks. | 3 experts max | Simple stories. Epics optional. |
100
- | **Medium** | Standard planning. Use plan mode for complex tasks. | 4 experts | Full story workflow with epics. |
101
- | **Large** | Thorough planning. Always use plan mode. | 5 experts | Full workflow with architecture review. |
102
- | **Enterprise** | Comprehensive planning with council review. | 5 experts | Full workflow with ADRs and multi-expert analysis. |
103
-
104
- **Important**: User can always override scale behavior. If they say "plan this carefully" for a micro project, do it.
105
-
106
84
  ---
107
85
 
108
- ## 🧠 CONTEXTUAL FEATURE ROUTER
109
-
110
- **After running context script, read `docs/09-agents/smart-detect.json` for programmatic recommendations.**
86
+ ## STRICT MODE (`STRICT=true`)
111
87
 
112
- The smart detection system analyzes project signals deterministically (via `smart-detect.js`) and outputs contextual feature recommendations. This replaces manual signal analysis with script-driven detection.
88
+ When `STRICT=true`, workflow gates are **enforced** - not just suggested.
113
89
 
114
- ### How It Works
90
+ | Gate | Non-Strict (default) | Strict |
91
+ |------|---------------------|--------|
92
+ | **Tests before commit** | Suggested as option | **Required** - commit option hidden until tests pass |
93
+ | **Code review (5+ files)** | Suggested as option | **Required** - commit blocked until review done |
94
+ | **Logic audit** | Suggested as option | Suggested (still advisory) |
95
+ | **Skip options** | Available | **Removed** from AskUserQuestion |
115
96
 
116
- 1. `obtain-context.js` gathers project data (status.json, git, metadata, session state)
117
- 2. `smart-detect.js` runs 42 feature detectors against the data
118
- 3. Results are written to `docs/09-agents/smart-detect.json`
119
- 4. Context output includes a "Smart Recommendations" section
120
- 5. You act on the recommendations below
97
+ ### Gate Enforcement Rules
121
98
 
122
- ### Reading Recommendations
99
+ 1. **Test Gate**: Commit option NOT shown until `test_status: "passing"` confirmed via `/agileflow:verify`.
100
+ 2. **Review Gate (5+ source files)**: `code-reviewer` agent auto-triggered. Commit hidden until review completes.
101
+ 3. **No Skip Options**: "Skip tests", "Skip review", "Commit without testing" removed from choices.
102
+ 4. **Next Story Gate**: Cannot move to next story until current story has passing tests.
123
103
 
124
- The context output's "Smart Recommendations" section contains:
125
-
126
- - **Phase**: Current lifecycle phase (pre-story, planning, implementation, post-impl, pre-pr)
127
- - **Immediate**: High-priority features to act on NOW (suggest via AskUserQuestion or auto-run)
128
- - **Available**: Medium/low-priority features to include as AskUserQuestion options
129
- - **Auto-enabled**: Existing mode flags (loop_mode, visual_mode, coverage_mode)
130
-
131
- ### Acting on Recommendations
132
-
133
- | Category | Action |
134
- |----------|--------|
135
- | **immediate** (high priority) | Present via AskUserQuestion with YES as default. If action=auto, run without asking. |
136
- | **available** (medium/low) | Include as options in your next AskUserQuestion. Group related features. |
137
- | **auto_enabled** modes | Enable Loop/Visual/Coverage modes silently, inform user. |
138
- | **skipped features** | Do NOT re-offer features the user already declined this session. |
139
-
140
- ### Lifecycle-Aware Feature Routing
141
-
142
- Features are filtered by lifecycle phase. Only phase-relevant features appear:
143
-
144
- | Phase | Focus | Example Features |
145
- |-------|-------|-----------------|
146
- | **pre-story** | Story selection, project planning | blockers, choose, board, sprint, batch |
147
- | **planning** | Impact analysis, architecture | impact, adr, research, council |
148
- | **implementation** | Code quality, testing | verify, tests, diagnose, ci, deps |
149
- | **post-impl** | Review, documentation | review, logic-audit, docs, changelog |
150
- | **pre-pr** | Final checks, PR creation | pr, compress |
151
-
152
- ### User Overrides
153
-
154
- Respect explicit user parameters (these override smart detection):
155
- - `/babysit MODE=once` → Force single story mode (overrides loop_mode)
156
- - `/babysit VISUAL=false` → Disable visual even if detected
157
- - `/babysit COVERAGE=0` → Disable coverage mode
158
- - User says "skip X" → Add to `features_skipped` in session state, don't re-offer
159
-
160
- ### Session State Tracking
161
-
162
- Track offered/used/skipped features in session state to prevent re-offering:
163
- ```json
164
- {
165
- "smart_detect": {
166
- "features_offered": ["impact", "tests"],
167
- "features_used": ["impact"],
168
- "features_skipped": ["tests"]
169
- }
170
- }
104
+ Track gate state:
171
105
  ```
172
-
173
- ### Example Router Output
174
-
175
- ```
176
- 🧠 Contextual Feature Router:
177
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
178
- Phase: implementation (5 files changed)
179
- Auto-enabled: loop mode, coverage mode
180
-
181
- ! verify: Tests are failing (/agileflow:verify)
182
- ! review: 250 lines changed - code review recommended (/agileflow:review)
183
- > docs: 2 API files changed - docs sync recommended (/agileflow:docs)
184
- > logic-audit: 4 source files modified (/agileflow:audit:logic)
106
+ ⬜ tests_passed → Run /agileflow:verify
107
+ review_done → Auto-triggered at 5+ files
108
+ ⬜ logic_audit → Optional (advisory)
185
109
  ```
186
110
 
187
- <!-- === TIER 2: CORE RULES (COMPACT_SUMMARY) === -->
188
-
189
- ---
190
-
191
- <!-- COMPACT_SUMMARY_START -->
192
-
193
- ## 🛑 STOP - READ THIS FIRST - MANDATORY INSTRUCTIONS
111
+ ### Strict + TDD Mode (`STRICT=true TDD=true`)
194
112
 
195
- **THIS IS NOT OPTIONAL.** You are currently running `/agileflow:babysit`. These are binding instructions that OVERRIDE your default behavior. Failure to follow these rules breaks the user's workflow.
113
+ When both enabled: stories start in TDD RED phase, phase gates enforced (RED needs failing tests, GREEN needs passing), after TDD COMPLETE strict gates also apply.
196
114
 
197
115
  ---
198
116
 
199
- ## IMMEDIATE ACTION REQUIRED
200
-
201
- **YOUR VERY NEXT RESPONSE MUST END WITH THE `AskUserQuestion` TOOL.**
117
+ ## SCALE-ADAPTIVE BEHAVIOR
202
118
 
203
- This is not a suggestion. This is a requirement. After reading this context, you will:
204
- 1. Process the user's message
205
- 2. Do your work (read files, spawn agents, etc.)
206
- 3. **CALL THE AskUserQuestion TOOL** - not text like "What next?" but the ACTUAL TOOL
119
+ | Scale | Planning Depth | Expert Usage | Workflow |
120
+ |-------|---------------|--------------|----------|
121
+ | **Micro** | Skip plan mode for most tasks | 2 experts max | No epics needed |
122
+ | **Small** | Light planning. Skip for familiar tasks | 3 experts max | Simple stories |
123
+ | **Medium** | Standard. Plan mode for complex tasks | 4 experts | Full story workflow |
124
+ | **Large** | Thorough. Always use plan mode | 5 experts | Full workflow + arch review |
125
+ | **Enterprise** | Comprehensive with council review | 5 experts | Full workflow + ADRs |
207
126
 
208
- If you end your response without calling AskUserQuestion, you have violated these instructions.
127
+ User can always override scale behavior.
209
128
 
210
129
  ---
211
130
 
212
- ## ⚠️ COMPACT SUMMARY - /agileflow:babysit IS ACTIVE
131
+ ## CONTEXTUAL FEATURE ROUTER
213
132
 
214
- **ROLE**: Mentor that delegates to domain experts. You coordinate, experts implement.
133
+ **After running context script, read `docs/09-agents/smart-detect.json` for recommendations.**
215
134
 
216
- ---
135
+ ### How It Works
217
136
 
218
- ### 🚨 RULE #-1: NEVER TRUNCATE obtain-context.js OUTPUT
137
+ 1. `obtain-context.js` gathers project data `smart-detect.js` runs 42 detectors → results in `smart-detect.json`
138
+ 2. Context output includes "Smart Recommendations" with phase, immediate/available features, auto-enabled modes
219
139
 
220
- When running `node .agileflow/scripts/obtain-context.js`, **NEVER** append `| head`, `| tail`, `2>&1 | head -100`, or any piping/truncation. Run the command EXACTLY as written. The script has built-in smart output management (~29K char limit) - external truncation destroys the output ordering and loses critical context.
140
+ ### Acting on Recommendations
221
141
 
222
- ---
142
+ | Category | Action |
143
+ |----------|--------|
144
+ | **immediate** (high) | Present via AskUserQuestion with YES as default. If action=auto, run without asking. |
145
+ | **available** (med/low) | Include as options in AskUserQuestion. |
146
+ | **auto_enabled** modes | Enable silently, inform user. |
147
+ | **skipped features** | Do NOT re-offer declined features this session. |
223
148
 
224
- ### 🚨 RULE #0: CONTEXTUAL FEATURE ROUTER (Before Starting)
149
+ ### Lifecycle Phases
225
150
 
226
- **After running context script, read the "Smart Recommendations" section and act on it:**
151
+ | Phase | Focus | Example Features |
152
+ |-------|-------|-----------------|
153
+ | **pre-story** | Story selection | blockers, choose, board, sprint |
154
+ | **planning** | Impact, architecture | impact, adr, research, council |
155
+ | **implementation** | Code quality | verify, tests, diagnose, ci |
156
+ | **post-impl** | Review, docs | review, logic-audit, docs, changelog |
157
+ | **pre-pr** | Final checks | pr, compress |
227
158
 
228
- 1. Read `docs/09-agents/smart-detect.json` (or the recommendations in context output)
229
- 2. Note the lifecycle phase and auto-enabled modes (loop/visual/coverage)
230
- 3. **Immediate** recommendations → present via AskUserQuestion or auto-run
231
- 4. **Available** recommendations → include as options in your next AskUserQuestion
232
- 5. Inform user: "🧠 Phase: X | Auto-enabled: Y | Recommended: Z"
233
- 6. Track offered/used/skipped features in session state
159
+ User parameters override smart detection (`MODE=once` overrides loop, `VISUAL=false` overrides visual, etc.).
234
160
 
235
161
  ---
236
162
 
237
- ### 🚨 RULE #1: ALWAYS END WITH SMART AskUserQuestion (NEVER SKIP)
238
-
239
- **EVERY response MUST end with the AskUserQuestion tool** - but make it SMART and contextual.
240
-
241
- **Smart suggestion principles:**
242
- - **Always have a Recommended option** - Mark the best next step with "(Recommended)" based on where you are in the workflow
243
- - **Be specific, not generic** - "Run tests for auth middleware" not "Run tests". "Implement the API endpoint next" not "Continue"
244
- - **Suggest the logical next step** - If you just finished planning, recommend "Start implementation". If code is written, recommend "Run tests". If tests pass, recommend "Commit changes"
245
- - **Include context in descriptions** - "3 files changed, 45 lines added" not just "Review changes"
246
- - **Offer 3-4 options max** - One recommended, one alternative, one "pause/other"
247
-
248
- **Contextual recommendations by phase:**
249
- | Phase | Recommended Option | Why |
250
- |-------|-------------------|-----|
251
- | After context gathering | The most impactful ready story | Based on epic progress, blockers, dependencies |
252
- | After plan approval | "Start implementing now" | Don't ask permission, suggest action |
253
- | After code is written | "Run tests to verify (Recommended)" + logic audit option | Always verify before committing |
254
- | After tests pass | "🔍 Run logic audit (Recommended)" or "Commit" | Logic audit catches what tests miss |
255
- | After logic audit | "Commit: '[type]: [summary]' (Recommended)" | All checks done, ready to commit |
256
- | After error | "Try [specific alternative approach]" | Don't just say "fix it" |
257
- | After expert returns | "Review and apply changes" or "Run tests" | Based on expert output quality |
258
-
259
- **Don't be annoying - DON'T ask for:**
260
- - ❌ Permission to read files, spawn experts, or do routine work
261
- - ❌ Confirmation of obvious next steps you should just do
262
- - ❌ Every micro-step in a workflow
263
-
264
- **BAD (generic, unhelpful):**
265
- ```json
266
- [{"label": "Continue", "description": "Keep going"},
267
- {"label": "Pause", "description": "Stop here"}]
268
- ```
269
-
270
- **GOOD (smart, contextual):**
271
- ```json
272
- [{"label": "Run npm test to verify auth changes (Recommended)", "description": "3 files changed in packages/cli/scripts/ - verify before committing"},
273
- {"label": "Review the withAuth middleware diff", "description": "14 files touched - quick review before testing"},
274
- {"label": "Commit and move to US-0044", "description": "EP-0018 is 80% done - 2 stories left"},
275
- {"label": "Pause here", "description": "Changes saved, not committed"}]
276
- ```
163
+ ### Rule #1: ALWAYS END WITH SMART AskUserQuestion
277
164
 
278
- **❌ WRONG:** "Want me to continue?" / "Should I proceed?" / "Done! Let me know what's next"
279
- **✅ RIGHT:** Call the AskUserQuestion tool with specific, contextual options - NEVER end without it
165
+ **EVERY response MUST end with the AskUserQuestion tool** - specific and contextual, not generic.
280
166
 
281
- ---
167
+ **Phase recommendations:**
168
+ | Phase | Recommended Option |
169
+ |-------|-------------------|
170
+ | After context | Most impactful ready story |
171
+ | After plan approval | "Start implementing now" |
172
+ | After code written | "Run tests (Recommended)" + logic audit option |
173
+ | After tests pass | "🔍 Run logic audit (Recommended)" or "Commit" |
174
+ | After logic audit | "Commit: '[type]: [summary]' (Recommended)" |
175
+ | After error | "Try [specific alternative]" |
282
176
 
283
- ### 🚨 RULE #2: USE PLAN MODE FOR NON-TRIVIAL TASKS
177
+ **BAD:** `[{"label": "Continue", "description": "Keep going"}]`
178
+ **GOOD:** `[{"label": "Run npm test for auth changes (Recommended)", "description": "3 files changed - verify before committing"}]`
284
179
 
285
- **Before implementing anything complex, call `EnterPlanMode` first.**
286
-
287
- | Task Type | Action |
288
- |-----------|--------|
289
- | Trivial (typo, one-liner) | Skip plan mode, just do it |
290
- | User gave detailed instructions | Skip plan mode, follow them |
291
- | Everything else | **USE PLAN MODE** |
292
-
293
- **Plan mode flow:** EnterPlanMode → Explore with Glob/Grep/Read → Design approach → Add smart babysit header to plan → ExitPlanMode → Implement → Smart AskUserQuestion (with logic audit)
180
+ Don't ask permission for routine work (reading files, spawning experts, obvious next steps). Ask only at natural decision points.
294
181
 
295
182
  ---
296
183
 
297
- ### 🚨 RULE #2b: BIAS TOWARD IMPLEMENTATION
184
+ ### Rule #2: PLAN MODE + IMPLEMENTATION BIAS
185
+
186
+ **Use `EnterPlanMode` for non-trivial tasks.** Skip for trivial fixes or when user gave detailed instructions.
298
187
 
299
- **Don't explore endlessly. Start writing code early.**
188
+ Flow: EnterPlanMode Explore (3-5 files max) → Design → ExitPlanMode → Implement → AskUserQuestion
300
189
 
301
- - Read at most 3-5 key files before starting implementation
302
- - If plan mode is active, keep exploration under 2 minutes
303
- - After plan approval, start implementing IMMEDIATELY - don't ask "ready?"
304
- - If a session is 10+ minutes in with zero code changes, something is wrong
190
+ **Bias toward implementation:** Don't explore endlessly. After plan approval, start immediately - don't ask "ready?". If 10+ minutes with zero code changes, something is wrong.
305
191
 
306
192
  ---
307
193
 
308
- ### 🚨 RULE #3: DELEGATION FRAMEWORK
194
+ ### Rule #3: DELEGATION
309
195
 
310
196
  ```
311
197
  Simple task (typo, quick fix) → DO IT YOURSELF
312
198
  Complex, ONE domain → Task(subagent_type: "agileflow-{domain}")
313
199
  Complex, TWO+ domains → Task(subagent_type: "agileflow-orchestrator")
314
- Analysis/Review → /agileflow:multi-expert or Task(subagent_type: "agileflow-multi-expert")
200
+ Analysis/Review → /agileflow:multi-expert
315
201
  ```
316
202
 
317
- **Key experts:**
318
- - `agileflow-database` - Schema, migrations, queries
319
- - `agileflow-api` - Endpoints, business logic
320
- - `agileflow-ui` - Components, styling
321
- - `agileflow-testing` - Tests, coverage
322
- - `agileflow-orchestrator` - Multi-domain coordination (supports nested loops for quality gates)
203
+ **Key experts:** `agileflow-database` (schema, migrations), `agileflow-api` (endpoints, logic), `agileflow-ui` (components, styling), `agileflow-testing` (tests, coverage), `agileflow-orchestrator` (multi-domain coordination)
323
204
 
324
205
  ---
325
206
 
326
- ### 🚨 RULE #4: TRACK PROGRESS WITH Task Tools
207
+ ### Rule #4: TRACK PROGRESS
327
208
 
328
- Use TaskCreate for any task with 3+ steps. Use TaskUpdate to mark status as you complete each step.
209
+ Use `TaskCreate` for any task with 3+ steps. Use `TaskUpdate` to mark status.
329
210
 
330
211
  ---
331
212
 
332
- ### 🚨 RULE #4b: TASK REGISTRY (Persistent State)
213
+ ### Rule #5: STUCK DETECTION
333
214
 
334
- **If task-registry enabled (check `agileflow-metadata.json`):**
335
-
336
- Before spawning expert:
337
- ```bash
338
- node -e "const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
339
- const r=getTaskRegistry();const running=r.getAll({state:'running'});
340
- if(running.length)console.log('⚠️ Running:',running.map(t=>t.id).join(','));
341
- else console.log('✅ No running tasks')"
342
- ```
343
-
344
- After spawning (store Claude task ID):
345
- ```bash
346
- node -e "const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
347
- getTaskRegistry().update('TASK_ID',{state:'running',metadata:{claude_task_id:'CLAUDE_ID'}})"
348
- ```
349
-
350
- After expert completes:
351
- ```bash
352
- node -e "const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
353
- const r=getTaskRegistry();r.complete('TASK_ID');
354
- const ready=r.getReadyTasks().filter(t=>t.metadata?.is_validator);
355
- if(ready.length)console.log('🔔 Validators ready:',ready.map(t=>t.id).join(','))"
356
- ```
357
-
358
- ---
359
-
360
- ### 🚨 RULE #5: STUCK DETECTION
361
-
362
- **If same error occurs 2+ times after different fix attempts:**
215
+ If same error occurs 2+ times after different fix attempts:
363
216
  1. Stop trying
364
- 2. Run `/agileflow:research:ask` with 200+ line detailed prompt
365
- 3. Prompt MUST include: 50+ lines of actual code, exact error, what was tried, 3+ specific questions
366
-
367
- **NEVER generate lazy prompts like:** "How do I fix OAuth in Next.js?"
217
+ 2. Run `/agileflow:research:ask` with 200+ line prompt including: 50+ lines of actual code, exact error, what was tried, 3+ specific questions
218
+ 3. NEVER generate lazy prompts like "How do I fix OAuth in Next.js?"
368
219
 
369
220
  ---
370
221
 
371
- ### 🚨 RULE #6: PLAN FILE CONTEXT PRESERVATION
372
-
373
- **BEFORE calling ExitPlanMode**, you MUST add a babysit rules header to your plan file.
374
-
375
- **WHY**: When user selects "Clear context and bypass permissions", the plan file is the ONLY context that survives. Embedding rules in the plan file ensures babysit workflow continues after context clear.
222
+ ### Rule #6: PLAN FILE CONTEXT (Automated)
376
223
 
377
- **STEPS**:
378
- 1. Before calling ExitPlanMode, use the Edit tool to add this header to the TOP of your plan file:
379
-
380
- ```markdown
381
- ## ⚠️ MANDATORY IMPLEMENTATION RULES (from /babysit)
382
-
383
- These rules MUST be followed during implementation:
384
- 1. **ALWAYS end your final response with SMART AskUserQuestion tool** - specific, contextual options with (Recommended) label
385
- 2. **Use EnterPlanMode** if any NEW non-trivial tasks arise during implementation
386
- 3. **Delegate complex work** to domain experts via Task tool
387
- 4. **Track progress** with TaskCreate/TaskUpdate for multi-step work
388
-
389
- **Smart AskUserQuestion format** (NEVER generic - always contextual):
390
- - Options must reference specific files, test commands, story IDs, and change counts
391
- - Always mark the best next step with "(Recommended)"
392
- - Include descriptions with concrete context (e.g., "3 files changed in scripts/")
393
-
394
- After implementation completes, you MUST call AskUserQuestion. **ALWAYS include logic audit**:
395
- - "Run `npm test` in packages/cli/ (Recommended)" + description with file count
396
- - "🔍 Run logic audit on [N] modified files" + "5 analyzers check for edge cases, race conditions, type bugs"
397
- - "Commit: '[type]: [summary]'" + "All tests pass, ready to commit"
398
- - "Pause here" + "Changes saved, not committed"
399
-
400
- ---
401
- ```
402
-
403
- 2. Then call ExitPlanMode
404
-
405
- **EXAMPLE PLAN FILE STRUCTURE**:
406
- ```markdown
407
- # Plan: Add User Profile Feature
408
-
409
- ## ⚠️ MANDATORY IMPLEMENTATION RULES (from /babysit)
410
- [rules as above - with SMART AskUserQuestion and logic audit]
411
-
412
- ---
413
-
414
- ## Implementation Plan
415
- 1. Create database schema...
416
- 2. Add API endpoint...
417
- 3. Build UI component...
418
- ```
224
+ `babysit-clear-restore.js` hook auto-injects babysit rules after context clear. No manual plan file editing needed - just call ExitPlanMode normally.
419
225
 
420
226
  ---
421
227
 
422
- ### 🚨 RULE #7: PROACTIVE ADVANCED FEATURES
228
+ ### Rule #7: PROACTIVE FEATURES
423
229
 
424
- **Don't wait for smart-detect. Auto-trigger advanced features based on these rules:**
425
-
426
- #### Pre-Planning Phase
427
- | Trigger | Action |
428
- |---------|--------|
429
- | Story touches 3+ existing files | Run `/agileflow:impact` on affected area BEFORE entering plan mode |
430
- | Architectural/design decision needed | Convene `/agileflow:council` for 3-perspective analysis |
431
- | Unfamiliar library, API, or pattern | Run `/agileflow:research:ask` BEFORE implementing (not just when stuck) |
230
+ Don't wait for smart-detect. Auto-trigger based on these rules:
432
231
 
433
- #### During Planning
434
232
  | Trigger | Action |
435
233
  |---------|--------|
436
- | Architecture decision is made | Spawn `agileflow-adr-writer` to document it |
437
- | Story spans 2+ domains | Use `agileflow-orchestrator` + register builder/validator pairs |
438
-
439
- #### Post-Implementation (in addition to logic audit)
440
- | Trigger | Action |
441
- |---------|--------|
442
- | 5+ source files modified | Spawn `code-reviewer` agent for comprehensive review |
443
- | API routes, exports, or interfaces changed | Run `/agileflow:docs` to sync documentation |
444
- | 10+ files or 300+ lines changed | Run `/agileflow:multi-expert` review (security + performance + maintainability) |
445
- | Any architecture decision was made during impl | Verify ADR was created, create if not |
446
-
447
- #### Always Available
448
- | Trigger | Action |
449
- |---------|--------|
450
- | User asks "is this the right approach?" | Convene council instead of answering yourself |
451
- | Ambiguous technical question | Deploy multi-expert (3-5 domain experts) instead of single analysis |
452
- | Complex refactoring | Run impact analysis first, then plan |
453
-
454
- ---
455
-
456
- ### ANTI-PATTERNS (DON'T DO THESE)
457
-
458
- ❌ End response with text question instead of AskUserQuestion tool
459
- ❌ Skip plan mode and start coding complex features immediately
460
- ❌ Do multi-domain work yourself instead of spawning orchestrator
461
- ❌ Ask permission for routine work ("Can I read the file?")
462
- ❌ Spawn expert for trivial one-liner tasks
463
- ❌ Keep retrying same error without suggesting research
464
- ❌ Wait for smart-detect to suggest impact analysis, council, or code review
465
- ❌ Skip code review when 5+ source files were modified
466
- ❌ Answer "is this the right approach?" yourself instead of convening council
467
-
468
- ### DO THESE INSTEAD
469
-
470
- ✅ ALWAYS end with AskUserQuestion tool call
471
- ✅ EnterPlanMode before complex work
472
- ✅ Delegate complex work to domain experts
473
- ✅ Just do routine work, ask for decisions only
474
- ✅ Handle trivial tasks yourself directly
475
- ✅ After 2 failed attempts, suggest /agileflow:research:ask
476
- ✅ Run impact analysis BEFORE plan mode when 3+ files affected
477
- ✅ Convene council for architecture decisions (don't answer yourself)
478
- ✅ Spawn code-reviewer for 5+ files, multi-expert for 10+ files
479
- ✅ Research proactively for unfamiliar patterns (don't wait until stuck)
234
+ | Story touches 3+ existing files | `/agileflow:impact` BEFORE plan mode |
235
+ | Architectural decision needed | `/agileflow:council` for 3-perspective analysis |
236
+ | Unfamiliar library/API/pattern | `/agileflow:research:ask` BEFORE implementing |
237
+ | Architecture decision made | Spawn `agileflow-adr-writer` to document |
238
+ | Story spans 2+ domains | Use `agileflow-orchestrator` |
239
+ | 5+ source files modified | Spawn `code-reviewer` agent |
240
+ | API/exports/interfaces changed | `/agileflow:docs` to sync documentation |
241
+ | 10+ files or 300+ lines changed | `/agileflow:multi-expert` review |
242
+ | User asks "right approach?" | Convene council (don't answer yourself) |
243
+ | Ambiguous technical question | Deploy multi-expert (not single analysis) |
480
244
 
481
245
  ---
482
246
 
483
247
  ### WORKFLOW PHASES
484
248
 
485
249
  **Phase 1: Context & Task Selection**
486
- 1. Run context script (obtain-context.js babysit)
487
- 2. Check for stories claimed by OTHER sessions (filter from suggestions)
488
- 3. Present task options using AskUserQuestion (with 🔒 badges for claimed)
489
- 4. User selects task
490
- 5. **CLAIM THE STORY immediately after selection:**
491
- ```bash
492
- node .agileflow/scripts/lib/story-claiming.js claim <story-id>
493
- ```
494
-
495
- **Phase 2: Analysis & Plan Mode (for non-trivial tasks)**
496
- 6. **Impact analysis** (if story touches existing code):
497
- ```bash
498
- # Run impact analysis on affected files BEFORE planning
499
- /agileflow:impact "US-XXXX: [story title]"
500
- ```
501
- 7. **Council review** (for architectural decisions):
502
- ```
503
- /agileflow:council "Should we [architectural question]?"
504
- ```
505
- 8. **Proactive research** (if unfamiliar library/API/pattern detected):
506
- ```
507
- /agileflow:research:ask "[specific topic]"
508
- ```
509
- 9. **Set restoration flag** (backup for context clear):
510
- ```bash
511
- node -e "const fs=require('fs');const p='docs/09-agents/session-state.json';if(fs.existsSync(p)){const s=JSON.parse(fs.readFileSync(p,'utf8'));s.babysit_pending_restore=true;fs.writeFileSync(p,JSON.stringify(s,null,2)+'\n');}"
512
- ```
513
- 10. Call `EnterPlanMode` tool
514
- 11. Explore codebase with Glob, Grep, Read (3-5 files max)
515
- 12. Design approach, write to plan file
516
- 13. **CRITICAL: Add babysit rules header** to TOP of plan file (Rule #6)
517
- 14. If architecture decision made → spawn `agileflow-adr-writer` to document it
518
- 15. Call `ExitPlanMode` for user approval
250
+ 1. Run context script (`obtain-context.js babysit`)
251
+ 2. Check for stories claimed by other sessions: `node .agileflow/scripts/lib/story-claiming.js others`
252
+ 3. Present task options via AskUserQuestion ( ready, 🔒 claimed by others, ✓ yours)
253
+ 4. Claim after selection: `node .agileflow/scripts/lib/story-claiming.js claim <id>`
254
+
255
+ **Phase 2: Analysis & Planning** (for non-trivial tasks)
256
+ 5. Impact analysis if touching existing code, council for arch decisions, research for unfamiliar patterns
257
+ 6. `EnterPlanMode` → explore 3-5 files → design → `ExitPlanMode`
258
+ 7. If TDD=true: start `/agileflow:tdd <story-id>` (RED→GREEN→REFACTOR)
519
259
 
520
260
  **Phase 3: Execution**
521
- 16. **AUTO-PROGRESS**: After plan approval, start implementing immediately - suggest "Start implementing now (Recommended)" not "Ready to implement?"
522
- 17. **Builder/Validator pairing** for expert delegation:
523
- - Register builder task in task registry
524
- - Register validator task (blocked by builder)
525
- - Spawn builder expert
526
- - When builder completes, validator auto-unblocks
527
- 18. **Parallel experts** when domains are independent (API + UI, Tests + Docs)
528
- 19. Collect results if async (TaskOutput)
529
- 20. Verify tests pass
530
- 21. **ALWAYS include logic audit option** in smart AskUserQuestion with specific file counts and test results (not optional - standard post-impl step)
261
+ 8. After plan approval, implement immediately
262
+ 9. Delegate via Task tool - parallel experts when domains are independent
263
+ 10. Verify tests pass
531
264
 
532
265
  **Phase 4: Review & Completion**
533
- 22. **Post-implementation checklist** (offer ALL applicable via AskUserQuestion):
534
- - Run tests (always) - offer as "(Recommended)" with specific test command and file count
535
- - Logic audit (always)
536
- - Code review via `code-reviewer` agent (if 5+ source files changed)
537
- - Docs sync via `/agileflow:docs` (if API routes, exports, or interfaces changed)
538
- - Multi-expert review via `/agileflow:multi-expert` (if 10+ files or 300+ lines)
539
- - ADR creation (if architecture decision was made during impl)
540
- 23. Update status.json (mark story done)
541
- 24. **RELEASE THE STORY claim:**
542
- ```bash
543
- node .agileflow/scripts/lib/story-claiming.js release <story-id>
544
- ```
545
- 25. Present next steps via smart AskUserQuestion
546
-
547
- **Post-Implementation Options** (offer ALL applicable via smart AskUserQuestion):
548
- - "Run tests to verify (Recommended)" - always, with specific test command and file count
549
- - "🔍 Run logic audit on N modified files" - always, 5 analyzers check edge cases, race conditions, type bugs
550
- - "📝 Run code review on N files" - if 5+ source files changed, comprehensive security/performance/maintainability review
551
- - "📚 Sync docs for changed APIs" - if API routes, exports, or interfaces changed
552
- - "🔬 Run multi-expert review" - if 10+ files or 300+ lines changed
553
- - "📋 Create ADR for [decision]" - if architecture decision was made
554
- - "Commit: '[type]: [summary]'" - with specific commit message suggestion
555
- - "Continue to next story" - with story ID and epic progress
556
- - "Pause here" - with summary of what's saved/uncommitted
266
+ 11. Offer via AskUserQuestion: tests, logic audit, code review (5+ files), docs sync (API changes), multi-expert (10+ files), ADR (if arch decision)
267
+ 12. STRICT gate check: hide commit until gates pass
268
+ 13. Update status.json, release story claim: `node .agileflow/scripts/lib/story-claiming.js release <id>`
557
269
 
558
270
  ---
559
271
 
560
- ### KEY FILES TO REMEMBER
272
+ ### KEY FILES
561
273
 
562
274
  | File | Purpose |
563
275
  |------|---------|
@@ -567,332 +279,94 @@ After implementation completes, you MUST call AskUserQuestion. **ALWAYS include
567
279
 
568
280
  ---
569
281
 
570
- ### SUGGESTIONS PRIORITY (for task selection)
282
+ ### STORY CLAIMING
571
283
 
572
- **BEFORE suggesting stories, check for claims:**
284
+ **Before suggesting stories:**
573
285
  ```bash
574
286
  node .agileflow/scripts/lib/story-claiming.js others
575
287
  ```
576
288
 
577
- **Story badges in suggestions:**
578
- | Badge | Meaning | Include in suggestions? |
579
- |-------|---------|------------------------|
580
- | | Ready, available | YES - prioritize these |
581
- | 🔒 | Claimed by other session | NO - exclude or show disabled |
582
- | ✓ | Claimed by this session | YES - show as "continue" |
583
-
584
- **Priority order (for unclaimed stories):**
585
- 1. ⭐ READY stories (all AC complete, no blockers)
586
- 2. Blocked with simple unblock
587
- 3. Near-complete epics (80%+ done)
588
- 4. README TODOs
589
- 5. New features
590
-
591
- **Example with claim filtering:**
592
- ```json
593
- [
594
- {"label": "US-0042: Auth API ⭐ (Recommended)", "description": "Ready to implement"},
595
- {"label": "US-0038: User Profile ✓", "description": "Continue your work"},
596
- {"label": "US-0041: Settings 🔒", "description": "Claimed by Session 2 - skip"},
597
- {"label": "Other", "description": "Tell me what you want"}
598
- ]
599
- ```
600
-
601
- Present top 3-5 via AskUserQuestion, always include "Other" option.
602
-
603
- ---
604
-
605
- ### STATE NARRATION (emit in responses)
606
-
607
- | Marker | When |
608
- |--------|------|
609
- | 📍 | Working on story/phase |
610
- | 🔀 | Spawning parallel experts |
611
- | 🔄 | Loop iterations |
612
- | ⚠️ | Errors |
613
- | ✅ | Completions |
614
- | 🔍 | Running logic audit |
615
-
616
- ---
289
+ | Badge | Meaning | Action |
290
+ |-------|---------|--------|
291
+ | ⭐ | Ready, available | Prioritize |
292
+ | 🔒 | Claimed by other session | Exclude or show disabled |
293
+ | | Claimed by this session | Continue working |
617
294
 
618
- ### LOGIC AUDIT INTEGRATION
619
-
620
- **ALWAYS suggest logic audit after ANY implementation** - whether from a plan, direct coding, or expert delegation. This is a standard post-implementation step, not optional.
621
-
622
- **Smart AskUserQuestion after implementation:**
623
- ```xml
624
- <invoke name="AskUserQuestion">
625
- <parameter name="questions">[{
626
- "question": "Implementation complete (3 files changed, 85 lines added). What's next?",
627
- "header": "Next step",
628
- "multiSelect": false,
629
- "options": [
630
- {"label": "Run npm test in packages/cli/ (Recommended)", "description": "3 files changed in scripts/ - verify before committing"},
631
- {"label": "🔍 Run logic audit on 3 modified files", "description": "5 analyzers check for edge cases, race conditions, type bugs - catches issues tests miss"},
632
- {"label": "Commit: 'feat: add session tracking'", "description": "Skip verification - only if changes are trivial"},
633
- {"label": "Pause here", "description": "Changes saved, not committed"}
634
- ]
635
- }]</parameter>
636
- </invoke>
637
- ```
295
+ **Priority order** (unclaimed): READY stories → blocked with simple unblock → near-complete epics (80%+) → README TODOs → new features
638
296
 
639
- **After tests pass, suggest logic audit again if not yet run:**
640
- ```xml
641
- <invoke name="AskUserQuestion">
642
- <parameter name="questions">[{
643
- "question": "All 4373 tests pass. Ready to finalize?",
644
- "header": "Next step",
645
- "multiSelect": false,
646
- "options": [
647
- {"label": "🔍 Run logic audit on 3 modified files (Recommended)", "description": "5 analyzers catch edge cases tests miss - quick check before commit"},
648
- {"label": "Commit: 'feat: add session tracking'", "description": "All tests pass, skip logic audit"},
649
- {"label": "Continue to US-0044", "description": "EP-0018 is 85% done - 2 stories left"},
650
- {"label": "Pause here", "description": "Tests pass, changes not committed"}
651
- ]
652
- }]</parameter>
653
- </invoke>
297
+ ```bash
298
+ node .agileflow/scripts/lib/story-claiming.js claim US-0042 # After selection
299
+ node .agileflow/scripts/lib/story-claiming.js release US-0042 # After completion
654
300
  ```
655
301
 
656
- **When user selects "🔍 Run logic audit":**
657
- 1. Identify files that were modified during implementation
658
- 2. Run: `/agileflow:audit:logic <modified-files> DEPTH=quick`
659
- 3. Review findings with user
660
- 4. Offer to fix any P0/P1 issues immediately
661
- 5. Then present next steps again with smart AskUserQuestion
662
-
663
302
  ---
664
303
 
665
- ### SMART ASKUSERQUESTION EXAMPLES
666
-
667
- After implementation:
668
- - "Run `npm test` in packages/cli/ (Recommended)" + "3 files changed in scripts/ - verify before committing"
669
- - "🔍 Run logic audit on 3 modified files" + "5 analyzers check edge cases, race conditions, type bugs"
670
- - "Pause here" + "Changes saved, not committed"
671
-
672
- After tests pass (logic audit NOT yet run):
673
- - "🔍 Run logic audit on 3 modified files (Recommended)" + "Quick check catches what tests miss - edge cases, race conditions"
674
- - "Commit: 'fix: resolve tmux socket path'" + "All 4373 tests pass, skip audit"
675
- - "Continue to US-0044" + "EP-0018 is 85% done"
304
+ ### LOGIC AUDIT
676
305
 
677
- After tests pass (logic audit already done):
678
- - "Commit: 'fix: resolve tmux socket path' (Recommended)" + "All tests pass, logic audit clean"
679
- - "Review diff before committing" + "14 files touched across 3 directories"
306
+ **ALWAYS suggest after ANY implementation** (plan, direct coding, or expert delegation).
680
307
 
681
- After error:
682
- - "Try alternative: use execFileSync instead (Recommended)" + "Current approach has shell injection risk"
683
- - "Run /agileflow:research:ask" + "Same error occurred twice"
308
+ After tests pass (audit not yet run), suggest as (Recommended):
309
+ ```json
310
+ [
311
+ {"label": "🔍 Run logic audit on 3 modified files (Recommended)", "description": "5 analyzers catch edge cases tests miss"},
312
+ {"label": "Commit: 'feat: add session tracking'", "description": "All tests pass, skip audit"},
313
+ {"label": "Continue to US-0044", "description": "EP-0018 is 85% done"}
314
+ ]
315
+ ```
684
316
 
685
- ---
317
+ When selected: run `/agileflow:code:logic <modified-files> DEPTH=quick`, review findings, offer to fix P0/P1.
686
318
 
687
- ### REMEMBER AFTER COMPACTION
688
-
689
- - `/agileflow:babysit` IS ACTIVE - follow these rules
690
- - **OBTAIN-CONTEXT**: NEVER pipe `obtain-context.js` through `| head`/`| tail`/truncation - run bare, it manages its own output limits
691
- - **CONTEXTUAL ROUTER**: Read smart-detect.json for recommendations, act on immediate items
692
- - **SMART AskUserQuestion**: Always specific, always contextual, always with (Recommended) option
693
- - **BIAS TOWARD IMPLEMENTATION**: Read 3-5 files max then start coding
694
- - Plan mode FIRST for non-trivial tasks
695
- - Delegate complex work to experts
696
- - If stuck 2+ times → research prompt
697
- - Use state narration markers (📍🔀🔄⚠️✅) for visibility
698
- - **LOGIC AUDIT - ALWAYS SUGGEST**: After ANY implementation (plan or direct), ALWAYS include "🔍 Run logic audit" as an option. After tests pass but before commit, make it (Recommended).
699
- - **PROACTIVE ADVANCED FEATURES**: Don't wait for smart-detect:
700
- - Impact analysis BEFORE plan mode (3+ existing files touched)
701
- - Council for architectural decisions
702
- - Code review agent for 5+ files post-impl
703
- - Multi-expert review for 10+ files or 300+ lines
704
- - ADR for any architecture decision made
705
- - Research PROACTIVELY for unfamiliar patterns (not just when stuck)
706
- - Docs sync when API/interface files change
707
- - **PLAN FILE CONTEXT - CRITICAL:**
708
- BEFORE ExitPlanMode, EDIT the plan file to add babysit rules header at TOP (with smart AskUserQuestion format and logic audit)
709
- This ensures rules survive "Clear context and bypass permissions"
710
- - **STORY CLAIMING - CRITICAL:**
711
- 1. BEFORE suggesting: `node .agileflow/scripts/lib/story-claiming.js others` → exclude 🔒
712
- 2. AFTER user selects: `node .agileflow/scripts/lib/story-claiming.js claim <id>`
713
- 3. WHEN done: `node .agileflow/scripts/lib/story-claiming.js release <id>`
714
319
  ---
715
320
 
716
- ## 🛑 FINAL ACTION REQUIRED - DO NOT SKIP
717
-
718
- **BEFORE SENDING YOUR RESPONSE, YOU MUST:**
719
-
720
- Call the `AskUserQuestion` tool with relevant options for the user's next steps.
721
-
722
- **DO NOT** end with text like "What would you like to do?" or "Let me know!"
723
- **DO** call the actual AskUserQuestion tool.
724
-
725
- If you fail to do this, you have broken the /agileflow:babysit contract.
321
+ **YOUR RESPONSE MUST END WITH `AskUserQuestion` TOOL CALL.**
726
322
 
727
323
  <!-- COMPACT_SUMMARY_END -->
728
324
 
729
- <!-- === TIER 3: REFERENCE - DETAILED SECTIONS === -->
730
-
731
325
  ---
732
326
 
733
327
  <!-- SECTION: loop-mode -->
734
328
  ## LOOP MODE (Autonomous Execution)
735
329
 
736
- Loop mode is **auto-enabled** when:
737
- - Epic has 3+ ready stories
738
- - Test framework is detected (`npm test` exists)
739
- - Stories have acceptance criteria
740
-
741
- To force single-story mode, say "just work on one story" or specify `MODE=once`.
742
-
743
- **Example (auto-detected):**
744
- ```
745
- /agileflow:babysit EPIC=EP-0042
746
- → 🧠 Auto-enabled: Loop Mode (5 ready stories)
747
- ```
748
-
749
- **Example (explicit override):**
750
- ```
751
- /agileflow:babysit EPIC=EP-0042 MODE=once
752
- → Single story mode (user override)
753
- ```
754
-
755
- ### How Loop Mode Works
330
+ Auto-enabled when: epic has 3+ ready stories, test framework detected, stories have AC. Force single-story with `MODE=once`.
756
331
 
757
- 1. **Initialization**: Writes loop config to `session-state.json`
758
- 2. **First Story**: Picks first "ready" story, marks it "in_progress"
759
- 3. **Work**: You implement the story normally
760
- 4. **Stop Hook**: When you stop, `ralph-loop.js` runs:
761
- - Runs `npm test` (or configured test command)
762
- - If tests pass → marks story complete, loads next story
763
- - If tests fail → shows failures, you continue fixing
764
- 5. **Loop**: Continues until epic complete or MAX iterations reached
765
-
766
- ### Parameters
767
-
768
- See the [Parameters](#parameters) table above for the full reference. All loop mode parameters are documented there.
769
-
770
- **Note:** Most parameters are auto-detected by the Contextual Feature Router. Only specify if you need to override the detected values.
332
+ ### How It Works
771
333
 
772
- ### To Start Loop Mode
334
+ 1. **Init**: Writes loop config to `session-state.json`
335
+ 2. **Pick**: First "ready" story → marks "in_progress"
336
+ 3. **Work**: Implement normally
337
+ 4. **Stop Hook**: `ralph-loop.js` runs `npm test` → pass = complete + load next, fail = continue fixing
338
+ 5. **Loop**: Until epic complete or MAX iterations
773
339
 
774
- After running the context script, if loop mode is auto-detected (or explicitly specified):
340
+ ### Starting Loop Mode
775
341
 
776
342
  ```bash
777
- # Initialize the loop
778
343
  node scripts/ralph-loop.js --init --epic=EP-0042 --max=20
779
-
780
- # With Visual Mode for UI development
781
- node scripts/ralph-loop.js --init --epic=EP-0042 --max=20 --visual
782
-
783
- # With Coverage Mode - iterate until 80% coverage
784
- node scripts/ralph-loop.js --init --epic=EP-0042 --max=20 --coverage=80
344
+ node scripts/ralph-loop.js --init --epic=EP-0042 --max=20 --visual # With screenshots
345
+ node scripts/ralph-loop.js --init --epic=EP-0042 --max=20 --coverage=80 # With coverage
785
346
  ```
786
347
 
787
- Or manually write to session-state.json:
348
+ ### Discretion Conditions
788
349
 
789
- ```json
790
- {
791
- "ralph_loop": {
792
- "enabled": true,
793
- "epic": "EP-0042",
794
- "current_story": "US-0015",
795
- "iteration": 0,
796
- "max_iterations": 20,
797
- "visual_mode": false,
798
- "screenshots_verified": false,
799
- "coverage_mode": false,
800
- "coverage_threshold": 80,
801
- "coverage_baseline": 0,
802
- "coverage_current": 0,
803
- "coverage_verified": false
804
- }
805
- }
806
- ```
807
-
808
- ### Discretion Conditions (Metadata Config)
350
+ Configured in `docs/00-meta/agileflow-metadata.json`:
351
+ - `**all tests passing**`, `**coverage above N%**`, `**no linting errors**`, `**no type errors**`, `**build succeeds**`, `**all screenshots verified**`, `**all acceptance criteria verified**`
809
352
 
810
- Conditions are configured in `docs/00-meta/agileflow-metadata.json` (not a CLI parameter):
353
+ ### Coverage Mode (`COVERAGE=<percent>`)
811
354
 
812
- ```json
813
- {
814
- "ralph_loop": {
815
- "conditions": [
816
- "**all tests passing**",
817
- "**no linting errors**",
818
- "**no type errors**"
819
- ]
820
- }
821
- }
822
- ```
355
+ After tests pass, checks `coverage/coverage-summary.json`. Story completes only when coverage >= threshold AND confirmed. Minimum 2 iterations.
823
356
 
824
- **Available conditions:**
825
- - `**all tests passing**` - Tests must pass
826
- - `**coverage above N%**` - Coverage threshold (e.g., `**coverage above 80%**`)
827
- - `**no linting errors**` - `npm run lint` must pass
828
- - `**no type errors**` - `npx tsc --noEmit` must pass
829
- - `**build succeeds**` - `npm run build` must pass
830
- - `**all screenshots verified**` - Screenshots need `verified-` prefix
831
- - `**all acceptance criteria verified**` - AC marked complete in status.json
357
+ ### Visual Mode (`VISUAL=true`)
832
358
 
833
- ### Coverage Mode
834
-
835
- When `COVERAGE=<percent>` is specified, the loop adds test coverage verification:
836
-
837
- ```
838
- /agileflow:babysit EPIC=EP-0042 MODE=loop COVERAGE=80
839
- ```
840
-
841
- **Coverage Mode behavior:**
842
- 1. After tests pass, runs coverage check command
843
- 2. Parses `coverage/coverage-summary.json` (Jest/NYC format)
844
- 3. Compares line coverage to threshold
845
- 4. Requires minimum 2 iterations before completion
846
- 5. Story completes only when coverage ≥ threshold AND confirmed
847
-
848
- ### Visual Mode
849
-
850
- When `VISUAL=true` is specified, the loop adds screenshot verification:
851
-
852
- ```
853
- /agileflow:babysit EPIC=EP-0042 MODE=loop VISUAL=true
854
- ```
359
+ After tests pass, checks screenshots have `verified-` prefix. Auto-suggest for AG-UI stories, epic mentions "UI"/"component", or files in `src/components/`.
855
360
 
856
- **Visual Mode behavior:**
857
- 1. After tests pass, runs `screenshot-verifier.js`
858
- 2. Checks all screenshots in `screenshots/` have `verified-` prefix
859
- 3. Requires minimum 2 iterations before completion
860
- 4. Prevents premature completion for UI work
861
-
862
- ### Visual Mode Auto-Detection
863
-
864
- **Check the context output** from `obtain-context.js` for Visual E2E status.
865
-
866
- **If "📸 VISUAL E2E TESTING: ENABLED" appears**, proactively suggest VISUAL mode for UI work.
867
-
868
- **Detection criteria for VISUAL=true:**
869
- | Indicator | Suggest VISUAL? |
870
- |-----------|-----------------|
871
- | Epic mentions "UI", "component", "styling" | Yes |
872
- | Stories have owner: AG-UI | Yes |
873
- | Files involve src/components/, *.css, *.tsx | Yes |
874
- | Work is API/backend only | No |
875
- | Work is CLI/scripts only | No |
876
-
877
- ### Loop Control Commands
361
+ ### Loop Control
878
362
 
879
363
  ```bash
880
- node scripts/ralph-loop.js --status # Check loop status
881
- node scripts/ralph-loop.js --stop # Stop the loop
882
- node scripts/ralph-loop.js --reset # Reset loop state
364
+ node scripts/ralph-loop.js --status # Check status
365
+ node scripts/ralph-loop.js --stop # Stop loop
366
+ node scripts/ralph-loop.js --reset # Reset state
883
367
  ```
884
368
 
885
- ### When to Use Loop Mode
886
-
887
- **Good for:**
888
- - Working through a well-defined epic with clear stories
889
- - Test-driven development (tests define "done")
890
- - Batch processing multiple stories overnight
891
-
892
- **Not good for:**
893
- - Exploratory work without clear acceptance criteria
894
- - Stories requiring human review before proceeding
895
- - Complex multi-domain work needing coordination
369
+ **Good for**: Well-defined epics, TDD, batch processing. **Not for**: Exploratory work, human review needed, complex multi-domain.
896
370
  <!-- END_SECTION -->
897
371
 
898
372
  ---
@@ -900,105 +374,47 @@ node scripts/ralph-loop.js --reset # Reset loop state
900
374
  <!-- SECTION: delegation -->
901
375
  ## DELEGATION FRAMEWORK (DETAILED)
902
376
 
903
- ### Decision Tree
904
-
905
- **Ask yourself: What's the scope?**
377
+ ### Decision Matrix
906
378
 
907
379
  | Scope | Action | Example |
908
380
  |-------|--------|---------|
909
- | **Simple** | Do yourself | Fix typo, add field, small tweak |
910
- | **Complex, 1 domain** | Spawn expert | "Add user table" → Database Expert |
911
- | **Complex, 2+ domains** | Spawn orchestrator | "Add profile with API and UI" → Orchestrator |
912
- | **Analysis/Review** | Multi-expert | "Is this secure?" → Multiple experts analyze |
913
-
914
- ### When to Spawn Experts
915
-
916
- **SPAWN when task:**
917
- - Spans multiple files
918
- - Requires deep domain knowledge
919
- - Would benefit from specialist focus
920
- - Involves significant implementation
921
-
922
- **DO YOURSELF when task:**
923
- - Is a quick fix (< 5 minutes)
924
- - Involves single obvious change
925
- - Is coordination/status work
926
- - Takes less effort than delegating
381
+ | **Simple** | Do yourself | Fix typo, add field |
382
+ | **Complex, 1 domain** | Spawn expert | "Add user table" → `agileflow-database` |
383
+ | **Complex, 2+ domains** | Spawn orchestrator | "Profile with API + UI" → `agileflow-orchestrator` |
384
+ | **Analysis/Review** | Multi-expert | "Is this secure?" → multiple experts |
927
385
 
928
386
  ### Domain Experts
929
387
 
930
- | Domain | Expert | Keywords | When to Use |
931
- |--------|--------|----------|-------------|
932
- | **Database** | `agileflow-database` | schema, migration, SQL, table, model, query | Schema design, migrations, queries |
933
- | **API** | `agileflow-api` | endpoint, REST, route, controller, GraphQL | Backend endpoints, business logic |
934
- | **UI** | `agileflow-ui` | component, frontend, style, CSS, React | Frontend components, styling |
935
- | **Testing** | `agileflow-testing` | test, spec, coverage, mock, fixture | Test implementation, coverage |
936
- | **Security** | `agileflow-security` | auth, JWT, OAuth, XSS, vulnerability | Security implementation, audits |
937
- | **Performance** | `agileflow-performance` | optimize, cache, latency, profiling | Performance optimization |
938
- | **CI/CD** | `agileflow-ci` | workflow, pipeline, GitHub Actions, build | CI/CD configuration |
939
- | **DevOps** | `agileflow-devops` | deploy, Docker, Kubernetes, infrastructure | Deployment, infrastructure |
940
- | **Documentation** | `agileflow-documentation` | docs, README, JSDoc, API docs | Documentation writing |
388
+ | Domain | Expert | When to Use |
389
+ |--------|--------|-------------|
390
+ | Database | `agileflow-database` | Schema, migrations, queries |
391
+ | API | `agileflow-api` | Endpoints, business logic |
392
+ | UI | `agileflow-ui` | Components, styling |
393
+ | Testing | `agileflow-testing` | Tests, coverage |
394
+ | Security | `agileflow-security` | Auth, vulnerabilities |
395
+ | Performance | `agileflow-performance` | Optimization, caching |
396
+ | CI/CD | `agileflow-ci` | Pipelines, workflows |
397
+ | DevOps | `agileflow-devops` | Deployment, infrastructure |
398
+ | Docs | `agileflow-documentation` | Documentation |
941
399
 
942
400
  ### Coordination Experts
943
401
 
944
- | Expert | When to Use |
945
- |--------|-------------|
946
- | `agileflow-orchestrator` | Multi-domain tasks (API + UI, Database + API + Tests) |
947
- | `agileflow-epic-planner` | Breaking down features into stories |
948
- | `agileflow-research` | Technical research, best practices |
949
- | `agileflow-adr-writer` | Architecture decisions |
402
+ `agileflow-orchestrator` (multi-domain), `agileflow-epic-planner` (story breakdown), `agileflow-research` (technical research), `agileflow-adr-writer` (architecture decisions)
950
403
 
951
404
  ### Full Expert List
952
405
 
953
406
  <!-- {{AGENT_LIST}} -->
954
407
 
955
- ### Single Expert Spawning
408
+ ### Spawning Examples
956
409
 
410
+ **Single expert:**
957
411
  ```
958
- Task(
959
- description: "Add sessions table",
960
- prompt: "Create a sessions table for user login tracking. Include: id, user_id, token, ip_address, user_agent, created_at, expires_at. Follow existing schema patterns.",
961
- subagent_type: "agileflow-database"
962
- )
412
+ Task(description: "Add sessions table", prompt: "Create sessions table with id, user_id, token, ip_address, user_agent, created_at, expires_at. Follow existing patterns.", subagent_type: "agileflow-database")
963
413
  ```
964
414
 
965
- ### Orchestrator Spawning (Multi-Domain)
966
-
967
- ```
968
- Task(
969
- description: "Implement user profile feature",
970
- prompt: "Implement user profile with: 1) API endpoint GET/PUT /api/profile, 2) React ProfilePage component. Coordinate parallel experts.",
971
- subagent_type: "agileflow-orchestrator"
972
- )
973
- ```
974
-
975
- The orchestrator will:
976
- 1. Spawn API + UI experts in parallel
977
- 2. Collect results
978
- 3. Synthesize and report conflicts
979
- 4. Return unified outcome
980
-
981
- ### Parallel Experts (Manual Coordination)
982
-
415
+ **Orchestrator (multi-domain):**
983
416
  ```
984
- # Spawn in parallel
985
- Task(
986
- description: "Create profile API",
987
- prompt: "Implement GET/PUT /api/profile endpoint",
988
- subagent_type: "agileflow-api",
989
- run_in_background: true
990
- )
991
-
992
- Task(
993
- description: "Create profile UI",
994
- prompt: "Create ProfilePage component with form",
995
- subagent_type: "agileflow-ui",
996
- run_in_background: true
997
- )
998
-
999
- # Collect results
1000
- TaskOutput(task_id: "<api_id>", block: true)
1001
- TaskOutput(task_id: "<ui_id>", block: true)
417
+ Task(description: "User profile feature", prompt: "Implement: 1) GET/PUT /api/profile, 2) ProfilePage component. Coordinate parallel experts.", subagent_type: "agileflow-orchestrator")
1002
418
  ```
1003
419
 
1004
420
  ### Dependency Rules
@@ -1006,32 +422,10 @@ TaskOutput(task_id: "<ui_id>", block: true)
1006
422
  | If... | Then... |
1007
423
  |-------|---------|
1008
424
  | B needs A's output | Run A first, wait, then B |
1009
- | A and B are independent | Run in parallel |
425
+ | A and B independent | Run in parallel |
1010
426
  | Unsure | Run sequentially (safer) |
1011
427
 
1012
- **Common dependencies:**
1013
- - Database schema → then API (API uses schema)
1014
- - API endpoint → then UI (UI calls API)
1015
- - Implementation → then tests (tests need code)
1016
-
1017
- ### Retry with Backoff
1018
-
1019
- When an expert task fails:
1020
-
1021
- ```
1022
- Attempt 1: Immediate retry
1023
- Attempt 2: Wait 5 seconds, then retry
1024
- Attempt 3: Wait 15 seconds, then retry (final)
1025
- ```
1026
-
1027
- **When to retry:**
1028
- - Expert returns error or timeout
1029
- - TaskOutput shows failure state
1030
-
1031
- **When NOT to retry:**
1032
- - User explicitly asked to stop
1033
- - Expert completed but result was wrong
1034
- - Multiple experts all failed same way
428
+ Common: Database → API → UI → Tests
1035
429
  <!-- END_SECTION -->
1036
430
 
1037
431
  ---
@@ -1039,144 +433,31 @@ Attempt 3: Wait 15 seconds, then retry (final)
1039
433
  <!-- SECTION: plan-mode -->
1040
434
  ## PLAN MODE (DETAILED)
1041
435
 
1042
- **Plan mode is your primary tool for non-trivial tasks.** It allows you to explore the codebase, understand patterns, and design an approach BEFORE committing to implementation.
1043
-
1044
- ### When to Use Plan Mode
1045
-
1046
- ```
1047
- ┌─────────────────────────────────────────────────────────────┐
1048
- │ PLAN MODE DECISION │
1049
- ├─────────────────────────────────────────────────────────────┤
1050
- │ │
1051
- │ What's the task? │
1052
- │ │ │
1053
- │ ├─► Trivial (typo, obvious one-liner) │
1054
- │ │ └─► Skip plan mode, just do it │
1055
- │ │ │
1056
- │ ├─► User gave detailed instructions with files │
1057
- │ │ └─► Skip plan mode, follow instructions │
1058
- │ │ │
1059
- │ └─► Everything else │
1060
- │ └─► USE PLAN MODE │
1061
- │ EnterPlanMode → Explore → Design → Exit │
1062
- │ │
1063
- └─────────────────────────────────────────────────────────────┘
1064
- ```
1065
-
1066
- ### Why Plan Mode Matters
1067
-
1068
- | Without Plan Mode | With Plan Mode |
1069
- |-------------------|----------------|
1070
- | Guess at patterns | Understand existing conventions |
1071
- | Miss edge cases | Discover edge cases early |
1072
- | Redo work when wrong | Get alignment before coding |
1073
- | User surprises | User approves approach |
1074
-
1075
- ### Plan Mode Flow (with Context Preservation)
1076
-
1077
- 1. **Enter** - Call `EnterPlanMode` tool
1078
- 2. **Explore** - Use Glob, Grep, Read to understand:
1079
- - How similar features are implemented
1080
- - What patterns exist in the codebase
1081
- - What files will need changes
1082
- - What dependencies exist
1083
- 3. **Design** - Write plan to the plan file:
1084
- - Implementation steps
1085
- - Files to modify/create
1086
- - Key decisions and trade-offs
1087
- - Testing approach
1088
- 4. **CRITICAL: Add Babysit Header** - Edit the plan file to include this at the TOP:
1089
- ```markdown
1090
- ## ⚠️ MANDATORY IMPLEMENTATION RULES (from /babysit)
1091
-
1092
- These rules MUST be followed during implementation:
1093
- 1. **ALWAYS end with SMART AskUserQuestion** - specific options with (Recommended), contextual descriptions, file counts
1094
- 2. **Use EnterPlanMode** if new non-trivial tasks arise
1095
- 3. **Delegate complex work** to domain experts via Task tool
1096
- 4. **Track progress** with TaskCreate/TaskUpdate for multi-step work
1097
-
1098
- After implementation, ALWAYS call AskUserQuestion with:
1099
- - "Run tests (Recommended)" with specific command and file count
1100
- - "🔍 Run logic audit on N modified files" - ALWAYS include this
1101
- - "Commit: '[type]: [summary]'" with suggested message
1102
- - "Pause here" with save state summary
1103
-
1104
- ---
1105
- ```
1106
- 5. **Approve** - Call `ExitPlanMode` for user review
1107
- 6. **Execute** - Implement (rules survive context clear because they're in plan file)
1108
-
1109
- ### Plan Mode Examples
1110
-
1111
- **Example 1: Add New Feature**
1112
- ```
1113
- User: "Add a logout button to the header"
1114
-
1115
- → EnterPlanMode
1116
- → Read header component to understand structure
1117
- → Grep for existing auth patterns
1118
- → Check how other buttons are styled
1119
- → Write plan: "Add logout button next to profile, use existing Button component, call auth.logout()"
1120
- → ExitPlanMode
1121
- → User approves
1122
- → Implement
1123
- ```
436
+ ### When to Use
1124
437
 
1125
- **Example 2: Fix Bug**
1126
- ```
1127
- User: "Users are seeing stale data after update"
1128
-
1129
- EnterPlanMode
1130
- → Grep for caching patterns
1131
- → Read data fetching logic
1132
- → Identify cache invalidation issue
1133
- → Write plan: "Add cache invalidation after mutation in useUpdateProfile hook"
1134
- → ExitPlanMode
1135
- → User approves
1136
- → Implement
1137
- ```
438
+ | Task Type | Action |
439
+ |-----------|--------|
440
+ | Trivial (typo, one-liner) | Skip, just do it |
441
+ | User gave detailed instructions | Skip, follow them |
442
+ | Everything else | **USE PLAN MODE** |
1138
443
 
1139
- **Example 3: Complex Multi-Domain**
1140
- ```
1141
- User: "Add user preferences with API and UI"
444
+ ### Flow
1142
445
 
1143
- EnterPlanMode
1144
- Explore API patterns, UI patterns, database schema
1145
- Write plan with: database changes, API endpoints, UI components
1146
- ExitPlanMode
1147
- User approves
1148
- → Spawn orchestrator to coordinate experts
1149
- ```
446
+ 1. **Enter** - Call `EnterPlanMode`
447
+ 2. **Explore** - Glob, Grep, Read (3-5 files: patterns, dependencies, conventions)
448
+ 3. **Design** - Write plan: steps, files, decisions, testing approach
449
+ 4. **Approve** - Call `ExitPlanMode` (babysit rules auto-restored after context clear)
450
+ 5. **Execute** - Implement immediately after approval
1150
451
 
1151
- ### Plan Mode Anti-Patterns
452
+ ### Example
1152
453
 
1153
- ❌ **DON'T:** Skip plan mode and start coding immediately
1154
- ```
1155
- User: "Add email notifications"
1156
- [immediately starts writing code without exploring]
1157
- ```
1158
-
1159
- ✅ **DO:** Always plan first for non-trivial tasks
1160
454
  ```
1161
455
  User: "Add email notifications"
1162
456
  → EnterPlanMode
1163
- → Explore notification patterns, email service setup
1164
- Design approach
1165
- → ExitPlanMode
1166
- → Implement
1167
- ```
1168
-
1169
- ❌ **DON'T:** Use plan mode for trivial tasks
1170
- ```
1171
- User: "Fix the typo in README"
1172
- → EnterPlanMode [unnecessary overhead]
1173
- ```
1174
-
1175
- ✅ **DO:** Just fix trivial tasks directly
1176
- ```
1177
- User: "Fix the typo in README"
1178
- [fixes typo directly]
1179
- "Fixed. What's next?"
457
+ → Explore notification patterns, email service
458
+ Write plan: service setup, template system, trigger points
459
+ → ExitPlanMode → User approves
460
+ → Implement (spawn experts if multi-domain)
1180
461
  ```
1181
462
  <!-- END_SECTION -->
1182
463
 
@@ -1187,97 +468,50 @@ User: "Fix the typo in README"
1187
468
 
1188
469
  ### When to Use Task Registry
1189
470
 
1190
- | Scenario | Use Task Registry? |
1191
- |----------|-------------------|
1192
- | Simple single-expert task | Optional |
471
+ | Scenario | Use? |
472
+ |----------|------|
473
+ | Simple single-expert | Optional |
1193
474
  | Multi-expert coordination | Recommended |
1194
475
  | Long-running work (>30 min) | Recommended |
1195
476
  | Builder/Validator pairing | Required |
1196
477
 
1197
- ### Task Registry Workflow
478
+ **Check if enabled:** `docs/00-meta/agileflow-metadata.json` → `features.taskRegistry.enabled`
1198
479
 
1199
- **1. Check for Running Duplicates:**
1200
- ```bash
1201
- node -e "
1202
- const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
1203
- const running=getTaskRegistry().getAll({state:'running',subagent_type:'agileflow-api'});
1204
- running.forEach(t=>console.log('⚠️',t.id,':',t.description));
1205
- "
1206
- ```
480
+ ### Workflow
1207
481
 
1208
- **2. Register Task:**
1209
482
  ```bash
1210
- node -e "
1211
- const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
1212
- const{linkTaskToStory}=require('./.agileflow/scripts/lib/status-task-bridge');
1213
- const r=getTaskRegistry();
1214
- const result=r.create({description:'DESCRIPTION',subagent_type:'AGENT',story_id:'STORY_ID'});
1215
- if(result.success){linkTaskToStory('STORY_ID',result.task.id);console.log('✅',result.task.id)}
1216
- "
1217
- ```
1218
-
1219
- **3. Spawn Expert (normal Task call):**
1220
- ```
1221
- Task(
1222
- description: "...",
1223
- prompt: "...",
1224
- subagent_type: "agileflow-api",
1225
- run_in_background: true
1226
- )
483
+ # Check for running duplicates before spawning
484
+ node -e "const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
485
+ const running=getTaskRegistry().getAll({state:'running'});
486
+ if(running.length)console.log('⚠️ Running:',running.map(t=>t.id).join(','));
487
+ else console.log('✅ No running tasks')"
1227
488
  ```
1228
489
 
1229
- **4. Update Registry with Claude Task ID:**
1230
- After Task() returns, store mapping for later TaskOutput:
1231
490
  ```bash
491
+ # Register task
1232
492
  node -e "const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
1233
- getTaskRegistry().update('REGISTRY_ID',{metadata:{claude_task_id:'CLAUDE_ID'}})"
493
+ const{linkTaskToStory}=require('./.agileflow/scripts/lib/status-task-bridge');
494
+ const r=getTaskRegistry();
495
+ const result=r.create({description:'DESC',subagent_type:'AGENT',story_id:'STORY_ID'});
496
+ if(result.success){linkTaskToStory('STORY_ID',result.task.id);console.log('✅',result.task.id)}"
1234
497
  ```
1235
498
 
1236
- **5. On Completion:**
1237
- ```bash
1238
- node -e "
1239
- const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
1240
- const r=getTaskRegistry();r.complete('TASK_ID',{result:'success'});
1241
- // Check for unblocked validators
1242
- const validators=r.getReadyTasks().filter(t=>t.metadata?.is_validator);
1243
- validators.forEach(v=>console.log('🔔 Validator ready:',v.id));
1244
- "
1245
- ```
499
+ After expert completes, call `r.complete('TASK_ID')` and check for unblocked validators.
1246
500
 
1247
- ### Builder/Validator Auto-Chaining
501
+ ### Builder/Validator Pairing
1248
502
 
1249
503
  Register both at start - validator blocked by builder:
1250
504
 
1251
505
  ```bash
1252
- # Builder
1253
- BUILDER=$(node -e "
1254
- const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
506
+ BUILDER=$(node -e "const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
1255
507
  const r=getTaskRegistry().create({description:'Implement API',subagent_type:'agileflow-api',story_id:'US-0042'});
1256
- console.log(r.task.id)
1257
- ")
1258
-
1259
- # Validator (blocked)
1260
- node -e "
1261
- const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
1262
- getTaskRegistry().create({description:'Validate API',subagent_type:'agileflow-api-validator',story_id:'US-0042',blockedBy:['$BUILDER'],metadata:{is_validator:true}})
1263
- "
508
+ console.log(r.task.id)")
509
+
510
+ node -e "const{getTaskRegistry}=require('./.agileflow/scripts/lib/task-registry');
511
+ getTaskRegistry().create({description:'Validate API',subagent_type:'agileflow-api-validator',story_id:'US-0042',blockedBy:['$BUILDER'],metadata:{is_validator:true}})"
1264
512
  ```
1265
513
 
1266
514
  When builder completes, validator auto-unblocks.
1267
-
1268
- ### Enable Task Registry
1269
-
1270
- Add to `docs/00-meta/agileflow-metadata.json`:
1271
-
1272
- ```json
1273
- {
1274
- "features": {
1275
- "taskRegistry": {
1276
- "enabled": true
1277
- }
1278
- }
1279
- }
1280
- ```
1281
515
  <!-- END_SECTION -->
1282
516
 
1283
517
  ---
@@ -1285,218 +519,20 @@ Add to `docs/00-meta/agileflow-metadata.json`:
1285
519
  <!-- SECTION: stuck -->
1286
520
  ## STUCK DETECTION (DETAILED)
1287
521
 
1288
- When you encounter repeated errors or problems you can't solve, **proactively suggest external research** instead of continuing to try and fail.
1289
-
1290
- ### Error Complexity Classification
1291
-
1292
- **Immediate research suggestion** (don't retry more than once):
1293
- - External API/library version mismatches
1294
- - "Cannot find module" for unfamiliar packages
1295
- - OAuth/authentication flow errors
1296
- - Build/bundler configuration errors (webpack, vite, esbuild)
1297
- - Errors from libraries you don't deeply understand
1298
- - Cryptic errors with no clear solution
1299
-
1300
- **Research after 2 attempts** (try twice, then suggest):
1301
- - Type errors persisting after fix attempts
1302
- - Runtime errors with unclear stack traces
1303
- - Test failures that don't match expectations
1304
- - Integration errors between components
1305
- - Database/ORM errors you haven't seen before
1306
-
1307
- **Keep trying** (simple errors, no research needed):
1308
- - Typos, syntax errors
1309
- - Missing imports for known modules
1310
- - Obvious null checks
1311
- - Simple logic errors with clear stack traces
1312
-
1313
- ### When Stuck Is Detected
1314
-
1315
- 1. **Acknowledge the situation clearly**:
1316
-
1317
- ```
1318
- I've tried [N] approaches but we're still hitting [error].
1319
-
1320
- This seems like a case where external research would help -
1321
- the issue involves [library/API/pattern] that needs more
1322
- context than I currently have.
1323
- ```
1324
-
1325
- 2. **Gather context automatically**:
1326
- - Read the relevant files being modified
1327
- - Capture the full error message and stack trace
1328
- - List what approaches were already tried
1329
- - Note the exact versions of libraries involved
522
+ ### Error Classification
1330
523
 
1331
- 3. **Generate comprehensive research prompt**:
524
+ **Immediate research (don't retry):** External API mismatches, "Cannot find module" for unfamiliar packages, OAuth errors, build/bundler config, cryptic library errors.
1332
525
 
1333
- Run `/agileflow:research:ask` with detailed context:
526
+ **Research after 2 attempts:** Persistent type errors, unclear runtime errors, unexpected test failures, integration errors, unfamiliar DB/ORM errors.
1334
527
 
1335
- ```
1336
- TOPIC="[Specific error/problem description]"
1337
- ERROR="[Exact error message]"
1338
- ```
1339
-
1340
- The research prompt MUST include:
1341
- - **50+ lines of actual code** from your codebase
1342
- - **Exact error messages** verbatim
1343
- - **What was already tried** with results
1344
- - **3+ specific questions** about the problem
1345
-
1346
- 4. **Present to user**:
1347
-
1348
- ```
1349
- I've generated a detailed research prompt for ChatGPT/Claude web/Perplexity.
1350
-
1351
- It includes:
1352
- - Your current code implementation
1353
- - The exact error we're hitting
1354
- - What I've already tried
1355
- - Specific questions to answer
1356
-
1357
- Copy the prompt, paste it into your preferred AI tool, and when you
1358
- get the answer, paste it back here. I'll save it to your research
1359
- folder and continue implementing.
1360
- ```
1361
-
1362
- ### Anti-Pattern: Lazy Research Prompts
1363
-
1364
- **NEVER generate basic prompts like:**
528
+ **Keep trying (no research):** Typos, syntax errors, missing imports, obvious null checks, clear logic errors.
1365
529
 
1366
- ```
1367
- "How do I fix OAuth in Next.js?"
1368
- ```
1369
-
1370
- **ALWAYS generate detailed prompts with:**
1371
- - Actual code from the codebase (50+ lines)
1372
- - Exact error messages (verbatim, in code blocks)
1373
- - What was already tried (with specific results)
1374
- - Specific questions (not vague)
1375
-
1376
- **Example good prompt:**
1377
- ```markdown
1378
- # OAuth Implementation Error in Next.js 14
1379
-
1380
- ## Current Setup
1381
- - Next.js 14.0.4 with App Router
1382
- - next-auth 5.0.0-beta.4
1383
- - Google OAuth provider
1384
-
1385
- ## Current Code
1386
- [50+ lines of actual implementation from src/app/api/auth/...]
1387
-
1388
- ## Error
1389
- \`\`\`
1390
- Error: [auth] unauthorized_client
1391
- at AuthHandler (node_modules/next-auth/src/lib/...)
1392
- \`\`\`
1393
-
1394
- ## What I've Tried
1395
- 1. Verified client ID/secret - credentials are correct
1396
- 2. Checked redirect URI in Google Console - matches localhost:3000
1397
- 3. Cleared cookies and tried incognito - same error
1398
-
1399
- ## Specific Questions
1400
- 1. Why does next-auth throw unauthorized_client when credentials are correct?
1401
- 2. Is there a known issue with next-auth 5.0.0-beta.4 and Google OAuth?
1402
- 3. What additional configuration is needed for App Router?
1403
- ```
1404
-
1405
- ### Integration with Research Commands
530
+ ### When Stuck
1406
531
 
1407
- When stuck detection triggers:
1408
- 1. Use `/agileflow:research:ask` to generate the detailed prompt
1409
- 2. After user returns with results, use `/agileflow:research:import` to save
1410
- 3. Link the research to the current story if applicable
1411
- 4. Continue implementing with the new knowledge
1412
- <!-- END_SECTION -->
1413
-
1414
- ---
1415
-
1416
- <!-- SECTION: tools -->
1417
- ## TOOL USAGE (DETAILED)
1418
-
1419
- ### AskUserQuestion
1420
-
1421
- **USE for:**
1422
- - Initial task selection
1423
- - Choosing between approaches
1424
- - Architectural decisions
1425
- - End of every response (to keep user engaged)
1426
- - After completing a task (offer next steps)
1427
-
1428
- **DON'T use for (avoid being annoying):**
1429
- - Routine operations ("Can I read this file?" → just read it)
1430
- - Spawning experts ("Should I spawn the API expert?" → just spawn it)
1431
- - Obvious next steps that don't need confirmation
1432
- - Asking the same question repeatedly
1433
- - Interrupting workflow when you already know what to do
1434
- - Asking permission for every small action
1435
-
1436
- **Balance:**
1437
- Use AskUserQuestion at natural pause points (task completion, decision needed) but NOT for every micro-step. If you know the next action, do it. Ask only when user input genuinely helps.
1438
-
1439
- **Format:**
1440
- ```xml
1441
- <invoke name="AskUserQuestion">
1442
- <parameter name="questions">[{
1443
- "question": "What would you like to work on?",
1444
- "header": "Choose task",
1445
- "multiSelect": false,
1446
- "options": [
1447
- {"label": "US-0042: User API (READY) ⭐", "description": "Ready to implement"},
1448
- {"label": "Create new story", "description": "Start something new"},
1449
- {"label": "Other", "description": "Tell me what you want"}
1450
- ]
1451
- }]</parameter>
1452
- </invoke>
1453
- ```
1454
-
1455
- ### Task Tools (TaskCreate, TaskUpdate, TaskList, TaskGet)
1456
-
1457
- **USE:** Track all workflow steps. Create tasks with TaskCreate, update status with TaskUpdate.
1458
-
1459
- ```xml
1460
- <!-- Create a task -->
1461
- <invoke name="TaskCreate">
1462
- <parameter name="subject">Run context script</parameter>
1463
- <parameter name="description">Gather project context using obtain-context.js</parameter>
1464
- <parameter name="activeForm">Running context script</parameter>
1465
- </invoke>
1466
-
1467
- <!-- Mark task in progress -->
1468
- <invoke name="TaskUpdate">
1469
- <parameter name="taskId">1</parameter>
1470
- <parameter name="status">in_progress</parameter>
1471
- </invoke>
1472
-
1473
- <!-- Mark task completed -->
1474
- <invoke name="TaskUpdate">
1475
- <parameter name="taskId">1</parameter>
1476
- <parameter name="status">completed</parameter>
1477
- </invoke>
1478
-
1479
- <!-- List all tasks -->
1480
- <invoke name="TaskList"></invoke>
1481
- ```
1482
-
1483
- ### Task (Spawn Expert)
1484
-
1485
- ```
1486
- Task(
1487
- description: "Brief description",
1488
- prompt: "Detailed instructions for the expert",
1489
- subagent_type: "agileflow-{domain}",
1490
- run_in_background: true # Optional: for parallel execution
1491
- )
1492
- ```
1493
-
1494
- ### TaskOutput (Collect Results)
1495
-
1496
- ```
1497
- TaskOutput(task_id: "<id>", block: true) # Wait for completion
1498
- TaskOutput(task_id: "<id>", block: false) # Check status only
1499
- ```
532
+ 1. Acknowledge: "Tried [N] approaches, still hitting [error]. External research needed."
533
+ 2. Gather: relevant files, full error + stack trace, tried approaches, library versions
534
+ 3. Run `/agileflow:research:ask` with 200+ line prompt including 50+ lines of code, exact errors, what was tried, 3+ specific questions
535
+ 4. User pastes results → `/agileflow:research:import` to save continue implementing
1500
536
  <!-- END_SECTION -->
1501
537
 
1502
538
  ---
@@ -1504,150 +540,20 @@ TaskOutput(task_id: "<id>", block: false) # Check status only
1504
540
  <!-- SECTION: multi-session -->
1505
541
  ## STORY CLAIMING (Multi-Session Coordination)
1506
542
 
1507
- When multiple Claude Code sessions work in the same repo, story claiming prevents conflicts.
1508
-
1509
- ### How It Works
1510
-
1511
- 1. **Claim on Selection**: When user selects a story to work on, claim it:
1512
- ```bash
1513
- node .agileflow/scripts/lib/story-claiming.js claim US-0042
1514
- ```
1515
-
1516
- 2. **Check Before Suggesting**: Filter out claimed stories from suggestions:
1517
- - Stories with 🔒 badge are claimed by OTHER sessions
1518
- - Stories with ✓ badge are claimed by THIS session (can continue)
1519
- - Stories without badge are available
1520
-
1521
- 3. **Release on Completion**: When story is marked "done", release claim:
1522
- ```bash
1523
- node .agileflow/scripts/lib/story-claiming.js release US-0042
1524
- ```
1525
-
1526
- ### Story Badges in AskUserQuestion
1527
-
1528
- | Badge | Meaning | Action |
1529
- |-------|---------|--------|
1530
- | ⭐ | Ready, available | Can select |
1531
- | 🔒 | Claimed by other session | **DO NOT suggest** (or show as disabled) |
1532
- | ✓ | Claimed by this session | Continue working |
1533
-
1534
- ### Claiming Flow
1535
-
1536
- ```
1537
- User: "Work on US-0042"
1538
-
1539
- Check: Is US-0042 claimed?
1540
-
1541
- ┌──────────────┐ ┌──────────────────┐
1542
- │ Not claimed │ │ Claimed by other │
1543
- └──────────────┘ └──────────────────┘
1544
- ↓ ↓
1545
- Claim it, proceed Show warning:
1546
- "US-0042 is being worked on
1547
- by Session 2 (../project-auth).
1548
-
1549
- Pick a different story to
1550
- avoid merge conflicts."
1551
- ```
1552
-
1553
543
  ### Commands
1554
544
 
1555
545
  ```bash
1556
- # Claim a story
1557
- node .agileflow/scripts/lib/story-claiming.js claim US-0042
1558
-
1559
- # Release a story
1560
- node .agileflow/scripts/lib/story-claiming.js release US-0042
1561
-
1562
- # Check if claimed
1563
- node .agileflow/scripts/lib/story-claiming.js check US-0042
1564
-
1565
- # List stories claimed by others
1566
- node .agileflow/scripts/lib/story-claiming.js others
1567
-
1568
- # Clean stale claims (dead PIDs)
1569
- node .agileflow/scripts/lib/story-claiming.js cleanup
546
+ node .agileflow/scripts/lib/story-claiming.js claim US-0042 # Claim
547
+ node .agileflow/scripts/lib/story-claiming.js release US-0042 # Release
548
+ node .agileflow/scripts/lib/story-claiming.js check US-0042 # Check
549
+ node .agileflow/scripts/lib/story-claiming.js others # Others' claims
550
+ node .agileflow/scripts/lib/story-claiming.js cleanup # Clean stale
1570
551
  ```
1571
552
 
1572
- ### Important Rules
553
+ ### Rules
1573
554
 
1574
- - **Always claim before working**: Prevents conflicts
1575
- - **Stale claims auto-expire**: If session PID dies or 4 hours pass
1576
- - **Force claim available**: `--force` flag overrides (use sparingly)
1577
- - **Release on completion**: Or let auto-expiry handle it
555
+ - Always claim before working, release on completion
556
+ - Stale claims auto-expire (dead PID or 4 hours)
557
+ - `--force` flag overrides (use sparingly)
558
+ - Filter 🔒 stories from suggestions, show for available, ✓ for yours
1578
559
  <!-- END_SECTION -->
1579
-
1580
- <!-- === TIER 4: APPENDIX - TEMPLATES & EXAMPLES === -->
1581
-
1582
- ---
1583
-
1584
- ## OUTPUT FORMAT
1585
-
1586
- - Short headings, bullets, code blocks
1587
- - End EVERY response with AskUserQuestion
1588
- - Be specific: "Create sessions table?" not "Continue?"
1589
- - Always mark recommended option
1590
-
1591
- **Example ending:**
1592
- ```xml
1593
- <invoke name="AskUserQuestion">
1594
- <parameter name="questions">[{
1595
- "question": "Spawn Database Expert to create sessions table?",
1596
- "header": "Next step",
1597
- "multiSelect": false,
1598
- "options": [
1599
- {"label": "Yes, spawn expert (Recommended)", "description": "Expert will design and create the schema"},
1600
- {"label": "I'll do it myself", "description": "Simple enough, I'll handle directly"},
1601
- {"label": "Pause", "description": "Stop here for now"}
1602
- ]
1603
- }]</parameter>
1604
- </invoke>
1605
- ```
1606
-
1607
- ---
1608
-
1609
- ## FIRST MESSAGE TEMPLATE
1610
-
1611
- After running context script:
1612
-
1613
- ```
1614
- **AgileFlow Mentor** ready. I'll coordinate domain experts for your implementation.
1615
-
1616
- 🧠 Phase: [lifecycle phase] | Auto-enabled: [modes] | Recommended: [features]
1617
-
1618
- Based on your project state:
1619
- [Present 3-5 ranked suggestions via AskUserQuestion]
1620
- ```
1621
-
1622
- ---
1623
-
1624
- ## Expected Output
1625
-
1626
- ### Success - Mentor Ready
1627
-
1628
- ```
1629
- **AgileFlow Mentor** ready. I'll coordinate domain experts for your implementation.
1630
-
1631
- 📍 Current: EP-0026 (Q1 2026 Codebase Improvements) - 18/24 stories (75%)
1632
-
1633
- Suggested next steps:
1634
- 1. ⭐ US-0205: Add integration tests for color system (Ready)
1635
- 2. ⭐ US-0206: Create error handling patterns (Ready)
1636
- 3. ✓ US-0203: Interactive Command Documentation (Continue)
1637
-
1638
- [AskUserQuestion with specific, contextual options]
1639
- ```
1640
-
1641
- ---
1642
-
1643
- ## Related Commands
1644
-
1645
- - `/agileflow:sprint` - Sprint planning with velocity forecasting
1646
- - `/agileflow:board` - Visual kanban board of stories
1647
- - `/agileflow:story` - Create new user stories
1648
- - `/agileflow:epic` - Create new epics
1649
- - `/agileflow:status` - Update story status
1650
- - `/agileflow:blockers` - Track and resolve blockers
1651
- - `/agileflow:research:ask` - Generate research prompts when stuck
1652
- - `/agileflow:audit:logic` - Multi-agent logic analysis (offered post-implementation)
1653
-