sequant 1.17.0 → 1.18.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 (63) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +14 -2
  3. package/dist/marketplace/external_plugins/sequant/.claude-plugin/plugin.json +21 -0
  4. package/dist/marketplace/external_plugins/sequant/README.md +38 -0
  5. package/dist/marketplace/external_plugins/sequant/hooks/post-tool.sh +292 -0
  6. package/dist/marketplace/external_plugins/sequant/hooks/pre-tool.sh +463 -0
  7. package/dist/marketplace/external_plugins/sequant/skills/_shared/references/prompt-templates.md +350 -0
  8. package/dist/marketplace/external_plugins/sequant/skills/_shared/references/subagent-types.md +131 -0
  9. package/dist/marketplace/external_plugins/sequant/skills/assess/SKILL.md +474 -0
  10. package/dist/marketplace/external_plugins/sequant/skills/clean/SKILL.md +211 -0
  11. package/dist/marketplace/external_plugins/sequant/skills/docs/SKILL.md +337 -0
  12. package/dist/marketplace/external_plugins/sequant/skills/exec/SKILL.md +807 -0
  13. package/dist/marketplace/external_plugins/sequant/skills/fullsolve/SKILL.md +678 -0
  14. package/dist/marketplace/external_plugins/sequant/skills/improve/SKILL.md +668 -0
  15. package/dist/marketplace/external_plugins/sequant/skills/loop/SKILL.md +374 -0
  16. package/dist/marketplace/external_plugins/sequant/skills/qa/SKILL.md +570 -0
  17. package/dist/marketplace/external_plugins/sequant/skills/qa/references/code-quality-exemplars.md +107 -0
  18. package/dist/marketplace/external_plugins/sequant/skills/qa/references/code-review-checklist.md +65 -0
  19. package/dist/marketplace/external_plugins/sequant/skills/qa/references/quality-gates.md +179 -0
  20. package/dist/marketplace/external_plugins/sequant/skills/qa/references/semgrep-rules.md +207 -0
  21. package/dist/marketplace/external_plugins/sequant/skills/qa/references/testing-requirements.md +109 -0
  22. package/dist/marketplace/external_plugins/sequant/skills/qa/scripts/quality-checks.sh +622 -0
  23. package/dist/marketplace/external_plugins/sequant/skills/reflect/SKILL.md +175 -0
  24. package/dist/marketplace/external_plugins/sequant/skills/reflect/references/documentation-tiers.md +70 -0
  25. package/dist/marketplace/external_plugins/sequant/skills/reflect/references/phase-reflection.md +95 -0
  26. package/dist/marketplace/external_plugins/sequant/skills/security-review/SKILL.md +358 -0
  27. package/dist/marketplace/external_plugins/sequant/skills/security-review/references/security-checklists.md +432 -0
  28. package/dist/marketplace/external_plugins/sequant/skills/solve/SKILL.md +697 -0
  29. package/dist/marketplace/external_plugins/sequant/skills/spec/SKILL.md +754 -0
  30. package/dist/marketplace/external_plugins/sequant/skills/spec/references/parallel-groups.md +72 -0
  31. package/dist/marketplace/external_plugins/sequant/skills/spec/references/recommended-workflow.md +92 -0
  32. package/dist/marketplace/external_plugins/sequant/skills/spec/references/verification-criteria.md +104 -0
  33. package/dist/marketplace/external_plugins/sequant/skills/test/SKILL.md +600 -0
  34. package/dist/marketplace/external_plugins/sequant/skills/testgen/SKILL.md +576 -0
  35. package/dist/marketplace/external_plugins/sequant/skills/verify/SKILL.md +281 -0
  36. package/dist/src/commands/run.d.ts +13 -280
  37. package/dist/src/commands/run.js +23 -1956
  38. package/dist/src/commands/sync.js +3 -0
  39. package/dist/src/commands/update.js +3 -0
  40. package/dist/src/lib/plugin-version-sync.d.ts +2 -1
  41. package/dist/src/lib/plugin-version-sync.js +28 -7
  42. package/dist/src/lib/solve-comment-parser.d.ts +26 -0
  43. package/dist/src/lib/solve-comment-parser.js +63 -7
  44. package/dist/src/lib/workflow/batch-executor.d.ts +117 -0
  45. package/dist/src/lib/workflow/batch-executor.js +574 -0
  46. package/dist/src/lib/workflow/phase-executor.d.ts +40 -0
  47. package/dist/src/lib/workflow/phase-executor.js +381 -0
  48. package/dist/src/lib/workflow/phase-mapper.d.ts +65 -0
  49. package/dist/src/lib/workflow/phase-mapper.js +147 -0
  50. package/dist/src/lib/workflow/pr-operations.d.ts +86 -0
  51. package/dist/src/lib/workflow/pr-operations.js +326 -0
  52. package/dist/src/lib/workflow/pr-status.d.ts +9 -7
  53. package/dist/src/lib/workflow/pr-status.js +13 -11
  54. package/dist/src/lib/workflow/run-summary.d.ts +36 -0
  55. package/dist/src/lib/workflow/run-summary.js +142 -0
  56. package/dist/src/lib/workflow/worktree-manager.d.ts +205 -0
  57. package/dist/src/lib/workflow/worktree-manager.js +918 -0
  58. package/package.json +3 -1
  59. package/templates/skills/fullsolve/SKILL.md +11 -1
  60. package/templates/skills/qa/SKILL.md +41 -1
  61. package/templates/skills/solve/SKILL.md +86 -0
  62. package/templates/skills/spec/SKILL.md +53 -0
  63. package/templates/skills/test/SKILL.md +10 -0
@@ -0,0 +1,807 @@
1
+ ---
2
+ name: exec
3
+ description: "Phase 2 - Implementation loop for a single GitHub issue until Acceptance Criteria are satisfied (or as close as practical)."
4
+ license: MIT
5
+ metadata:
6
+ author: sequant
7
+ version: "1.0"
8
+ allowed-tools:
9
+ # File operations (required for implementation)
10
+ - Read
11
+ - Glob
12
+ - Grep
13
+ - Edit
14
+ - Write
15
+ # Build and test
16
+ - Bash(npm test:*)
17
+ - Bash(npm run build:*)
18
+ - Bash(npm install:*)
19
+ - Bash(npx tsc:*)
20
+ # Git operations
21
+ - Bash(git status:*)
22
+ - Bash(git diff:*)
23
+ - Bash(git add:*)
24
+ - Bash(git commit:*)
25
+ - Bash(git log:*)
26
+ - Bash(git push:*)
27
+ - Bash(git worktree:*)
28
+ # Worktree management
29
+ - Bash(./scripts/dev/new-feature.sh:*)
30
+ - Bash(./scripts/dev/cleanup-worktree.sh:*)
31
+ # GitHub CLI
32
+ - Bash(gh issue view:*)
33
+ - Bash(gh issue comment:*)
34
+ - Bash(gh issue edit:*)
35
+ - Bash(gh pr create:*)
36
+ - Bash(gh pr view:*)
37
+ # Optional MCP tools (enhanced functionality if available)
38
+ - mcp__context7__* # Library documentation lookup - falls back to web search if unavailable
39
+ - mcp__sequential-thinking__* # Complex reasoning - falls back to standard analysis if unavailable
40
+ # Task management
41
+ - Task(general-purpose)
42
+ - TodoWrite
43
+ ---
44
+
45
+ # Implementation Command
46
+
47
+ You are the Phase 2 "Implementation Agent" for the current repository.
48
+
49
+ ## Purpose
50
+
51
+ When invoked as `/exec`, your job is to:
52
+
53
+ 1. Take an existing, agreed plan and AC (often created by `/spec`).
54
+ 2. Create a feature worktree for the issue.
55
+ 3. Implement the changes in small, safe steps.
56
+ 4. Run checks via `npm test` and, when appropriate, `npm run build`.
57
+ 5. Iterate until the AC appear satisfied or clear blockers are reached.
58
+ 6. Draft a progress update for the GitHub issue.
59
+
60
+ ## Phase Detection (Smart Resumption)
61
+
62
+ **Before executing**, check if this phase has already been completed or if prerequisites are met:
63
+
64
+ ```bash
65
+ # Check for existing phase markers
66
+ phase_data=$(gh issue view <issue-number> --json comments --jq '[.comments[].body]' | \
67
+ grep -o '{[^}]*}' | grep '"phase"' | tail -1 || true)
68
+
69
+ if [[ -n "$phase_data" ]]; then
70
+ phase=$(echo "$phase_data" | jq -r '.phase')
71
+ status=$(echo "$phase_data" | jq -r '.status')
72
+
73
+ # Skip if exec is already completed
74
+ if [[ "$phase" == "exec" && "$status" == "completed" ]]; then
75
+ echo "⏭️ Exec phase already completed. Skipping."
76
+ # Exit early — no work needed
77
+ fi
78
+
79
+ # Resume if exec previously failed
80
+ if [[ "$phase" == "exec" && "$status" == "failed" ]]; then
81
+ echo "🔄 Exec phase previously failed. Resuming from failure point."
82
+ # Continue execution — will retry the implementation
83
+ fi
84
+ fi
85
+ ```
86
+
87
+ **Behavior:**
88
+ - If `exec:completed` → Skip with message
89
+ - If `exec:failed` → Resume (retry implementation)
90
+ - If `spec:completed` (no exec marker) → Normal execution
91
+ - If no markers found → Normal execution (fresh start)
92
+ - If detection fails (API error) → Fall through to normal execution
93
+
94
+ **Phase Marker Emission:**
95
+
96
+ When posting the progress update comment to GitHub, append a phase marker at the end:
97
+
98
+ ```markdown
99
+ <!-- SEQUANT_PHASE: {"phase":"exec","status":"completed","timestamp":"<ISO-8601>","pr":<PR_NUMBER>} -->
100
+ ```
101
+
102
+ If exec fails, emit a failure marker:
103
+ ```markdown
104
+ <!-- SEQUANT_PHASE: {"phase":"exec","status":"failed","timestamp":"<ISO-8601>","error":"<error message>"} -->
105
+ ```
106
+
107
+ Include this marker in every `gh issue comment` that represents phase completion or failure.
108
+
109
+ ## Behavior
110
+
111
+ Invocation:
112
+
113
+ - `/exec 123`:
114
+ - Treat `123` as the GitHub issue number.
115
+ - Assume a plan may already exist in the issue or from `/spec`.
116
+ - `/exec <freeform description>`:
117
+ - Treat the text as a lightweight description + AC if no issue context is available.
118
+
119
+ ### 0. Pre-flight Check (After Context Restoration)
120
+
121
+ **CRITICAL:** If continuing from a restored/summarized conversation, verify git state first:
122
+
123
+ ```bash
124
+ # Check current state - are we in a worktree or main repo?
125
+ pwd
126
+ git log --oneline -3 --stat
127
+
128
+ # Check for existing PRs or branches for this issue
129
+ gh pr list --search "<issue-number>"
130
+ git branch -a | grep -i "<issue-number>" || true
131
+ ```
132
+
133
+ **Why this matters:** After context restoration, PRs may have merged, branches may have changed, or work may already be complete. Always verify before creating duplicate work.
134
+
135
+ **If PR already merged:** The issue may be complete - verify and close if so.
136
+
137
+ ### 1. Check Implementation Readiness
138
+
139
+ **FIRST STEP:** Review the issue readiness and proceed with implementation.
140
+
141
+ **Read the latest GitHub comment** (especially from `/spec`) and look for:
142
+ ```markdown
143
+ ## Implementation Readiness
144
+
145
+ **Status:** [READY / NOT READY]
146
+ ```
147
+
148
+ **Implementation Policy:**
149
+ - Always proceed with implementation when invoked via `/exec`
150
+ - Log any warnings or concerns about readiness
151
+ - Add notes to progress update if implementing despite blockers
152
+
153
+ **Readiness Notes to Include in Progress Update:**
154
+ - If P2/P3/P4 priority: Note that this is a non-critical issue being implemented
155
+ - If technical blockers exist: Note the blockers and explain workarounds/stubs used
156
+ - If dependencies are open: Note which issues block full integration
157
+
158
+ **Only stop implementation if:**
159
+ - Issue is labeled `planning`, `research`, or `rfc` (not for implementation)
160
+ - Issue is already closed
161
+ - No acceptance criteria exist and cannot be inferred
162
+
163
+ ### 2. Re-establish Context
164
+
165
+ - **Read all GitHub issue comments** to gather complete context:
166
+ - Comments often contain clarifications, updates, or additional AC added after the initial issue description
167
+ - Look for discussion about implementation details, edge cases, or requirements mentioned in comments
168
+ - Review feedback from previous implementation cycles or review comments
169
+ - Summarize briefly:
170
+ - The AC checklist (AC-1, AC-2, ...) from the issue and all comments
171
+ - The current implementation plan (from issue comments or `/spec`)
172
+ - If there is no plan:
173
+ - Ask whether to quickly propose one (or suggest using `/spec` first).
174
+
175
+ ### Feature Worktree Workflow
176
+
177
+ **Execution Phase:** Create and work in a feature worktree.
178
+
179
+ 1. **Check if worktree already exists:**
180
+ - Check if you're already in a worktree: `git worktree list` or check if `../worktrees/` contains a directory for this issue
181
+ - If worktree exists, navigate to it and continue work there
182
+
183
+ 2. **Create worktree if needed:**
184
+ - From the main repository directory, run: `./scripts/dev/new-feature.sh <issue-number>`
185
+ - This will:
186
+ - Fetch issue details from GitHub
187
+ - Create branch: `feature/<issue-number>-<issue-title-slug>`
188
+ - Create worktree in: `../worktrees/feature/<branch-name>/`
189
+ - Install dependencies
190
+ - Copy environment files if they exist
191
+ - Navigate to the worktree directory: `cd ../worktrees/feature/<branch-name>/`
192
+
193
+ 3. **Work in the worktree:**
194
+ - All implementation work happens in the worktree directory
195
+ - Run `npm test` and `npm run build` from the worktree
196
+ - Make commits in the worktree (they'll be on the feature branch)
197
+
198
+ 4. **After implementation is complete:**
199
+ - Push the branch: `git push -u origin feature/<branch-name>`
200
+ - Create PR (manually or via script)
201
+ - The worktree will be cleaned up after PR merge using `./scripts/dev/cleanup-worktree.sh <branch-name>`
202
+
203
+ **Important:** Always work in the worktree directory, not the main repository, once the worktree is created.
204
+
205
+ ### PR Creation and Verification
206
+
207
+ After implementation is complete and all checks pass, create and verify the PR:
208
+
209
+ 1. **Push the branch:**
210
+ ```bash
211
+ git push -u origin <branch-name>
212
+ ```
213
+
214
+ 2. **Create the PR with HEREDOC formatting:**
215
+ ```bash
216
+ gh pr create --title "feat(#<issue>): <title>" --body "$(cat <<'EOF'
217
+ ## Summary
218
+ <1-3 bullet points>
219
+
220
+ ## Test plan
221
+ - [ ] Manual testing steps...
222
+
223
+ Closes #<issue>
224
+
225
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
226
+ EOF
227
+ )"
228
+ ```
229
+
230
+ 3. **Immediately verify PR was created:**
231
+ ```bash
232
+ # Verify PR exists - this MUST succeed
233
+ gh pr view --json number,url
234
+ ```
235
+
236
+ 4. **If verification fails, retry once:**
237
+ ```bash
238
+ # Wait 2 seconds and retry
239
+ sleep 2
240
+ gh pr view --json number,url || echo "ERROR: PR verification failed after retry"
241
+ ```
242
+
243
+ 5. **Capture PR URL for progress update:**
244
+ - If PR exists: Record the URL from `gh pr view` output
245
+ - If PR creation failed: Record the error and include manual creation instructions
246
+
247
+ **PR Verification Failure Handling:**
248
+
249
+ If `gh pr view` fails after retry:
250
+ 1. Log the error clearly: `"PR Creation: FAILED - [error message]"`
251
+ 2. Include manual creation instructions in progress update:
252
+ ```markdown
253
+ ### Manual PR Creation Required
254
+
255
+ PR creation failed. Create manually:
256
+ \`\`\`bash
257
+ gh pr create --title "feat(#<issue>): <title>" --body "..."
258
+ \`\`\`
259
+ ```
260
+ 3. Do NOT report the phase as fully successful - note the PR failure
261
+
262
+ **Important:** The implementation is complete regardless of PR status, but the progress update MUST accurately reflect whether the PR was created.
263
+
264
+ ### Check Patterns Catalog Before Implementing
265
+
266
+ **IMPORTANT:** Before creating any new utility functions, components, or types:
267
+
268
+ 1. Read `docs/patterns/README.md` for quick lookup
269
+ 2. Check `docs/patterns/HELPERS.md` for existing helper functions
270
+ 3. Check `docs/patterns/COMPONENTS.md` for existing React components
271
+ 4. Check `docs/patterns/TYPES.md` for existing TypeScript types
272
+
273
+ **Do NOT create duplicates.** If a similar utility exists:
274
+ - Use the existing one
275
+ - If it needs modification, extend it rather than creating a new one
276
+ - Document why existing utilities don't meet requirements before creating new ones
277
+
278
+ ### Check Framework Gotchas on Runtime Errors
279
+
280
+ **When encountering unexpected runtime errors or build failures:**
281
+
282
+ 1. Check `references/shared/framework-gotchas.md` for known framework-specific issues
283
+ 2. Common gotchas include:
284
+ - AG Grid v35+ module registration requirements
285
+ - React 19 concurrent mode behavior changes
286
+ - Next.js 15 caching and async API changes
287
+ - Tailwind v4 CSS-first configuration
288
+
289
+ If you discover a new framework-specific issue that caused debugging time, add it to the gotchas file following the template.
290
+
291
+ ### MCP Tools Integration
292
+
293
+ This section covers optional MCP tools that enhance implementation quality when available.
294
+
295
+ #### MCP Availability Check
296
+
297
+ **Before using MCP tools**, verify they are available in your session. If unavailable, use the documented fallback behavior.
298
+
299
+ ```markdown
300
+ **MCP Status Check (perform at session start):**
301
+ - [ ] Context7: Try `mcp__context7__resolve-library-id` - if available, proceed
302
+ - [ ] Sequential Thinking: Try `mcp__sequential-thinking__sequentialthinking` - if available, proceed
303
+ - [ ] Chrome DevTools: Try `mcp__chrome-devtools__take_snapshot` - if available, proceed
304
+
305
+ If any MCP is unavailable, use fallback strategies documented below.
306
+ ```
307
+
308
+ ---
309
+
310
+ #### Context7 - Library Documentation Lookup
311
+
312
+ **Tool Names:**
313
+ - `mcp__context7__resolve-library-id` - Resolve package name to Context7 library ID
314
+ - `mcp__context7__query-docs` - Query documentation for a specific library
315
+
316
+ **When to Use Context7:**
317
+
318
+ | Trigger | Example | Action |
319
+ |---------|---------|--------|
320
+ | Unfamiliar npm package API | First time using `ag-grid-react` | Use Context7 |
321
+ | Library version upgrade | Migrating from v1 to v2 of a library | Use Context7 |
322
+ | Type errors from third-party lib | `Property 'X' does not exist on type 'Y'` from library | Use Context7 |
323
+ | Missing documentation in code | Library patterns not in codebase | Use Context7 |
324
+ | **Skip** - Patterns in codebase | Similar usage exists in project | Use Grep/Glob first |
325
+ | **Skip** - Standard Node/Browser APIs | `fs`, `path`, `fetch`, `Promise` | Skip Context7 |
326
+ | **Skip** - Project's own code | Internal modules, utils, components | Use Grep/Glob |
327
+
328
+ **How to Use Context7:**
329
+
330
+ ```javascript
331
+ // Step 1: Resolve library name to Context7 ID
332
+ mcp__context7__resolve-library-id({
333
+ libraryName: "ag-grid-react",
334
+ query: "How to configure column definitions in AG Grid React"
335
+ })
336
+ // Returns: { libraryId: "/ag-grid/ag-grid", ... }
337
+
338
+ // Step 2: Query documentation with specific question
339
+ mcp__context7__query-docs({
340
+ libraryId: "/ag-grid/ag-grid",
341
+ query: "column definitions with custom cell renderers"
342
+ })
343
+ // Returns: Relevant documentation and code examples
344
+ ```
345
+
346
+ **Decision Flow:**
347
+
348
+ ```
349
+ Need to use external library API?
350
+
351
+ ├─ YES: Check codebase for existing patterns
352
+ │ │
353
+ │ ├─ Patterns found? → Use Glob/Grep (skip Context7)
354
+ │ │
355
+ │ └─ No patterns? → Use Context7 for documentation
356
+
357
+ └─ NO: Skip Context7 (internal code or standard APIs)
358
+ ```
359
+
360
+ **Fallback (if Context7 unavailable):**
361
+ 1. Use WebSearch to find official documentation
362
+ 2. Search codebase with Grep for existing usage patterns
363
+ 3. Check library's GitHub README via WebFetch
364
+ 4. Search for `<library-name> example` or `<library-name> typescript`
365
+
366
+ ---
367
+
368
+ #### Sequential Thinking - Complex Reasoning
369
+
370
+ **Tool Name:** `mcp__sequential-thinking__sequentialthinking`
371
+
372
+ **When to Use Sequential Thinking:**
373
+
374
+ | Trigger | Example | Action |
375
+ |---------|---------|--------|
376
+ | 3+ valid architectural approaches | "Should we use Redux, Context, or Zustand?" | Use Sequential Thinking |
377
+ | Complex debugging with multiple causes | "Tests fail intermittently" | Use Sequential Thinking |
378
+ | Algorithm with edge cases | Implementing rate limiting, caching logic | Use Sequential Thinking |
379
+ | Unclear refactoring boundaries | "How to split this 500-line component?" | Use Sequential Thinking |
380
+ | Issue labeled `complex`, `refactor`, `architecture` | Check issue labels | Consider Sequential Thinking |
381
+ | Previous attempt failed | Already tried one approach, it failed | Use Sequential Thinking to analyze |
382
+ | **Skip** - Simple CRUD | Add/edit/delete with clear requirements | Skip |
383
+ | **Skip** - Following existing patterns | Similar feature exists in codebase | Skip |
384
+ | **Skip** - Clear, unambiguous requirements | "Add a button that calls X" | Skip |
385
+
386
+ **How to Use Sequential Thinking:**
387
+
388
+ ```javascript
389
+ // Start a thinking chain for complex decisions
390
+ mcp__sequential-thinking__sequentialthinking({
391
+ thought: "Analyzing authentication flow options. We need to decide between JWT, session-based auth, or OAuth. Let me consider the trade-offs: 1) JWT - stateless, works for API-first, but token revocation is complex. 2) Session-based - simple, secure, but requires sticky sessions for scale. 3) OAuth - good for third-party login, but adds complexity...",
392
+ thoughtNumber: 1,
393
+ totalThoughts: 5,
394
+ nextThoughtNeeded: true
395
+ })
396
+
397
+ // Continue the chain
398
+ mcp__sequential-thinking__sequentialthinking({
399
+ thought: "Based on the project requirements (admin dashboard, single tenant), session-based auth seems most appropriate. The trade-offs favor simplicity over scalability at this stage...",
400
+ thoughtNumber: 2,
401
+ totalThoughts: 5,
402
+ nextThoughtNeeded: true
403
+ })
404
+
405
+ // Conclude with a decision
406
+ mcp__sequential-thinking__sequentialthinking({
407
+ thought: "Final decision: Implement session-based auth using the existing cookie library. This aligns with the admin-only use case and existing patterns in the codebase.",
408
+ thoughtNumber: 5,
409
+ totalThoughts: 5,
410
+ nextThoughtNeeded: false
411
+ })
412
+ ```
413
+
414
+ **Decision Flow:**
415
+
416
+ ```
417
+ Facing implementation decision?
418
+
419
+ ├─ Multiple valid approaches (3+)?
420
+ │ │
421
+ │ ├─ YES → Use Sequential Thinking
422
+ │ │
423
+ │ └─ NO → Standard implementation
424
+
425
+ ├─ Complex algorithm or edge cases?
426
+ │ │
427
+ │ ├─ YES → Use Sequential Thinking
428
+ │ │
429
+ │ └─ NO → Standard implementation
430
+
431
+ └─ Previous attempt failed?
432
+
433
+ ├─ YES → Use Sequential Thinking to analyze
434
+
435
+ └─ NO → Standard implementation
436
+ ```
437
+
438
+ **Fallback (if Sequential Thinking unavailable):**
439
+ 1. Use explicit step-by-step analysis in your response
440
+ 2. Create a pros/cons table for each approach
441
+ 3. Document trade-offs in issue comments before deciding
442
+ 4. Break complex decisions into smaller, sequential questions
443
+
444
+ ---
445
+
446
+ #### Database MCP Tools
447
+
448
+ If your project uses a database MCP (e.g., Supabase, Postgres):
449
+ - Verify table schemas before writing queries
450
+ - Check access policies before data access code
451
+ - Validate data models match TypeScript types
452
+
453
+ ---
454
+
455
+ #### General MCP Guidelines
456
+
457
+ 1. **Codebase First:** Always check for existing patterns with Glob/Grep before using MCPs
458
+ 2. **Minimal Usage:** Only invoke MCPs when they provide clear value
459
+ 3. **Graceful Degradation:** If an MCP is unavailable, use the fallback strategy
460
+ 4. **Document Decisions:** When using Sequential Thinking, summarize the conclusion
461
+
462
+ ### 3. Checks-first Mindset
463
+
464
+ - Before and after meaningful changes, plan to run:
465
+ - `npm test`
466
+ - For larger changes or anything that might impact build/runtime:
467
+ - Suggest running `npm run build` and interpret any errors.
468
+
469
+ Do NOT silently skip checks. Always state which commands you intend to run and why.
470
+
471
+ ### 4. Implementation Loop
472
+
473
+ - Implement in **small, incremental diffs**.
474
+ - Prefer touching the minimal number of files required.
475
+ - Align with repository conventions described in CLAUDE.md (naming, patterns, etc.).
476
+ - After each meaningful change:
477
+ 1. Run `npm test` (and optionally `npm run build`).
478
+ 2. If checks fail:
479
+ - Inspect the failure output.
480
+ - Identify the root cause.
481
+ - Apply small, targeted fixes.
482
+ - Repeat until checks pass or a clear blocker appears.
483
+
484
+ ### 4a. Parallel Execution (for multi-task issues)
485
+
486
+ When the `/spec` output includes a `## Parallel Groups` section, you can execute independent tasks in parallel using background agents to reduce execution time by 50-70%.
487
+
488
+ **Check for Parallel Groups:**
489
+ Look in the issue comments (especially from `/spec`) for:
490
+ ```markdown
491
+ ## Parallel Groups
492
+
493
+ ### Group 1 (no dependencies)
494
+ - [ ] Task A
495
+ - [ ] Task B
496
+
497
+ ### Group 2 (depends on Group 1)
498
+ - [ ] Task C
499
+ ```
500
+
501
+ **If Parallel Groups exist:**
502
+
503
+ 1. **Create group marker before spawning agents:**
504
+ ```bash
505
+ touch /tmp/claude-parallel-group-1.marker
506
+ ```
507
+
508
+ 2. **Determine model for each task:**
509
+
510
+ Check for model annotations in the task line: `[model: haiku]` or `[model: sonnet]`
511
+
512
+ **Model Selection Priority:**
513
+ 1. `CLAUDE_PARALLEL_MODEL` env var (if set, overrides all)
514
+ 2. `[model: X]` annotation from the task line
515
+ 3. Default to `haiku` if no annotation
516
+
517
+ 3. **Spawn parallel agents with the appropriate model in a SINGLE message:**
518
+ ```
519
+ Task(subagent_type="general-purpose",
520
+ model="haiku",
521
+ run_in_background=true,
522
+ prompt="Implement: Create types/metrics.ts with MetricEvent interface.
523
+ Working directory: [worktree path]
524
+ After completion, report what files were created/modified.")
525
+ ```
526
+
527
+ 4. **Wait for all agents to complete:**
528
+ ```
529
+ TaskOutput(task_id="...", block=true)
530
+ ```
531
+
532
+ 5. **Clean up marker and run post-group formatting:**
533
+ ```bash
534
+ rm /tmp/claude-parallel-group-1.marker
535
+ npx prettier --write [files modified by agents]
536
+ ```
537
+
538
+ 6. **Proceed to next group or sequential tasks**
539
+
540
+ **If no Parallel Groups section exists:**
541
+ Fall back to sequential execution (standard implementation loop).
542
+
543
+ **Parallel Execution Rules:**
544
+ - Maximum 3 agents per group (prevents resource exhaustion)
545
+ - Create marker file BEFORE spawning agents
546
+ - Delete marker file AFTER all agents complete
547
+ - Run Prettier on all modified files after each group (agents skip auto-format)
548
+ - On any agent failure: stop remaining agents, log error, continue with sequential
549
+ - File locking prevents concurrent edits to the same file
550
+ - **Use prompt templates** for each agent — see [Section 4c](#4c-prompt-templates-for-sub-agents)
551
+
552
+ **Error Handling with Automatic Retry:**
553
+
554
+ When an agent fails, automatic retry kicks in before marking the agent as failed:
555
+
556
+ 1. **Retry Configuration:**
557
+ - Default: 1 retry attempt
558
+ - Configurable via: `CLAUDE_PARALLEL_RETRIES=N` (N = max retry attempts)
559
+ - Exponential backoff: 1s, 2s, 4s between retries
560
+ - After max retries: mark agent as failed
561
+
562
+ 2. **Enhanced Retry Prompt:**
563
+ When retrying a failed agent, add this context to the original prompt:
564
+ ```markdown
565
+ ## RETRY CONTEXT
566
+
567
+ **Previous attempt failed with error:**
568
+ [Original error message from TaskOutput]
569
+
570
+ **CRITICAL CONSTRAINTS (re-emphasized):**
571
+ - You MUST use the worktree path: /path/to/worktrees/feature/XXX/
572
+ - Do NOT edit files outside the worktree
573
+ - Complete the task in fewer tool calls
574
+ ```
575
+
576
+ ### 4b. Detecting Agent Failures
577
+
578
+ **Important:** `TaskOutput.status` may show `"completed"` even when an agent failed due to hook blocks or other issues. The actual failure is reported in the output text, not the status field.
579
+
580
+ **Failure Detection Keywords:**
581
+ Parse the agent's output text for these patterns to detect failures:
582
+
583
+ | Pattern | Meaning |
584
+ |---------|---------|
585
+ | `HOOK_BLOCKED:` | Hook prevented the operation (most reliable) |
586
+ | `unable to proceed` | Agent could not complete the task |
587
+ | `blocked by hook` | Operation was blocked by pre-tool hook |
588
+ | `I'm unable to` | Agent hit a blocking constraint |
589
+
590
+ ### 4c. Prompt Templates for Sub-Agents
591
+
592
+ When spawning sub-agents for implementation tasks, use task-specific prompt templates for better results. See [prompt-templates.md](../_shared/references/prompt-templates.md) for the full reference.
593
+
594
+ **Template Selection:**
595
+
596
+ Templates are selected automatically based on keywords in the task description:
597
+
598
+ | Keywords | Template |
599
+ |----------|----------|
600
+ | `component`, `Component`, `React` | Component Template |
601
+ | `type`, `interface`, `types/` | Type Definition Template |
602
+ | `CLI`, `command`, `script`, `bin/` | CLI/Script Template |
603
+ | `test`, `spec`, `.test.` | Test Template |
604
+ | `refactor`, `restructure`, `migrate` | Refactor Template |
605
+ | (none matched) | Generic Template |
606
+
607
+ **Explicit Override:**
608
+
609
+ Use `[template: X]` annotation to force a specific template:
610
+
611
+ ```
612
+ [template: component] Create UserCard in components/admin/
613
+ [template: cli] Add export command to scripts/
614
+ ```
615
+
616
+ **Example with Template:**
617
+
618
+ Instead of a generic prompt:
619
+ ```
620
+ Task(subagent_type="general-purpose",
621
+ model="haiku",
622
+ prompt="Create MetricsCard component in components/admin/")
623
+ ```
624
+
625
+ Use a structured template prompt:
626
+ ```
627
+ Task(subagent_type="general-purpose",
628
+ model="haiku",
629
+ prompt="## Task: Create React Component
630
+
631
+ **Component:** MetricsCard
632
+ **Location:** components/admin/metrics/MetricsCard.tsx
633
+
634
+ **Requirements:**
635
+ - [ ] TypeScript with proper prop types
636
+ - [ ] Follow existing component patterns
637
+ - [ ] Include displayName for debugging
638
+ - [ ] No inline styles
639
+
640
+ **Constraints:**
641
+ - Working directory: [worktree path]
642
+ - Do NOT create test files
643
+
644
+ **Deliverable:**
645
+ Report: files created, component name, props interface")
646
+ ```
647
+
648
+ **Error Recovery with Enhanced Context:**
649
+
650
+ When retrying a failed agent, use the error recovery template from [prompt-templates.md](../_shared/references/prompt-templates.md#error-recovery-template):
651
+
652
+ ```markdown
653
+ ## RETRY: Previous Attempt Failed
654
+
655
+ **Original Task:** [task]
656
+ **Previous Error:** [error from TaskOutput]
657
+
658
+ **Diagnosis Checklist:**
659
+ - [ ] Check imports are correct
660
+ - [ ] Verify file paths use worktree directory
661
+ - [ ] Confirm types match expected signatures
662
+ - [ ] Look for typos in identifiers
663
+
664
+ **Fix Strategy:**
665
+ 1. Read the failing file
666
+ 2. Identify the specific error location
667
+ 3. Apply minimal fix
668
+ 4. Verify fix compiles
669
+ ```
670
+
671
+ ## Implementation Quality Standards
672
+
673
+ Before each commit, self-check against these standards:
674
+
675
+ ### 1. Scope Check
676
+ Does this change directly address an AC item?
677
+ - **Yes** → Proceed
678
+ - **No** → Is this refactor necessary for the AC? If not, skip it.
679
+
680
+ ### 2. Type Safety Check
681
+ Am I maintaining or improving types?
682
+ - **Avoid:** Adding `any`, removing type annotations, using `as any`
683
+ - **Good:** Adding types, making types more specific, proper type inference
684
+
685
+ ### 3. Test Coverage Check
686
+ Am I preserving existing test coverage?
687
+ - **Never** delete tests to "make build pass"
688
+ - **Always** update tests when behavior changes, add tests for new behavior
689
+
690
+ ### 4. Size Check
691
+ Is this change proportional to the AC?
692
+ - **Simple AC** (display, button, styling): <100 LOC
693
+ - **Medium AC** (CRUD, admin page, form): 100-300 LOC
694
+ - **Complex AC** (major feature, multi-component): 300-500 LOC
695
+ - **If larger:** Break into smaller, focused commits
696
+
697
+ ### 5. Integration Check
698
+ Are new files actually used?
699
+ - **Never** create components that aren't imported anywhere
700
+ - **Never** create utility functions that aren't called
701
+ - **Never** create API routes that aren't used from UI
702
+ - **Always** verify new exports are imported in at least one location
703
+
704
+ **Quick verification:**
705
+ ```bash
706
+ # Check for unused exports in new files
707
+ npm run knip 2>/dev/null | grep -E "unused|Unused" || echo "No unused exports"
708
+ ```
709
+
710
+ ### 6. Test Impact Check (File Conversions)
711
+
712
+ When converting files to stubs, deleting content, or significantly changing file structure:
713
+
714
+ Use the Grep tool to check if any tests depend on the modified file's content:
715
+ ```
716
+ Grep(pattern="filename.md", path="__tests__/")
717
+ Grep(pattern="filename", path="__tests__/")
718
+ # Then filter out .snap files from results
719
+ ```
720
+
721
+ **If tests are found:**
722
+ 1. Review what the tests are checking (file existence vs. content)
723
+ 2. Update tests to check the new location if content moved
724
+ 3. Run `npm test` after ALL file conversions are complete
725
+
726
+ **Why this matters:** Tests may pass during implementation but fail after final changes if they depend on content that was converted to a stub or moved elsewhere.
727
+
728
+ ### Red Flags to Avoid
729
+
730
+ These patterns indicate scope creep or over-engineering:
731
+ - Renaming functions/variables not related to AC
732
+ - Reformatting files you didn't otherwise modify
733
+ - "While I was here" improvements
734
+ - Converting JS to TS as a side effect
735
+ - Changing linting rules or config
736
+ - Adding abstractions for one-time use
737
+ - Creating utilities not required by AC
738
+
739
+ ### Quality Commitment
740
+
741
+ When in doubt, choose:
742
+ - **Minimal** over comprehensive
743
+ - **Explicit** over clever
744
+ - **Focused** over thorough
745
+ - **Working** over perfect
746
+
747
+ The goal is to satisfy AC with the smallest, safest change possible.
748
+
749
+ ### 5. Progress Summary and Draft Issue Update
750
+
751
+ At the end of a session:
752
+
753
+ 1. Summarize:
754
+ - Which AC items appear satisfied (AC-1, AC-2, ...).
755
+ - Which AC items are partially or not yet satisfied.
756
+ - Which checks were run and their outcomes (`npm test`, `npm run build`, etc.).
757
+ - Any remaining TODOs or recommended follow-ups.
758
+
759
+ 2. Draft a Markdown snippet as a **progress update** for the GitHub issue:
760
+
761
+ - Include:
762
+ - AC coverage summary
763
+ - Brief list of key files changed
764
+ - **PR Status** (Created with URL, or Failed with reason and manual instructions)
765
+ - Any known gaps or open questions
766
+
767
+ - Label it clearly as:
768
+
769
+ ```md
770
+ --- DRAFT GITHUB ISSUE COMMENT (PROGRESS UPDATE) ---
771
+
772
+ ...
773
+
774
+ ```
775
+
776
+ 3. **Update GitHub Issue**
777
+
778
+ - After drafting the progress update comment, post it to the GitHub issue:
779
+ ```bash
780
+ gh issue comment <issue-number> --body "$(cat <<'EOF'
781
+ [draft comment content]
782
+ EOF
783
+ )"
784
+ ```
785
+ - Include the AC coverage summary, files changed, and any gaps or questions in the comment.
786
+ - If the issue has status fields or labels, update them appropriately based on progress (e.g., mark as "in progress"):
787
+ ```bash
788
+ gh issue edit <issue-number> --add-label "in-progress"
789
+ ```
790
+
791
+ You may be invoked multiple times for the same issue. Each time, re-establish context, ensure you're in the correct worktree, and continue iterating until we are as close as practical to meeting the AC.
792
+
793
+ ---
794
+
795
+ ## Output Verification
796
+
797
+ **Before responding, verify your output includes ALL of these:**
798
+
799
+ - [ ] **AC Progress Summary** - Which AC items are satisfied, partially met, or blocked
800
+ - [ ] **Files Changed** - List of key files modified
801
+ - [ ] **Test/Build Results** - Output from `npm test` and `npm run build`
802
+ - [ ] **PR Status** - Created (with URL) or Failed (with error and manual instructions)
803
+ - [ ] **Progress Update Draft** - Formatted comment for GitHub issue
804
+ - [ ] **Documentation Reminder** - Note if README/docs need updating (checked in /qa)
805
+ - [ ] **Next Steps** - Clear guidance on remaining work
806
+
807
+ **DO NOT respond until all items are verified.**