claude-flow-novice 2.2.4 → 2.2.5

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 (288) hide show
  1. package/package.json +9 -8
  2. package/scripts/.claude-flow/metrics/agent-metrics.json +1 -0
  3. package/scripts/.claude-flow/metrics/performance.json +9 -0
  4. package/scripts/.claude-flow/metrics/task-metrics.json +10 -0
  5. package/scripts/CLEANUP_OPTIMIZATION_REPORT.json +312 -0
  6. package/scripts/CLEANUP_PERFORMANCE_OPTIMIZATION.md +387 -0
  7. package/scripts/CLEANUP_QUICK_START.md +268 -0
  8. package/scripts/CLEANUP_TEST_RESULTS.md +205 -0
  9. package/scripts/README.md +339 -0
  10. package/scripts/ace-query.sh +384 -0
  11. package/scripts/agent-token-analysis.js +430 -0
  12. package/scripts/auto-setup.js +332 -0
  13. package/scripts/build/README.md +167 -0
  14. package/scripts/build/build-config.js +27 -0
  15. package/scripts/build/build-prompt-copier.sh +30 -0
  16. package/scripts/build/performance-monitor.js +869 -0
  17. package/scripts/build/prepare-publish.js +150 -0
  18. package/scripts/build/typescript-fixer.js +621 -0
  19. package/scripts/build/unified-builder.sh +428 -0
  20. package/scripts/build/update-bin-version.js +32 -0
  21. package/scripts/build/validate-agents.js +238 -0
  22. package/scripts/build-index.js +43 -0
  23. package/scripts/build-orchestrator.js +320 -0
  24. package/scripts/check-routing-stats.cjs +122 -0
  25. package/scripts/ci-validation.js +375 -0
  26. package/scripts/cleanup-blocking-coordination.sh +420 -0
  27. package/scripts/cleanup-idle-sessions.sh +59 -0
  28. package/scripts/collect-build-metrics.js +65 -0
  29. package/scripts/demo/README.md +79 -0
  30. package/scripts/demo/autoscaling-demo-simplified.js +963 -0
  31. package/scripts/demo/comprehensive-dashboard-test.js +693 -0
  32. package/scripts/demo/confidence-log.js +87 -0
  33. package/scripts/demo/confidence-report.js +82 -0
  34. package/scripts/demo/demo-multi-swarm-coordination.js +325 -0
  35. package/scripts/demo/demo-production-deployment.js +399 -0
  36. package/scripts/demo/demo-visualization-system.js +149 -0
  37. package/scripts/demo/performance-analysis.cjs +71 -0
  38. package/scripts/demo/performance-analysis.js +71 -0
  39. package/scripts/demo/test-autoscaling-demo.js +314 -0
  40. package/scripts/dependency-optimizer.js +349 -0
  41. package/scripts/dependency-security-assessment.js +331 -0
  42. package/scripts/deploy-sdk.sh +176 -0
  43. package/scripts/deployment-readiness-report.json +179 -0
  44. package/scripts/dev/README.md +264 -0
  45. package/scripts/dev/claude-flow-wrapper.sh +35 -0
  46. package/scripts/dev/claude-monitor.py +419 -0
  47. package/scripts/dev/claude-sparc.sh +562 -0
  48. package/scripts/dev/claude-wrapper.sh +17 -0
  49. package/scripts/dev/demo-phase3-compliance.js +172 -0
  50. package/scripts/dev/demo-task-system.ts +224 -0
  51. package/scripts/dev/deployment-validator.js +315 -0
  52. package/scripts/dev/spawn-claude-terminal.sh +32 -0
  53. package/scripts/dev/start-portal.sh +506 -0
  54. package/scripts/dev/start-web-ui.js +15 -0
  55. package/scripts/dev/stop-portal.sh +311 -0
  56. package/scripts/dev/validate-examples.ts +288 -0
  57. package/scripts/dev/validate-phase2.cjs +451 -0
  58. package/scripts/dev/validate-phase2.js +785 -0
  59. package/scripts/dev/validate-phase3.cjs +208 -0
  60. package/scripts/dev/validate-security-remediation.js +1 -0
  61. package/scripts/ecosystem.config.cjs +90 -0
  62. package/scripts/fix-js-extensions.js +167 -0
  63. package/scripts/generate-basic-types.js +73 -0
  64. package/scripts/generate-changelog.js +318 -0
  65. package/scripts/git-hooks/pre-commit.sh +143 -0
  66. package/scripts/health-checks.js +634 -0
  67. package/scripts/hook-wrapper.sh +54 -0
  68. package/scripts/install/README.md +375 -0
  69. package/scripts/install/REDIS_SETUP_VALIDATION.json +245 -0
  70. package/scripts/install/check-prerequisites.js +303 -0
  71. package/scripts/install/config-wizard.js +606 -0
  72. package/scripts/install/dependency-checker.js +385 -0
  73. package/scripts/install/health-check.js +765 -0
  74. package/scripts/install/install.js +256 -0
  75. package/scripts/install/installation-benchmark.js +461 -0
  76. package/scripts/install/quick-install.js +720 -0
  77. package/scripts/install/quick-start-wizard.js +295 -0
  78. package/scripts/install/redis-cli.js +289 -0
  79. package/scripts/install/redis-install-guides.md +407 -0
  80. package/scripts/install/redis-setup.js +559 -0
  81. package/scripts/install/redis-test.js +278 -0
  82. package/scripts/install/service-manager.js +672 -0
  83. package/scripts/install/setup.js +832 -0
  84. package/scripts/install/uninstall.js +526 -0
  85. package/scripts/install/update.js +461 -0
  86. package/scripts/install-pre-commit-hook.sh +127 -0
  87. package/scripts/legacy/README.md +272 -0
  88. package/scripts/legacy/batch-fix-ts.sh +54 -0
  89. package/scripts/legacy/build-migration.sh +105 -0
  90. package/scripts/legacy/build-monitor.js +209 -0
  91. package/scripts/legacy/build-with-filter.sh +84 -0
  92. package/scripts/legacy/build-workaround.sh +71 -0
  93. package/scripts/legacy/fix-ts-advanced.js +358 -0
  94. package/scripts/legacy/fix-ts-final.sh +50 -0
  95. package/scripts/legacy/fix-ts-targeted.sh +49 -0
  96. package/scripts/legacy/fix-typescript-errors.js +305 -0
  97. package/scripts/legacy/force-build.sh +63 -0
  98. package/scripts/legacy/optimize-performance.js +400 -0
  99. package/scripts/legacy/performance-monitor.js +263 -0
  100. package/scripts/legacy/performance-monitoring.js +532 -0
  101. package/scripts/legacy/performance-test-runner.js +645 -0
  102. package/scripts/legacy/quick-fix-ts.js +281 -0
  103. package/scripts/legacy/safe-build.sh +63 -0
  104. package/scripts/memory-monitor-coordinator.js +322 -0
  105. package/scripts/migrate-to-sdk.sh +520 -0
  106. package/scripts/migration/QUICK-START.md +189 -0
  107. package/scripts/migration/QUICK-START.md.backup-1760135091363 +189 -0
  108. package/scripts/migration/README.md +464 -0
  109. package/scripts/migration/TASK-1.3.2-COMPLETION-REPORT.md +500 -0
  110. package/scripts/migration/TASK-1.3.2-COMPLETION-REPORT.md.backup-1760135091348 +500 -0
  111. package/scripts/migration/UPDATE-PATHS-README.md +464 -0
  112. package/scripts/migration/UPDATE-PATHS-README.md.backup-1760135091337 +464 -0
  113. package/scripts/migration/example-patterns.json +19 -0
  114. package/scripts/migration/install-arm64.js +78 -0
  115. package/scripts/migration/install.js +83 -0
  116. package/scripts/migration/migrate-hooks.js +173 -0
  117. package/scripts/migration/migration-examples.ts +318 -0
  118. package/scripts/migration/reorganize-workspace.js +504 -0
  119. package/scripts/migration/test-update-paths.js +359 -0
  120. package/scripts/migration/update-paths.js +664 -0
  121. package/scripts/migration/validate-migration.js +647 -0
  122. package/scripts/monitor-loop.sh +65 -0
  123. package/scripts/monitor-memory.sh +47 -0
  124. package/scripts/monitor-migration.js +339 -0
  125. package/scripts/monitor.py +43 -0
  126. package/scripts/monitoring/README.md +178 -0
  127. package/scripts/monitoring/alert-monitor.sh +220 -0
  128. package/scripts/monitoring/analyze-resources.sh +199 -0
  129. package/scripts/monitoring/dashboards/rate-limiting-dashboard.json +211 -0
  130. package/scripts/monitoring/dynamic-monitor.sh +85 -0
  131. package/scripts/monitoring/launch-stability-test.sh +184 -0
  132. package/scripts/monitoring/monitor-test.sh +93 -0
  133. package/scripts/monitoring/pre-test-validation.sh +208 -0
  134. package/scripts/monitoring/quick-test-alerting.sh +118 -0
  135. package/scripts/monitoring/quick-test-rate-limiting.sh +206 -0
  136. package/scripts/monitoring/rate-limiting-monitor.sh +380 -0
  137. package/scripts/monitoring/resource-monitor.sh +126 -0
  138. package/scripts/monitoring/stability-monitor.js +429 -0
  139. package/scripts/monitoring/test-monitor-quick.sh +54 -0
  140. package/scripts/monitoring/view-alerts.sh +307 -0
  141. package/scripts/npm-metrics-collector.js +482 -0
  142. package/scripts/npm-package-validation.cjs +299 -0
  143. package/scripts/optimization/build-optimizer.js +438 -0
  144. package/scripts/optimization/config-validator.js +761 -0
  145. package/scripts/optimization/test-optimization.js +432 -0
  146. package/scripts/optimization/unified-activation.js +839 -0
  147. package/scripts/optimize-package-swarm.js +54 -0
  148. package/scripts/performance/ACTIVATION_COMMANDS.md +292 -0
  149. package/scripts/performance/sqlite-enhanced-activation.sh +583 -0
  150. package/scripts/performance/test-enhanced-backend.sh +504 -0
  151. package/scripts/performance-monitor.js +644 -0
  152. package/scripts/performance-test-runner.js +698 -0
  153. package/scripts/post-deployment-monitoring.js +350 -0
  154. package/scripts/post-edit-pipeline.js +2091 -0
  155. package/scripts/post-install-claude-md.js +78 -0
  156. package/scripts/postinstall.js +79 -0
  157. package/scripts/pre-publish-validation.cjs +212 -0
  158. package/scripts/pre-publish-validation.js +429 -0
  159. package/scripts/redis-lua/cleanup-blocking-coordination.lua +198 -0
  160. package/scripts/release-announcement.js +425 -0
  161. package/scripts/release-notification.js +248 -0
  162. package/scripts/release-rollback.js +376 -0
  163. package/scripts/release-validation.js +460 -0
  164. package/scripts/rollback-sdk.sh +66 -0
  165. package/scripts/run-production-validation.ts +590 -0
  166. package/scripts/run-stability-validation.sh +687 -0
  167. package/scripts/security/README.md +339 -0
  168. package/scripts/security/deployment-validation.cjs +279 -0
  169. package/scripts/security/envelope-encryption-confidence-report.cjs +422 -0
  170. package/scripts/security/install-git-hooks.sh +132 -0
  171. package/scripts/security/install-git-secrets.sh +295 -0
  172. package/scripts/security/rotate-api-keys.js +469 -0
  173. package/scripts/security/ruv-swarm-safe.js +74 -0
  174. package/scripts/security/security-audit.cjs +538 -0
  175. package/scripts/security/setup-redis-auth.sh +397 -0
  176. package/scripts/security/validate-envelope-encryption.cjs +340 -0
  177. package/scripts/security-scan.js +492 -0
  178. package/scripts/src/web/frontend/.claude-flow/metrics/agent-metrics.json +1 -0
  179. package/scripts/src/web/frontend/.claude-flow/metrics/performance.json +9 -0
  180. package/scripts/src/web/frontend/.claude-flow/metrics/task-metrics.json +10 -0
  181. package/scripts/switch-api.sh +158 -0
  182. package/scripts/sync-agents.js +290 -0
  183. package/scripts/test/50-agent-test.js +625 -0
  184. package/scripts/test/NEW_STABILITY_TEST_GUIDE.md +407 -0
  185. package/scripts/test/README.md +236 -0
  186. package/scripts/test/STABILITY_TEST_EXAMPLE.md +347 -0
  187. package/scripts/test/STABILITY_TEST_README.md +480 -0
  188. package/scripts/test/agent-worker.js +309 -0
  189. package/scripts/test/ai-coordination-test.js +650 -0
  190. package/scripts/test/ai-mesh-coordination-test.js +416 -0
  191. package/scripts/test/check-links.ts +274 -0
  192. package/scripts/test/check-performance-regression.ts +168 -0
  193. package/scripts/test/cli-agent-coordination-test.js +313 -0
  194. package/scripts/test/coordinator-multilingual-test.js +396 -0
  195. package/scripts/test/coordinator-transparency-demo.js +585 -0
  196. package/scripts/test/coverage-report.ts +692 -0
  197. package/scripts/test/generate-swarm-tests.js +633 -0
  198. package/scripts/test/integration-test-validation.cjs +253 -0
  199. package/scripts/test/load-test-swarm.js +576 -0
  200. package/scripts/test/mesh-coordination-zero-overlap-test.js +740 -0
  201. package/scripts/test/multilingual-hello-world-test.js +390 -0
  202. package/scripts/test/quick-multilingual-demo.js +464 -0
  203. package/scripts/test/real-agent-test.js +312 -0
  204. package/scripts/test/run-phase3-compliance-tests.js +427 -0
  205. package/scripts/test/run-stability-test-examples.sh +292 -0
  206. package/scripts/test/stability-results/stability-metrics.jsonl +83 -0
  207. package/scripts/test/stability-results/stability-test-report.json +128 -0
  208. package/scripts/test/stability-results/stability-test.log +1827 -0
  209. package/scripts/test/stability-test-50-agents.js +734 -0
  210. package/scripts/test/test-batch-tasks.ts +29 -0
  211. package/scripts/test/test-byzantine-resolution.js +246 -0
  212. package/scripts/test/test-claude-spawn-options.sh +63 -0
  213. package/scripts/test/test-cli-wizard.js +331 -0
  214. package/scripts/test/test-comprehensive.js +401 -0
  215. package/scripts/test/test-coordination-features.ts +238 -0
  216. package/scripts/test/test-fallback-systems.js +276 -0
  217. package/scripts/test/test-init-command.ts +302 -0
  218. package/scripts/test/test-mcp.ts +251 -0
  219. package/scripts/test/test-runner.ts +568 -0
  220. package/scripts/test/test-swarm-integration.sh +92 -0
  221. package/scripts/test/test-swarm.ts +142 -0
  222. package/scripts/test/validation-summary.ts +408 -0
  223. package/scripts/test-cleanup-performance.sh +416 -0
  224. package/scripts/test-dashboard-auth.cjs +203 -0
  225. package/scripts/test-docker-deployment.sh +207 -0
  226. package/scripts/test-npm-package.cjs +167 -0
  227. package/scripts/test-provider-routing.cjs +226 -0
  228. package/scripts/test-routing-telemetry.cjs +147 -0
  229. package/scripts/test-runner.cjs +154 -0
  230. package/scripts/test-zai-10k.cjs +81 -0
  231. package/scripts/test-zai-api.cjs +191 -0
  232. package/scripts/test-zai-diagnostic.cjs +151 -0
  233. package/scripts/test-zai-final.cjs +128 -0
  234. package/scripts/test-zai-with-env.cjs +85 -0
  235. package/scripts/utils/README.md +261 -0
  236. package/scripts/utils/clean-build-artifacts.sh +94 -0
  237. package/scripts/utils/cleanup-root.sh +69 -0
  238. package/scripts/utils/fix-cliffy-imports.js +307 -0
  239. package/scripts/utils/fix-duplicate-imports.js +114 -0
  240. package/scripts/utils/fix-error-handling.cjs +70 -0
  241. package/scripts/utils/fix-import-paths.js +104 -0
  242. package/scripts/utils/fix-imports.js +116 -0
  243. package/scripts/utils/fix-shebang.js +78 -0
  244. package/scripts/utils/fix-test-modules.js +27 -0
  245. package/scripts/utils/fix-timezone-issue-246.js +200 -0
  246. package/scripts/utils/fix-ts-comprehensive.py +182 -0
  247. package/scripts/utils/fix-ts-targeted-batch.js +250 -0
  248. package/scripts/utils/remove-benchmark-conflicts.sh +140 -0
  249. package/scripts/utils/simple-test-fixer.js +190 -0
  250. package/scripts/utils/validate-metrics-structure.cjs +144 -0
  251. package/scripts/validate-agent-hooks.js +506 -0
  252. package/scripts/validate-changelog.js +241 -0
  253. package/scripts/validate-coordination-cli.js +69 -0
  254. package/scripts/validate-coordination-toggle-integration.cjs +501 -0
  255. package/scripts/validate-docker-infrastructure.sh +502 -0
  256. package/scripts/validate-entry-points.js +300 -0
  257. package/scripts/validate-stage3-performance.ts +377 -0
  258. package/scripts/validate-template-bundling.js +180 -0
  259. package/scripts/validation/README.md +33 -0
  260. package/scripts/validation/acl-security-validation.cjs +214 -0
  261. package/scripts/validation/acl-security-validation.js +402 -0
  262. package/scripts/validation/byzantine-verification.js +407 -0
  263. package/scripts/validation/final-phase-2-consensus.cjs +219 -0
  264. package/scripts/validation/final-security-validation.js +791 -0
  265. package/scripts/validation/final-wasm-validation.cjs +840 -0
  266. package/scripts/validation/integration-test-analysis.js +105 -0
  267. package/scripts/validation/phase-0-comprehensive-validation.js +474 -0
  268. package/scripts/validation/phase-0-consensus-report.js +139 -0
  269. package/scripts/validation/phase-0-final-report.js +112 -0
  270. package/scripts/validation/phase-0-redis-consensus-report.js +129 -0
  271. package/scripts/validation/phase-0-validation-improved.js +490 -0
  272. package/scripts/validation/phase-0-validation-test.js +65 -0
  273. package/scripts/validation/phase-1-consensus-report.cjs +342 -0
  274. package/scripts/validation/phase-1-consensus-validation.cjs +551 -0
  275. package/scripts/validation/phase-1-consensus-validation.js +551 -0
  276. package/scripts/validation/phase-2-consensus-report.cjs +186 -0
  277. package/scripts/validation/phase-2-validation.cjs +171 -0
  278. package/scripts/validation/phase-2-validation.js +171 -0
  279. package/scripts/validation/phase-4-consensus-report.js +181 -0
  280. package/scripts/validation/phase-4-final-validation.js +351 -0
  281. package/scripts/validation/phase-5-consensus-report.cjs +113 -0
  282. package/scripts/validation/phase-5-consensus-report.js +113 -0
  283. package/scripts/validation/security-analysis.js +49 -0
  284. package/scripts/validation/security-validation.js +492 -0
  285. package/scripts/validation/simple-security-validation.js +464 -0
  286. package/scripts/verify-installation.js +112 -0
  287. package/scripts/verify-mcp-server.js +86 -0
  288. package/scripts/verify-sdk-phase1.cjs +293 -0
@@ -0,0 +1,2091 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Unified Post-Edit Validation Pipeline
5
+ * Combines comprehensive validation with TDD enforcement
6
+ *
7
+ * Features:
8
+ * - Progressive validation (syntax → interface → integration → full)
9
+ * - TDD enforcement with test-first compliance
10
+ * - Single-file testing without full system compilation
11
+ * - Real-time coverage analysis
12
+ * - Rust-specific quality enforcements
13
+ * - Multi-language support
14
+ * - Security scanning
15
+ * - Agent coordination
16
+ */
17
+
18
+ import path from 'path';
19
+ import fs from 'fs';
20
+ import fsSync from 'fs';
21
+ import { exec, spawn } from 'child_process';
22
+ import { promisify } from 'util';
23
+
24
+ const execAsync = promisify(exec);
25
+
26
+ // Enhanced logging utilities
27
+ class Logger {
28
+ static success(msg, data = {}) {
29
+ console.log(`āœ… ${msg}`);
30
+ return { level: 'success', message: msg, data };
31
+ }
32
+
33
+ static error(msg, data = {}) {
34
+ console.log(`āŒ ${msg}`);
35
+ return { level: 'error', message: msg, data };
36
+ }
37
+
38
+ static warning(msg, data = {}) {
39
+ console.log(`āš ļø ${msg}`);
40
+ return { level: 'warning', message: msg, data };
41
+ }
42
+
43
+ static info(msg, data = {}) {
44
+ console.log(`ā„¹ļø ${msg}`);
45
+ return { level: 'info', message: msg, data };
46
+ }
47
+
48
+ static test(msg, data = {}) {
49
+ console.log(`🧪 ${msg}`);
50
+ return { level: 'test', message: msg, data };
51
+ }
52
+
53
+ static coverage(msg, data = {}) {
54
+ console.log(`šŸ“Š ${msg}`);
55
+ return { level: 'coverage', message: msg, data };
56
+ }
57
+
58
+ static tdd(msg, data = {}) {
59
+ console.log(`šŸ”“šŸŸ¢ā™»ļø ${msg}`);
60
+ return { level: 'tdd', message: msg, data };
61
+ }
62
+ }
63
+
64
+ // Single-file test execution engine
65
+ class SingleFileTestEngine {
66
+ constructor() {
67
+ this.testRunners = {
68
+ '.js': this.runJavaScriptTests.bind(this),
69
+ '.jsx': this.runJavaScriptTests.bind(this),
70
+ '.ts': this.runTypeScriptTests.bind(this),
71
+ '.tsx': this.runTypeScriptTests.bind(this),
72
+ '.py': this.runPythonTests.bind(this),
73
+ '.go': this.runGoTests.bind(this),
74
+ '.rs': this.runRustTests.bind(this),
75
+ '.java': this.runJavaTests.bind(this),
76
+ '.cpp': this.runCPPTests.bind(this),
77
+ '.c': this.runCTests.bind(this)
78
+ };
79
+ }
80
+
81
+ async executeTests(file, content) {
82
+ const ext = path.extname(file).toLowerCase();
83
+ const runner = this.testRunners[ext];
84
+
85
+ if (!runner) {
86
+ return {
87
+ executed: false,
88
+ reason: `No test runner available for ${ext} files`,
89
+ framework: null,
90
+ results: null,
91
+ coverage: null,
92
+ tddCompliance: null
93
+ };
94
+ }
95
+
96
+ const isTestFile = this.isTestFile(file);
97
+ const relatedFile = isTestFile ? this.findSourceFile(file) : this.findTestFile(file);
98
+
99
+ return await runner(file, content, { isTestFile, relatedFile });
100
+ }
101
+
102
+ async runJavaScriptTests(file, content, options = {}) {
103
+ const { isTestFile, relatedFile } = options;
104
+
105
+ try {
106
+ const framework = await this.detectJSTestFramework();
107
+
108
+ if (!framework) {
109
+ return {
110
+ executed: false,
111
+ reason: 'No JavaScript test framework detected (jest, mocha, etc.)',
112
+ framework: null,
113
+ results: null,
114
+ coverage: null,
115
+ tddCompliance: this.checkTDDCompliance(file, relatedFile, null)
116
+ };
117
+ }
118
+
119
+ let testResults = null;
120
+ let coverage = null;
121
+
122
+ if (framework === 'jest') {
123
+ testResults = await this.runJestSingleFile(file, isTestFile);
124
+ coverage = await this.getJestCoverage(file);
125
+ } else if (framework === 'mocha') {
126
+ testResults = await this.runMochaSingleFile(file, isTestFile);
127
+ }
128
+
129
+ const tddCompliance = this.checkTDDCompliance(file, relatedFile, testResults);
130
+
131
+ return {
132
+ executed: true,
133
+ framework,
134
+ results: testResults,
135
+ coverage,
136
+ tddCompliance,
137
+ singleFileMode: true
138
+ };
139
+
140
+ } catch (error) {
141
+ return {
142
+ executed: false,
143
+ reason: `Test execution failed: ${error.message}`,
144
+ framework: null,
145
+ results: null,
146
+ coverage: null,
147
+ tddCompliance: null,
148
+ error: error.message
149
+ };
150
+ }
151
+ }
152
+
153
+ async runTypeScriptTests(file, content, options = {}) {
154
+ const jsResult = await this.runJavaScriptTests(file, content, options);
155
+ if (jsResult.executed) {
156
+ jsResult.language = 'typescript';
157
+ jsResult.compiled = true;
158
+ }
159
+ return jsResult;
160
+ }
161
+
162
+ async runPythonTests(file, content, options = {}) {
163
+ const { isTestFile, relatedFile } = options;
164
+
165
+ try {
166
+ const framework = await this.detectPythonTestFramework();
167
+
168
+ if (!framework) {
169
+ return {
170
+ executed: false,
171
+ reason: 'No Python test framework detected (pytest, unittest)',
172
+ framework: null,
173
+ results: null,
174
+ coverage: null,
175
+ tddCompliance: this.checkTDDCompliance(file, relatedFile, null)
176
+ };
177
+ }
178
+
179
+ let testResults = null;
180
+ let coverage = null;
181
+
182
+ if (framework === 'pytest') {
183
+ testResults = await this.runPytestSingleFile(file, isTestFile);
184
+ coverage = await this.getPytestCoverage(file);
185
+ } else if (framework === 'unittest') {
186
+ testResults = await this.runUnittestSingleFile(file, isTestFile);
187
+ }
188
+
189
+ const tddCompliance = this.checkTDDCompliance(file, relatedFile, testResults);
190
+
191
+ return {
192
+ executed: true,
193
+ framework,
194
+ results: testResults,
195
+ coverage,
196
+ tddCompliance,
197
+ singleFileMode: true
198
+ };
199
+
200
+ } catch (error) {
201
+ return {
202
+ executed: false,
203
+ reason: `Python test execution failed: ${error.message}`,
204
+ framework: null,
205
+ results: null,
206
+ coverage: null,
207
+ tddCompliance: null,
208
+ error: error.message
209
+ };
210
+ }
211
+ }
212
+
213
+ async runGoTests(file, content, options = {}) {
214
+ const { isTestFile, relatedFile } = options;
215
+
216
+ try {
217
+ if (!isTestFile) {
218
+ const testFile = this.findTestFile(file);
219
+ if (!testFile || !await this.fileExists(testFile)) {
220
+ return {
221
+ executed: false,
222
+ reason: 'No corresponding test file found for Go source',
223
+ framework: 'go test',
224
+ results: null,
225
+ coverage: null,
226
+ tddCompliance: this.checkTDDCompliance(file, null, null)
227
+ };
228
+ }
229
+ file = testFile;
230
+ }
231
+
232
+ const testResults = await this.runGoTestSingleFile(file);
233
+ const coverage = await this.getGoCoverage(file);
234
+ const tddCompliance = this.checkTDDCompliance(file, relatedFile, testResults);
235
+
236
+ return {
237
+ executed: true,
238
+ framework: 'go test',
239
+ results: testResults,
240
+ coverage,
241
+ tddCompliance,
242
+ singleFileMode: true
243
+ };
244
+
245
+ } catch (error) {
246
+ return {
247
+ executed: false,
248
+ reason: `Go test execution failed: ${error.message}`,
249
+ framework: 'go test',
250
+ results: null,
251
+ coverage: null,
252
+ tddCompliance: null,
253
+ error: error.message
254
+ };
255
+ }
256
+ }
257
+
258
+ async runRustTests(file, content, options = {}) {
259
+ const { isTestFile, relatedFile } = options;
260
+
261
+ try {
262
+ const testResults = await this.runCargoTestSingleFile(file);
263
+ const coverage = await this.getRustCoverage(file);
264
+ const tddCompliance = this.checkTDDCompliance(file, relatedFile, testResults);
265
+
266
+ return {
267
+ executed: true,
268
+ framework: 'cargo test',
269
+ results: testResults,
270
+ coverage,
271
+ tddCompliance,
272
+ singleFileMode: true
273
+ };
274
+
275
+ } catch (error) {
276
+ return {
277
+ executed: false,
278
+ reason: `Rust test execution failed: ${error.message}`,
279
+ framework: 'cargo test',
280
+ results: null,
281
+ coverage: null,
282
+ tddCompliance: null,
283
+ error: error.message
284
+ };
285
+ }
286
+ }
287
+
288
+ async runJavaTests(file, content, options = {}) {
289
+ const { isTestFile, relatedFile } = options;
290
+
291
+ try {
292
+ const framework = await this.detectJavaTestFramework();
293
+
294
+ if (!framework) {
295
+ return {
296
+ executed: false,
297
+ reason: 'No Java test framework detected (JUnit, TestNG)',
298
+ framework: null,
299
+ results: null,
300
+ coverage: null,
301
+ tddCompliance: this.checkTDDCompliance(file, relatedFile, null)
302
+ };
303
+ }
304
+
305
+ const testResults = await this.runJavaTestSingleFile(file, framework);
306
+ const tddCompliance = this.checkTDDCompliance(file, relatedFile, testResults);
307
+
308
+ return {
309
+ executed: true,
310
+ framework,
311
+ results: testResults,
312
+ coverage: null,
313
+ tddCompliance,
314
+ singleFileMode: true
315
+ };
316
+
317
+ } catch (error) {
318
+ return {
319
+ executed: false,
320
+ reason: `Java test execution failed: ${error.message}`,
321
+ framework: null,
322
+ results: null,
323
+ coverage: null,
324
+ tddCompliance: null,
325
+ error: error.message
326
+ };
327
+ }
328
+ }
329
+
330
+ async runCPPTests(file, content, options = {}) {
331
+ return this.runCTests(file, content, options);
332
+ }
333
+
334
+ async runCTests(file, content, options = {}) {
335
+ const { isTestFile, relatedFile } = options;
336
+
337
+ try {
338
+ const framework = await this.detectCTestFramework();
339
+
340
+ if (!framework) {
341
+ return {
342
+ executed: false,
343
+ reason: 'No C/C++ test framework detected (gtest, catch2)',
344
+ framework: null,
345
+ results: null,
346
+ coverage: null,
347
+ tddCompliance: this.checkTDDCompliance(file, relatedFile, null)
348
+ };
349
+ }
350
+
351
+ const testResults = await this.runCTestSingleFile(file, framework);
352
+ const tddCompliance = this.checkTDDCompliance(file, relatedFile, testResults);
353
+
354
+ return {
355
+ executed: true,
356
+ framework,
357
+ results: testResults,
358
+ coverage: null,
359
+ tddCompliance,
360
+ singleFileMode: true
361
+ };
362
+
363
+ } catch (error) {
364
+ return {
365
+ executed: false,
366
+ reason: `C/C++ test execution failed: ${error.message}`,
367
+ framework: null,
368
+ results: null,
369
+ coverage: null,
370
+ tddCompliance: null,
371
+ error: error.message
372
+ };
373
+ }
374
+ }
375
+
376
+ // Framework detection methods
377
+ async detectJSTestFramework() {
378
+ try {
379
+ const possiblePaths = [
380
+ path.join(process.cwd(), 'package.json'),
381
+ path.join(path.dirname(process.cwd()), 'package.json'),
382
+ ];
383
+
384
+ for (const packagePath of possiblePaths) {
385
+ try {
386
+ const packageContent = await fs.promises.readFile(packagePath, 'utf8');
387
+ const packageJson = JSON.parse(packageContent);
388
+ const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
389
+
390
+ if (deps.jest) return 'jest';
391
+ if (deps.mocha) return 'mocha';
392
+ if (deps.ava) return 'ava';
393
+ if (deps.tap) return 'tap';
394
+ } catch {
395
+ continue;
396
+ }
397
+ }
398
+
399
+ return null;
400
+ } catch {
401
+ return null;
402
+ }
403
+ }
404
+
405
+ async detectPythonTestFramework() {
406
+ try {
407
+ await execAsync('pytest --version');
408
+ return 'pytest';
409
+ } catch {
410
+ try {
411
+ await execAsync('python -m unittest --help');
412
+ return 'unittest';
413
+ } catch {
414
+ return null;
415
+ }
416
+ }
417
+ }
418
+
419
+ async detectJavaTestFramework() {
420
+ try {
421
+ const buildFiles = ['pom.xml', 'build.gradle', 'build.gradle.kts'];
422
+
423
+ for (const buildFile of buildFiles) {
424
+ if (await this.fileExists(buildFile)) {
425
+ const content = await fs.promises.readFile(buildFile, 'utf8');
426
+ if (content.includes('junit')) return 'junit';
427
+ if (content.includes('testng')) return 'testng';
428
+ }
429
+ }
430
+
431
+ return null;
432
+ } catch {
433
+ return null;
434
+ }
435
+ }
436
+
437
+ async detectCTestFramework() {
438
+ try {
439
+ await execAsync('pkg-config --exists gtest');
440
+ return 'gtest';
441
+ } catch {
442
+ try {
443
+ await execAsync('pkg-config --exists catch2');
444
+ return 'catch2';
445
+ } catch {
446
+ return null;
447
+ }
448
+ }
449
+ }
450
+
451
+ // Test execution implementations
452
+ async runJestSingleFile(file, isTestFile) {
453
+ try {
454
+ const testPattern = isTestFile ? file : this.findTestFile(file);
455
+
456
+ if (!testPattern || !await this.fileExists(testPattern)) {
457
+ return {
458
+ passed: false,
459
+ reason: 'No test file found',
460
+ tests: [],
461
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
462
+ };
463
+ }
464
+
465
+ const result = await execAsync(`npx jest "${path.basename(testPattern)}" --json --coverage=false`, {
466
+ cwd: path.dirname(testPattern)
467
+ });
468
+
469
+ const jestOutput = JSON.parse(result.stdout);
470
+
471
+ return {
472
+ passed: jestOutput.success,
473
+ tests: jestOutput.testResults[0]?.assertionResults || [],
474
+ summary: {
475
+ total: jestOutput.numTotalTests,
476
+ passed: jestOutput.numPassedTests,
477
+ failed: jestOutput.numFailedTests,
478
+ skipped: jestOutput.numPendingTests
479
+ },
480
+ duration: jestOutput.testResults[0]?.endTime - jestOutput.testResults[0]?.startTime
481
+ };
482
+
483
+ } catch (error) {
484
+ return {
485
+ passed: false,
486
+ error: error.message,
487
+ tests: [],
488
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
489
+ };
490
+ }
491
+ }
492
+
493
+ async runMochaSingleFile(file, isTestFile) {
494
+ try {
495
+ const testFile = isTestFile ? file : this.findTestFile(file);
496
+
497
+ if (!testFile || !await this.fileExists(testFile)) {
498
+ return {
499
+ passed: false,
500
+ reason: 'No test file found',
501
+ tests: [],
502
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
503
+ };
504
+ }
505
+
506
+ const result = await execAsync(`npx mocha "${testFile}" --reporter json`);
507
+ const mochaOutput = JSON.parse(result.stdout);
508
+
509
+ return {
510
+ passed: mochaOutput.failures === 0,
511
+ tests: mochaOutput.tests || [],
512
+ summary: {
513
+ total: mochaOutput.tests.length,
514
+ passed: mochaOutput.passes,
515
+ failed: mochaOutput.failures,
516
+ skipped: mochaOutput.pending
517
+ }
518
+ };
519
+
520
+ } catch (error) {
521
+ return {
522
+ passed: false,
523
+ error: error.message,
524
+ tests: [],
525
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
526
+ };
527
+ }
528
+ }
529
+
530
+ async runPytestSingleFile(file, isTestFile) {
531
+ try {
532
+ const testFile = isTestFile ? file : this.findTestFile(file);
533
+
534
+ if (!testFile || !await this.fileExists(testFile)) {
535
+ return {
536
+ passed: false,
537
+ reason: 'No test file found',
538
+ tests: [],
539
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
540
+ };
541
+ }
542
+
543
+ const result = await execAsync(`pytest "${testFile}" -v`);
544
+
545
+ // Parse pytest output (simplified)
546
+ return {
547
+ passed: result.code === 0,
548
+ tests: [],
549
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
550
+ };
551
+
552
+ } catch (error) {
553
+ return {
554
+ passed: false,
555
+ error: error.message,
556
+ tests: [],
557
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
558
+ };
559
+ }
560
+ }
561
+
562
+ async runUnittestSingleFile(file, isTestFile) {
563
+ try {
564
+ const testFile = isTestFile ? file : this.findTestFile(file);
565
+
566
+ if (!testFile || !await this.fileExists(testFile)) {
567
+ return {
568
+ passed: false,
569
+ reason: 'No test file found',
570
+ tests: [],
571
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
572
+ };
573
+ }
574
+
575
+ const result = await execAsync(`python -m unittest "${testFile}" -v`);
576
+
577
+ return {
578
+ passed: result.code === 0,
579
+ tests: [],
580
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
581
+ };
582
+
583
+ } catch (error) {
584
+ return {
585
+ passed: false,
586
+ error: error.message,
587
+ tests: [],
588
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
589
+ };
590
+ }
591
+ }
592
+
593
+ async runGoTestSingleFile(file) {
594
+ try {
595
+ const result = await execAsync(`go test "${file}" -json`);
596
+
597
+ const lines = result.stdout.trim().split('\n');
598
+ const tests = [];
599
+ let passed = 0, failed = 0, skipped = 0;
600
+
601
+ for (const line of lines) {
602
+ try {
603
+ const testResult = JSON.parse(line);
604
+ if (testResult.Action === 'pass' || testResult.Action === 'fail' || testResult.Action === 'skip') {
605
+ tests.push(testResult);
606
+ if (testResult.Action === 'pass') passed++;
607
+ else if (testResult.Action === 'fail') failed++;
608
+ else if (testResult.Action === 'skip') skipped++;
609
+ }
610
+ } catch {
611
+ continue;
612
+ }
613
+ }
614
+
615
+ return {
616
+ passed: failed === 0,
617
+ tests,
618
+ summary: {
619
+ total: passed + failed + skipped,
620
+ passed,
621
+ failed,
622
+ skipped
623
+ }
624
+ };
625
+
626
+ } catch (error) {
627
+ return {
628
+ passed: false,
629
+ error: error.message,
630
+ tests: [],
631
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
632
+ };
633
+ }
634
+ }
635
+
636
+ async runCargoTestSingleFile(file) {
637
+ try {
638
+ const result = await execAsync(`cargo test --message-format=json`, {
639
+ cwd: path.dirname(file)
640
+ });
641
+
642
+ const lines = result.stdout.trim().split('\n');
643
+ const tests = [];
644
+ let passed = 0, failed = 0;
645
+
646
+ for (const line of lines) {
647
+ try {
648
+ const testResult = JSON.parse(line);
649
+ if (testResult.type === 'test') {
650
+ tests.push(testResult);
651
+ if (testResult.event === 'ok') passed++;
652
+ else if (testResult.event === 'failed') failed++;
653
+ }
654
+ } catch {
655
+ continue;
656
+ }
657
+ }
658
+
659
+ return {
660
+ passed: failed === 0,
661
+ tests,
662
+ summary: {
663
+ total: passed + failed,
664
+ passed,
665
+ failed,
666
+ skipped: 0
667
+ }
668
+ };
669
+
670
+ } catch (error) {
671
+ return {
672
+ passed: false,
673
+ error: error.message,
674
+ tests: [],
675
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
676
+ };
677
+ }
678
+ }
679
+
680
+ async runJavaTestSingleFile(file, framework) {
681
+ // Simplified - would need actual implementation
682
+ return {
683
+ passed: false,
684
+ reason: 'Java test execution not fully implemented',
685
+ tests: [],
686
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
687
+ };
688
+ }
689
+
690
+ async runCTestSingleFile(file, framework) {
691
+ // Simplified - would need actual implementation
692
+ return {
693
+ passed: false,
694
+ reason: 'C/C++ test execution not fully implemented',
695
+ tests: [],
696
+ summary: { total: 0, passed: 0, failed: 0, skipped: 0 }
697
+ };
698
+ }
699
+
700
+ // Coverage analysis
701
+ async getJestCoverage(file) {
702
+ try {
703
+ await execAsync(`npx jest "${file}" --coverage --coverageReporters=json --silent`);
704
+
705
+ const coveragePath = path.join(process.cwd(), 'coverage', 'coverage-final.json');
706
+ const coverageData = JSON.parse(await fs.promises.readFile(coveragePath, 'utf8'));
707
+
708
+ const fileCoverage = coverageData[path.resolve(file)] || {};
709
+
710
+ return {
711
+ lines: {
712
+ total: Object.keys(fileCoverage.s || {}).length,
713
+ covered: Object.values(fileCoverage.s || {}).filter(v => v > 0).length,
714
+ percentage: this.calculatePercentage(fileCoverage.s)
715
+ },
716
+ functions: {
717
+ total: Object.keys(fileCoverage.f || {}).length,
718
+ covered: Object.values(fileCoverage.f || {}).filter(v => v > 0).length,
719
+ percentage: this.calculatePercentage(fileCoverage.f)
720
+ },
721
+ branches: {
722
+ total: Object.keys(fileCoverage.b || {}).length,
723
+ covered: Object.values(fileCoverage.b || {}).flat().filter(v => v > 0).length,
724
+ percentage: this.calculatePercentage(fileCoverage.b, true)
725
+ },
726
+ statements: {
727
+ total: Object.keys(fileCoverage.s || {}).length,
728
+ covered: Object.values(fileCoverage.s || {}).filter(v => v > 0).length,
729
+ percentage: this.calculatePercentage(fileCoverage.s)
730
+ }
731
+ };
732
+
733
+ } catch (error) {
734
+ return {
735
+ error: error.message,
736
+ available: false
737
+ };
738
+ }
739
+ }
740
+
741
+ async getPytestCoverage(file) {
742
+ try {
743
+ const result = await execAsync(`pytest "${file}" --cov="${path.dirname(file)}" --cov-report=json:/tmp/coverage.json`);
744
+
745
+ const coverageData = JSON.parse(await fs.promises.readFile('/tmp/coverage.json', 'utf8'));
746
+ const fileCoverage = coverageData.files[path.resolve(file)] || {};
747
+
748
+ return {
749
+ lines: {
750
+ total: fileCoverage.summary?.num_statements || 0,
751
+ covered: fileCoverage.summary?.covered_lines || 0,
752
+ percentage: fileCoverage.summary?.percent_covered || 0
753
+ },
754
+ missing: fileCoverage.missing_lines || [],
755
+ executed: fileCoverage.executed_lines || []
756
+ };
757
+
758
+ } catch (error) {
759
+ return {
760
+ error: error.message,
761
+ available: false
762
+ };
763
+ }
764
+ }
765
+
766
+ async getRustCoverage(file) {
767
+ try {
768
+ // Try to check if cargo-tarpaulin is available
769
+ try {
770
+ await execAsync('cargo tarpaulin --version');
771
+ } catch {
772
+ return {
773
+ error: 'cargo-tarpaulin not installed',
774
+ available: false,
775
+ suggestion: 'Install with: cargo install cargo-tarpaulin'
776
+ };
777
+ }
778
+
779
+ const projectDir = path.dirname(file);
780
+ let rootDir = projectDir;
781
+
782
+ // Find Cargo.toml root
783
+ while (rootDir !== path.dirname(rootDir)) {
784
+ if (fsSync.existsSync(path.join(rootDir, 'Cargo.toml'))) {
785
+ break;
786
+ }
787
+ rootDir = path.dirname(rootDir);
788
+ }
789
+
790
+ const result = await execAsync(`cargo tarpaulin --out Json --output-dir /tmp`, {
791
+ cwd: rootDir
792
+ });
793
+
794
+ const coverageData = JSON.parse(await fs.promises.readFile('/tmp/tarpaulin-report.json', 'utf8'));
795
+
796
+ return {
797
+ lines: {
798
+ total: coverageData.files[file]?.total_lines || 0,
799
+ covered: coverageData.files[file]?.covered_lines || 0,
800
+ percentage: coverageData.files[file]?.coverage || 0
801
+ },
802
+ overall: {
803
+ percentage: coverageData.coverage || 0
804
+ }
805
+ };
806
+
807
+ } catch (error) {
808
+ return {
809
+ error: error.message,
810
+ available: false
811
+ };
812
+ }
813
+ }
814
+
815
+ async getGoCoverage(file) {
816
+ try {
817
+ const result = await execAsync(`go test -coverprofile=/tmp/coverage.out "${file}"`);
818
+
819
+ const coverageOutput = await fs.promises.readFile('/tmp/coverage.out', 'utf8');
820
+ const lines = coverageOutput.split('\n').filter(line => line.includes(file));
821
+
822
+ let totalStatements = 0;
823
+ let coveredStatements = 0;
824
+
825
+ lines.forEach(line => {
826
+ const match = line.match(/(\d+)\s+(\d+)\s+(\d+)/);
827
+ if (match) {
828
+ const count = parseInt(match[3]);
829
+ totalStatements++;
830
+ if (count > 0) coveredStatements++;
831
+ }
832
+ });
833
+
834
+ const percentage = totalStatements > 0 ? Math.round((coveredStatements / totalStatements) * 100) : 0;
835
+
836
+ return {
837
+ lines: {
838
+ total: totalStatements,
839
+ covered: coveredStatements,
840
+ percentage
841
+ }
842
+ };
843
+
844
+ } catch (error) {
845
+ return {
846
+ error: error.message,
847
+ available: false
848
+ };
849
+ }
850
+ }
851
+
852
+ // TDD compliance checking
853
+ checkTDDCompliance(sourceFile, testFile, testResults) {
854
+ const compliance = {
855
+ hasTests: false,
856
+ testFirst: false,
857
+ redGreenRefactor: false,
858
+ coverage: 0,
859
+ testsPassed: 0,
860
+ testsFailed: 0,
861
+ recommendations: []
862
+ };
863
+
864
+ // Check if tests exist
865
+ if (testFile && this.fileExistsSync(testFile)) {
866
+ compliance.hasTests = true;
867
+ } else {
868
+ compliance.recommendations.push({
869
+ type: 'tdd_violation',
870
+ priority: 'high',
871
+ message: 'No test file found - TDD requires tests first',
872
+ action: `Create test file: ${this.suggestTestFileName(sourceFile)}`
873
+ });
874
+ }
875
+
876
+ // Check test results
877
+ if (testResults && testResults.summary) {
878
+ const { total, passed, failed } = testResults.summary;
879
+
880
+ compliance.testsPassed = passed;
881
+ compliance.testsFailed = failed;
882
+
883
+ if (total === 0) {
884
+ compliance.recommendations.push({
885
+ type: 'tdd_violation',
886
+ priority: 'high',
887
+ message: 'No tests found in test file',
888
+ action: 'Write tests before implementing functionality'
889
+ });
890
+ } else if (failed > 0) {
891
+ compliance.redGreenRefactor = true;
892
+ compliance.recommendations.push({
893
+ type: 'tdd_red_phase',
894
+ priority: 'medium',
895
+ message: `${failed} failing tests - in RED phase of TDD`,
896
+ action: 'Implement minimal code to make tests pass'
897
+ });
898
+ } else if (passed > 0) {
899
+ compliance.redGreenRefactor = true;
900
+ compliance.recommendations.push({
901
+ type: 'tdd_green_phase',
902
+ priority: 'low',
903
+ message: 'All tests passing - in GREEN phase of TDD',
904
+ action: 'Consider refactoring for better design'
905
+ });
906
+ }
907
+ }
908
+
909
+ return compliance;
910
+ }
911
+
912
+ // Utility methods
913
+ isTestFile(file) {
914
+ const fileName = path.basename(file);
915
+ return fileName.includes('.test.') ||
916
+ fileName.includes('.spec.') ||
917
+ fileName.includes('_test') ||
918
+ fileName.endsWith('Test.java') ||
919
+ fileName.endsWith('Test.cpp') ||
920
+ file.includes('/test/') ||
921
+ file.includes('/tests/');
922
+ }
923
+
924
+ findTestFile(sourceFile) {
925
+ const ext = path.extname(sourceFile);
926
+ const base = path.basename(sourceFile, ext);
927
+ const dir = path.dirname(sourceFile);
928
+
929
+ const testPatterns = [
930
+ `${base}.test${ext}`,
931
+ `${base}.spec${ext}`,
932
+ `${base}_test${ext}`,
933
+ `test_${base}${ext}`,
934
+ `${base}Test${ext}`
935
+ ];
936
+
937
+ for (const pattern of testPatterns) {
938
+ const testPath = path.join(dir, pattern);
939
+ if (this.fileExistsSync(testPath)) return testPath;
940
+ }
941
+
942
+ const testDirs = ['test', 'tests', '__tests__', 'spec'];
943
+ for (const testDir of testDirs) {
944
+ for (const pattern of testPatterns) {
945
+ const testPath = path.join(dir, testDir, pattern);
946
+ if (this.fileExistsSync(testPath)) return testPath;
947
+ }
948
+ }
949
+
950
+ return null;
951
+ }
952
+
953
+ findSourceFile(testFile) {
954
+ const ext = path.extname(testFile);
955
+ let base = path.basename(testFile, ext);
956
+
957
+ base = base.replace(/\.(test|spec)$/, '')
958
+ .replace(/_test$/, '')
959
+ .replace(/^test_/, '')
960
+ .replace(/Test$/, '');
961
+
962
+ const dir = path.dirname(testFile);
963
+ const sourcePatterns = [`${base}${ext}`];
964
+
965
+ const parentDir = path.dirname(dir);
966
+ for (const pattern of sourcePatterns) {
967
+ const sourcePath = path.join(parentDir, pattern);
968
+ if (this.fileExistsSync(sourcePath)) return sourcePath;
969
+ }
970
+
971
+ for (const pattern of sourcePatterns) {
972
+ const sourcePath = path.join(dir, pattern);
973
+ if (this.fileExistsSync(sourcePath)) return sourcePath;
974
+ }
975
+
976
+ return null;
977
+ }
978
+
979
+ suggestTestFileName(sourceFile) {
980
+ const ext = path.extname(sourceFile);
981
+ const base = path.basename(sourceFile, ext);
982
+ const dir = path.dirname(sourceFile);
983
+
984
+ if (['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {
985
+ return path.join(dir, `${base}.test${ext}`);
986
+ } else if (ext === '.py') {
987
+ return path.join(dir, `test_${base}${ext}`);
988
+ } else if (ext === '.go') {
989
+ return path.join(dir, `${base}_test${ext}`);
990
+ } else if (ext === '.java') {
991
+ return path.join(dir, `${base}Test${ext}`);
992
+ } else {
993
+ return path.join(dir, `${base}_test${ext}`);
994
+ }
995
+ }
996
+
997
+ calculatePercentage(coverage, isBranch = false) {
998
+ if (!coverage) return 0;
999
+
1000
+ const values = isBranch ? Object.values(coverage).flat() : Object.values(coverage);
1001
+ const total = values.length;
1002
+ const covered = values.filter(v => v > 0).length;
1003
+
1004
+ return total > 0 ? Math.round((covered / total) * 100) : 0;
1005
+ }
1006
+
1007
+ fileExistsSync(filePath) {
1008
+ try {
1009
+ fsSync.accessSync(filePath, fsSync.constants.F_OK);
1010
+ return true;
1011
+ } catch {
1012
+ return false;
1013
+ }
1014
+ }
1015
+
1016
+ async fileExists(filePath) {
1017
+ try {
1018
+ await fs.promises.access(filePath, fs.constants.F_OK);
1019
+ return true;
1020
+ } catch {
1021
+ return false;
1022
+ }
1023
+ }
1024
+ }
1025
+
1026
+ // Rust-specific quality enforcement with enhanced validation
1027
+ class RustQualityEnforcer {
1028
+ constructor(options = {}) {
1029
+ this.config = {
1030
+ allowUnwrap: options.allowUnwrap !== undefined ? options.allowUnwrap : false,
1031
+ allowExpect: options.allowExpect !== undefined ? options.allowExpect : true,
1032
+ allowPanic: options.allowPanic !== undefined ? options.allowPanic : false,
1033
+ allowTodo: options.allowTodo !== undefined ? options.allowTodo : false,
1034
+ allowUnimplemented: options.allowUnimplemented !== undefined ? options.allowUnimplemented : false
1035
+ };
1036
+ }
1037
+
1038
+ async analyzeFile(filePath, content) {
1039
+ const issues = [];
1040
+ const lines = content.split('\n');
1041
+
1042
+ // Regex patterns that skip comments
1043
+ const unwrapPattern = /(?<!\/\/.*)\.unwrap\(\)/;
1044
+ const expectPattern = /(?<!\/\/.*)\.expect\(/;
1045
+ const panicPattern = /(?<!\/\/)panic!\(/;
1046
+ const todoPattern = /(?<!\/\/)todo!\(/;
1047
+ const unimplementedPattern = /(?<!\/\/)unimplemented!\(/;
1048
+
1049
+ lines.forEach((line, index) => {
1050
+ // Remove comments from the line for accurate analysis
1051
+ const cleanedLine = line.replace(/\/\/.*$/, '').replace(/\/\*[\s\S]*?\*\//, '');
1052
+
1053
+ if (unwrapPattern.test(cleanedLine)) {
1054
+ if (!this.config.allowUnwrap) {
1055
+ issues.push({
1056
+ type: 'rust_unwrap',
1057
+ severity: 'critical',
1058
+ priority: 'high',
1059
+ message: 'Use of .unwrap() in production code - may panic',
1060
+ line: index + 1,
1061
+ code: line.trim(),
1062
+ suggestion: 'Use match, if let, or ? operator instead',
1063
+ action: 'Replace .unwrap() with proper error handling'
1064
+ });
1065
+ }
1066
+ }
1067
+
1068
+ if (expectPattern.test(cleanedLine)) {
1069
+ if (!this.config.allowExpect) {
1070
+ issues.push({
1071
+ type: 'rust_expect',
1072
+ severity: 'warning',
1073
+ priority: 'medium',
1074
+ message: 'Use of .expect() may panic at runtime',
1075
+ line: index + 1,
1076
+ code: line.trim(),
1077
+ suggestion: 'Consider propagating errors with ?',
1078
+ action: 'Replace .expect() with proper error handling'
1079
+ });
1080
+ }
1081
+ }
1082
+
1083
+ if (panicPattern.test(cleanedLine)) {
1084
+ if (!this.config.allowPanic) {
1085
+ issues.push({
1086
+ type: 'rust_panic',
1087
+ severity: 'critical',
1088
+ priority: 'high',
1089
+ message: 'panic!() will crash the program',
1090
+ line: index + 1,
1091
+ code: line.trim(),
1092
+ suggestion: 'Return Result<T, E> and handle errors properly',
1093
+ action: 'Replace panic!() with error propagation'
1094
+ });
1095
+ }
1096
+ }
1097
+
1098
+ if (todoPattern.test(cleanedLine)) {
1099
+ if (!this.config.allowTodo) {
1100
+ issues.push({
1101
+ type: 'rust_todo',
1102
+ severity: 'error',
1103
+ priority: 'high',
1104
+ message: 'todo!() detected - incomplete code',
1105
+ line: index + 1,
1106
+ code: line.trim(),
1107
+ suggestion: 'Implement the missing functionality',
1108
+ action: 'Complete the implementation'
1109
+ });
1110
+ }
1111
+ }
1112
+
1113
+ if (unimplementedPattern.test(cleanedLine)) {
1114
+ if (!this.config.allowUnimplemented) {
1115
+ issues.push({
1116
+ type: 'rust_unimplemented',
1117
+ severity: 'error',
1118
+ priority: 'high',
1119
+ message: 'unimplemented!() detected - incomplete code',
1120
+ line: index + 1,
1121
+ code: line.trim(),
1122
+ suggestion: 'Implement the missing functionality',
1123
+ action: 'Complete the implementation'
1124
+ });
1125
+ }
1126
+ }
1127
+ });
1128
+
1129
+ return {
1130
+ passed: issues.filter(i => i.severity === 'error' || i.severity === 'critical').length === 0,
1131
+ issues,
1132
+ suggestions: issues.map(i => i.suggestion).filter((v, i, a) => a.indexOf(v) === i),
1133
+ coverage: 'advanced',
1134
+ summary: {
1135
+ unwrap: issues.filter(i => i.type === 'rust_unwrap').length,
1136
+ expect: issues.filter(i => i.type === 'rust_expect').length,
1137
+ panic: issues.filter(i => i.type === 'rust_panic').length,
1138
+ todo: issues.filter(i => i.type === 'rust_todo').length,
1139
+ unimplemented: issues.filter(i => i.type === 'rust_unimplemented').length
1140
+ }
1141
+ };
1142
+ }
1143
+ }
1144
+
1145
+ // Main unified pipeline
1146
+ class UnifiedPostEditPipeline {
1147
+ constructor(options = {}) {
1148
+ this.tddMode = options.tddMode || false;
1149
+ this.minimumCoverage = options.minimumCoverage || 80;
1150
+ this.blockOnTDDViolations = options.blockOnTDDViolations || false;
1151
+ this.rustStrict = options.rustStrict || false;
1152
+ this.config = this.loadConfig();
1153
+ this.testEngine = new SingleFileTestEngine();
1154
+ this.rustEnforcer = new RustQualityEnforcer({
1155
+ allowUnwrap: !this.rustStrict,
1156
+ allowExpect: !this.rustStrict, // In strict mode, also warn about .expect()
1157
+ allowPanic: !this.rustStrict,
1158
+ allowTodo: false,
1159
+ allowUnimplemented: false
1160
+ });
1161
+
1162
+ this.languageDetectors = {
1163
+ '.js': 'javascript',
1164
+ '.jsx': 'javascript',
1165
+ '.ts': 'typescript',
1166
+ '.tsx': 'typescript',
1167
+ '.py': 'python',
1168
+ '.rs': 'rust',
1169
+ '.go': 'go',
1170
+ '.java': 'java',
1171
+ '.cpp': 'cpp',
1172
+ '.c': 'c',
1173
+ '.php': 'php',
1174
+ '.rb': 'ruby',
1175
+ '.cs': 'csharp',
1176
+ '.json': 'json',
1177
+ '.yaml': 'yaml',
1178
+ '.yml': 'yaml',
1179
+ '.toml': 'toml',
1180
+ '.md': 'markdown',
1181
+ };
1182
+ }
1183
+
1184
+ loadConfig() {
1185
+ const configPath = path.join(process.cwd(), 'config', 'hooks', 'pipeline-config.json');
1186
+ try {
1187
+ if (fs.existsSync(configPath)) {
1188
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
1189
+ }
1190
+ } catch (error) {
1191
+ console.warn('Using default pipeline configuration');
1192
+ }
1193
+
1194
+ return {
1195
+ formatters: {
1196
+ javascript: ['prettier', '--write'],
1197
+ typescript: ['prettier', '--write'],
1198
+ python: ['black', '--quiet'],
1199
+ rust: ['rustfmt'],
1200
+ go: ['gofmt', '-w'],
1201
+ json: ['prettier', '--write'],
1202
+ yaml: ['prettier', '--write'],
1203
+ markdown: ['prettier', '--write']
1204
+ },
1205
+ linters: {
1206
+ javascript: ['eslint', '--fix'],
1207
+ typescript: ['eslint', '--fix'],
1208
+ python: ['flake8'],
1209
+ rust: ['clippy'],
1210
+ go: ['golint']
1211
+ },
1212
+ typeCheckers: {
1213
+ typescript: ['tsc', '--noEmit'],
1214
+ python: ['mypy'],
1215
+ rust: ['cargo', 'check'],
1216
+ go: ['go', 'vet']
1217
+ }
1218
+ };
1219
+ }
1220
+
1221
+ detectLanguage(filePath) {
1222
+ const ext = path.extname(filePath).toLowerCase();
1223
+ return this.languageDetectors[ext] || 'unknown';
1224
+ }
1225
+
1226
+ async runCommand(command, args, cwd = process.cwd(), options = {}) {
1227
+ const {
1228
+ timeout = 30000, // 30 second default timeout
1229
+ maxBufferSize = 1024 * 1024, // 1MB max buffer size
1230
+ killOnTimeout = true,
1231
+ killOnOversize = true
1232
+ } = options;
1233
+
1234
+ return new Promise((resolve, reject) => {
1235
+ let stdout = '';
1236
+ let stderr = '';
1237
+ let killed = false;
1238
+ let timeoutId;
1239
+
1240
+ const proc = spawn(command, args, {
1241
+ cwd,
1242
+ stdio: ['ignore', 'pipe', 'pipe'],
1243
+ detached: false
1244
+ });
1245
+
1246
+ // Set up timeout
1247
+ if (timeout > 0) {
1248
+ timeoutId = setTimeout(() => {
1249
+ if (!killed) {
1250
+ killed = true;
1251
+ console.warn(`āš ļø Process timeout: ${command} ${args.join(' ')} (${timeout}ms)`);
1252
+
1253
+ if (killOnTimeout) {
1254
+ try {
1255
+ proc.kill('SIGTERM');
1256
+ setTimeout(() => {
1257
+ try {
1258
+ proc.kill('SIGKILL');
1259
+ } catch (e) {
1260
+ // Process already dead
1261
+ }
1262
+ }, 5000);
1263
+ } catch (e) {
1264
+ // Process already dead
1265
+ }
1266
+ }
1267
+
1268
+ resolve({
1269
+ code: 124, // timeout exit code
1270
+ stdout,
1271
+ stderr,
1272
+ killed: true,
1273
+ reason: 'timeout'
1274
+ });
1275
+ }
1276
+ }, timeout);
1277
+ }
1278
+
1279
+ // Handle stdout with size limits
1280
+ proc.stdout.on('data', (data) => {
1281
+ if (!killed) {
1282
+ const chunk = data.toString();
1283
+
1284
+ // Check buffer size limit
1285
+ if (stdout.length + chunk.length > maxBufferSize) {
1286
+ if (killOnOversize) {
1287
+ killed = true;
1288
+ console.warn(`āš ļø Process output too large: ${command} ${args.join(' ')} (${stdout.length + chunk.length} > ${maxBufferSize} bytes)`);
1289
+
1290
+ try {
1291
+ proc.kill('SIGKILL');
1292
+ } catch (e) {
1293
+ // Process already dead
1294
+ }
1295
+
1296
+ resolve({
1297
+ code: 125, // output too large exit code
1298
+ stdout,
1299
+ stderr,
1300
+ killed: true,
1301
+ reason: 'oversize'
1302
+ });
1303
+ } else {
1304
+ // Truncate output
1305
+ stdout = stdout.substring(0, maxBufferSize - chunk.length) + chunk;
1306
+ }
1307
+ } else {
1308
+ stdout += chunk;
1309
+ }
1310
+ }
1311
+ });
1312
+
1313
+ // Handle stderr with size limits
1314
+ proc.stderr.on('data', (data) => {
1315
+ if (!killed) {
1316
+ const chunk = data.toString();
1317
+
1318
+ // Check buffer size limit
1319
+ if (stderr.length + chunk.length > maxBufferSize) {
1320
+ if (killOnOversize) {
1321
+ killed = true;
1322
+ console.warn(`āš ļø Process error output too large: ${command} ${args.join(' ')} (${stderr.length + chunk.length} > ${maxBufferSize} bytes)`);
1323
+
1324
+ try {
1325
+ proc.kill('SIGKILL');
1326
+ } catch (e) {
1327
+ // Process already dead
1328
+ }
1329
+
1330
+ resolve({
1331
+ code: 125, // output too large exit code
1332
+ stdout,
1333
+ stderr,
1334
+ killed: true,
1335
+ reason: 'oversize'
1336
+ });
1337
+ } else {
1338
+ // Truncate output
1339
+ stderr = stderr.substring(0, maxBufferSize - chunk.length) + chunk;
1340
+ }
1341
+ } else {
1342
+ stderr += chunk;
1343
+ }
1344
+ }
1345
+ });
1346
+
1347
+ // Handle process completion
1348
+ proc.on('close', (code) => {
1349
+ if (!killed) {
1350
+ if (timeoutId) {
1351
+ clearTimeout(timeoutId);
1352
+ }
1353
+ resolve({ code, stdout, stderr, killed: false });
1354
+ }
1355
+ });
1356
+
1357
+ // Handle process errors
1358
+ proc.on('error', (error) => {
1359
+ if (!killed) {
1360
+ if (timeoutId) {
1361
+ clearTimeout(timeoutId);
1362
+ }
1363
+ resolve({ code: 1, stdout: '', stderr: error.message, killed: false });
1364
+ }
1365
+ });
1366
+
1367
+ // Handle process exit (additional safety)
1368
+ proc.on('exit', (code, signal) => {
1369
+ if (!killed) {
1370
+ if (timeoutId) {
1371
+ clearTimeout(timeoutId);
1372
+ }
1373
+ // Process already handled by 'close' event
1374
+ }
1375
+ });
1376
+ });
1377
+ }
1378
+
1379
+ async checkToolAvailable(tool) {
1380
+ try {
1381
+ const { code } = await this.runCommand('which', [tool]);
1382
+ return code === 0;
1383
+ } catch {
1384
+ return false;
1385
+ }
1386
+ }
1387
+
1388
+ async formatFile(filePath, language) {
1389
+ const formatters = this.config.formatters[language];
1390
+ if (!formatters) return { success: true, message: 'No formatter configured' };
1391
+
1392
+ const [tool, ...args] = formatters;
1393
+ if (!(await this.checkToolAvailable(tool))) {
1394
+ return { success: false, message: `Formatter ${tool} not available` };
1395
+ }
1396
+
1397
+ // Format files with shorter timeout and smaller buffer
1398
+ const result = await this.runCommand(tool, [...args, filePath], undefined, {
1399
+ timeout: 10000, // 10 second timeout for formatters
1400
+ maxBufferSize: 512 * 1024 // 512KB buffer for formatters
1401
+ });
1402
+
1403
+ return {
1404
+ success: result.code === 0 && !result.killed,
1405
+ message: result.killed
1406
+ ? `Formatting ${result.reason === 'timeout' ? 'timed out' : 'output too large'}`
1407
+ : (result.code === 0 ? 'Formatted successfully' : result.stderr),
1408
+ output: result.stdout,
1409
+ killed: result.killed,
1410
+ reason: result.reason
1411
+ };
1412
+ }
1413
+
1414
+ async lintFile(filePath, language) {
1415
+ const linters = this.config.linters[language];
1416
+ if (!linters) return { success: true, message: 'No linter configured' };
1417
+
1418
+ const [tool, ...args] = linters;
1419
+ if (!(await this.checkToolAvailable(tool))) {
1420
+ return { success: false, message: `Linter ${tool} not available` };
1421
+ }
1422
+
1423
+ // Lint files with moderate timeout and buffer
1424
+ const result = await this.runCommand(tool, [...args, filePath], undefined, {
1425
+ timeout: 15000, // 15 second timeout for linters
1426
+ maxBufferSize: 256 * 1024 // 256KB buffer for linters
1427
+ });
1428
+
1429
+ return {
1430
+ success: result.code === 0 && !result.killed,
1431
+ message: result.killed
1432
+ ? `Linting ${result.reason === 'timeout' ? 'timed out' : 'output too large'}`
1433
+ : (result.code === 0 ? 'Linting passed' : 'Linting issues found'),
1434
+ output: result.stdout + result.stderr,
1435
+ issues: result.code !== 0 ? result.stderr : '',
1436
+ killed: result.killed,
1437
+ reason: result.reason
1438
+ };
1439
+ }
1440
+
1441
+ async typeCheck(filePath, language) {
1442
+ const typeCheckers = this.config.typeCheckers[language];
1443
+ if (!typeCheckers) return { success: true, message: 'No type checker configured' };
1444
+
1445
+ const [tool, ...args] = typeCheckers;
1446
+ if (!(await this.checkToolAvailable(tool))) {
1447
+ return { success: false, message: `Type checker ${tool} not available` };
1448
+ }
1449
+
1450
+ const projectDir = this.findProjectRoot(filePath);
1451
+
1452
+ // Type checking with longer timeout but smaller buffer (type errors can be verbose)
1453
+ const result = await this.runCommand(tool, args, { cwd: projectDir }, {
1454
+ timeout: 60000, // 60 second timeout for type checkers (they can be slow)
1455
+ maxBufferSize: 512 * 1024 // 512KB buffer for type checkers
1456
+ });
1457
+
1458
+ return {
1459
+ success: result.code === 0 && !result.killed,
1460
+ message: result.killed
1461
+ ? `Type checking ${result.reason === 'timeout' ? 'timed out' : 'output too large'}`
1462
+ : (result.code === 0 ? 'Type checking passed' : 'Type errors found'),
1463
+ output: result.stdout + result.stderr,
1464
+ errors: result.code !== 0 ? result.stderr : '',
1465
+ killed: result.killed,
1466
+ reason: result.reason
1467
+ };
1468
+ }
1469
+
1470
+ findProjectRoot(filePath) {
1471
+ const markers = ['package.json', 'Cargo.toml', 'go.mod', 'pyproject.toml', 'setup.py'];
1472
+ let dir = path.dirname(filePath);
1473
+
1474
+ while (dir !== path.dirname(dir)) {
1475
+ if (markers.some(marker => fs.existsSync(path.join(dir, marker)))) {
1476
+ return dir;
1477
+ }
1478
+ dir = path.dirname(dir);
1479
+ }
1480
+
1481
+ return process.cwd();
1482
+ }
1483
+
1484
+ extractAgentContext(options = {}) {
1485
+ const context = {
1486
+ memoryKey: options.memoryKey || process.env.MEMORY_KEY || null,
1487
+ agentType: options.agentType || process.env.AGENT_TYPE || null,
1488
+ agentName: options.agentName || process.env.AGENT_NAME || null,
1489
+ swarmId: options.swarmId || process.env.SWARM_ID || null,
1490
+ taskId: options.taskId || process.env.TASK_ID || null,
1491
+ sessionId: options.sessionId || process.env.SESSION_ID || null
1492
+ };
1493
+
1494
+ if (context.memoryKey && !context.agentType) {
1495
+ const keyParts = context.memoryKey.split('/');
1496
+ if (keyParts.length >= 2) {
1497
+ context.agentType = keyParts[1];
1498
+ }
1499
+ if (keyParts.length >= 3) {
1500
+ context.taskStep = keyParts[2];
1501
+ }
1502
+ }
1503
+
1504
+ return context;
1505
+ }
1506
+
1507
+ formatTimestamp(isoTimestamp) {
1508
+ const date = new Date(isoTimestamp);
1509
+ const month = String(date.getMonth() + 1).padStart(2, '0');
1510
+ const day = String(date.getDate()).padStart(2, '0');
1511
+ const year = date.getFullYear();
1512
+ const hours = String(date.getHours()).padStart(2, '0');
1513
+ const minutes = String(date.getMinutes()).padStart(2, '0');
1514
+
1515
+ return `${month}/${day}/${year} ${hours}:${minutes}`;
1516
+ }
1517
+
1518
+ async logToRootFile(results) {
1519
+ const logPath = path.join(process.cwd(), 'post-edit-pipeline.log');
1520
+ const MAX_ENTRIES = 500;
1521
+
1522
+ const logEntry = {
1523
+ timestamp: results.timestamp,
1524
+ displayTimestamp: this.formatTimestamp(results.timestamp),
1525
+ file: results.file,
1526
+ editId: results.editId || 'N/A',
1527
+ language: results.language,
1528
+ agent: results.agentContext,
1529
+ status: results.summary.success ? 'PASSED' : (results.blocking ? 'BLOCKED' : 'FAILED'),
1530
+ tddMode: this.tddMode,
1531
+ tddPhase: results.tddPhase || 'N/A',
1532
+ errors: results.summary.errors.length,
1533
+ warnings: results.summary.warnings.length,
1534
+ steps: results.steps || {},
1535
+ testing: results.testing || {},
1536
+ coverage: results.coverage || {},
1537
+ tddCompliance: results.tddCompliance || {},
1538
+ rustQuality: results.rustQuality || {},
1539
+ recommendations: results.recommendations || [],
1540
+ details: {
1541
+ errors: results.summary.errors,
1542
+ warnings: results.summary.warnings,
1543
+ suggestions: results.summary.suggestions
1544
+ }
1545
+ };
1546
+
1547
+ const logText = [
1548
+ '═'.repeat(80),
1549
+ `TIMESTAMP: ${logEntry.displayTimestamp}`,
1550
+ `FILE: ${logEntry.file}`,
1551
+ `EDIT ID: ${logEntry.editId}`,
1552
+ `LANGUAGE: ${logEntry.language}`,
1553
+ `STATUS: ${logEntry.status}`,
1554
+ `TDD MODE: ${logEntry.tddMode ? 'ENABLED' : 'DISABLED'}`,
1555
+ `TDD PHASE: ${logEntry.tddPhase}`,
1556
+ '',
1557
+ 'AGENT CONTEXT:',
1558
+ ` Memory Key: ${logEntry.agent.memoryKey || 'N/A'}`,
1559
+ ` Agent Type: ${logEntry.agent.agentType || 'N/A'}`,
1560
+ '',
1561
+ 'JSON:',
1562
+ JSON.stringify(logEntry, null, 2),
1563
+ '═'.repeat(80),
1564
+ '',
1565
+ ''
1566
+ ].join('\n');
1567
+
1568
+ try {
1569
+ let existingEntries = [];
1570
+ if (fs.existsSync(logPath)) {
1571
+ const existingLog = fs.readFileSync(logPath, 'utf8');
1572
+ const entrySections = existingLog.split('═'.repeat(80)).filter(s => s.trim());
1573
+
1574
+ for (const section of entrySections) {
1575
+ const jsonStart = section.indexOf('JSON:');
1576
+ if (jsonStart !== -1) {
1577
+ const jsonText = section.substring(jsonStart + 5).trim();
1578
+ let braceCount = 0;
1579
+ let jsonEnd = 0;
1580
+ let inString = false;
1581
+ let escapeNext = false;
1582
+
1583
+ for (let i = 0; i < jsonText.length; i++) {
1584
+ const char = jsonText[i];
1585
+
1586
+ if (escapeNext) {
1587
+ escapeNext = false;
1588
+ continue;
1589
+ }
1590
+
1591
+ if (char === '\\') {
1592
+ escapeNext = true;
1593
+ continue;
1594
+ }
1595
+
1596
+ if (char === '"') {
1597
+ inString = !inString;
1598
+ continue;
1599
+ }
1600
+
1601
+ if (!inString) {
1602
+ if (char === '{') braceCount++;
1603
+ if (char === '}') {
1604
+ braceCount--;
1605
+ if (braceCount === 0) {
1606
+ jsonEnd = i + 1;
1607
+ break;
1608
+ }
1609
+ }
1610
+ }
1611
+ }
1612
+
1613
+ if (jsonEnd > 0) {
1614
+ try {
1615
+ const entry = JSON.parse(jsonText.substring(0, jsonEnd));
1616
+ existingEntries.push(entry);
1617
+ } catch (e) {
1618
+ console.error(`Failed to parse JSON entry: ${e.message}`);
1619
+ }
1620
+ }
1621
+ }
1622
+ }
1623
+ }
1624
+
1625
+ existingEntries.unshift(logEntry);
1626
+
1627
+ if (existingEntries.length > MAX_ENTRIES) {
1628
+ existingEntries = existingEntries.slice(0, MAX_ENTRIES);
1629
+ console.log(`\nšŸ—‘ļø Trimmed log to ${MAX_ENTRIES} most recent entries`);
1630
+ }
1631
+
1632
+ const rebuiltLog = existingEntries.map(entry => {
1633
+ return [
1634
+ '═'.repeat(80),
1635
+ `TIMESTAMP: ${entry.displayTimestamp}`,
1636
+ `FILE: ${entry.file}`,
1637
+ `EDIT ID: ${entry.editId || 'N/A'}`,
1638
+ `LANGUAGE: ${entry.language}`,
1639
+ `STATUS: ${entry.status}`,
1640
+ `TDD MODE: ${entry.tddMode ? 'ENABLED' : 'DISABLED'}`,
1641
+ `TDD PHASE: ${entry.tddPhase || 'N/A'}`,
1642
+ '',
1643
+ 'AGENT CONTEXT:',
1644
+ ` Memory Key: ${entry.agent?.memoryKey || 'N/A'}`,
1645
+ ` Agent Type: ${entry.agent?.agentType || 'N/A'}`,
1646
+ '',
1647
+ 'JSON:',
1648
+ JSON.stringify(entry, null, 2),
1649
+ '═'.repeat(80),
1650
+ '',
1651
+ ''
1652
+ ].join('\n');
1653
+ }).join('');
1654
+
1655
+ fs.writeFileSync(logPath, rebuiltLog, 'utf8');
1656
+
1657
+ console.log(`\nšŸ“ Logged to: ${logPath} (${existingEntries.length}/${MAX_ENTRIES} entries)`);
1658
+ } catch (error) {
1659
+ console.error(`āš ļø Failed to write log: ${error.message}`);
1660
+ }
1661
+ }
1662
+
1663
+ async run(filePath, options = {}) {
1664
+ const language = this.detectLanguage(filePath);
1665
+
1666
+ // Bypass non-code files (config/documentation)
1667
+ const bypassExtensions = ['.toml', '.md', '.txt', '.json', '.yaml', '.yml'];
1668
+ const ext = path.extname(filePath).toLowerCase();
1669
+ if (bypassExtensions.includes(ext)) {
1670
+ console.log(`\nā­ļø BYPASSED: ${ext} files don't require validation`);
1671
+ return {
1672
+ file: filePath,
1673
+ language,
1674
+ timestamp: new Date().toISOString(),
1675
+ editId: `edit-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1676
+ agentContext: this.extractAgentContext(options),
1677
+ status: 'BYPASSED',
1678
+ bypassed: true,
1679
+ reason: `${ext} files are configuration/documentation and don't require validation`,
1680
+ summary: {
1681
+ success: true,
1682
+ warnings: [],
1683
+ errors: [],
1684
+ suggestions: []
1685
+ }
1686
+ };
1687
+ }
1688
+
1689
+ // Auto-enable Rust strict mode for .rs files
1690
+ if (language === 'rust' && !this.rustStrict) {
1691
+ this.rustStrict = true;
1692
+ console.log('šŸ¦€ Auto-enabled Rust strict mode for .rs file');
1693
+ }
1694
+
1695
+ const results = {
1696
+ file: filePath,
1697
+ language,
1698
+ timestamp: new Date().toISOString(),
1699
+ editId: `edit-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1700
+ agentContext: this.extractAgentContext(options),
1701
+ steps: {},
1702
+ testing: null,
1703
+ coverage: null,
1704
+ tddCompliance: null,
1705
+ tddPhase: 'unknown',
1706
+ rustQuality: null,
1707
+ recommendations: [],
1708
+ blocking: false,
1709
+ summary: {
1710
+ success: true,
1711
+ warnings: [],
1712
+ errors: [],
1713
+ suggestions: []
1714
+ }
1715
+ };
1716
+
1717
+ console.log(`\nšŸ” UNIFIED POST-EDIT PIPELINE`);
1718
+ console.log(`šŸ“„ File: ${path.basename(filePath)}`);
1719
+ console.log(`šŸ“‹ Language: ${language.toUpperCase()}`);
1720
+ console.log(`🧪 TDD Mode: ${this.tddMode ? 'ENABLED' : 'DISABLED'}`);
1721
+
1722
+ let content = '';
1723
+ try {
1724
+ content = fs.readFileSync(filePath, 'utf8');
1725
+ } catch (error) {
1726
+ results.summary.errors.push(`Cannot read file: ${error.message}`);
1727
+ results.summary.success = false;
1728
+ await this.logToRootFile(results);
1729
+ return results;
1730
+ }
1731
+
1732
+ // Step 1: Format
1733
+ console.log('\nšŸ“ FORMATTING...');
1734
+ results.steps.formatting = await this.formatFile(filePath, language);
1735
+ this.logStepResult('Format', results.steps.formatting);
1736
+
1737
+ // Step 2: Lint
1738
+ console.log('\nšŸ” LINTING...');
1739
+ results.steps.linting = await this.lintFile(filePath, language);
1740
+ this.logStepResult('Lint', results.steps.linting);
1741
+ if (!results.steps.linting.success) {
1742
+ results.summary.warnings.push(`Linting issues in ${path.basename(filePath)}`);
1743
+ }
1744
+
1745
+ // Step 3: Type Check
1746
+ console.log('\nšŸŽÆ TYPE CHECKING...');
1747
+ results.steps.typeCheck = await this.typeCheck(filePath, language);
1748
+ this.logStepResult('Type Check', results.steps.typeCheck);
1749
+ if (!results.steps.typeCheck.success) {
1750
+ results.summary.errors.push(`Type errors in ${path.basename(filePath)}`);
1751
+ results.summary.success = false;
1752
+ }
1753
+
1754
+ // Step 4: Rust Quality Enforcement (if Rust and strict mode)
1755
+ if (language === 'rust' && this.rustStrict) {
1756
+ console.log('\nšŸ¦€ RUST QUALITY ENFORCEMENT...');
1757
+ results.rustQuality = await this.rustEnforcer.analyzeFile(filePath, content);
1758
+
1759
+ if (!results.rustQuality.passed) {
1760
+ console.log(` āŒ Rust quality issues found`);
1761
+ results.rustQuality.issues.forEach(issue => {
1762
+ console.log(` [${issue.severity.toUpperCase()}] ${issue.message}`);
1763
+ results.recommendations.push(issue);
1764
+
1765
+ if (issue.severity === 'error') {
1766
+ results.summary.errors.push(issue.message);
1767
+ results.summary.success = false;
1768
+ } else {
1769
+ results.summary.warnings.push(issue.message);
1770
+ }
1771
+ });
1772
+ } else {
1773
+ console.log(` āœ… Rust quality checks passed`);
1774
+ }
1775
+ }
1776
+
1777
+ // Step 5: TDD Testing (if enabled)
1778
+ if (this.tddMode) {
1779
+ console.log('\n🧪 TDD TESTING...');
1780
+ results.testing = await this.testEngine.executeTests(filePath, content);
1781
+
1782
+ if (results.testing.executed) {
1783
+ Logger.success(`Tests executed with ${results.testing.framework}`);
1784
+
1785
+ if (results.testing.results) {
1786
+ const { total, passed, failed } = results.testing.results.summary;
1787
+ Logger.test(`Test results: ${passed}/${total} passed, ${failed} failed`);
1788
+
1789
+ if (failed > 0) {
1790
+ results.tddPhase = 'red';
1791
+ Logger.tdd('TDD Phase: RED (failing tests)');
1792
+ } else if (passed > 0) {
1793
+ results.tddPhase = 'green';
1794
+ Logger.tdd('TDD Phase: GREEN (passing tests)');
1795
+ }
1796
+ }
1797
+ } else {
1798
+ Logger.warning(`Tests not executed: ${results.testing.reason}`);
1799
+ }
1800
+
1801
+ // Step 6: Coverage Analysis
1802
+ if (results.testing.coverage) {
1803
+ results.coverage = results.testing.coverage;
1804
+
1805
+ if (results.coverage.lines) {
1806
+ const coveragePercent = results.coverage.lines.percentage;
1807
+ Logger.coverage(`Line coverage: ${coveragePercent}%`);
1808
+
1809
+ if (coveragePercent < this.minimumCoverage) {
1810
+ Logger.warning(`Coverage below minimum (${this.minimumCoverage}%)`);
1811
+ results.recommendations.push({
1812
+ type: 'coverage',
1813
+ priority: 'medium',
1814
+ message: `Increase test coverage from ${coveragePercent}% to ${this.minimumCoverage}%`,
1815
+ action: 'Add tests for uncovered lines and branches'
1816
+ });
1817
+ }
1818
+ }
1819
+ }
1820
+
1821
+ // Step 7: TDD Compliance
1822
+ results.tddCompliance = results.testing.tddCompliance;
1823
+
1824
+ if (results.tddCompliance) {
1825
+ if (!results.tddCompliance.hasTests) {
1826
+ Logger.error('TDD Violation: No tests found');
1827
+
1828
+ if (this.blockOnTDDViolations) {
1829
+ results.blocking = true;
1830
+ results.summary.success = false;
1831
+ Logger.error('BLOCKING: TDD requires tests first');
1832
+ }
1833
+ } else {
1834
+ Logger.success('TDD Compliance: Tests exist');
1835
+ }
1836
+
1837
+ if (results.tddCompliance.recommendations) {
1838
+ results.recommendations.push(...results.tddCompliance.recommendations);
1839
+ }
1840
+ }
1841
+ }
1842
+
1843
+ // Generate summary
1844
+ this.printSummary(results);
1845
+
1846
+ // Log to root file
1847
+ await this.logToRootFile(results);
1848
+
1849
+ return results;
1850
+ }
1851
+
1852
+ logStepResult(step, result) {
1853
+ if (result.success) {
1854
+ console.log(` āœ… ${step}: ${result.message}`);
1855
+ } else {
1856
+ console.log(` āŒ ${step}: ${result.message}`);
1857
+ if (result.issues || result.errors) {
1858
+ console.log(` ${(result.issues || result.errors).slice(0, 200)}...`);
1859
+ }
1860
+ }
1861
+ }
1862
+
1863
+ printSummary(results) {
1864
+ console.log('\n' + '='.repeat(60));
1865
+ console.log('šŸ“Š VALIDATION SUMMARY');
1866
+ console.log('='.repeat(60));
1867
+
1868
+ if (results.blocking) {
1869
+ console.log('🚫 Overall Status: BLOCKED');
1870
+ } else if (results.summary.success) {
1871
+ console.log('āœ… Overall Status: PASSED');
1872
+ } else {
1873
+ console.log('āŒ Overall Status: FAILED');
1874
+ }
1875
+
1876
+ if (this.tddMode && results.testing) {
1877
+ console.log(`\n🧪 TDD Phase: ${results.tddPhase.toUpperCase()}`);
1878
+ if (results.testing.executed && results.testing.results) {
1879
+ const { total, passed, failed } = results.testing.results.summary;
1880
+ console.log(` Tests: ${passed}/${total} passed, ${failed} failed`);
1881
+ }
1882
+ if (results.coverage && results.coverage.lines) {
1883
+ console.log(` Coverage: ${results.coverage.lines.percentage}%`);
1884
+ }
1885
+ }
1886
+
1887
+ if (results.summary.errors.length > 0) {
1888
+ console.log('\n🚨 ERRORS:');
1889
+ results.summary.errors.forEach(error => console.log(` • ${error}`));
1890
+ }
1891
+
1892
+ if (results.summary.warnings.length > 0) {
1893
+ console.log('\nāš ļø WARNINGS:');
1894
+ results.summary.warnings.forEach(warning => console.log(` • ${warning}`));
1895
+ }
1896
+
1897
+ if (results.recommendations.length > 0) {
1898
+ console.log('\nšŸ’” RECOMMENDATIONS:');
1899
+ results.recommendations.slice(0, 5).forEach((rec, i) => {
1900
+ console.log(` ${i + 1}. [${rec.priority.toUpperCase()}] ${rec.message}`);
1901
+ if (rec.action) console.log(` Action: ${rec.action}`);
1902
+ });
1903
+ }
1904
+
1905
+ console.log('='.repeat(60));
1906
+ }
1907
+ }
1908
+
1909
+ // CLI execution
1910
+ // Memory and process monitoring
1911
+ class ProcessMonitor {
1912
+ constructor(maxMemoryMB = 500, maxDurationMs = 300000) {
1913
+ this.maxMemoryMB = maxMemoryMB;
1914
+ this.maxDurationMs = maxDurationMs;
1915
+ this.startTime = Date.now();
1916
+ this.monitoring = false;
1917
+ this.monitorInterval = null;
1918
+ }
1919
+
1920
+ start() {
1921
+ if (this.monitoring) return;
1922
+ this.monitoring = true;
1923
+
1924
+ this.monitorInterval = setInterval(() => {
1925
+ this.checkMemory();
1926
+ this.checkDuration();
1927
+ }, 5000); // Check every 5 seconds
1928
+ }
1929
+
1930
+ stop() {
1931
+ if (this.monitorInterval) {
1932
+ clearInterval(this.monitorInterval);
1933
+ this.monitorInterval = null;
1934
+ }
1935
+ this.monitoring = false;
1936
+ }
1937
+
1938
+ checkMemory() {
1939
+ const memoryUsage = process.memoryUsage();
1940
+ const memoryMB = memoryUsage.heapUsed / 1024 / 1024;
1941
+
1942
+ if (memoryMB > this.maxMemoryMB) {
1943
+ console.error(`🚨 MEMORY LIMIT EXCEEDED: ${memoryMB.toFixed(1)}MB > ${this.maxMemoryMB}MB`);
1944
+ console.error('šŸ”„ EMERGENCY SHUTDOWN - Process killed to prevent system crash');
1945
+
1946
+ // Force cleanup before exit
1947
+ this.cleanup();
1948
+ process.exit(137); // SIGKILL exit code
1949
+ }
1950
+
1951
+ // Warning at 80% of limit
1952
+ if (memoryMB > this.maxMemoryMB * 0.8) {
1953
+ console.warn(`āš ļø High memory usage: ${memoryMB.toFixed(1)}MB (limit: ${this.maxMemoryMB}MB)`);
1954
+ }
1955
+ }
1956
+
1957
+ checkDuration() {
1958
+ const elapsed = Date.now() - this.startTime;
1959
+
1960
+ if (elapsed > this.maxDurationMs) {
1961
+ console.error(`🚨 TIME LIMIT EXCEEDED: ${(elapsed / 1000).toFixed(1)}s > ${(this.maxDurationMs / 1000).toFixed(1)}s`);
1962
+ console.error('šŸ”„ EMERGENCY SHUTDOWN - Process killed to prevent hanging');
1963
+
1964
+ this.cleanup();
1965
+ process.exit(124); // timeout exit code
1966
+ }
1967
+ }
1968
+
1969
+ cleanup() {
1970
+ // Clean up any spawned processes
1971
+ try {
1972
+ // Kill any child processes
1973
+ process.kill(0, 'SIGTERM');
1974
+ } catch (e) {
1975
+ // Ignore errors
1976
+ }
1977
+ }
1978
+ }
1979
+
1980
+ async function main() {
1981
+ const filePath = process.argv[2];
1982
+
1983
+ if (!filePath) {
1984
+ console.log(`
1985
+ šŸ”“šŸŸ¢ā™»ļø UNIFIED POST-EDIT PIPELINE - v3.0.0 (Memory-Safe)
1986
+
1987
+ Usage: post-edit-pipeline.js <file> [options]
1988
+
1989
+ Options:
1990
+ --memory-key <key> Store results with specific memory key
1991
+ --tdd-mode Enable TDD testing and enforcement
1992
+ --minimum-coverage <percent> Minimum coverage threshold (default: 80)
1993
+ --block-on-tdd-violations Block execution on TDD violations
1994
+ --rust-strict Enable strict Rust quality checks
1995
+ --structured Return structured JSON data
1996
+ --max-memory <MB> Maximum memory usage (default: 500MB)
1997
+ --max-duration <seconds> Maximum execution time (default: 300s)
1998
+
1999
+ Examples:
2000
+ node post-edit-pipeline.js src/app.js --tdd-mode --minimum-coverage 90
2001
+ node post-edit-pipeline.js src/lib.rs --rust-strict --max-memory 1000
2002
+ node post-edit-pipeline.js src/test.ts --tdd-mode --max-duration 600
2003
+
2004
+ Features:
2005
+ āœ… Progressive validation (syntax → interface → integration → full)
2006
+ āœ… TDD enforcement with Red-Green-Refactor detection
2007
+ āœ… Single-file testing without full compilation
2008
+ āœ… Real-time coverage analysis
2009
+ āœ… Rust quality enforcement (.unwrap(), panic!, todo! detection)
2010
+ āœ… Multi-language support (JS, TS, Python, Rust, Go, Java, C/C++)
2011
+ āœ… Security scanning and dependency analysis
2012
+ āœ… Agent coordination and memory storage
2013
+ āœ… Memory leak protection and auto-kill safeguards
2014
+ `);
2015
+ return;
2016
+ }
2017
+
2018
+ if (!fs.existsSync(filePath)) {
2019
+ console.error(`File not found: ${filePath}`);
2020
+ process.exit(1);
2021
+ }
2022
+
2023
+ const args = process.argv.slice(3);
2024
+ const options = {};
2025
+
2026
+ // Parse command-line options
2027
+ for (let i = 0; i < args.length; i++) {
2028
+ if (args[i] === '--memory-key' && args[i + 1]) {
2029
+ options.memoryKey = args[i + 1];
2030
+ i++;
2031
+ } else if (args[i] === '--agent-type' && args[i + 1]) {
2032
+ options.agentType = args[i + 1];
2033
+ i++;
2034
+ } else if (args[i] === '--minimum-coverage' && args[i + 1]) {
2035
+ options.minimumCoverage = parseInt(args[i + 1]) || 80;
2036
+ i++;
2037
+ }
2038
+ }
2039
+
2040
+ // Initialize process monitor with limits
2041
+ const maxMemoryMB = (() => {
2042
+ const memArg = args.find(arg => arg.startsWith('--max-memory='));
2043
+ return memArg ? parseInt(memArg.split('=')[1]) : 500;
2044
+ })();
2045
+
2046
+ const maxDurationMs = (() => {
2047
+ const durArg = args.find(arg => arg.startsWith('--max-duration='));
2048
+ return durArg ? parseInt(durArg.split('=')[1]) * 1000 : 300000; // 5 minutes default
2049
+ })();
2050
+
2051
+ const monitor = new ProcessMonitor(maxMemoryMB, maxDurationMs);
2052
+ monitor.start();
2053
+
2054
+ console.log(`šŸ›”ļø Process limits: ${maxMemoryMB}MB memory, ${(maxDurationMs / 1000).toFixed(0)}s duration`);
2055
+
2056
+ try {
2057
+ const pipelineOptions = {
2058
+ tddMode: args.includes('--tdd-mode'),
2059
+ minimumCoverage: options.minimumCoverage || 80,
2060
+ blockOnTDDViolations: args.includes('--block-on-tdd-violations'),
2061
+ rustStrict: args.includes('--rust-strict'),
2062
+ structured: args.includes('--structured')
2063
+ };
2064
+
2065
+ const pipeline = new UnifiedPostEditPipeline(pipelineOptions);
2066
+ const results = await pipeline.run(filePath, options);
2067
+
2068
+ if (pipelineOptions.structured) {
2069
+ console.log('\nšŸ“‹ STRUCTURED OUTPUT:');
2070
+ console.log(JSON.stringify(results, null, 2));
2071
+ }
2072
+
2073
+ monitor.stop();
2074
+ process.exit(results.summary.success && !results.blocking ? 0 : 1);
2075
+
2076
+ } catch (error) {
2077
+ console.error('šŸ’„ Pipeline error:', error.message);
2078
+ monitor.stop();
2079
+ process.exit(1);
2080
+ }
2081
+ }
2082
+
2083
+ // Run if called directly
2084
+ if (import.meta.url === `file://${process.argv[1]}`) {
2085
+ main().catch(error => {
2086
+ console.error('Pipeline error:', error);
2087
+ process.exit(1);
2088
+ });
2089
+ }
2090
+
2091
+ export { UnifiedPostEditPipeline, SingleFileTestEngine, RustQualityEnforcer };