chati-dev 1.4.0 → 2.0.2

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 (208) hide show
  1. package/README.md +40 -24
  2. package/framework/agents/build/dev.md +343 -0
  3. package/framework/agents/clarity/architect.md +112 -0
  4. package/framework/agents/clarity/brief.md +182 -0
  5. package/framework/agents/clarity/brownfield-wu.md +181 -0
  6. package/framework/agents/clarity/detail.md +110 -0
  7. package/framework/agents/clarity/greenfield-wu.md +153 -0
  8. package/framework/agents/clarity/ux.md +112 -0
  9. package/framework/config.yaml +3 -3
  10. package/framework/constitution.md +31 -1
  11. package/framework/context/governance.md +37 -0
  12. package/framework/context/protocols.md +34 -0
  13. package/framework/context/quality.md +27 -0
  14. package/framework/context/root.md +24 -0
  15. package/framework/data/entity-registry.yaml +1 -1
  16. package/framework/domains/agents/architect.yaml +51 -0
  17. package/framework/domains/agents/brief.yaml +47 -0
  18. package/framework/domains/agents/brownfield-wu.yaml +49 -0
  19. package/framework/domains/agents/detail.yaml +47 -0
  20. package/framework/domains/agents/dev.yaml +49 -0
  21. package/framework/domains/agents/devops.yaml +43 -0
  22. package/framework/domains/agents/greenfield-wu.yaml +47 -0
  23. package/framework/domains/agents/orchestrator.yaml +49 -0
  24. package/framework/domains/agents/phases.yaml +47 -0
  25. package/framework/domains/agents/qa-implementation.yaml +43 -0
  26. package/framework/domains/agents/qa-planning.yaml +44 -0
  27. package/framework/domains/agents/tasks.yaml +48 -0
  28. package/framework/domains/agents/ux.yaml +50 -0
  29. package/framework/domains/constitution.yaml +77 -0
  30. package/framework/domains/global.yaml +64 -0
  31. package/framework/domains/workflows/brownfield-discovery.yaml +16 -0
  32. package/framework/domains/workflows/brownfield-fullstack.yaml +26 -0
  33. package/framework/domains/workflows/brownfield-service.yaml +22 -0
  34. package/framework/domains/workflows/brownfield-ui.yaml +22 -0
  35. package/framework/domains/workflows/greenfield-fullstack.yaml +26 -0
  36. package/framework/hooks/constitution-guard.js +101 -0
  37. package/framework/hooks/mode-governance.js +92 -0
  38. package/framework/hooks/model-governance.js +76 -0
  39. package/framework/hooks/prism-engine.js +89 -0
  40. package/framework/hooks/session-digest.js +60 -0
  41. package/framework/hooks/settings.json +44 -0
  42. package/framework/i18n/en.yaml +3 -3
  43. package/framework/i18n/es.yaml +3 -3
  44. package/framework/i18n/fr.yaml +3 -3
  45. package/framework/i18n/pt.yaml +3 -3
  46. package/framework/intelligence/decision-engine.md +1 -1
  47. package/framework/migrations/v1.4-to-v2.0.yaml +167 -0
  48. package/framework/migrations/v2.0-to-v2.0.1.yaml +132 -0
  49. package/framework/orchestrator/chati.md +284 -6
  50. package/framework/tasks/architect-api-design.md +63 -0
  51. package/framework/tasks/architect-consolidate.md +47 -0
  52. package/framework/tasks/architect-db-design.md +73 -0
  53. package/framework/tasks/architect-design.md +95 -0
  54. package/framework/tasks/architect-security-review.md +62 -0
  55. package/framework/tasks/architect-stack-selection.md +53 -0
  56. package/framework/tasks/brief-consolidate.md +249 -0
  57. package/framework/tasks/brief-constraint-identify.md +277 -0
  58. package/framework/tasks/brief-extract-requirements.md +339 -0
  59. package/framework/tasks/brief-stakeholder-map.md +176 -0
  60. package/framework/tasks/brief-validate-completeness.md +121 -0
  61. package/framework/tasks/brownfield-wu-architecture-map.md +394 -0
  62. package/framework/tasks/brownfield-wu-deep-discovery.md +312 -0
  63. package/framework/tasks/brownfield-wu-dependency-scan.md +359 -0
  64. package/framework/tasks/brownfield-wu-migration-plan.md +483 -0
  65. package/framework/tasks/brownfield-wu-report.md +325 -0
  66. package/framework/tasks/brownfield-wu-risk-assess.md +424 -0
  67. package/framework/tasks/detail-acceptance-criteria.md +372 -0
  68. package/framework/tasks/detail-consolidate.md +138 -0
  69. package/framework/tasks/detail-edge-case-analysis.md +300 -0
  70. package/framework/tasks/detail-expand-prd.md +389 -0
  71. package/framework/tasks/detail-nfr-extraction.md +223 -0
  72. package/framework/tasks/dev-code-review.md +404 -0
  73. package/framework/tasks/dev-consolidate.md +543 -0
  74. package/framework/tasks/dev-debug.md +322 -0
  75. package/framework/tasks/dev-implement.md +252 -0
  76. package/framework/tasks/dev-iterate.md +411 -0
  77. package/framework/tasks/dev-pr-prepare.md +497 -0
  78. package/framework/tasks/dev-refactor.md +342 -0
  79. package/framework/tasks/dev-test-write.md +306 -0
  80. package/framework/tasks/devops-ci-setup.md +412 -0
  81. package/framework/tasks/devops-consolidate.md +712 -0
  82. package/framework/tasks/devops-deploy-config.md +598 -0
  83. package/framework/tasks/devops-monitoring-setup.md +658 -0
  84. package/framework/tasks/devops-release-prepare.md +673 -0
  85. package/framework/tasks/greenfield-wu-analyze-empty.md +169 -0
  86. package/framework/tasks/greenfield-wu-report.md +266 -0
  87. package/framework/tasks/greenfield-wu-scaffold-detection.md +203 -0
  88. package/framework/tasks/greenfield-wu-tech-stack-assess.md +255 -0
  89. package/framework/tasks/orchestrator-deviation.md +260 -0
  90. package/framework/tasks/orchestrator-escalate.md +276 -0
  91. package/framework/tasks/orchestrator-handoff.md +243 -0
  92. package/framework/tasks/orchestrator-health.md +372 -0
  93. package/framework/tasks/orchestrator-mode-switch.md +262 -0
  94. package/framework/tasks/orchestrator-resume.md +189 -0
  95. package/framework/tasks/orchestrator-route.md +169 -0
  96. package/framework/tasks/orchestrator-spawn-terminal.md +358 -0
  97. package/framework/tasks/orchestrator-status.md +260 -0
  98. package/framework/tasks/orchestrator-suggest-mode.md +372 -0
  99. package/framework/tasks/phases-breakdown.md +91 -0
  100. package/framework/tasks/phases-dependency-mapping.md +67 -0
  101. package/framework/tasks/phases-mvp-scoping.md +94 -0
  102. package/framework/tasks/qa-impl-consolidate.md +522 -0
  103. package/framework/tasks/qa-impl-performance-test.md +487 -0
  104. package/framework/tasks/qa-impl-regression-check.md +413 -0
  105. package/framework/tasks/qa-impl-sast-scan.md +402 -0
  106. package/framework/tasks/qa-impl-test-execute.md +344 -0
  107. package/framework/tasks/qa-impl-verdict.md +339 -0
  108. package/framework/tasks/qa-planning-consolidate.md +309 -0
  109. package/framework/tasks/qa-planning-coverage-plan.md +338 -0
  110. package/framework/tasks/qa-planning-gate-define.md +339 -0
  111. package/framework/tasks/qa-planning-risk-matrix.md +631 -0
  112. package/framework/tasks/qa-planning-test-strategy.md +217 -0
  113. package/framework/tasks/tasks-acceptance-write.md +75 -0
  114. package/framework/tasks/tasks-consolidate.md +57 -0
  115. package/framework/tasks/tasks-decompose.md +80 -0
  116. package/framework/tasks/tasks-estimate.md +66 -0
  117. package/framework/tasks/ux-a11y-check.md +49 -0
  118. package/framework/tasks/ux-component-map.md +55 -0
  119. package/framework/tasks/ux-consolidate.md +46 -0
  120. package/framework/tasks/ux-user-flow.md +46 -0
  121. package/framework/tasks/ux-wireframe.md +76 -0
  122. package/package.json +2 -2
  123. package/scripts/bundle-framework.js +2 -0
  124. package/scripts/changelog-generator.js +222 -0
  125. package/scripts/codebase-mapper.js +728 -0
  126. package/scripts/commit-message-generator.js +167 -0
  127. package/scripts/coverage-analyzer.js +260 -0
  128. package/scripts/dependency-analyzer.js +280 -0
  129. package/scripts/framework-analyzer.js +308 -0
  130. package/scripts/generate-constitution-domain.js +253 -0
  131. package/scripts/health-check.js +481 -0
  132. package/scripts/ide-sync.js +327 -0
  133. package/scripts/performance-analyzer.js +325 -0
  134. package/scripts/plan-tracker.js +278 -0
  135. package/scripts/populate-entity-registry.js +481 -0
  136. package/scripts/pr-review.js +317 -0
  137. package/scripts/rollback-manager.js +310 -0
  138. package/scripts/stuck-detector.js +343 -0
  139. package/scripts/test-quality-assessment.js +257 -0
  140. package/scripts/validate-agents.js +367 -0
  141. package/scripts/validate-tasks.js +465 -0
  142. package/src/autonomy/autonomous-gate.js +293 -0
  143. package/src/autonomy/index.js +51 -0
  144. package/src/autonomy/mode-manager.js +225 -0
  145. package/src/autonomy/mode-suggester.js +283 -0
  146. package/src/autonomy/progress-reporter.js +268 -0
  147. package/src/autonomy/safety-net.js +320 -0
  148. package/src/context/bracket-tracker.js +79 -0
  149. package/src/context/domain-loader.js +107 -0
  150. package/src/context/engine.js +144 -0
  151. package/src/context/formatter.js +184 -0
  152. package/src/context/index.js +4 -0
  153. package/src/context/layers/l0-constitution.js +28 -0
  154. package/src/context/layers/l1-global.js +37 -0
  155. package/src/context/layers/l2-agent.js +39 -0
  156. package/src/context/layers/l3-workflow.js +42 -0
  157. package/src/context/layers/l4-task.js +24 -0
  158. package/src/decision/analyzer.js +167 -0
  159. package/src/decision/engine.js +270 -0
  160. package/src/decision/index.js +38 -0
  161. package/src/decision/registry-healer.js +450 -0
  162. package/src/decision/registry-updater.js +330 -0
  163. package/src/gates/circuit-breaker.js +119 -0
  164. package/src/gates/g1-planning-complete.js +153 -0
  165. package/src/gates/g2-qa-planning.js +153 -0
  166. package/src/gates/g3-implementation.js +188 -0
  167. package/src/gates/g4-qa-implementation.js +207 -0
  168. package/src/gates/g5-deploy-ready.js +180 -0
  169. package/src/gates/gate-base.js +144 -0
  170. package/src/gates/index.js +46 -0
  171. package/src/installer/brownfield-upgrader.js +249 -0
  172. package/src/installer/core.js +82 -11
  173. package/src/installer/file-hasher.js +51 -0
  174. package/src/installer/manifest.js +117 -0
  175. package/src/installer/templates.js +17 -15
  176. package/src/installer/transaction.js +229 -0
  177. package/src/installer/validator.js +18 -1
  178. package/src/intelligence/registry-manager.js +2 -2
  179. package/src/memory/agent-memory.js +255 -0
  180. package/src/memory/gotchas-injector.js +72 -0
  181. package/src/memory/gotchas.js +361 -0
  182. package/src/memory/index.js +35 -0
  183. package/src/memory/search.js +233 -0
  184. package/src/memory/session-digest.js +239 -0
  185. package/src/merger/env-merger.js +112 -0
  186. package/src/merger/index.js +56 -0
  187. package/src/merger/replace-merger.js +51 -0
  188. package/src/merger/yaml-merger.js +127 -0
  189. package/src/orchestrator/agent-selector.js +285 -0
  190. package/src/orchestrator/deviation-handler.js +350 -0
  191. package/src/orchestrator/handoff-engine.js +271 -0
  192. package/src/orchestrator/index.js +67 -0
  193. package/src/orchestrator/intent-classifier.js +264 -0
  194. package/src/orchestrator/pipeline-manager.js +492 -0
  195. package/src/orchestrator/pipeline-state.js +223 -0
  196. package/src/orchestrator/session-manager.js +409 -0
  197. package/src/tasks/executor.js +195 -0
  198. package/src/tasks/handoff.js +226 -0
  199. package/src/tasks/index.js +4 -0
  200. package/src/tasks/loader.js +210 -0
  201. package/src/tasks/router.js +182 -0
  202. package/src/terminal/collector.js +216 -0
  203. package/src/terminal/index.js +30 -0
  204. package/src/terminal/isolation.js +129 -0
  205. package/src/terminal/monitor.js +277 -0
  206. package/src/terminal/spawner.js +269 -0
  207. package/src/upgrade/checker.js +1 -1
  208. package/src/wizard/i18n.js +3 -3
@@ -0,0 +1,342 @@
1
+ ---
2
+ id: dev-refactor
3
+ agent: dev
4
+ trigger: dev-test-write
5
+ phase: build
6
+ requires_input: false
7
+ parallelizable: false
8
+ outputs: [refactored-code]
9
+ handoff_to: dev-debug
10
+ autonomous_gate: true
11
+ criteria:
12
+ - No code duplication
13
+ - Functions under 50 lines
14
+ - Naming is clear
15
+ ---
16
+ # Refactor Code
17
+
18
+ ## Purpose
19
+ Improve code quality, readability, and maintainability while preserving functionality, applying DRY, SOLID principles, and project conventions.
20
+
21
+ ## Prerequisites
22
+ - Implementation complete with passing tests
23
+ - Test suite provides safety net
24
+ - Implementation log and test report available
25
+ - Code compiles and lints successfully
26
+ - Understanding of project architecture
27
+
28
+ ## Steps
29
+
30
+ ### 1. Review Current Code State
31
+ Analyze the implementation for refactoring opportunities:
32
+ - Read all newly created files
33
+ - Review modified sections
34
+ - Identify code smells
35
+ - Note complexity hotspots
36
+ - Check for duplication
37
+
38
+ ### 2. Identify Duplication
39
+ Find repeated code patterns:
40
+ - Use Grep to search for similar patterns
41
+ - Look for copy-pasted blocks
42
+ - Find repeated logic
43
+ - Note similar function structures
44
+ - Identify duplicated constants or types
45
+
46
+ ### 3. Extract Common Functions
47
+ Pull out reusable utilities:
48
+ - Create helper functions for repeated logic
49
+ - Move to appropriate utility modules
50
+ - Name functions clearly and descriptively
51
+ - Add proper documentation
52
+ - Ensure single responsibility
53
+
54
+ Example:
55
+ ```typescript
56
+ // Before
57
+ function validateEmail(email: string): boolean {
58
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
59
+ }
60
+
61
+ function validateUsername(username: string): boolean {
62
+ return /^[a-zA-Z0-9_]{3,20}$/.test(username);
63
+ }
64
+
65
+ // After - extract to validators.ts
66
+ export const patterns = {
67
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
68
+ username: /^[a-zA-Z0-9_]{3,20}$/
69
+ };
70
+
71
+ export function matchesPattern(value: string, pattern: RegExp): boolean {
72
+ return pattern.test(value);
73
+ }
74
+ ```
75
+
76
+ ### 4. Break Down Large Functions
77
+ Split functions exceeding 50 lines:
78
+ - Identify logical sections
79
+ - Extract to named sub-functions
80
+ - Maintain clear data flow
81
+ - Keep functions focused
82
+ - Use descriptive names
83
+
84
+ ### 5. Improve Naming
85
+ Enhance clarity through better names:
86
+ - Replace abbreviations with full words
87
+ - Use domain language
88
+ - Make boolean functions ask questions
89
+ - Use verbs for functions, nouns for classes
90
+ - Be specific and descriptive
91
+
92
+ Examples:
93
+ - `proc()` → `processPayment()`
94
+ - `data` → `userProfile`
95
+ - `check()` → `isValid()`
96
+ - `handle()` → `handleSubmit()`
97
+
98
+ ### 6. Apply SOLID Principles
99
+ Refactor toward clean architecture:
100
+
101
+ **Single Responsibility**: Each class/function does one thing
102
+ **Open/Closed**: Open for extension, closed for modification
103
+ **Liskov Substitution**: Subtypes must be substitutable
104
+ **Interface Segregation**: Small, focused interfaces
105
+ **Dependency Inversion**: Depend on abstractions
106
+
107
+ ### 7. Simplify Complex Conditionals
108
+ Make logic easier to understand:
109
+ - Extract conditions to named variables
110
+ - Use early returns to reduce nesting
111
+ - Convert complex if-else to strategy patterns
112
+ - Use guard clauses
113
+ - Simplify boolean expressions
114
+
115
+ Example:
116
+ ```typescript
117
+ // Before
118
+ if (user && user.isActive && user.hasPermission('write') && !user.isBanned) {
119
+ // do something
120
+ }
121
+
122
+ // After
123
+ const canWrite = user?.isActive
124
+ && user?.hasPermission('write')
125
+ && !user?.isBanned;
126
+
127
+ if (canWrite) {
128
+ // do something
129
+ }
130
+ ```
131
+
132
+ ### 8. Optimize Data Structures
133
+ Choose appropriate structures:
134
+ - Use Map/Set when appropriate
135
+ - Consider arrays vs objects
136
+ - Use immutable patterns
137
+ - Avoid nested structures
138
+ - Flatten where possible
139
+
140
+ ### 9. Improve Error Handling
141
+ Make errors more robust:
142
+ - Create custom error classes
143
+ - Add error context
144
+ - Use typed errors
145
+ - Centralize error handling
146
+ - Add recovery mechanisms
147
+
148
+ ### 10. Enhance Type Safety
149
+ Strengthen TypeScript usage:
150
+ - Replace `any` with specific types
151
+ - Use union types appropriately
152
+ - Add type guards
153
+ - Use const assertions
154
+ - Leverage utility types
155
+
156
+ ### 11. Add Code Comments
157
+ Document complex logic:
158
+ - Explain "why", not "what"
159
+ - Document assumptions
160
+ - Note edge cases
161
+ - Warn about gotchas
162
+ - Keep comments up to date
163
+
164
+ ### 12. Run Tests Continuously
165
+ Verify refactoring doesn't break functionality:
166
+ - Run test suite after each change
167
+ - Commit working state frequently
168
+ - Use test coverage to find gaps
169
+ - Add tests if coverage drops
170
+ - Verify all acceptance criteria still pass
171
+
172
+ ## Decision Points
173
+
174
+ ### When to Stop Refactoring
175
+ Refactoring is complete when:
176
+ 1. No obvious duplication remains
177
+ 2. Functions are reasonably sized
178
+ 3. Names are clear and consistent
179
+ 4. Tests still pass
180
+ 5. Code complexity is acceptable
181
+
182
+ Don't over-optimize or chase perfection.
183
+
184
+ ### When Architecture Needs Changing
185
+ If refactoring reveals architectural issues:
186
+ 1. Document the problem
187
+ 2. Assess impact of change
188
+ 3. Discuss with orchestrator
189
+ 4. May need to loop back to architect
190
+ 5. Don't make major changes without approval
191
+
192
+ ### When Performance Suffers
193
+ If refactoring impacts performance:
194
+ 1. Profile before and after
195
+ 2. Identify the bottleneck
196
+ 3. Consider optimization
197
+ 4. Balance readability vs speed
198
+ 5. Document performance decisions
199
+
200
+ ## Error Handling
201
+
202
+ ### Tests Failing After Refactor
203
+ - Identify which tests broke
204
+ - Review changes made
205
+ - Check for logic errors
206
+ - Verify test assumptions still valid
207
+ - Revert if necessary and try smaller changes
208
+
209
+ ### Type Errors After Changes
210
+ - Review type definitions
211
+ - Check generic constraints
212
+ - Verify imports
213
+ - Update type annotations
214
+ - Use type guards where needed
215
+
216
+ ### Lint Violations
217
+ - Run auto-fix: `npm run lint -- --fix`
218
+ - Review remaining issues
219
+ - Update lint rules if too strict
220
+ - Ensure consistency with codebase
221
+ - Don't disable rules without good reason
222
+
223
+ ### Merge Conflicts (if collaborative)
224
+ - Resolve conflicts carefully
225
+ - Run tests after merge
226
+ - Review combined changes
227
+ - Ensure refactoring still makes sense
228
+ - Re-run refactoring if needed
229
+
230
+ ## Output Format
231
+
232
+ Create `.chati/artifacts/build/refactor-report.yaml`:
233
+
234
+ ```yaml
235
+ task_id: "3.2.1"
236
+ agent: dev
237
+ action: refactor
238
+ timestamp: "2026-02-13T12:00:00Z"
239
+ duration_minutes: 40
240
+
241
+ files_refactored:
242
+ - path: "src/modules/chat/chat-service.ts"
243
+ changes:
244
+ - "Extracted message validation to validators.ts"
245
+ - "Split handleMessage into 3 smaller functions"
246
+ - "Renamed ambiguous variables"
247
+ lines_before: 156
248
+ lines_after: 142
249
+ - path: "src/modules/chat/utils.ts"
250
+ changes:
251
+ - "Created utility module for shared functions"
252
+ - "Moved sanitization logic here"
253
+ lines_before: 0
254
+ lines_after: 45
255
+
256
+ duplication_removed:
257
+ - description: "Message validation logic"
258
+ instances: 3
259
+ extracted_to: "src/modules/chat/validators.ts"
260
+ - description: "Database error handling"
261
+ instances: 5
262
+ extracted_to: "src/lib/db-utils.ts"
263
+
264
+ functions_split:
265
+ - original: "ChatService.handleMessage (78 lines)"
266
+ new_functions:
267
+ - "validateMessage (15 lines)"
268
+ - "persistMessage (22 lines)"
269
+ - "broadcastMessage (18 lines)"
270
+ rationale: "Separate validation, persistence, and broadcasting concerns"
271
+
272
+ naming_improvements:
273
+ - old: "proc"
274
+ new: "processMessage"
275
+ file: "chat-service.ts"
276
+ - old: "data"
277
+ new: "messageData"
278
+ file: "chat-service.ts"
279
+ - old: "check"
280
+ new: "isValidMessage"
281
+ file: "validators.ts"
282
+
283
+ solid_principles_applied:
284
+ - principle: "Single Responsibility"
285
+ change: "Split ChatService into ChatService and ChatRepository"
286
+ rationale: "Separate business logic from data access"
287
+ - principle: "Dependency Inversion"
288
+ change: "ChatService now depends on IMessageRepository interface"
289
+ rationale: "Easier to test and swap implementations"
290
+
291
+ complexity_reduction:
292
+ - function: "validateMessage"
293
+ cyclomatic_complexity_before: 12
294
+ cyclomatic_complexity_after: 5
295
+ changes: "Used early returns, extracted conditions"
296
+
297
+ type_safety_improvements:
298
+ - change: "Replaced any with MessageData type"
299
+ file: "chat-service.ts"
300
+ impact: "Catch type errors at compile time"
301
+ - change: "Added type guards for message validation"
302
+ file: "validators.ts"
303
+ impact: "Runtime type safety"
304
+
305
+ test_status:
306
+ all_tests_passing: true
307
+ coverage_before: 87.5
308
+ coverage_after: 89.2
309
+ coverage_change: "+1.7%"
310
+ tests_added: 2
311
+ tests_modified: 4
312
+
313
+ code_quality_metrics:
314
+ average_function_length: 18
315
+ max_function_length: 45
316
+ functions_over_50_lines: 0
317
+ code_duplication_percentage: 2.3
318
+ maintainability_index: 82
319
+
320
+ issues_found:
321
+ - description: "Message broadcasting could be extracted to separate service"
322
+ severity: minor
323
+ plan: "Consider for future iteration"
324
+ - description: "Error messages could be more specific"
325
+ severity: minor
326
+ plan: "Improve in dev-iterate if time permits"
327
+
328
+ next_steps:
329
+ - "Run full test suite to verify refactoring"
330
+ - "Debug any failing tests"
331
+ - "Prepare for code review"
332
+ ```
333
+
334
+ ## Success Criteria
335
+ - All tests still pass
336
+ - No code duplication (or minimal <5%)
337
+ - All functions under 50 lines
338
+ - Variable and function names are clear
339
+ - Cyclomatic complexity is reasonable
340
+ - Code follows SOLID principles
341
+ - Refactor report is complete
342
+ - Coverage maintained or improved
@@ -0,0 +1,306 @@
1
+ ---
2
+ id: dev-test-write
3
+ agent: dev
4
+ trigger: dev-implement
5
+ phase: build
6
+ requires_input: false
7
+ parallelizable: true
8
+ outputs: [test-files]
9
+ handoff_to: dev-refactor
10
+ autonomous_gate: true
11
+ criteria:
12
+ - Tests cover all acceptance criteria
13
+ - Edge cases tested
14
+ - Tests pass
15
+ ---
16
+ # Write Tests
17
+
18
+ ## Purpose
19
+ Create comprehensive unit and integration tests that verify all acceptance criteria are met and edge cases are handled correctly.
20
+
21
+ ## Prerequisites
22
+ - Implementation complete (dev-implement finished)
23
+ - Implementation log exists at `.chati/artifacts/build/implementation-log.yaml`
24
+ - Test framework configured (Jest, Vitest, or similar)
25
+ - Test utilities and helpers available
26
+ - Source code compiles successfully
27
+
28
+ ## Steps
29
+
30
+ ### 1. Load Implementation Context
31
+ Review the implementation log to understand:
32
+ - Which files were created
33
+ - Which files were modified
34
+ - Acceptance criteria to verify
35
+ - Design decisions that need testing
36
+ - Known technical debt or edge cases
37
+
38
+ ### 2. Analyze Test Requirements
39
+ Map acceptance criteria to test scenarios:
40
+ - Given-When-Then statements become test cases
41
+ - Identify happy path scenarios
42
+ - List error conditions
43
+ - Note boundary conditions
44
+ - Consider race conditions or timing issues
45
+
46
+ ### 3. Set Up Test Structure
47
+ Create test file organization:
48
+ - Name test files: `{module}.test.ts` or `{module}.spec.ts`
49
+ - Mirror source directory structure
50
+ - Set up test suites with `describe` blocks
51
+ - Group related tests logically
52
+ - Use clear, descriptive test names
53
+
54
+ ### 4. Write Unit Tests
55
+ Test individual functions and classes in isolation:
56
+ - Mock external dependencies
57
+ - Test one function per test case
58
+ - Verify return values
59
+ - Check state changes
60
+ - Validate error throwing
61
+
62
+ Example structure:
63
+ ```typescript
64
+ describe('ChatService', () => {
65
+ describe('sendMessage', () => {
66
+ it('should persist message to database', async () => {
67
+ // Arrange
68
+ const mockDb = createMockDb();
69
+ const service = new ChatService(mockDb);
70
+
71
+ // Act
72
+ const result = await service.sendMessage({
73
+ text: 'Hello',
74
+ userId: '123'
75
+ });
76
+
77
+ // Assert
78
+ expect(mockDb.insert).toHaveBeenCalledWith(
79
+ expect.objectContaining({ text: 'Hello' })
80
+ );
81
+ expect(result.id).toBeDefined();
82
+ });
83
+ });
84
+ });
85
+ ```
86
+
87
+ ### 5. Write Integration Tests
88
+ Test components working together:
89
+ - Use real dependencies where possible
90
+ - Test API endpoints end-to-end
91
+ - Verify database interactions
92
+ - Check event propagation
93
+ - Validate state management flows
94
+
95
+ ### 6. Test Edge Cases
96
+ Cover boundary and error conditions:
97
+ - Null or undefined inputs
98
+ - Empty strings or arrays
99
+ - Maximum length inputs
100
+ - Concurrent operations
101
+ - Network failures
102
+ - Database errors
103
+ - Invalid data formats
104
+
105
+ ### 7. Test Error Handling
106
+ Verify error scenarios:
107
+ - Exceptions are thrown correctly
108
+ - Error messages are meaningful
109
+ - Cleanup happens on failure
110
+ - State remains consistent
111
+ - Errors propagate appropriately
112
+
113
+ ### 8. Add Test Utilities
114
+ Create reusable test helpers:
115
+ - Factory functions for test data
116
+ - Mock builders
117
+ - Assertion helpers
118
+ - Setup and teardown utilities
119
+ - Database seeders
120
+
121
+ ### 9. Check Test Coverage
122
+ Verify adequate coverage:
123
+ - Run `npm run test:coverage`
124
+ - Aim for >80% line coverage
125
+ - Ensure all branches tested
126
+ - Cover all acceptance criteria
127
+ - Don't chase 100% blindly
128
+
129
+ ### 10. Optimize Test Performance
130
+ Make tests run efficiently:
131
+ - Avoid unnecessary async operations
132
+ - Use test.concurrent for independent tests
133
+ - Mock expensive operations
134
+ - Clear state between tests
135
+ - Use beforeEach/afterEach wisely
136
+
137
+ ### 11. Document Test Scenarios
138
+ Add clarity to tests:
139
+ - Use descriptive test names
140
+ - Add comments for complex setup
141
+ - Document assumptions
142
+ - Note flaky tests
143
+ - Reference acceptance criteria
144
+
145
+ ### 12. Create Test Report
146
+ Document testing work:
147
+ - List test files created
148
+ - Note coverage metrics
149
+ - Document test strategy
150
+ - Flag areas needing more tests
151
+ - Record any skipped tests
152
+
153
+ ## Decision Points
154
+
155
+ ### When Coverage is Low
156
+ If coverage is below 80%:
157
+ 1. Identify untested branches
158
+ 2. Prioritize critical paths
159
+ 3. Add tests for high-risk areas
160
+ 4. Document why some code isn't tested
161
+ 5. Plan to add tests in iteration phase
162
+
163
+ ### When Tests are Flaky
164
+ If tests fail intermittently:
165
+ 1. Identify timing dependencies
166
+ 2. Add proper async handling
167
+ 3. Mock time-dependent code
168
+ 4. Increase timeouts if needed
169
+ 5. Document flaky tests
170
+
171
+ ### When Integration Tests Fail
172
+ If integrated components don't work:
173
+ 1. Check component boundaries
174
+ 2. Verify API contracts
175
+ 3. Review data flow
176
+ 4. Add debugging logs
177
+ 5. May need to return to implementation
178
+
179
+ ## Error Handling
180
+
181
+ ### Test Framework Issues
182
+ - Verify test framework installed
183
+ - Check configuration files
184
+ - Review import paths
185
+ - Ensure test globals available
186
+ - Check for TypeScript config issues
187
+
188
+ ### Mock Setup Problems
189
+ - Verify mock library imported
190
+ - Check mock syntax
191
+ - Ensure mocks reset between tests
192
+ - Review mock return values
193
+ - Use spy functions for verification
194
+
195
+ ### Async Test Failures
196
+ - Always return promises or use async/await
197
+ - Set appropriate timeouts
198
+ - Handle promise rejections
199
+ - Use waitFor utilities
200
+ - Check for unhandled promise rejections
201
+
202
+ ### Coverage Tool Errors
203
+ - Verify coverage tool configured
204
+ - Check ignore patterns
205
+ - Review threshold settings
206
+ - Ensure source maps generated
207
+ - Check for instrumentation issues
208
+
209
+ ## Output Format
210
+
211
+ Create `.chati/artifacts/build/test-report.yaml`:
212
+
213
+ ```yaml
214
+ task_id: "3.2.1"
215
+ agent: dev
216
+ action: test-write
217
+ timestamp: "2026-02-13T11:15:00Z"
218
+ duration_minutes: 35
219
+
220
+ test_files_created:
221
+ - path: "src/modules/chat/chat-service.test.ts"
222
+ test_count: 12
223
+ lines: 245
224
+ - path: "src/modules/chat/chat-integration.test.ts"
225
+ test_count: 8
226
+ lines: 180
227
+
228
+ test_summary:
229
+ total_tests: 20
230
+ passing: 20
231
+ failing: 0
232
+ skipped: 0
233
+ duration_ms: 1847
234
+
235
+ coverage:
236
+ statements: 87.5
237
+ branches: 82.3
238
+ functions: 91.2
239
+ lines: 86.8
240
+ uncovered_files: []
241
+
242
+ acceptance_criteria_coverage:
243
+ - id: "AC-1"
244
+ description: "Chat messages persist to database"
245
+ tests:
246
+ - "ChatService.sendMessage should persist message to database"
247
+ - "ChatService.sendMessage should return saved message with ID"
248
+ status: fully_covered
249
+ - id: "AC-2"
250
+ description: "Real-time updates via WebSocket"
251
+ tests:
252
+ - "ChatService should emit message event on send"
253
+ - "Integration: WebSocket receives new messages"
254
+ status: fully_covered
255
+ - id: "AC-3"
256
+ description: "Message validation and sanitization"
257
+ tests:
258
+ - "ChatService should reject empty messages"
259
+ - "ChatService should sanitize HTML in messages"
260
+ - "ChatService should validate message length"
261
+ status: fully_covered
262
+
263
+ edge_cases_tested:
264
+ - scenario: "Null or undefined message text"
265
+ test: "should throw ValidationError for null text"
266
+ - scenario: "Message exceeding max length"
267
+ test: "should throw ValidationError for oversized message"
268
+ - scenario: "Concurrent message sends"
269
+ test: "should handle concurrent sends without corruption"
270
+ - scenario: "Database connection lost"
271
+ test: "should throw DatabaseError on connection failure"
272
+ - scenario: "WebSocket disconnect during send"
273
+ test: "should complete send even if broadcast fails"
274
+
275
+ test_utilities_added:
276
+ - name: "createMockChatService"
277
+ purpose: "Factory for test instances"
278
+ - name: "createTestMessage"
279
+ purpose: "Generate valid test messages"
280
+ - name: "seedChatDatabase"
281
+ purpose: "Populate test database"
282
+
283
+ areas_needing_attention:
284
+ - description: "Performance testing for 1000+ messages"
285
+ reason: "Not covered in unit tests"
286
+ plan: "Add performance test suite in Phase 4"
287
+ - description: "WebSocket reconnection scenarios"
288
+ reason: "Complex to test, low priority"
289
+ plan: "Add in iteration if time permits"
290
+
291
+ flaky_tests: []
292
+
293
+ next_steps:
294
+ - "Review test coverage with QA perspective"
295
+ - "Refactor any duplicate test setup code"
296
+ - "Consider additional edge cases"
297
+ ```
298
+
299
+ ## Success Criteria
300
+ - All tests pass
301
+ - Coverage is above 80%
302
+ - All acceptance criteria have corresponding tests
303
+ - Edge cases are tested
304
+ - Error scenarios are covered
305
+ - Test report is complete
306
+ - Tests run in reasonable time (<5s for unit tests)