@paths.design/caws-cli 9.3.2 → 10.0.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 (273) hide show
  1. package/README.md +58 -27
  2. package/dist/commands/archive.js +67 -28
  3. package/dist/commands/burnup.js +20 -11
  4. package/dist/commands/diagnose.js +34 -22
  5. package/dist/commands/evaluate.js +27 -15
  6. package/dist/commands/gates.js +122 -0
  7. package/dist/commands/init.js +143 -15
  8. package/dist/commands/iterate.js +77 -4
  9. package/dist/commands/parallel.js +4 -0
  10. package/dist/commands/plan.js +9 -19
  11. package/dist/commands/provenance.js +53 -17
  12. package/dist/commands/quality-monitor.js +64 -45
  13. package/dist/commands/sidecar.js +71 -0
  14. package/dist/commands/specs.js +233 -44
  15. package/dist/commands/status.js +113 -9
  16. package/dist/commands/tutorial.js +10 -9
  17. package/dist/commands/validate.js +49 -6
  18. package/dist/commands/verify-acs.js +35 -78
  19. package/dist/commands/waivers.js +69 -12
  20. package/dist/commands/worktree.js +50 -25
  21. package/dist/error-handler.js +2 -13
  22. package/dist/gates/budget-limit.js +116 -0
  23. package/dist/gates/feedback.js +260 -0
  24. package/dist/gates/format.js +179 -0
  25. package/dist/gates/god-object.js +117 -0
  26. package/dist/gates/pipeline.js +167 -0
  27. package/dist/gates/scope-boundary.js +93 -0
  28. package/dist/gates/spec-completeness.js +102 -0
  29. package/dist/gates/todo-detection.js +205 -0
  30. package/dist/index.js +130 -151
  31. package/dist/parallel/parallel-manager.js +3 -3
  32. package/dist/policy/PolicyManager.js +42 -10
  33. package/dist/scaffold/claude-hooks.js +24 -1
  34. package/dist/scaffold/git-hooks.js +45 -102
  35. package/dist/scaffold/index.js +4 -3
  36. package/dist/session/session-manager.js +71 -14
  37. package/dist/sidecars/index.js +33 -0
  38. package/dist/sidecars/listeners.js +40 -0
  39. package/dist/sidecars/provenance-summary.js +238 -0
  40. package/dist/sidecars/quality-gaps.js +258 -0
  41. package/dist/sidecars/schema.js +149 -0
  42. package/dist/sidecars/spec-drift.js +151 -0
  43. package/dist/sidecars/waiver-draft.js +176 -0
  44. package/dist/templates/.caws/schemas/policy.schema.json +50 -0
  45. package/dist/templates/.caws/schemas/waivers.schema.json +30 -24
  46. package/dist/templates/.caws/schemas/working-spec.schema.json +51 -8
  47. package/dist/templates/.caws/schemas/worktrees.schema.json +3 -1
  48. package/dist/templates/.caws/templates/working-spec.template.yml +7 -3
  49. package/dist/templates/.claude/hooks/audit.sh +0 -0
  50. package/dist/templates/.claude/hooks/block-dangerous.sh +52 -11
  51. package/dist/templates/.claude/hooks/classify_command.py +592 -0
  52. package/dist/templates/.claude/hooks/doc-frontmatter-check.sh +173 -0
  53. package/dist/templates/.claude/hooks/quality-check.sh +23 -10
  54. package/dist/templates/.claude/hooks/scope-guard.sh +34 -32
  55. package/dist/templates/.claude/hooks/session-caws-status.sh +2 -2
  56. package/dist/templates/.claude/hooks/session-log.sh +76 -3
  57. package/dist/templates/.claude/hooks/stop-worktree-check.sh +1 -1
  58. package/dist/templates/.claude/hooks/test_classify_command.py +370 -0
  59. package/dist/templates/.claude/hooks/test_wrapper_smoke.sh +96 -0
  60. package/dist/templates/.claude/hooks/worktree-guard.sh +2 -2
  61. package/dist/templates/.claude/hooks/worktree-write-guard.sh +1 -1
  62. package/dist/templates/.claude/settings.json +26 -0
  63. package/dist/templates/.cursor/hooks/caws-quality-check.sh +4 -4
  64. package/dist/templates/.cursor/hooks/caws-scope-guard.sh +1 -1
  65. package/dist/templates/.cursor/hooks/session-log.sh +924 -0
  66. package/dist/templates/.cursor/hooks.json +25 -0
  67. package/dist/templates/.cursor/rules/02-quality-gates.mdc +3 -5
  68. package/dist/templates/.cursor/rules/10-documentation-quality-standards.mdc +6 -11
  69. package/dist/templates/.cursor/rules/11-scope-management-waivers.mdc +14 -18
  70. package/dist/templates/.cursor/rules/12-implementation-completeness.mdc +4 -4
  71. package/dist/templates/.cursor/rules/13-language-agnostic-standards.mdc +3 -13
  72. package/dist/templates/.github/copilot-instructions.md +5 -5
  73. package/dist/templates/.idea/runConfigurations/CAWS_Evaluate.xml +1 -1
  74. package/dist/templates/.junie/guidelines.md +2 -2
  75. package/dist/templates/.vscode/settings.json +3 -1
  76. package/dist/templates/.windsurf/rules/caws-quality-standards.md +2 -2
  77. package/dist/templates/.windsurf/workflows/caws-guided-development.md +3 -3
  78. package/dist/templates/CLAUDE.md +43 -8
  79. package/dist/templates/agents.md +29 -9
  80. package/dist/templates/docs/README.md +8 -7
  81. package/dist/templates/scripts/new_feature.sh +80 -0
  82. package/dist/test-analysis.js +43 -30
  83. package/dist/tool-loader.js +1 -1
  84. package/dist/utils/agent-session.js +202 -0
  85. package/dist/utils/detection.js +8 -2
  86. package/dist/utils/finalization.js +7 -6
  87. package/dist/utils/gitignore-updater.js +3 -0
  88. package/dist/utils/lifecycle-events.js +94 -0
  89. package/dist/utils/quality-gates-utils.js +29 -44
  90. package/dist/utils/schema-validator.js +42 -0
  91. package/dist/utils/spec-resolver.js +93 -21
  92. package/dist/utils/working-state.js +505 -0
  93. package/dist/validation/spec-validation.js +92 -22
  94. package/dist/waivers-manager.js +60 -6
  95. package/dist/worktree/worktree-manager.js +390 -93
  96. package/package.json +6 -6
  97. package/templates/.caws/schemas/policy.schema.json +50 -0
  98. package/templates/.caws/schemas/waivers.schema.json +30 -24
  99. package/templates/.caws/schemas/working-spec.schema.json +51 -8
  100. package/templates/.caws/schemas/worktrees.schema.json +3 -1
  101. package/templates/.caws/templates/working-spec.template.yml +7 -3
  102. package/templates/.claude/hooks/block-dangerous.sh +52 -11
  103. package/templates/.claude/hooks/classify_command.py +592 -0
  104. package/templates/.claude/hooks/doc-frontmatter-check.sh +173 -0
  105. package/templates/.claude/hooks/quality-check.sh +23 -10
  106. package/templates/.claude/hooks/scope-guard.sh +34 -32
  107. package/templates/.claude/hooks/session-caws-status.sh +2 -2
  108. package/templates/.claude/hooks/session-log.sh +76 -3
  109. package/templates/.claude/hooks/stop-worktree-check.sh +1 -1
  110. package/templates/.claude/hooks/test_classify_command.py +370 -0
  111. package/templates/.claude/hooks/test_wrapper_smoke.sh +96 -0
  112. package/templates/.claude/hooks/worktree-guard.sh +2 -2
  113. package/templates/.claude/hooks/worktree-write-guard.sh +1 -1
  114. package/templates/.claude/settings.json +26 -0
  115. package/templates/.cursor/hooks/caws-quality-check.sh +4 -4
  116. package/templates/.cursor/hooks/caws-scope-guard.sh +1 -1
  117. package/templates/.cursor/hooks/session-log.sh +924 -0
  118. package/templates/.cursor/hooks.json +25 -0
  119. package/templates/.cursor/rules/02-quality-gates.mdc +3 -5
  120. package/templates/.cursor/rules/10-documentation-quality-standards.mdc +6 -11
  121. package/templates/.cursor/rules/11-scope-management-waivers.mdc +14 -18
  122. package/templates/.cursor/rules/12-implementation-completeness.mdc +4 -4
  123. package/templates/.cursor/rules/13-language-agnostic-standards.mdc +3 -13
  124. package/templates/.github/copilot-instructions.md +5 -5
  125. package/templates/.idea/runConfigurations/CAWS_Evaluate.xml +1 -1
  126. package/templates/.junie/guidelines.md +2 -2
  127. package/templates/.vscode/settings.json +3 -1
  128. package/templates/.windsurf/rules/caws-quality-standards.md +2 -2
  129. package/templates/.windsurf/workflows/caws-guided-development.md +3 -3
  130. package/templates/CLAUDE.md +43 -8
  131. package/templates/{AGENTS.md → agents.md} +29 -9
  132. package/templates/docs/README.md +8 -7
  133. package/templates/scripts/new_feature.sh +80 -0
  134. package/dist/budget-derivation.d.ts +0 -74
  135. package/dist/budget-derivation.d.ts.map +0 -1
  136. package/dist/cicd-optimizer.d.ts +0 -142
  137. package/dist/cicd-optimizer.d.ts.map +0 -1
  138. package/dist/commands/archive.d.ts +0 -51
  139. package/dist/commands/archive.d.ts.map +0 -1
  140. package/dist/commands/burnup.d.ts +0 -6
  141. package/dist/commands/burnup.d.ts.map +0 -1
  142. package/dist/commands/diagnose.d.ts +0 -52
  143. package/dist/commands/diagnose.d.ts.map +0 -1
  144. package/dist/commands/evaluate.d.ts +0 -8
  145. package/dist/commands/evaluate.d.ts.map +0 -1
  146. package/dist/commands/init.d.ts +0 -5
  147. package/dist/commands/init.d.ts.map +0 -1
  148. package/dist/commands/iterate.d.ts +0 -8
  149. package/dist/commands/iterate.d.ts.map +0 -1
  150. package/dist/commands/mode.d.ts +0 -25
  151. package/dist/commands/mode.d.ts.map +0 -1
  152. package/dist/commands/parallel.d.ts +0 -7
  153. package/dist/commands/parallel.d.ts.map +0 -1
  154. package/dist/commands/plan.d.ts +0 -49
  155. package/dist/commands/plan.d.ts.map +0 -1
  156. package/dist/commands/provenance.d.ts +0 -32
  157. package/dist/commands/provenance.d.ts.map +0 -1
  158. package/dist/commands/quality-gates.d.ts +0 -6
  159. package/dist/commands/quality-gates.d.ts.map +0 -1
  160. package/dist/commands/quality-gates.js +0 -444
  161. package/dist/commands/quality-monitor.d.ts +0 -17
  162. package/dist/commands/quality-monitor.d.ts.map +0 -1
  163. package/dist/commands/session.d.ts +0 -7
  164. package/dist/commands/session.d.ts.map +0 -1
  165. package/dist/commands/specs.d.ts +0 -77
  166. package/dist/commands/specs.d.ts.map +0 -1
  167. package/dist/commands/status.d.ts +0 -44
  168. package/dist/commands/status.d.ts.map +0 -1
  169. package/dist/commands/templates.d.ts +0 -74
  170. package/dist/commands/templates.d.ts.map +0 -1
  171. package/dist/commands/tool.d.ts +0 -13
  172. package/dist/commands/tool.d.ts.map +0 -1
  173. package/dist/commands/troubleshoot.d.ts +0 -8
  174. package/dist/commands/troubleshoot.d.ts.map +0 -1
  175. package/dist/commands/troubleshoot.js +0 -104
  176. package/dist/commands/tutorial.d.ts +0 -55
  177. package/dist/commands/tutorial.d.ts.map +0 -1
  178. package/dist/commands/validate.d.ts +0 -15
  179. package/dist/commands/validate.d.ts.map +0 -1
  180. package/dist/commands/waivers.d.ts +0 -8
  181. package/dist/commands/waivers.d.ts.map +0 -1
  182. package/dist/commands/workflow.d.ts +0 -85
  183. package/dist/commands/workflow.d.ts.map +0 -1
  184. package/dist/commands/worktree.d.ts +0 -7
  185. package/dist/commands/worktree.d.ts.map +0 -1
  186. package/dist/config/index.d.ts +0 -29
  187. package/dist/config/index.d.ts.map +0 -1
  188. package/dist/config/lite-scope.d.ts +0 -33
  189. package/dist/config/lite-scope.d.ts.map +0 -1
  190. package/dist/config/modes.d.ts +0 -264
  191. package/dist/config/modes.d.ts.map +0 -1
  192. package/dist/constants/spec-types.d.ts +0 -93
  193. package/dist/constants/spec-types.d.ts.map +0 -1
  194. package/dist/error-handler.d.ts +0 -151
  195. package/dist/error-handler.d.ts.map +0 -1
  196. package/dist/generators/jest-config-generator.d.ts +0 -32
  197. package/dist/generators/jest-config-generator.d.ts.map +0 -1
  198. package/dist/generators/jest-config.d.ts +0 -32
  199. package/dist/generators/jest-config.d.ts.map +0 -1
  200. package/dist/generators/jest-config.js +0 -242
  201. package/dist/generators/working-spec.d.ts +0 -13
  202. package/dist/generators/working-spec.d.ts.map +0 -1
  203. package/dist/index-new.d.ts +0 -5
  204. package/dist/index-new.d.ts.map +0 -1
  205. package/dist/index-new.js +0 -317
  206. package/dist/index.d.ts +0 -5
  207. package/dist/index.d.ts.map +0 -1
  208. package/dist/index.js.backup +0 -4711
  209. package/dist/minimal-cli.d.ts +0 -3
  210. package/dist/minimal-cli.d.ts.map +0 -1
  211. package/dist/parallel/parallel-manager.d.ts +0 -67
  212. package/dist/parallel/parallel-manager.d.ts.map +0 -1
  213. package/dist/policy/PolicyManager.d.ts +0 -104
  214. package/dist/policy/PolicyManager.d.ts.map +0 -1
  215. package/dist/scaffold/claude-hooks.d.ts +0 -28
  216. package/dist/scaffold/claude-hooks.d.ts.map +0 -1
  217. package/dist/scaffold/cursor-hooks.d.ts +0 -7
  218. package/dist/scaffold/cursor-hooks.d.ts.map +0 -1
  219. package/dist/scaffold/git-hooks.d.ts +0 -38
  220. package/dist/scaffold/git-hooks.d.ts.map +0 -1
  221. package/dist/scaffold/index.d.ts +0 -17
  222. package/dist/scaffold/index.d.ts.map +0 -1
  223. package/dist/session/session-manager.d.ts +0 -94
  224. package/dist/session/session-manager.d.ts.map +0 -1
  225. package/dist/spec/SpecFileManager.d.ts +0 -146
  226. package/dist/spec/SpecFileManager.d.ts.map +0 -1
  227. package/dist/templates/.cursor/hooks/caws-tool-validation.sh +0 -121
  228. package/dist/templates/.github/copilot/instructions.md +0 -311
  229. package/dist/test-analysis.d.ts +0 -231
  230. package/dist/test-analysis.d.ts.map +0 -1
  231. package/dist/tool-interface.d.ts +0 -236
  232. package/dist/tool-interface.d.ts.map +0 -1
  233. package/dist/tool-loader.d.ts +0 -77
  234. package/dist/tool-loader.d.ts.map +0 -1
  235. package/dist/tool-validator.d.ts +0 -72
  236. package/dist/tool-validator.d.ts.map +0 -1
  237. package/dist/utils/async-utils.d.ts +0 -73
  238. package/dist/utils/async-utils.d.ts.map +0 -1
  239. package/dist/utils/command-wrapper.d.ts +0 -66
  240. package/dist/utils/command-wrapper.d.ts.map +0 -1
  241. package/dist/utils/detection.d.ts +0 -14
  242. package/dist/utils/detection.d.ts.map +0 -1
  243. package/dist/utils/error-categories.d.ts +0 -52
  244. package/dist/utils/error-categories.d.ts.map +0 -1
  245. package/dist/utils/finalization.d.ts +0 -17
  246. package/dist/utils/finalization.d.ts.map +0 -1
  247. package/dist/utils/git-lock.d.ts +0 -13
  248. package/dist/utils/git-lock.d.ts.map +0 -1
  249. package/dist/utils/gitignore-updater.d.ts +0 -39
  250. package/dist/utils/gitignore-updater.d.ts.map +0 -1
  251. package/dist/utils/ide-detection.d.ts +0 -89
  252. package/dist/utils/ide-detection.d.ts.map +0 -1
  253. package/dist/utils/project-analysis.d.ts +0 -34
  254. package/dist/utils/project-analysis.d.ts.map +0 -1
  255. package/dist/utils/promise-utils.d.ts +0 -30
  256. package/dist/utils/promise-utils.d.ts.map +0 -1
  257. package/dist/utils/quality-gates-utils.d.ts +0 -49
  258. package/dist/utils/quality-gates-utils.d.ts.map +0 -1
  259. package/dist/utils/quality-gates.d.ts +0 -49
  260. package/dist/utils/quality-gates.d.ts.map +0 -1
  261. package/dist/utils/quality-gates.js +0 -402
  262. package/dist/utils/spec-resolver.d.ts +0 -80
  263. package/dist/utils/spec-resolver.d.ts.map +0 -1
  264. package/dist/utils/typescript-detector.d.ts +0 -66
  265. package/dist/utils/typescript-detector.d.ts.map +0 -1
  266. package/dist/utils/yaml-validation.d.ts +0 -32
  267. package/dist/utils/yaml-validation.d.ts.map +0 -1
  268. package/dist/validation/spec-validation.d.ts +0 -43
  269. package/dist/validation/spec-validation.d.ts.map +0 -1
  270. package/dist/waivers-manager.d.ts +0 -167
  271. package/dist/waivers-manager.d.ts.map +0 -1
  272. package/dist/worktree/worktree-manager.d.ts +0 -54
  273. package/dist/worktree/worktree-manager.d.ts.map +0 -1
@@ -0,0 +1,179 @@
1
+ /**
2
+ * @fileoverview Report formatters for quality gate results
3
+ * Provides human-readable text and machine-readable JSON output.
4
+ * @author @darianrosebrook
5
+ */
6
+
7
+ const STATUS_ICONS = {
8
+ pass: '\u2713', // checkmark
9
+ fail: '\u2717', // X mark
10
+ warn: '\u26A0', // warning triangle
11
+ skipped: '\u2014', // em dash
12
+ };
13
+
14
+ /**
15
+ * Format gate report as human-readable text for terminal output
16
+ * @param {Object} report - Report from evaluateGates()
17
+ * @returns {string} Formatted text output
18
+ */
19
+ function formatText(report) {
20
+ const lines = [];
21
+
22
+ lines.push('Quality Gates Report');
23
+ lines.push('====================');
24
+ lines.push('');
25
+
26
+ for (const gate of report.gates) {
27
+ const icon = STATUS_ICONS[gate.status] || '?';
28
+ const modeLabel = gate.mode === 'block' ? '[BLOCK]' : gate.mode === 'warn' ? '[WARN]' : `[${gate.mode.toUpperCase()}]`;
29
+ const waiverNote = gate.waived ? ' (waived)' : '';
30
+
31
+ lines.push(` ${icon} ${gate.name} ${modeLabel}${waiverNote} (${gate.duration}ms)`);
32
+
33
+ if (gate.messages && gate.messages.length > 0) {
34
+ for (const msg of gate.messages) {
35
+ lines.push(` ${msg}`);
36
+ }
37
+ }
38
+ }
39
+
40
+ lines.push('');
41
+ lines.push('--------------------');
42
+
43
+ const { summary } = report;
44
+ const parts = [];
45
+ if (summary.passed > 0) parts.push(`${summary.passed} passed`);
46
+ if (summary.warned > 0) parts.push(`${summary.warned} warned`);
47
+ if (summary.blocked > 0) parts.push(`${summary.blocked} blocked`);
48
+ if (summary.skipped > 0) parts.push(`${summary.skipped} skipped`);
49
+ if (summary.waived > 0) parts.push(`${summary.waived} waived`);
50
+
51
+ lines.push(`Summary: ${parts.join(', ')}`);
52
+
53
+ if (report.warnings && report.warnings.length > 0) {
54
+ for (const w of report.warnings) {
55
+ lines.push(`WARNING: ${w}`);
56
+ }
57
+ }
58
+
59
+ if (report.passed) {
60
+ // Only say "all passed" if every enabled gate actually ran and passed
61
+ const enabledGates = report.gates.filter(g => g.status !== 'skipped');
62
+ const allRanAndPassed = enabledGates.length > 0 && enabledGates.every(g => g.status === 'pass');
63
+ if (allRanAndPassed) {
64
+ lines.push('Result: All enabled gates passed.');
65
+ } else {
66
+ lines.push('Result: No blocking failures.');
67
+ }
68
+ } else {
69
+ lines.push('Result: Commit blocked by failing gates.');
70
+ }
71
+
72
+ return lines.join('\n');
73
+ }
74
+
75
+ /**
76
+ * Format gate report as JSON for CI/hooks consumption
77
+ * @param {Object} report - Report from evaluateGates()
78
+ * @returns {string} JSON string
79
+ */
80
+ function formatJson(report) {
81
+ return JSON.stringify({
82
+ passed: report.passed,
83
+ summary: report.summary,
84
+ gates: report.gates.map(g => ({
85
+ name: g.name,
86
+ mode: g.mode,
87
+ status: g.status,
88
+ waived: g.waived,
89
+ waiverId: g.waiverId || null,
90
+ messages: g.messages,
91
+ duration: g.duration,
92
+ })),
93
+ warnings: report.warnings || [],
94
+ timestamp: new Date().toISOString(),
95
+ }, null, 2);
96
+ }
97
+
98
+ /**
99
+ * Format gate report with enriched feedback for failed/warned gates.
100
+ * Falls back to standard format for gates without enrichment.
101
+ * @param {Object} report - Report from evaluateGates()
102
+ * @param {Map<string, Object>} enrichments - Map of gate name → enrichment from feedback.js
103
+ * @returns {string} Formatted text output
104
+ */
105
+ function formatEnrichedText(report, enrichments) {
106
+ const lines = [];
107
+
108
+ lines.push('Quality Gates Report');
109
+ lines.push('====================');
110
+ lines.push('');
111
+
112
+ for (const gate of report.gates) {
113
+ const icon = STATUS_ICONS[gate.status] || '?';
114
+ const modeLabel = gate.mode === 'block' ? '[BLOCK]' : gate.mode === 'warn' ? '[WARN]' : `[${gate.mode.toUpperCase()}]`;
115
+ const waiverNote = gate.waived ? ' (waived)' : '';
116
+ const enrichment = enrichments.get(gate.name);
117
+ const categoryTag = enrichment ? ` [${enrichment.category}]` : '';
118
+
119
+ lines.push(` ${icon} ${gate.name} ${modeLabel}${categoryTag}${waiverNote} (${gate.duration}ms)`);
120
+
121
+ // Raw messages first
122
+ if (gate.messages && gate.messages.length > 0) {
123
+ for (const msg of gate.messages) {
124
+ lines.push(` ${msg}`);
125
+ }
126
+ }
127
+
128
+ // Enrichment details for failed/warned gates
129
+ if (enrichment) {
130
+ if (enrichment.why) {
131
+ lines.push(` Why: ${enrichment.why}`);
132
+ }
133
+ if (enrichment.recurrence) {
134
+ lines.push(` Recurring: failed ${enrichment.recurrence.count} time(s) (last: ${enrichment.recurrence.lastSeen})`);
135
+ }
136
+ if (enrichment.nextStep) {
137
+ lines.push(` Next step: ${enrichment.nextStep}`);
138
+ }
139
+ if (enrichment.remediation) {
140
+ lines.push(` Fix: ${enrichment.remediation}`);
141
+ }
142
+ }
143
+ }
144
+
145
+ lines.push('');
146
+ lines.push('--------------------');
147
+
148
+ const { summary } = report;
149
+ const parts = [];
150
+ if (summary.passed > 0) parts.push(`${summary.passed} passed`);
151
+ if (summary.warned > 0) parts.push(`${summary.warned} warned`);
152
+ if (summary.blocked > 0) parts.push(`${summary.blocked} blocked`);
153
+ if (summary.skipped > 0) parts.push(`${summary.skipped} skipped`);
154
+ if (summary.waived > 0) parts.push(`${summary.waived} waived`);
155
+
156
+ lines.push(`Summary: ${parts.join(', ')}`);
157
+
158
+ if (report.warnings && report.warnings.length > 0) {
159
+ for (const w of report.warnings) {
160
+ lines.push(`WARNING: ${w}`);
161
+ }
162
+ }
163
+
164
+ if (report.passed) {
165
+ const enabledGates = report.gates.filter(g => g.status !== 'skipped');
166
+ const allRanAndPassed = enabledGates.length > 0 && enabledGates.every(g => g.status === 'pass');
167
+ if (allRanAndPassed) {
168
+ lines.push('Result: All enabled gates passed.');
169
+ } else {
170
+ lines.push('Result: No blocking failures.');
171
+ }
172
+ } else {
173
+ lines.push('Result: Commit blocked by failing gates.');
174
+ }
175
+
176
+ return lines.join('\n');
177
+ }
178
+
179
+ module.exports = { formatText, formatJson, formatEnrichedText };
@@ -0,0 +1,117 @@
1
+ /**
2
+ * @fileoverview God object detection gate
3
+ * Flags large files that exceed line-count thresholds.
4
+ * Test files use a higher threshold since large integration tests are normal.
5
+ * @author @darianrosebrook
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ const name = 'god_object';
12
+
13
+ const SOURCE_EXTENSIONS = ['.js', '.ts', '.tsx', '.jsx', '.py', '.rs', '.go', '.java', '.rb', '.cs'];
14
+
15
+ /** Directories and patterns that are always excluded (generated/vendored content) */
16
+ const DEFAULT_EXCLUDE_DIRS = [
17
+ 'dist/', 'dist-bundle/', 'build/', '.next/', 'out/',
18
+ 'node_modules/', '__pycache__/', '.nuxt/', 'coverage/',
19
+ 'vendor/', '.cache/',
20
+ ];
21
+
22
+ /** File patterns that are always excluded */
23
+ const DEFAULT_EXCLUDE_PATTERNS = ['.min.', '.bundle.', '.generated.'];
24
+
25
+ /** Patterns that identify test files (get higher thresholds) */
26
+ const TEST_PATTERNS = [
27
+ '.test.', '.spec.', '_test.', '_spec.',
28
+ 'tests/', 'test/', '__tests__/', '__test__/',
29
+ 'proving-grounds/', 'fixtures/',
30
+ ];
31
+
32
+ /** Default multiplier for test file thresholds (2x = test files get double the threshold) */
33
+ const TEST_THRESHOLD_MULTIPLIER = 2;
34
+
35
+ /**
36
+ * Check if a file should be excluded from god-object analysis.
37
+ * @param {string} filePath - Relative file path
38
+ * @returns {boolean} Whether the file is excluded
39
+ */
40
+ function isExcluded(filePath) {
41
+ for (const dir of DEFAULT_EXCLUDE_DIRS) {
42
+ if (filePath.startsWith(dir) || filePath.includes('/' + dir)) return true;
43
+ }
44
+ for (const pat of DEFAULT_EXCLUDE_PATTERNS) {
45
+ if (filePath.includes(pat)) return true;
46
+ }
47
+ return false;
48
+ }
49
+
50
+ /**
51
+ * Check if a file is a test file.
52
+ * @param {string} filePath - Relative file path
53
+ * @returns {boolean}
54
+ */
55
+ function isTestFile(filePath) {
56
+ const lower = filePath.toLowerCase();
57
+ return TEST_PATTERNS.some(pat => lower.includes(pat));
58
+ }
59
+
60
+ /**
61
+ * Run the god object detection gate
62
+ * @param {Object} params - Gate parameters
63
+ * @param {string[]} params.stagedFiles - Staged file paths
64
+ * @param {string} params.projectRoot - Project root
65
+ * @param {Object} [params.thresholds] - Override thresholds
66
+ * @param {number} [params.thresholds.warning=1750] - Warning line threshold
67
+ * @param {number} [params.thresholds.critical=2000] - Critical/fail line threshold
68
+ * @returns {Promise<Object>} Gate result with status and messages
69
+ */
70
+ async function run({ stagedFiles, projectRoot, thresholds }) {
71
+ const baseWarning = thresholds?.warning || 1750;
72
+ const baseCritical = thresholds?.critical || 2000;
73
+ const messages = [];
74
+ let hasCritical = false;
75
+ let hasWarning = false;
76
+
77
+ const sourceFiles = stagedFiles.filter(f =>
78
+ SOURCE_EXTENSIONS.some(ext => f.endsWith(ext)) && !isExcluded(f)
79
+ );
80
+
81
+ for (const file of sourceFiles) {
82
+ try {
83
+ const fullPath = path.resolve(projectRoot, file);
84
+ if (!fs.existsSync(fullPath)) continue;
85
+
86
+ const content = fs.readFileSync(fullPath, 'utf8');
87
+ const lineCount = content.split('\n').length;
88
+
89
+ // Test files get a higher threshold — large integration tests are normal
90
+ const mult = isTestFile(file) ? TEST_THRESHOLD_MULTIPLIER : 1;
91
+ const warningThreshold = baseWarning * mult;
92
+ const criticalThreshold = baseCritical * mult;
93
+
94
+ if (lineCount >= criticalThreshold) {
95
+ hasCritical = true;
96
+ const label = mult > 1 ? 'CRITICAL (test file)' : 'CRITICAL';
97
+ messages.push(`${label}: ${file} has ${lineCount} lines (threshold: ${criticalThreshold})`);
98
+ } else if (lineCount >= warningThreshold) {
99
+ hasWarning = true;
100
+ const label = mult > 1 ? 'WARNING (test file)' : 'WARNING';
101
+ messages.push(`${label}: ${file} has ${lineCount} lines (threshold: ${warningThreshold})`);
102
+ }
103
+ } catch (err) {
104
+ messages.push(`WARNING: Could not read ${file}: ${err.message}`);
105
+ }
106
+ }
107
+
108
+ if (hasCritical) {
109
+ return { status: 'fail', messages };
110
+ }
111
+ if (hasWarning) {
112
+ return { status: 'warn', messages };
113
+ }
114
+ return { status: 'pass', messages };
115
+ }
116
+
117
+ module.exports = { name, run };
@@ -0,0 +1,167 @@
1
+ /**
2
+ * @fileoverview Central gate evaluation pipeline
3
+ * Auto-discovers gate modules and evaluates them against policy configuration.
4
+ * @author @darianrosebrook
5
+ */
6
+
7
+ const fs = require('fs-extra');
8
+ const path = require('path');
9
+ const { PolicyManager } = require('../policy/PolicyManager');
10
+ const WaiversManager = require('../waivers-manager');
11
+ const { lifecycle, EVENTS } = require('../utils/lifecycle-events');
12
+
13
+ /**
14
+ * Auto-discover gate modules from the gates directory
15
+ * Skips pipeline.js and format.js; requires each module to export `name` and `run`.
16
+ * @returns {Object} Map of gate name to gate module
17
+ */
18
+ function loadGates() {
19
+ const gateDir = __dirname;
20
+ const gates = {};
21
+ for (const file of fs.readdirSync(gateDir)) {
22
+ if (file === 'pipeline.js' || file === 'format.js' || !file.endsWith('.js')) continue;
23
+ try {
24
+ const gate = require(path.join(gateDir, file));
25
+ if (gate.name && typeof gate.run === 'function') {
26
+ gates[gate.name] = gate;
27
+ }
28
+ } catch { /* skip broken gate modules */ }
29
+ }
30
+ return gates;
31
+ }
32
+
33
+ /**
34
+ * Evaluate all configured gates against staged files and spec
35
+ * @param {Object} params - Evaluation parameters
36
+ * @param {string} params.projectRoot - Project root directory
37
+ * @param {string[]} params.stagedFiles - List of staged file paths
38
+ * @param {Object} [params.spec] - Working spec object
39
+ * @param {Object} [params.context] - Additional context
40
+ * @returns {Promise<Object>} Evaluation report with gate results and summary
41
+ */
42
+ async function evaluateGates({ projectRoot, stagedFiles, spec, context }) {
43
+ const policyManager = new PolicyManager();
44
+ const policy = await policyManager.loadPolicy(projectRoot);
45
+ const riskTier = spec?.risk_tier || policy?.risk_tiers?.default || 2;
46
+ const usingDefaults = !!policy?._isDefault;
47
+
48
+ const availableGates = loadGates();
49
+ const gateConfigs = policy?.gates || {};
50
+ const results = [];
51
+ const waiversManager = new WaiversManager({ projectRoot });
52
+
53
+ for (const [gateName, config] of Object.entries(gateConfigs)) {
54
+ if (!config.enabled) continue;
55
+
56
+ const mode = config.mode || 'warn';
57
+ if (mode === 'skip') {
58
+ results.push({ name: gateName, mode, status: 'skipped', waived: false, messages: [], duration: 0 });
59
+ continue;
60
+ }
61
+
62
+ // Check waivers
63
+ let waived = false;
64
+ let waiverId = null;
65
+ try {
66
+ const waiverResult = await waiversManager.getActiveWaiverForGate(gateName);
67
+ if (waiverResult) {
68
+ waived = true;
69
+ waiverId = waiverResult.waiverId;
70
+ results.push({ name: gateName, mode, status: 'pass', waived: true, waiverId, messages: [`Waived: ${waiverResult.reason}`], duration: 0 });
71
+ continue;
72
+ }
73
+ } catch (err) {
74
+ // Waiver check failed — log it so the failure is visible, then proceed without waiver
75
+ results.push({
76
+ name: gateName, mode, status: 'fail', waived: false,
77
+ messages: [`Waiver check error (fail-closed): ${err.message}`], duration: 0,
78
+ });
79
+ continue;
80
+ }
81
+
82
+ const gate = availableGates[gateName];
83
+ if (!gate) {
84
+ // Fail-closed for block/warn mode: a gate referenced in policy but not found is a config error
85
+ const status = mode === 'block' ? 'fail' : 'warn';
86
+ results.push({
87
+ name: gateName, mode, status, waived: false,
88
+ messages: [`Gate "${gateName}" is configured in policy but not implemented. Check for typos in policy.yaml.`],
89
+ duration: 0,
90
+ });
91
+ continue;
92
+ }
93
+
94
+ const start = Date.now();
95
+ try {
96
+ const result = await gate.run({ stagedFiles, spec, policy, projectRoot, riskTier, thresholds: config.thresholds, context });
97
+ results.push({
98
+ name: gateName,
99
+ mode,
100
+ status: result.status,
101
+ waived,
102
+ waiverId,
103
+ messages: result.messages || [],
104
+ duration: Date.now() - start,
105
+ });
106
+ } catch (err) {
107
+ results.push({
108
+ name: gateName,
109
+ mode,
110
+ status: 'fail',
111
+ waived: false,
112
+ messages: [`Gate error: ${err.message}`],
113
+ duration: Date.now() - start,
114
+ });
115
+ }
116
+ }
117
+
118
+ const blocked = results.filter(r => r.mode === 'block' && r.status === 'fail' && !r.waived);
119
+ const warned = results.filter(r => r.status === 'warn' || (r.mode === 'warn' && r.status === 'fail'));
120
+ const passed = results.filter(r => r.status === 'pass');
121
+ const skipped = results.filter(r => r.status === 'skipped');
122
+ const waivedGates = results.filter(r => r.waived);
123
+
124
+ const report = {
125
+ passed: blocked.length === 0,
126
+ gates: results,
127
+ summary: {
128
+ blocked: blocked.length,
129
+ warned: warned.length,
130
+ passed: passed.length,
131
+ skipped: skipped.length,
132
+ waived: waivedGates.length,
133
+ },
134
+ };
135
+
136
+ if (usingDefaults) {
137
+ report.warnings = report.warnings || [];
138
+ report.warnings.push('No policy.yaml found — using built-in defaults. Create .caws/policy.yaml for project-specific gate configuration.');
139
+ }
140
+
141
+ // Emit lifecycle events
142
+ try {
143
+ if (blocked.length > 0) {
144
+ for (const b of blocked) {
145
+ lifecycle.emit(EVENTS.GATES_BLOCKED, {
146
+ specId: spec?.id || null,
147
+ gateName: b.name,
148
+ mode: b.mode,
149
+ messages: b.messages,
150
+ context,
151
+ timestamp: new Date().toISOString(),
152
+ });
153
+ }
154
+ } else {
155
+ lifecycle.emit(EVENTS.GATES_PASSED, {
156
+ specId: spec?.id || null,
157
+ summary: report.summary,
158
+ context,
159
+ timestamp: new Date().toISOString(),
160
+ });
161
+ }
162
+ } catch { /* non-fatal */ }
163
+
164
+ return report;
165
+ }
166
+
167
+ module.exports = { evaluateGates, loadGates };
@@ -0,0 +1,93 @@
1
+ /**
2
+ * @fileoverview Scope enforcement gate
3
+ * Validates staged files against spec.scope.in and spec.scope.out patterns.
4
+ * @author @darianrosebrook
5
+ */
6
+
7
+ const picomatch = require('picomatch');
8
+
9
+ const name = 'scope_boundary';
10
+
11
+ /**
12
+ * Check if a file path matches any of the given glob patterns.
13
+ * Uses picomatch for correct glob semantics (** matches zero or more segments).
14
+ * @param {string} filePath - File path to check
15
+ * @param {string[]} patterns - Glob patterns
16
+ * @returns {boolean} Whether the file matches any pattern
17
+ */
18
+ function matchesAny(filePath, patterns) {
19
+ if (!patterns || patterns.length === 0) return false;
20
+ return picomatch.isMatch(filePath, patterns, { dot: true });
21
+ }
22
+
23
+ /**
24
+ * Check if a file is an infrastructure file that always passes scope checks.
25
+ * Root-level files are exempt UNLESS they match an explicit scope.out pattern.
26
+ * @param {string} filePath - File path to check
27
+ * @returns {boolean} Whether the file is exempt from scope.in checks
28
+ */
29
+ function isExempt(filePath) {
30
+ // .caws and .claude directories always pass (infrastructure)
31
+ if (filePath.startsWith('.caws/') || filePath.startsWith('.claude/')) return true;
32
+ return false;
33
+ }
34
+
35
+ /**
36
+ * Check if a file is a root-level file (no directory separator).
37
+ * Root-level files skip scope.in checks but still respect scope.out.
38
+ * @param {string} filePath - File path to check
39
+ * @returns {boolean} Whether the file is root-level
40
+ */
41
+ function isRootLevel(filePath) {
42
+ return !filePath.includes('/');
43
+ }
44
+
45
+ /**
46
+ * Run the scope boundary gate
47
+ * @param {Object} params - Gate parameters
48
+ * @param {string[]} params.stagedFiles - Staged file paths
49
+ * @param {Object} params.spec - Working spec with scope.in/scope.out
50
+ * @returns {Promise<Object>} Gate result with status and messages
51
+ */
52
+ async function run({ stagedFiles, spec }) {
53
+ const messages = [];
54
+ const violations = [];
55
+
56
+ const scopeIn = spec?.scope?.in || [];
57
+ const scopeOut = spec?.scope?.out || [];
58
+
59
+ // If no scope defined, pass
60
+ if (scopeIn.length === 0 && scopeOut.length === 0) {
61
+ return { status: 'pass', messages: ['No scope boundaries defined'] };
62
+ }
63
+
64
+ for (const file of stagedFiles) {
65
+ // Infrastructure dirs are always exempt
66
+ if (isExempt(file)) continue;
67
+
68
+ // Check scope.out first (explicit exclusion) — applies to ALL files including root-level
69
+ if (scopeOut.length > 0 && matchesAny(file, scopeOut)) {
70
+ violations.push(file);
71
+ messages.push(`Out of scope (excluded): ${file}`);
72
+ continue;
73
+ }
74
+
75
+ // Root-level files skip scope.in checks (but scope.out above still applies)
76
+ if (isRootLevel(file)) continue;
77
+
78
+ // Check scope.in (must match if defined)
79
+ if (scopeIn.length > 0 && !matchesAny(file, scopeIn)) {
80
+ violations.push(file);
81
+ messages.push(`Out of scope (not in allowed paths): ${file}`);
82
+ }
83
+ }
84
+
85
+ if (violations.length > 0) {
86
+ messages.unshift(`${violations.length} file(s) outside spec scope boundaries`);
87
+ return { status: 'fail', messages };
88
+ }
89
+
90
+ return { status: 'pass', messages };
91
+ }
92
+
93
+ module.exports = { name, run };
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @fileoverview Schema validation gate
3
+ * Validates the working spec against the CAWS schema.
4
+ * @author @darianrosebrook
5
+ */
6
+
7
+ const fs = require('fs-extra');
8
+ const path = require('path');
9
+ const yaml = require('js-yaml');
10
+ const Ajv = require('ajv');
11
+
12
+ const name = 'spec_completeness';
13
+
14
+ /**
15
+ * Run the spec completeness gate
16
+ * @param {Object} params - Gate parameters
17
+ * @param {string} params.projectRoot - Project root
18
+ * @returns {Promise<Object>} Gate result with status and messages
19
+ */
20
+ async function run({ projectRoot, spec }) {
21
+ const messages = [];
22
+
23
+ let specObject = spec;
24
+ if (!specObject) {
25
+ const specPath = path.join(projectRoot, '.caws', 'working-spec.yaml');
26
+ if (!await fs.pathExists(specPath)) {
27
+ return {
28
+ status: 'fail',
29
+ messages: ['No working-spec.yaml found. Create one with: caws init or caws specs create <id>'],
30
+ };
31
+ }
32
+
33
+ try {
34
+ const content = await fs.readFile(specPath, 'utf8');
35
+ specObject = yaml.load(content);
36
+ } catch (err) {
37
+ return { status: 'fail', messages: [`Failed to parse working-spec.yaml: ${err.message}`] };
38
+ }
39
+ }
40
+
41
+ if (!specObject) {
42
+ return { status: 'fail', messages: ['Resolved spec is empty'] };
43
+ }
44
+
45
+ // Try to find and load the schema
46
+ const schemaPaths = [
47
+ path.join(projectRoot, '.caws', 'schemas', 'working-spec.schema.json'),
48
+ path.join(projectRoot, 'node_modules', '@caws', 'cli', 'templates', '.caws', 'schemas', 'working-spec.schema.json'),
49
+ ];
50
+
51
+ let schema = null;
52
+ for (const schemaPath of schemaPaths) {
53
+ if (await fs.pathExists(schemaPath)) {
54
+ try {
55
+ const schemaContent = await fs.readFile(schemaPath, 'utf8');
56
+ schema = JSON.parse(schemaContent);
57
+ break;
58
+ } catch {
59
+ // Try next path
60
+ }
61
+ }
62
+ }
63
+
64
+ if (!schema) {
65
+ // No schema available; do basic structural validation
66
+ const requiredFields = ['title', 'risk_tier'];
67
+ const missing = requiredFields.filter(f => !(f in specObject));
68
+ if (missing.length > 0) {
69
+ messages.push(`Missing required fields: ${missing.join(', ')}`);
70
+ return { status: 'fail', messages };
71
+ }
72
+ return { status: 'pass', messages: ['Basic structure valid (no schema file found for full validation)'] };
73
+ }
74
+
75
+ // Validate with AJV — use 2020-12 draft if schema requires it
76
+ try {
77
+ const isDraft2020 = schema.$schema && schema.$schema.includes('2020-12');
78
+ let ajv;
79
+ if (isDraft2020) {
80
+ const Ajv2020 = require('ajv/dist/2020');
81
+ ajv = new Ajv2020({ allErrors: true, strict: false });
82
+ } else {
83
+ ajv = new Ajv({ allErrors: true, strict: false });
84
+ }
85
+ const validate = ajv.compile(schema);
86
+ const valid = validate(specObject);
87
+
88
+ if (!valid) {
89
+ for (const error of validate.errors) {
90
+ const location = error.instancePath || '/';
91
+ messages.push(`${location}: ${error.message}`);
92
+ }
93
+ return { status: 'fail', messages };
94
+ }
95
+
96
+ return { status: 'pass', messages };
97
+ } catch (err) {
98
+ return { status: 'fail', messages: [`Schema validation error: ${err.message}`] };
99
+ }
100
+ }
101
+
102
+ module.exports = { name, run };