continuous-improvement 3.1.0 → 3.9.1

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 (136) hide show
  1. package/.claude-plugin/marketplace.json +66 -0
  2. package/CHANGELOG.md +216 -0
  3. package/QUICKSTART.md +79 -12
  4. package/README.md +229 -349
  5. package/SKILL.md +87 -9
  6. package/action.yml +1 -1
  7. package/bin/analyze.sh +9 -1
  8. package/bin/backfill.mjs +172 -0
  9. package/bin/check-doc-runtime-claims.mjs +120 -0
  10. package/bin/check-docs-substrings.mjs +333 -0
  11. package/bin/check-everything-mirror.mjs +145 -0
  12. package/bin/check-routing-targets.mjs +151 -0
  13. package/bin/check-skill-law-tag.mjs +128 -0
  14. package/bin/check-skill-mirror.mjs +119 -0
  15. package/bin/check-skill-tiers.mjs +116 -0
  16. package/bin/check-third-party-shape.mjs +202 -0
  17. package/bin/generate-plugin-manifests.mjs +171 -0
  18. package/bin/harvest-friction.mjs +279 -0
  19. package/bin/hook-stats.mjs +258 -0
  20. package/bin/install.mjs +407 -499
  21. package/bin/lint-transcript.mjs +182 -210
  22. package/bin/mcp-server.mjs +834 -608
  23. package/bin/observe.mjs +148 -0
  24. package/bin/pre-commit-block-strays.sh +49 -0
  25. package/bin/refresh-third-party.mjs +416 -0
  26. package/bin/unified-cli.mjs +533 -0
  27. package/commands/continuous-improvement.md +43 -2
  28. package/commands/discipline.md +14 -0
  29. package/commands/harvest.md +76 -0
  30. package/commands/learn-eval.md +117 -0
  31. package/commands/planning-with-files.md +66 -0
  32. package/commands/proceed-with-the-recommendation.md +62 -0
  33. package/commands/ralph.md +103 -0
  34. package/commands/release-train.md +81 -0
  35. package/commands/seven-laws.md +16 -0
  36. package/commands/superpowers.md +180 -0
  37. package/commands/swarm.md +101 -0
  38. package/commands/workspace-surface-audit.md +77 -0
  39. package/hooks/gateguard.mjs +172 -0
  40. package/hooks/observe.sh +42 -4
  41. package/hooks/session.sh +3 -3
  42. package/hooks/three-section-close.mjs +181 -0
  43. package/instinct-packs/meta.json +16 -0
  44. package/lib/cli-anything.mjs +401 -0
  45. package/lib/compound-engineering.mjs +831 -0
  46. package/lib/gateguard-state.mjs +85 -0
  47. package/lib/observe-event.mjs +128 -0
  48. package/lib/plugin-metadata.mjs +435 -0
  49. package/lib/pm-marketplace.mjs +61 -0
  50. package/lib/pm-skills.mjs +1274 -0
  51. package/lib/resolve-home-dir.mjs +43 -0
  52. package/lib/skill-tiers.mjs +137 -0
  53. package/lib/unified-plugin.mjs +924 -0
  54. package/llms.txt +32 -7
  55. package/package.json +29 -19
  56. package/plugins/beginner.json +17 -6
  57. package/plugins/continuous-improvement/.claude-plugin/marketplace.json +20 -0
  58. package/plugins/continuous-improvement/.claude-plugin/plugin.json +26 -0
  59. package/plugins/continuous-improvement/LICENSE +21 -0
  60. package/plugins/continuous-improvement/README.md +57 -0
  61. package/plugins/continuous-improvement/agents/README.md +120 -0
  62. package/plugins/continuous-improvement/agents/code-reviewer.md +97 -0
  63. package/plugins/continuous-improvement/agents/security-auditor.md +101 -0
  64. package/plugins/continuous-improvement/agents/test-engineer.md +95 -0
  65. package/plugins/continuous-improvement/bin/backfill.mjs +172 -0
  66. package/plugins/continuous-improvement/bin/mcp-server.mjs +889 -0
  67. package/plugins/continuous-improvement/bin/observe.mjs +148 -0
  68. package/plugins/continuous-improvement/commands/continuous-improvement.md +115 -0
  69. package/plugins/continuous-improvement/commands/dashboard.md +56 -0
  70. package/plugins/continuous-improvement/commands/discipline.md +51 -0
  71. package/plugins/continuous-improvement/commands/harvest.md +76 -0
  72. package/plugins/continuous-improvement/commands/learn-eval.md +117 -0
  73. package/plugins/continuous-improvement/commands/planning-with-files.md +66 -0
  74. package/plugins/continuous-improvement/commands/proceed-with-the-recommendation.md +62 -0
  75. package/plugins/continuous-improvement/commands/ralph.md +103 -0
  76. package/plugins/continuous-improvement/commands/release-train.md +81 -0
  77. package/plugins/continuous-improvement/commands/seven-laws.md +16 -0
  78. package/plugins/continuous-improvement/commands/superpowers.md +180 -0
  79. package/plugins/continuous-improvement/commands/swarm.md +101 -0
  80. package/plugins/continuous-improvement/commands/workspace-surface-audit.md +77 -0
  81. package/plugins/continuous-improvement/hooks/gateguard.mjs +172 -0
  82. package/plugins/continuous-improvement/hooks/hooks.json +65 -0
  83. package/plugins/continuous-improvement/hooks/observe.sh +172 -0
  84. package/plugins/continuous-improvement/hooks/session.sh +106 -0
  85. package/plugins/continuous-improvement/hooks/three-section-close.mjs +181 -0
  86. package/plugins/continuous-improvement/instinct-packs/go.json +58 -0
  87. package/plugins/continuous-improvement/instinct-packs/meta.json +16 -0
  88. package/plugins/continuous-improvement/instinct-packs/python.json +58 -0
  89. package/plugins/continuous-improvement/instinct-packs/react.json +58 -0
  90. package/plugins/continuous-improvement/lib/observe-event.mjs +128 -0
  91. package/plugins/continuous-improvement/lib/plugin-metadata.mjs +435 -0
  92. package/plugins/continuous-improvement/lib/resolve-home-dir.mjs +43 -0
  93. package/plugins/continuous-improvement/skills/README.md +37 -0
  94. package/plugins/continuous-improvement/skills/continuous-improvement/SKILL.md +249 -0
  95. package/plugins/continuous-improvement/skills/deploy-receipt/SKILL.md +178 -0
  96. package/plugins/continuous-improvement/skills/gateguard/SKILL.md +163 -0
  97. package/plugins/continuous-improvement/skills/para-memory-files/SKILL.md +108 -0
  98. package/plugins/continuous-improvement/skills/proceed-with-the-recommendation/SKILL.md +447 -0
  99. package/plugins/continuous-improvement/skills/ralph/SKILL.md +221 -0
  100. package/plugins/continuous-improvement/skills/recovery-classification/SKILL.md +73 -0
  101. package/plugins/continuous-improvement/skills/safety-guard/SKILL.md +76 -0
  102. package/plugins/continuous-improvement/skills/state-reconciliation/SKILL.md +63 -0
  103. package/plugins/continuous-improvement/skills/strategic-compact/SKILL.md +104 -0
  104. package/plugins/continuous-improvement/skills/superpowers/SKILL.md +219 -0
  105. package/plugins/continuous-improvement/skills/tdd-workflow/SKILL.md +411 -0
  106. package/plugins/continuous-improvement/skills/token-budget-advisor/SKILL.md +136 -0
  107. package/plugins/continuous-improvement/skills/verification-loop/SKILL.md +224 -0
  108. package/plugins/continuous-improvement/skills/wild-risa-balance/SKILL.md +191 -0
  109. package/plugins/continuous-improvement/skills/workspace-surface-audit/SKILL.md +147 -0
  110. package/plugins/continuous-improvement/skills/worktree-safety/SKILL.md +66 -0
  111. package/plugins/continuous-improvement/templates/planning-with-files/findings.md +8 -0
  112. package/plugins/continuous-improvement/templates/planning-with-files/progress.md +7 -0
  113. package/plugins/continuous-improvement/templates/planning-with-files/task_plan.md +23 -0
  114. package/plugins/expert.json +26 -5
  115. package/skills/README.md +79 -0
  116. package/skills/deploy-receipt.md +178 -0
  117. package/skills/gateguard.md +163 -0
  118. package/skills/para-memory-files.md +108 -0
  119. package/skills/proceed-with-the-recommendation.md +447 -0
  120. package/skills/ralph.md +221 -0
  121. package/skills/recovery-classification.md +73 -0
  122. package/skills/safety-guard.md +76 -0
  123. package/skills/state-reconciliation.md +63 -0
  124. package/skills/strategic-compact.md +104 -0
  125. package/skills/superpowers.md +219 -0
  126. package/skills/tdd-workflow.md +411 -0
  127. package/skills/token-budget-advisor.md +136 -0
  128. package/skills/verification-loop.md +224 -0
  129. package/skills/wild-risa-balance.md +191 -0
  130. package/skills/workspace-surface-audit.md +147 -0
  131. package/skills/worktree-safety.md +66 -0
  132. package/templates/insights-claude-md.md +91 -0
  133. package/templates/planning-with-files/findings.md +8 -0
  134. package/templates/planning-with-files/progress.md +7 -0
  135. package/templates/planning-with-files/task_plan.md +23 -0
  136. package/templates/verify-ladder.example.json +60 -0
@@ -0,0 +1,219 @@
1
+ ---
2
+ name: superpowers
3
+ tier: companion
4
+ description: "Law activator for the 7 Laws of AI Agent Discipline. Unified four-source dispatcher — routes tasks to the correct Law-aligned specialist across the CI plugin (tdd-workflow, verification-loop, gateguard, ralph, deploy-receipt) and four registered upstream companions (Obra superpowers, addy agent-skills, ruflo-swarm, oh-my-claudecode) so the right discipline fires automatically instead of the agent skipping a step. Product-management coverage comes from phuryn/pm-skills via an out-of-band marketplace install (see docs/THIRD_PARTY.md). Not a peer skill — a dispatcher for the others."
5
+ origin: https://github.com/obra/superpowers
6
+ ---
7
+
8
+ # Superpowers — Mandatory Agent Workflows (Five-Source Dispatcher)
9
+
10
+ Superpowers enforces a structured development workflow. Skills activate automatically when their trigger conditions are met. This is not optional guidance — it is mandatory workflow.
11
+
12
+ ## Philosophy
13
+
14
+ AI agents skip steps, guess, and declare "done" without verifying. Superpowers blocks this by making workflow stages explicit and enforced.
15
+
16
+ ## What changed in v3.8.0
17
+
18
+ The dispatcher now routes across **four registered marketplaces** instead of relying on Obra installed separately. All four are installable from one marketplace entry:
19
+
20
+ ```
21
+ /plugin install superpowers@continuous-improvement # Obra's 14 workflow skills
22
+ /plugin install agent-skills@continuous-improvement # Addy's 21 SDLC skills
23
+ /plugin install ruflo-swarm@continuous-improvement # Agent swarm + Monitor stream
24
+ /plugin install oh-my-claudecode@continuous-improvement # 39 skills + 19 agents
25
+ ```
26
+
27
+ The CI plugin (this dispatcher + `tdd-workflow`, `verification-loop`, `gateguard`, `ralph`, `deploy-receipt`, etc.) installs by default. The four companions are opt-in — install only what you need.
28
+
29
+ Product-management coverage (PRD, OKRs, personas, GTM, etc.) is provided by `phuryn/pm-skills` via an out-of-band Claude Code marketplace install:
30
+
31
+ ```
32
+ claude plugin marketplace add phuryn/pm-skills
33
+ claude plugin install pm-toolkit@pm-skills
34
+ claude plugin install pm-product-strategy@pm-skills
35
+ claude plugin install pm-product-discovery@pm-skills
36
+ claude plugin install pm-market-research@pm-skills
37
+ claude plugin install pm-data-analytics@pm-skills
38
+ claude plugin install pm-marketing-growth@pm-skills
39
+ claude plugin install pm-go-to-market@pm-skills
40
+ claude plugin install pm-execution@pm-skills
41
+ ```
42
+
43
+ See `docs/THIRD_PARTY.md` for plugin-by-plugin scope.
44
+
45
+ ## The Basic Workflow
46
+
47
+ | Order | Skill | When It Activates |
48
+ |-------|-------|-------------------|
49
+ | 1 | **brainstorming** | Before writing code. Refines rough ideas through questions, explores alternatives, presents design in sections for validation. |
50
+ | 2 | **using-git-worktrees** | After design approval. Creates isolated workspace on new branch, runs project setup, verifies clean test baseline. |
51
+ | 3 | **writing-plans** | With approved design. Breaks work into bite-sized tasks (2-5 minutes each). Every task has exact file paths, complete code, verification steps. |
52
+ | 4 | **subagent-driven-development** or **executing-plans** | With plan. Dispatches fresh subagent per task with two-stage review (spec compliance, then code quality), or executes in batches with human checkpoints. |
53
+ | 5 | **test-driven-development** | During implementation. Enforces RED-GREEN-REFACTOR: write failing test, watch it fail, write minimal code, watch it pass, commit. Deletes code written before tests. |
54
+ | 6 | **requesting-code-review** | Between tasks. Reviews against plan, reports issues by severity. Critical issues block progress. |
55
+ | 7 | **finishing-a-development-branch** | When tasks complete. Verifies tests, presents options (merge/PR/keep/discard), cleans up worktree. |
56
+ | 8 | **deploy-receipt** | When the deploy branch auto-deploys (Railway / Cloudflare Workers / Vercel / Netlify / Fly.io / etc.). Verifies deployed SHA matches merge SHA and healthcheck returns 200. Until the receipt is COMPLETE the merge is not reported as done. |
57
+
58
+ The agent checks for relevant skills before any task. These are mandatory workflows, not suggestions.
59
+
60
+ ## Four-Source Routing Table
61
+
62
+ When a task trigger fires, the dispatcher resolves to the first available skill in the preference chain. Order = preference order. Items prefixed with `ci:` are bundled in this plugin; others are namespaced by their installed plugin name.
63
+
64
+ | Trigger | Law | Preferred → Fallback chain |
65
+ |---|---|---|
66
+ | Write a failing test before code | 3+4 | `ci:tdd-workflow` → `superpowers:test-driven-development` → `agent-skills:test-driven-development` |
67
+ | Verify before declaring done | 4 | `ci:verification-loop` → `superpowers:verification-before-completion` |
68
+ | Block edit until investigation present | 1 | `ci:gateguard` (no equivalents) |
69
+ | Diagnose root cause across layers | 6 | `superpowers:systematic-debugging` → `agent-skills:debugging-and-error-recovery` |
70
+ | Refine vague request into design | 2 | `superpowers:brainstorming` → `agent-skills:idea-refine` |
71
+ | Decompose plan into atomic tasks | 2 | `superpowers:writing-plans` → `agent-skills:planning-and-task-breakdown` → `ci:planning-with-files` |
72
+ | Execute plan with checkpoints | 3+6 | `superpowers:executing-plans` → `agent-skills:incremental-implementation` |
73
+ | Spawn fresh subagent per task | 3 | `superpowers:subagent-driven-development` → `superpowers:dispatching-parallel-agents` |
74
+ | Fan out N parallel agents on isolated worktrees | 3 | `superpowers:dispatching-parallel-agents` → `ruflo-swarm:swarm-init` |
75
+ | Stream live observation of long agent runs | 4 | `ruflo-swarm:monitor-stream` (only source) |
76
+ | Isolate work on a new branch | 3 | `superpowers:using-git-worktrees` (only source) |
77
+ | Decide merge / PR / discard at branch end | 3+4 | `superpowers:finishing-a-development-branch` → `agent-skills:shipping-and-launch` |
78
+ | Pre-review checklist before requesting review | 4 | `superpowers:requesting-code-review` → `agent-skills:code-review-and-quality` |
79
+ | Respond to reviewer feedback | 4 | `superpowers:receiving-code-review` |
80
+ | Verify deployed SHA matches merge SHA | 4 | `ci:deploy-receipt` (only source) |
81
+ | Audit repo / MCP / env at session start | 1 | `ci:workspace-surface-audit` (only source) |
82
+ | Run autonomous PRD loop | 6 | `ci:ralph` → `oh-my-claudecode:ralph` (heavy overlap; prefer CI) |
83
+ | Audit-then-execute production fix sweep | all | `ci:proceed-with-the-recommendation` (only source) |
84
+ | Spec-first contract before implementation | 2 | `agent-skills:spec-driven-development` (only source) |
85
+ | Source-first reading before writing | 1 | `agent-skills:source-driven-development` (only source) |
86
+ | Curate the right context window | 1 | `agent-skills:context-engineering` → `ci:context-budget` |
87
+ | Simplify code, remove duplication | 6 | `agent-skills:code-simplification` → `simplify` |
88
+ | Security review for auth/input/secrets | 4 | `agent-skills:security-and-hardening` → `security-review` |
89
+ | Browser-level visual regression | 4 | `oh-my-claudecode:visual-verdict` (only source) |
90
+ | Reflect after session, extract patterns | 5+7 | `ci:learn-eval` → `oh-my-claudecode:retrospective` |
91
+ | Long autonomous run with quality gates | 6 | `oh-my-claudecode:ultrawork` → `ci:ralph` |
92
+ | Coordinator role for staged hand-off | 3 | `ruflo-swarm:agents/coordinator` (when ruflo installed) |
93
+ | Product-management work (PRD, OKRs, personas, GTM, growth, market research, analytics) | 1+2+5 | Install `phuryn/pm-skills` via Claude Code marketplace — see docs/THIRD_PARTY.md. Eight installable plugins (`pm-toolkit`, `pm-product-strategy`, `pm-product-discovery`, `pm-market-research`, `pm-data-analytics`, `pm-marketing-growth`, `pm-go-to-market`, `pm-execution`) cover the full lifecycle. Out of band — not a `/plugin install <name>@continuous-improvement` target. |
94
+
95
+ When no installed plugin in the chain resolves, the dispatcher falls back to the inline protocols below (Test-Driven Development, Brainstorming, Plan Format, etc.) so the workflow still works on a clean install.
96
+
97
+ ## Stacked-PR Plan Precondition (≥3 files)
98
+
99
+ Any change touching three or more files — across `skills/`, `src/`, `bin/`, `commands/`, or any combination — must produce a stacked-PR plan as a precondition to the first edit landing. The 28-day usage report shows a clean correlation: sessions that opened with a stacked-PR plan landed at `fully_achieved`; sessions that began as a single big-bang multi-file edit landed at `partially_achieved` (landing-page dark theme, market-data-hub wiring, RAG misrouting). Single-concern PRs are the lever that closes that gap.
100
+
101
+ The required plan output has four components, in this order:
102
+
103
+ 1. **Per-PR table** — title, scope (files), test strategy, merge order. One row per PR.
104
+ 2. **Dependency graph** — which PRs depend on which (or "independent" if none).
105
+ 3. **Worktree per PR** — branch name + base commit. Sequential by default; parallel only when items share no state.
106
+ 4. **Out-of-scope list** — anything explicitly NOT in the train. Drive-by temptations get logged here, not implemented.
107
+
108
+ The plan ships as the FIRST commit of the train's first PR (under `docs/plans/YYYY-MM-DD-<slug>.md`) and is cited by every subsequent commit it produces.
109
+
110
+ ### When this rule does NOT fire
111
+
112
+ The threshold targets multi-concern feature work, not high-volume mechanical changes. The rule does NOT fire on:
113
+
114
+ - **Markdown-only commits** — README, CHANGELOG, docs/ updates that touch many files but ship one concern.
115
+ - **Lockfile-only commits** — `package-lock.json`, `pnpm-lock.yaml`, `Cargo.lock`, etc. updated in isolation by a dependency bump.
116
+ - **Generated-only commits** — output of `npm run build`, `tsc`, codemod sweeps, or any tool whose input is one source file and whose output is many derived files. The source change is what counts toward the threshold; the regenerated artifacts ride free.
117
+ - **Vendor-snapshot refreshes** — `third-party/<name>/` updated by a documented `bin/refresh-third-party.mjs` driver. The single source of change is the upstream SHA bump.
118
+ - **Skill-mirror sync commits** — `skills/<name>.md` + `plugins/continuous-improvement/skills/<name>/SKILL.md` count as one file pair, not two, since the CONTRIBUTING.md skill mirror rule treats them as the same concern.
119
+
120
+ If you are unsure whether the rule applies, the fall-through default is to write the plan. A 30-line plan doc is cheap; a stranded big-bang edit is expensive.
121
+
122
+ ## Skill Library
123
+
124
+ ### Testing
125
+ - **test-driven-development** — RED-GREEN-REFACTOR cycle (includes testing anti-patterns reference)
126
+
127
+ ### Debugging
128
+ - **systematic-debugging** — 4-phase root cause process (includes root-cause-tracing, defense-in-depth, condition-based-waiting techniques)
129
+ - **verification-before-completion** — Ensure it's actually fixed
130
+
131
+ ### Collaboration
132
+ - **brainstorming** — Socratic design refinement
133
+ - **writing-plans** — Detailed implementation plans
134
+ - **executing-plans** — Batch execution with checkpoints
135
+ - **dispatching-parallel-agents** — Concurrent subagent workflows
136
+ - **requesting-code-review** — Pre-review checklist
137
+ - **receiving-code-review** — Responding to feedback
138
+ - **using-git-worktrees** — Parallel development branches
139
+ - **finishing-a-development-branch** — Merge/PR decision workflow
140
+ - **subagent-driven-development** — Fast iteration with two-stage review (spec compliance, then code quality)
141
+
142
+ ### Deployment Verification
143
+ - **deploy-receipt** — Closes the merge-to-production gap on auto-deploy targets (CI-side companion to `finishing-a-development-branch`)
144
+
145
+ ### Meta
146
+ - **writing-skills** — Create new skills following best practices (includes testing methodology)
147
+ - **using-superpowers** — Introduction to the skills system
148
+
149
+ ## Test-Driven Development (Mandatory)
150
+
151
+ ```
152
+ RED: Write failing test → Watch it fail
153
+ GREEN: Write minimal code → Watch it pass
154
+ REFACTOR: Improve while staying green → Commit
155
+ ```
156
+
157
+ Code written before tests is deleted. No exceptions.
158
+
159
+ ## Brainstorming Protocol
160
+
161
+ When given a vague request:
162
+
163
+ 1. Ask clarifying questions
164
+ 2. Explore 2-3 alternative approaches
165
+ 3. Present design in sections
166
+ 4. Wait for explicit approval before proceeding
167
+
168
+ ## Plan Format
169
+
170
+ Every task in a plan must include:
171
+
172
+ ```yaml
173
+ - task: "Specific action"
174
+ file: "exact/path/to/file.ext"
175
+ code: "Complete implementation"
176
+ verify: "How to confirm it works"
177
+ estimate: "2-5 minutes"
178
+ ```
179
+
180
+ ## Code Review Severity
181
+
182
+ | Level | Action |
183
+ |-------|--------|
184
+ | Critical | Blocks progress. Must fix before continuing. |
185
+ | Warning | Should fix. Note and continue. |
186
+ | Info | Noted for later. No action required. |
187
+
188
+ ## Subagent Development
189
+
190
+ Two-stage review for every task:
191
+
192
+ 1. **Spec compliance** — Does it match the plan?
193
+ 2. **Code quality** — Is it clean, tested, and maintainable?
194
+
195
+ Both must pass. Fresh subagent per task prevents context pollution.
196
+
197
+ ## Git Worktrees
198
+
199
+ Each feature gets an isolated workspace:
200
+
201
+ ```bash
202
+ git worktree add -b feature-name ../feature-name
203
+ ```
204
+
205
+ Clean separation, parallel development, easy cleanup.
206
+
207
+ ## Using Superpowers
208
+
209
+ Superpowers skills activate when their trigger conditions are detected. The dispatcher resolves each trigger through the five-source routing table above:
210
+
211
+ - "Create a feature" → `superpowers:brainstorming` → `superpowers:writing-plans` → `superpowers:executing-plans`
212
+ - "Fix this bug" → `superpowers:systematic-debugging` → `superpowers:verification-before-completion`
213
+ - "Review this PR" → `superpowers:requesting-code-review`
214
+ - "Draft a PRD" / "Write OKRs" / "Build a persona" → install `phuryn/pm-skills` (out of band — see docs/THIRD_PARTY.md)
215
+ - "Run this PRD autonomously" → `ci:ralph`
216
+ - "Fan out parallel provider migration" → `superpowers:dispatching-parallel-agents` or `/swarm` (PR D)
217
+ - "Visual regression check the landing page" → `oh-my-claudecode:visual-verdict`
218
+
219
+ No manual skill selection. The framework detects the trigger, resolves the chain, and enforces.
@@ -0,0 +1,411 @@
1
+ ---
2
+ name: tdd-workflow
3
+ tier: "1"
4
+ description: Enforces Law 3 (One Thing at a Time) and Law 4 (Verify Before Reporting) of the 7 Laws of AI Agent Discipline. Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.
5
+ origin: continuous-improvement
6
+ ---
7
+
8
+ # Test-Driven Development Workflow
9
+
10
+ This skill ensures all code development follows TDD principles with comprehensive test coverage.
11
+
12
+ ## When to Activate
13
+
14
+ - Writing new features or functionality
15
+ - Fixing bugs or issues
16
+ - Refactoring existing code
17
+ - Adding API endpoints
18
+ - Creating new components
19
+
20
+ ## Core Principles
21
+
22
+ ### 1. Tests BEFORE Code
23
+ ALWAYS write tests first, then implement code to make tests pass.
24
+
25
+ ### 2. Coverage Requirements
26
+ - Minimum 80% coverage (unit + integration + E2E)
27
+ - All edge cases covered
28
+ - Error scenarios tested
29
+ - Boundary conditions verified
30
+
31
+ ### 3. Test Types
32
+
33
+ #### Unit Tests
34
+ - Individual functions and utilities
35
+ - Component logic
36
+ - Pure functions
37
+ - Helpers and utilities
38
+
39
+ #### Integration Tests
40
+ - API endpoints
41
+ - Database operations
42
+ - Service interactions
43
+ - External API calls
44
+
45
+ #### E2E Tests (Playwright)
46
+ - Critical user flows
47
+ - Complete workflows
48
+ - Browser automation
49
+ - UI interactions
50
+
51
+ ## TDD Workflow Steps
52
+
53
+ ### Step 1: Write User Journeys
54
+ ```
55
+ As a [role], I want to [action], so that [benefit]
56
+
57
+ Example:
58
+ As a user, I want to search for markets semantically,
59
+ so that I can find relevant markets even without exact keywords.
60
+ ```
61
+
62
+ ### Step 2: Generate Test Cases
63
+ For each user journey, create comprehensive test cases:
64
+
65
+ ```typescript
66
+ describe('Semantic Search', () => {
67
+ it('returns relevant markets for query', async () => {
68
+ // Test implementation
69
+ })
70
+
71
+ it('handles empty query gracefully', async () => {
72
+ // Test edge case
73
+ })
74
+
75
+ it('falls back to substring search when Redis unavailable', async () => {
76
+ // Test fallback behavior
77
+ })
78
+
79
+ it('sorts results by similarity score', async () => {
80
+ // Test sorting logic
81
+ })
82
+ })
83
+ ```
84
+
85
+ ### Step 3: Run Tests (They Should Fail)
86
+ ```bash
87
+ npm test
88
+ # Tests should fail - we haven't implemented yet
89
+ ```
90
+
91
+ ### Step 4: Implement Code
92
+ Write minimal code to make tests pass:
93
+
94
+ ```typescript
95
+ // Implementation guided by tests
96
+ export async function searchMarkets(query: string) {
97
+ // Implementation here
98
+ }
99
+ ```
100
+
101
+ ### Step 5: Run Tests Again
102
+ ```bash
103
+ npm test
104
+ # Tests should now pass
105
+ ```
106
+
107
+ ### Step 6: Refactor
108
+ Improve code quality while keeping tests green:
109
+ - Remove duplication
110
+ - Improve naming
111
+ - Optimize performance
112
+ - Enhance readability
113
+
114
+ ### Step 7: Verify Coverage
115
+ ```bash
116
+ npm run test:coverage
117
+ # Verify 80%+ coverage achieved
118
+ ```
119
+
120
+ ## Testing Patterns
121
+
122
+ ### Unit Test Pattern (Jest/Vitest)
123
+ ```typescript
124
+ import { render, screen, fireEvent } from '@testing-library/react'
125
+ import { Button } from './Button'
126
+
127
+ describe('Button Component', () => {
128
+ it('renders with correct text', () => {
129
+ render(<Button>Click me</Button>)
130
+ expect(screen.getByText('Click me')).toBeInTheDocument()
131
+ })
132
+
133
+ it('calls onClick when clicked', () => {
134
+ const handleClick = jest.fn()
135
+ render(<Button onClick={handleClick}>Click</Button>)
136
+
137
+ fireEvent.click(screen.getByRole('button'))
138
+
139
+ expect(handleClick).toHaveBeenCalledTimes(1)
140
+ })
141
+
142
+ it('is disabled when disabled prop is true', () => {
143
+ render(<Button disabled>Click</Button>)
144
+ expect(screen.getByRole('button')).toBeDisabled()
145
+ })
146
+ })
147
+ ```
148
+
149
+ ### API Integration Test Pattern
150
+ ```typescript
151
+ import { NextRequest } from 'next/server'
152
+ import { GET } from './route'
153
+
154
+ describe('GET /api/markets', () => {
155
+ it('returns markets successfully', async () => {
156
+ const request = new NextRequest('http://localhost/api/markets')
157
+ const response = await GET(request)
158
+ const data = await response.json()
159
+
160
+ expect(response.status).toBe(200)
161
+ expect(data.success).toBe(true)
162
+ expect(Array.isArray(data.data)).toBe(true)
163
+ })
164
+
165
+ it('validates query parameters', async () => {
166
+ const request = new NextRequest('http://localhost/api/markets?limit=invalid')
167
+ const response = await GET(request)
168
+
169
+ expect(response.status).toBe(400)
170
+ })
171
+
172
+ it('handles database errors gracefully', async () => {
173
+ // Mock database failure
174
+ const request = new NextRequest('http://localhost/api/markets')
175
+ // Test error handling
176
+ })
177
+ })
178
+ ```
179
+
180
+ ### E2E Test Pattern (Playwright)
181
+ ```typescript
182
+ import { test, expect } from '@playwright/test'
183
+
184
+ test('user can search and filter markets', async ({ page }) => {
185
+ // Navigate to markets page
186
+ await page.goto('/')
187
+ await page.click('a[href="/markets"]')
188
+
189
+ // Verify page loaded
190
+ await expect(page.locator('h1')).toContainText('Markets')
191
+
192
+ // Search for markets
193
+ await page.fill('input[placeholder="Search markets"]', 'election')
194
+
195
+ // Wait for debounce and results
196
+ await page.waitForTimeout(600)
197
+
198
+ // Verify search results displayed
199
+ const results = page.locator('[data-testid="market-card"]')
200
+ await expect(results).toHaveCount(5, { timeout: 5000 })
201
+
202
+ // Verify results contain search term
203
+ const firstResult = results.first()
204
+ await expect(firstResult).toContainText('election', { ignoreCase: true })
205
+
206
+ // Filter by status
207
+ await page.click('button:has-text("Active")')
208
+
209
+ // Verify filtered results
210
+ await expect(results).toHaveCount(3)
211
+ })
212
+
213
+ test('user can create a new market', async ({ page }) => {
214
+ // Login first
215
+ await page.goto('/creator-dashboard')
216
+
217
+ // Fill market creation form
218
+ await page.fill('input[name="name"]', 'Test Market')
219
+ await page.fill('textarea[name="description"]', 'Test description')
220
+ await page.fill('input[name="endDate"]', '2025-12-31')
221
+
222
+ // Submit form
223
+ await page.click('button[type="submit"]')
224
+
225
+ // Verify success message
226
+ await expect(page.locator('text=Market created successfully')).toBeVisible()
227
+
228
+ // Verify redirect to market page
229
+ await expect(page).toHaveURL(/\/markets\/test-market/)
230
+ })
231
+ ```
232
+
233
+ ## Test File Organization
234
+
235
+ ```
236
+ src/
237
+ ├── components/
238
+ │ ├── Button/
239
+ │ │ ├── Button.tsx
240
+ │ │ ├── Button.test.tsx # Unit tests
241
+ │ │ └── Button.stories.tsx # Storybook
242
+ │ └── MarketCard/
243
+ │ ├── MarketCard.tsx
244
+ │ └── MarketCard.test.tsx
245
+ ├── app/
246
+ │ └── api/
247
+ │ └── markets/
248
+ │ ├── route.ts
249
+ │ └── route.test.ts # Integration tests
250
+ └── e2e/
251
+ ├── markets.spec.ts # E2E tests
252
+ ├── trading.spec.ts
253
+ └── auth.spec.ts
254
+ ```
255
+
256
+ ## Mocking External Services
257
+
258
+ ### Supabase Mock
259
+ ```typescript
260
+ jest.mock('@/lib/supabase', () => ({
261
+ supabase: {
262
+ from: jest.fn(() => ({
263
+ select: jest.fn(() => ({
264
+ eq: jest.fn(() => Promise.resolve({
265
+ data: [{ id: 1, name: 'Test Market' }],
266
+ error: null
267
+ }))
268
+ }))
269
+ }))
270
+ }
271
+ }))
272
+ ```
273
+
274
+ ### Redis Mock
275
+ ```typescript
276
+ jest.mock('@/lib/redis', () => ({
277
+ searchMarketsByVector: jest.fn(() => Promise.resolve([
278
+ { slug: 'test-market', similarity_score: 0.95 }
279
+ ])),
280
+ checkRedisHealth: jest.fn(() => Promise.resolve({ connected: true }))
281
+ }))
282
+ ```
283
+
284
+ ### OpenAI Mock
285
+ ```typescript
286
+ jest.mock('@/lib/openai', () => ({
287
+ generateEmbedding: jest.fn(() => Promise.resolve(
288
+ new Array(1536).fill(0.1) // Mock 1536-dim embedding
289
+ ))
290
+ }))
291
+ ```
292
+
293
+ ## Test Coverage Verification
294
+
295
+ ### Run Coverage Report
296
+ ```bash
297
+ npm run test:coverage
298
+ ```
299
+
300
+ ### Coverage Thresholds
301
+ ```json
302
+ {
303
+ "jest": {
304
+ "coverageThresholds": {
305
+ "global": {
306
+ "branches": 80,
307
+ "functions": 80,
308
+ "lines": 80,
309
+ "statements": 80
310
+ }
311
+ }
312
+ }
313
+ }
314
+ ```
315
+
316
+ ## Common Testing Mistakes to Avoid
317
+
318
+ ### FAIL: WRONG: Testing Implementation Details
319
+ ```typescript
320
+ // Don't test internal state
321
+ expect(component.state.count).toBe(5)
322
+ ```
323
+
324
+ ### PASS: CORRECT: Test User-Visible Behavior
325
+ ```typescript
326
+ // Test what users see
327
+ expect(screen.getByText('Count: 5')).toBeInTheDocument()
328
+ ```
329
+
330
+ ### FAIL: WRONG: Brittle Selectors
331
+ ```typescript
332
+ // Breaks easily
333
+ await page.click('.css-class-xyz')
334
+ ```
335
+
336
+ ### PASS: CORRECT: Semantic Selectors
337
+ ```typescript
338
+ // Resilient to changes
339
+ await page.click('button:has-text("Submit")')
340
+ await page.click('[data-testid="submit-button"]')
341
+ ```
342
+
343
+ ### FAIL: WRONG: No Test Isolation
344
+ ```typescript
345
+ // Tests depend on each other
346
+ test('creates user', () => { /* ... */ })
347
+ test('updates same user', () => { /* depends on previous test */ })
348
+ ```
349
+
350
+ ### PASS: CORRECT: Independent Tests
351
+ ```typescript
352
+ // Each test sets up its own data
353
+ test('creates user', () => {
354
+ const user = createTestUser()
355
+ // Test logic
356
+ })
357
+
358
+ test('updates user', () => {
359
+ const user = createTestUser()
360
+ // Update logic
361
+ })
362
+ ```
363
+
364
+ ## Continuous Testing
365
+
366
+ ### Watch Mode During Development
367
+ ```bash
368
+ npm test -- --watch
369
+ # Tests run automatically on file changes
370
+ ```
371
+
372
+ ### Pre-Commit Hook
373
+ ```bash
374
+ # Runs before every commit
375
+ npm test && npm run lint
376
+ ```
377
+
378
+ ### CI/CD Integration
379
+ ```yaml
380
+ # GitHub Actions
381
+ - name: Run Tests
382
+ run: npm test -- --coverage
383
+ - name: Upload Coverage
384
+ uses: codecov/codecov-action@v3
385
+ ```
386
+
387
+ ## Best Practices
388
+
389
+ 1. **Write Tests First** - Always TDD
390
+ 2. **One Assert Per Test** - Focus on single behavior
391
+ 3. **Descriptive Test Names** - Explain what's tested
392
+ 4. **Arrange-Act-Assert** - Clear test structure
393
+ 5. **Mock External Dependencies** - Isolate unit tests
394
+ 6. **Test Edge Cases** - Null, undefined, empty, large
395
+ 7. **Test Error Paths** - Not just happy paths
396
+ 8. **Keep Tests Fast** - Unit tests < 50ms each
397
+ 9. **Clean Up After Tests** - No side effects
398
+ 10. **Review Coverage Reports** - Identify gaps
399
+
400
+ ## Success Metrics
401
+
402
+ - 80%+ code coverage achieved
403
+ - All tests passing (green)
404
+ - No skipped or disabled tests
405
+ - Fast test execution (< 30s for unit tests)
406
+ - E2E tests cover critical user flows
407
+ - Tests catch bugs before production
408
+
409
+ ---
410
+
411
+ **Remember**: Tests are not optional. They are the safety net that enables confident refactoring, rapid development, and production reliability.