@claude-flow/cli 3.32.3 → 3.32.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 (683) hide show
  1. package/.claude/helpers/helpers.manifest.json +2 -2
  2. package/catalog-manifest.json +2 -2
  3. package/dist/src/agenticow/speculative-exploration.d.ts +148 -0
  4. package/dist/src/agenticow/speculative-exploration.js +218 -0
  5. package/dist/src/appliance/gguf-engine.d.ts +91 -0
  6. package/dist/src/appliance/gguf-engine.js +425 -0
  7. package/dist/src/appliance/ruvllm-bridge.d.ts +102 -0
  8. package/dist/src/appliance/ruvllm-bridge.js +292 -0
  9. package/dist/src/appliance/rvfa-builder.d.ts +44 -0
  10. package/dist/src/appliance/rvfa-builder.js +329 -0
  11. package/dist/src/appliance/rvfa-distribution.d.ts +97 -0
  12. package/dist/src/appliance/rvfa-distribution.js +370 -0
  13. package/dist/src/appliance/rvfa-format.d.ts +111 -0
  14. package/dist/src/appliance/rvfa-format.js +393 -0
  15. package/dist/src/appliance/rvfa-runner.d.ts +69 -0
  16. package/dist/src/appliance/rvfa-runner.js +237 -0
  17. package/dist/src/appliance/rvfa-signing.d.ts +123 -0
  18. package/dist/src/appliance/rvfa-signing.js +347 -0
  19. package/dist/src/auth/client.d.ts +89 -0
  20. package/dist/src/auth/client.js +242 -0
  21. package/dist/src/auth/constants.d.ts +7 -0
  22. package/dist/src/auth/constants.js +7 -0
  23. package/dist/src/auth/scopes.d.ts +14 -0
  24. package/dist/src/auth/scopes.js +21 -0
  25. package/dist/src/auth/security-bridge.d.ts +36 -0
  26. package/dist/src/auth/security-bridge.js +42 -0
  27. package/dist/src/auth/session.d.ts +20 -0
  28. package/dist/src/auth/session.js +32 -0
  29. package/dist/src/auth/state.d.ts +19 -0
  30. package/dist/src/auth/state.js +53 -0
  31. package/dist/src/auth/types.d.ts +27 -0
  32. package/dist/src/auth/types.js +11 -0
  33. package/dist/src/autopilot-state.d.ts +77 -0
  34. package/dist/src/autopilot-state.js +271 -0
  35. package/dist/src/benchmarks/gaia-agent-planning.smoke.d.ts +18 -0
  36. package/dist/src/benchmarks/gaia-agent-planning.smoke.js +253 -0
  37. package/dist/src/benchmarks/gaia-agent.d.ts +198 -0
  38. package/dist/src/benchmarks/gaia-agent.js +651 -0
  39. package/dist/src/benchmarks/gaia-causal-memory.d.ts +133 -0
  40. package/dist/src/benchmarks/gaia-causal-memory.js +281 -0
  41. package/dist/src/benchmarks/gaia-causal-memory.smoke.d.ts +22 -0
  42. package/dist/src/benchmarks/gaia-causal-memory.smoke.js +300 -0
  43. package/dist/src/benchmarks/gaia-convergence.d.ts +138 -0
  44. package/dist/src/benchmarks/gaia-convergence.js +260 -0
  45. package/dist/src/benchmarks/gaia-convergence.smoke.d.ts +19 -0
  46. package/dist/src/benchmarks/gaia-convergence.smoke.js +246 -0
  47. package/dist/src/benchmarks/gaia-critic.d.ts +123 -0
  48. package/dist/src/benchmarks/gaia-critic.js +312 -0
  49. package/dist/src/benchmarks/gaia-critic.smoke.d.ts +21 -0
  50. package/dist/src/benchmarks/gaia-critic.smoke.js +327 -0
  51. package/dist/src/benchmarks/gaia-decomposer.d.ts +125 -0
  52. package/dist/src/benchmarks/gaia-decomposer.js +350 -0
  53. package/dist/src/benchmarks/gaia-decomposer.smoke.d.ts +21 -0
  54. package/dist/src/benchmarks/gaia-decomposer.smoke.js +228 -0
  55. package/dist/src/benchmarks/gaia-e2e-smoke.d.ts +27 -0
  56. package/dist/src/benchmarks/gaia-e2e-smoke.js +136 -0
  57. package/dist/src/benchmarks/gaia-extract.smoke.d.ts +45 -0
  58. package/dist/src/benchmarks/gaia-extract.smoke.js +242 -0
  59. package/dist/src/benchmarks/gaia-hardness/features.d.ts +46 -0
  60. package/dist/src/benchmarks/gaia-hardness/features.js +170 -0
  61. package/dist/src/benchmarks/gaia-hardness/predictor.d.ts +105 -0
  62. package/dist/src/benchmarks/gaia-hardness/predictor.js +260 -0
  63. package/dist/src/benchmarks/gaia-hardness/predictor.smoke.d.ts +20 -0
  64. package/dist/src/benchmarks/gaia-hardness/predictor.smoke.js +235 -0
  65. package/dist/src/benchmarks/gaia-hardness/train-data-loader.d.ts +51 -0
  66. package/dist/src/benchmarks/gaia-hardness/train-data-loader.js +179 -0
  67. package/dist/src/benchmarks/gaia-judge.d.ts +88 -0
  68. package/dist/src/benchmarks/gaia-judge.js +437 -0
  69. package/dist/src/benchmarks/gaia-loader.d.ts +87 -0
  70. package/dist/src/benchmarks/gaia-loader.js +326 -0
  71. package/dist/src/benchmarks/gaia-tools/file_read.d.ts +35 -0
  72. package/dist/src/benchmarks/gaia-tools/file_read.js +403 -0
  73. package/dist/src/benchmarks/gaia-tools/grounded_query.d.ts +126 -0
  74. package/dist/src/benchmarks/gaia-tools/grounded_query.js +225 -0
  75. package/dist/src/benchmarks/gaia-tools/index.d.ts +32 -0
  76. package/dist/src/benchmarks/gaia-tools/index.js +36 -0
  77. package/dist/src/benchmarks/gaia-tools/types.d.ts +62 -0
  78. package/dist/src/benchmarks/gaia-tools/types.js +12 -0
  79. package/dist/src/benchmarks/gaia-tools/web_search.d.ts +30 -0
  80. package/dist/src/benchmarks/gaia-tools/web_search.js +210 -0
  81. package/dist/src/benchmarks/gaia-voting.d.ts +88 -0
  82. package/dist/src/benchmarks/gaia-voting.js +297 -0
  83. package/dist/src/benchmarks/gaia-voting.smoke.d.ts +20 -0
  84. package/dist/src/benchmarks/gaia-voting.smoke.js +332 -0
  85. package/dist/src/benchmarks/pretrain/index.d.ts +58 -0
  86. package/dist/src/benchmarks/pretrain/index.js +404 -0
  87. package/dist/src/business-pods/bbs-budget-tracker.d.ts +139 -0
  88. package/dist/src/business-pods/bbs-budget-tracker.js +358 -0
  89. package/dist/src/business-pods/domain-affinity-policy.d.ts +47 -0
  90. package/dist/src/business-pods/domain-affinity-policy.js +65 -0
  91. package/dist/src/business-pods/pod-schema.d.ts +96 -0
  92. package/dist/src/business-pods/pod-schema.js +225 -0
  93. package/dist/src/commands/advisor.d.ts +15 -0
  94. package/dist/src/commands/advisor.js +94 -0
  95. package/dist/src/commands/agent-wasm.d.ts +14 -0
  96. package/dist/src/commands/agent-wasm.js +333 -0
  97. package/dist/src/commands/agent.d.ts +8 -0
  98. package/dist/src/commands/agent.js +927 -0
  99. package/dist/src/commands/analyze.d.ts +19 -0
  100. package/dist/src/commands/analyze.js +2047 -0
  101. package/dist/src/commands/announcements.d.ts +17 -0
  102. package/dist/src/commands/announcements.js +0 -0
  103. package/dist/src/commands/appliance-advanced.d.ts +9 -0
  104. package/dist/src/commands/appliance-advanced.js +215 -0
  105. package/dist/src/commands/appliance.d.ts +8 -0
  106. package/dist/src/commands/appliance.js +404 -0
  107. package/dist/src/commands/auth.d.ts +15 -0
  108. package/dist/src/commands/auth.js +244 -0
  109. package/dist/src/commands/autopilot.d.ts +15 -0
  110. package/dist/src/commands/autopilot.js +407 -0
  111. package/dist/src/commands/benchmark.d.ts +10 -0
  112. package/dist/src/commands/benchmark.js +460 -0
  113. package/dist/src/commands/claims.d.ts +10 -0
  114. package/dist/src/commands/claims.js +620 -0
  115. package/dist/src/commands/cleanup.d.ts +13 -0
  116. package/dist/src/commands/cleanup.js +250 -0
  117. package/dist/src/commands/completions.d.ts +10 -0
  118. package/dist/src/commands/completions.js +539 -0
  119. package/dist/src/commands/config.d.ts +8 -0
  120. package/dist/src/commands/config.js +428 -0
  121. package/dist/src/commands/daemon.d.ts +59 -0
  122. package/dist/src/commands/daemon.js +1733 -0
  123. package/dist/src/commands/deployment.d.ts +10 -0
  124. package/dist/src/commands/deployment.js +672 -0
  125. package/dist/src/commands/doctor.d.ts +10 -0
  126. package/dist/src/commands/doctor.js +1902 -0
  127. package/dist/src/commands/eject.d.ts +33 -0
  128. package/dist/src/commands/eject.js +195 -0
  129. package/dist/src/commands/embeddings.d.ts +18 -0
  130. package/dist/src/commands/embeddings.js +1623 -0
  131. package/dist/src/commands/funnel.d.ts +18 -0
  132. package/dist/src/commands/funnel.js +302 -0
  133. package/dist/src/commands/gaia-bench.d.ts +40 -0
  134. package/dist/src/commands/gaia-bench.js +597 -0
  135. package/dist/src/commands/guidance.d.ts +8 -0
  136. package/dist/src/commands/guidance.js +556 -0
  137. package/dist/src/commands/hive-mind.d.ts +11 -0
  138. package/dist/src/commands/hive-mind.js +1319 -0
  139. package/dist/src/commands/hooks.d.ts +8 -0
  140. package/dist/src/commands/hooks.js +4606 -0
  141. package/dist/src/commands/index.d.ts +118 -0
  142. package/dist/src/commands/index.js +366 -0
  143. package/dist/src/commands/init.d.ts +13 -0
  144. package/dist/src/commands/init.js +1297 -0
  145. package/dist/src/commands/issues.d.ts +21 -0
  146. package/dist/src/commands/issues.js +567 -0
  147. package/dist/src/commands/mcp.d.ts +11 -0
  148. package/dist/src/commands/mcp.js +732 -0
  149. package/dist/src/commands/memory-backup.d.ts +11 -0
  150. package/dist/src/commands/memory-backup.js +46 -0
  151. package/dist/src/commands/memory-distill.d.ts +27 -0
  152. package/dist/src/commands/memory-distill.js +374 -0
  153. package/dist/src/commands/memory.d.ts +8 -0
  154. package/dist/src/commands/memory.js +1596 -0
  155. package/dist/src/commands/metaharness.d.ts +39 -0
  156. package/dist/src/commands/metaharness.js +215 -0
  157. package/dist/src/commands/migrate.d.ts +8 -0
  158. package/dist/src/commands/migrate.js +742 -0
  159. package/dist/src/commands/neural.d.ts +10 -0
  160. package/dist/src/commands/neural.js +4331 -0
  161. package/dist/src/commands/performance.d.ts +10 -0
  162. package/dist/src/commands/performance.js +583 -0
  163. package/dist/src/commands/plugins.d.ts +11 -0
  164. package/dist/src/commands/plugins.js +826 -0
  165. package/dist/src/commands/process.d.ts +10 -0
  166. package/dist/src/commands/process.js +694 -0
  167. package/dist/src/commands/progress.d.ts +11 -0
  168. package/dist/src/commands/progress.js +259 -0
  169. package/dist/src/commands/providers.d.ts +10 -0
  170. package/dist/src/commands/providers.js +502 -0
  171. package/dist/src/commands/proxy-lifecycle.d.ts +20 -0
  172. package/dist/src/commands/proxy-lifecycle.js +277 -0
  173. package/dist/src/commands/proxy.d.ts +21 -0
  174. package/dist/src/commands/proxy.js +403 -0
  175. package/dist/src/commands/route.d.ts +16 -0
  176. package/dist/src/commands/route.js +822 -0
  177. package/dist/src/commands/ruvector/backup.d.ts +11 -0
  178. package/dist/src/commands/ruvector/backup.js +747 -0
  179. package/dist/src/commands/ruvector/benchmark.d.ts +11 -0
  180. package/dist/src/commands/ruvector/benchmark.js +490 -0
  181. package/dist/src/commands/ruvector/import.d.ts +18 -0
  182. package/dist/src/commands/ruvector/import.js +373 -0
  183. package/dist/src/commands/ruvector/index.d.ts +29 -0
  184. package/dist/src/commands/ruvector/index.js +129 -0
  185. package/dist/src/commands/ruvector/init.d.ts +11 -0
  186. package/dist/src/commands/ruvector/init.js +467 -0
  187. package/dist/src/commands/ruvector/migrate.d.ts +11 -0
  188. package/dist/src/commands/ruvector/migrate.js +498 -0
  189. package/dist/src/commands/ruvector/optimize.d.ts +11 -0
  190. package/dist/src/commands/ruvector/optimize.js +505 -0
  191. package/dist/src/commands/ruvector/pg-utils.d.ts +14 -0
  192. package/dist/src/commands/ruvector/pg-utils.js +41 -0
  193. package/dist/src/commands/ruvector/setup.d.ts +18 -0
  194. package/dist/src/commands/ruvector/setup.js +765 -0
  195. package/dist/src/commands/ruvector/status.d.ts +11 -0
  196. package/dist/src/commands/ruvector/status.js +479 -0
  197. package/dist/src/commands/security.d.ts +10 -0
  198. package/dist/src/commands/security.js +1012 -0
  199. package/dist/src/commands/session.d.ts +8 -0
  200. package/dist/src/commands/session.js +757 -0
  201. package/dist/src/commands/settings.d.ts +19 -0
  202. package/dist/src/commands/settings.js +180 -0
  203. package/dist/src/commands/spinner.d.ts +16 -0
  204. package/dist/src/commands/spinner.js +329 -0
  205. package/dist/src/commands/start.d.ts +8 -0
  206. package/dist/src/commands/start.js +418 -0
  207. package/dist/src/commands/status.d.ts +8 -0
  208. package/dist/src/commands/status.js +608 -0
  209. package/dist/src/commands/swarm.d.ts +8 -0
  210. package/dist/src/commands/swarm.js +891 -0
  211. package/dist/src/commands/task.d.ts +8 -0
  212. package/dist/src/commands/task.js +675 -0
  213. package/dist/src/commands/transfer-store.d.ts +13 -0
  214. package/dist/src/commands/transfer-store.js +428 -0
  215. package/dist/src/commands/update.d.ts +8 -0
  216. package/dist/src/commands/update.js +276 -0
  217. package/dist/src/commands/verify.d.ts +19 -0
  218. package/dist/src/commands/verify.js +261 -0
  219. package/dist/src/commands/version.d.ts +42 -0
  220. package/dist/src/commands/version.js +106 -0
  221. package/dist/src/commands/workflow.d.ts +8 -0
  222. package/dist/src/commands/workflow.js +617 -0
  223. package/dist/src/config/harness-feedback-applier.d.ts +50 -0
  224. package/dist/src/config/harness-feedback-applier.js +122 -0
  225. package/dist/src/config/proven-config-refresh.d.ts +39 -0
  226. package/dist/src/config/proven-config-refresh.js +154 -0
  227. package/dist/src/config/proven-config-rvfa.d.ts +23 -0
  228. package/dist/src/config/proven-config-rvfa.js +73 -0
  229. package/dist/src/config/proven-config.d.ts +86 -0
  230. package/dist/src/config/proven-config.js +176 -0
  231. package/dist/src/config-adapter.d.ts +15 -0
  232. package/dist/src/config-adapter.js +186 -0
  233. package/dist/src/encryption/vault.d.ts +94 -0
  234. package/dist/src/encryption/vault.js +172 -0
  235. package/dist/src/fs-secure.d.ts +86 -0
  236. package/dist/src/fs-secure.js +133 -0
  237. package/dist/src/funnel/advisor-tip.d.ts +58 -0
  238. package/dist/src/funnel/advisor-tip.js +92 -0
  239. package/dist/src/funnel/attribution.d.ts +37 -0
  240. package/dist/src/funnel/attribution.js +101 -0
  241. package/dist/src/funnel/consent.d.ts +22 -0
  242. package/dist/src/funnel/consent.js +58 -0
  243. package/dist/src/funnel/credit-errors.d.ts +31 -0
  244. package/dist/src/funnel/credit-errors.js +88 -0
  245. package/dist/src/funnel/credit-notifier.d.ts +44 -0
  246. package/dist/src/funnel/credit-notifier.js +74 -0
  247. package/dist/src/funnel/disclosure.d.ts +47 -0
  248. package/dist/src/funnel/disclosure.js +109 -0
  249. package/dist/src/funnel/enrollment.d.ts +36 -0
  250. package/dist/src/funnel/enrollment.js +64 -0
  251. package/dist/src/funnel/environment.d.ts +17 -0
  252. package/dist/src/funnel/environment.js +39 -0
  253. package/dist/src/funnel/event-transport.d.ts +51 -0
  254. package/dist/src/funnel/event-transport.js +199 -0
  255. package/dist/src/funnel/events.d.ts +42 -0
  256. package/dist/src/funnel/events.js +150 -0
  257. package/dist/src/funnel/index.d.ts +21 -0
  258. package/dist/src/funnel/index.js +21 -0
  259. package/dist/src/funnel/insights.d.ts +50 -0
  260. package/dist/src/funnel/insights.js +120 -0
  261. package/dist/src/funnel/local-signals.d.ts +20 -0
  262. package/dist/src/funnel/local-signals.js +77 -0
  263. package/dist/src/funnel/message-transport.d.ts +51 -0
  264. package/dist/src/funnel/message-transport.js +149 -0
  265. package/dist/src/funnel/messages.d.ts +55 -0
  266. package/dist/src/funnel/messages.js +160 -0
  267. package/dist/src/funnel/payout.d.ts +40 -0
  268. package/dist/src/funnel/payout.js +60 -0
  269. package/dist/src/funnel/power-saver-notifier.d.ts +44 -0
  270. package/dist/src/funnel/power-saver-notifier.js +92 -0
  271. package/dist/src/funnel/precedence.d.ts +16 -0
  272. package/dist/src/funnel/precedence.js +85 -0
  273. package/dist/src/funnel/promo.d.ts +41 -0
  274. package/dist/src/funnel/promo.js +144 -0
  275. package/dist/src/funnel/rate-limit-notifier.d.ts +55 -0
  276. package/dist/src/funnel/rate-limit-notifier.js +102 -0
  277. package/dist/src/funnel/rotation.d.ts +19 -0
  278. package/dist/src/funnel/rotation.js +70 -0
  279. package/dist/src/funnel/state.d.ts +13 -0
  280. package/dist/src/funnel/state.js +52 -0
  281. package/dist/src/funnel/toggle-cooldown.d.ts +17 -0
  282. package/dist/src/funnel/toggle-cooldown.js +32 -0
  283. package/dist/src/funnel/types.d.ts +98 -0
  284. package/dist/src/funnel/types.js +26 -0
  285. package/dist/src/index.d.ts +81 -0
  286. package/dist/src/index.js +609 -0
  287. package/dist/src/infrastructure/in-memory-repositories.d.ts +68 -0
  288. package/dist/src/infrastructure/in-memory-repositories.js +264 -0
  289. package/dist/src/init/claudemd-generator.d.ts +16 -0
  290. package/dist/src/init/claudemd-generator.js +368 -0
  291. package/dist/src/init/executor.d.ts +41 -0
  292. package/dist/src/init/executor.js +2142 -0
  293. package/dist/src/init/helper-refresh.d.ts +79 -0
  294. package/dist/src/init/helper-refresh.js +347 -0
  295. package/dist/src/init/helper-signing.d.ts +37 -0
  296. package/dist/src/init/helper-signing.js +67 -0
  297. package/dist/src/init/helpers-generator.d.ts +87 -0
  298. package/dist/src/init/helpers-generator.js +1456 -0
  299. package/dist/src/init/index.d.ts +13 -0
  300. package/dist/src/init/index.js +15 -0
  301. package/dist/src/init/mcp-generator.d.ts +26 -0
  302. package/dist/src/init/mcp-generator.js +126 -0
  303. package/dist/src/init/memory-package-resolver.d.ts +53 -0
  304. package/dist/src/init/memory-package-resolver.js +118 -0
  305. package/dist/src/init/settings-generator.d.ts +14 -0
  306. package/dist/src/init/settings-generator.js +462 -0
  307. package/dist/src/init/statusline-generator.d.ts +28 -0
  308. package/dist/src/init/statusline-generator.js +177 -0
  309. package/dist/src/init/types.d.ts +331 -0
  310. package/dist/src/init/types.js +276 -0
  311. package/dist/src/log-filters.d.ts +46 -0
  312. package/dist/src/log-filters.js +107 -0
  313. package/dist/src/mcp-client.d.ts +92 -0
  314. package/dist/src/mcp-client.js +397 -0
  315. package/dist/src/mcp-server.d.ts +163 -0
  316. package/dist/src/mcp-server.js +751 -0
  317. package/dist/src/mcp-tools/agent-execute-core.d.ts +115 -0
  318. package/dist/src/mcp-tools/agent-execute-core.js +587 -0
  319. package/dist/src/mcp-tools/agent-tools.d.ts +9 -0
  320. package/dist/src/mcp-tools/agent-tools.js +837 -0
  321. package/dist/src/mcp-tools/agentbbs-tools.d.ts +28 -0
  322. package/dist/src/mcp-tools/agentbbs-tools.js +394 -0
  323. package/dist/src/mcp-tools/agentdb-tools.d.ts +35 -0
  324. package/dist/src/mcp-tools/agentdb-tools.js +1473 -0
  325. package/dist/src/mcp-tools/agenticow-loader.d.ts +59 -0
  326. package/dist/src/mcp-tools/agenticow-loader.js +105 -0
  327. package/dist/src/mcp-tools/agenticow-speculate-tools.d.ts +24 -0
  328. package/dist/src/mcp-tools/agenticow-speculate-tools.js +209 -0
  329. package/dist/src/mcp-tools/agenticow-tools.d.ts +36 -0
  330. package/dist/src/mcp-tools/agenticow-tools.js +360 -0
  331. package/dist/src/mcp-tools/analyze-tools.d.ts +38 -0
  332. package/dist/src/mcp-tools/analyze-tools.js +346 -0
  333. package/dist/src/mcp-tools/auto-install.d.ts +83 -0
  334. package/dist/src/mcp-tools/auto-install.js +131 -0
  335. package/dist/src/mcp-tools/autopilot-tools.d.ts +12 -0
  336. package/dist/src/mcp-tools/autopilot-tools.js +231 -0
  337. package/dist/src/mcp-tools/browser-intent-tools.d.ts +162 -0
  338. package/dist/src/mcp-tools/browser-intent-tools.js +548 -0
  339. package/dist/src/mcp-tools/browser-session-tools.d.ts +27 -0
  340. package/dist/src/mcp-tools/browser-session-tools.js +398 -0
  341. package/dist/src/mcp-tools/browser-tools.d.ts +21 -0
  342. package/dist/src/mcp-tools/browser-tools.js +760 -0
  343. package/dist/src/mcp-tools/business-pod-tools.d.ts +20 -0
  344. package/dist/src/mcp-tools/business-pod-tools.js +169 -0
  345. package/dist/src/mcp-tools/claims-tools.d.ts +12 -0
  346. package/dist/src/mcp-tools/claims-tools.js +863 -0
  347. package/dist/src/mcp-tools/config-tools.d.ts +8 -0
  348. package/dist/src/mcp-tools/config-tools.js +411 -0
  349. package/dist/src/mcp-tools/coordination-tools.d.ts +13 -0
  350. package/dist/src/mcp-tools/coordination-tools.js +729 -0
  351. package/dist/src/mcp-tools/daa-tools.d.ts +13 -0
  352. package/dist/src/mcp-tools/daa-tools.js +534 -0
  353. package/dist/src/mcp-tools/embeddings-tools.d.ts +9 -0
  354. package/dist/src/mcp-tools/embeddings-tools.js +904 -0
  355. package/dist/src/mcp-tools/github-tools.d.ts +9 -0
  356. package/dist/src/mcp-tools/github-tools.js +659 -0
  357. package/dist/src/mcp-tools/guidance-tools.d.ts +15 -0
  358. package/dist/src/mcp-tools/guidance-tools.js +639 -0
  359. package/dist/src/mcp-tools/hive-mind-tools.d.ts +8 -0
  360. package/dist/src/mcp-tools/hive-mind-tools.js +953 -0
  361. package/dist/src/mcp-tools/hooks-tools.d.ts +65 -0
  362. package/dist/src/mcp-tools/hooks-tools.js +4836 -0
  363. package/dist/src/mcp-tools/http-fetch-tools.d.ts +55 -0
  364. package/dist/src/mcp-tools/http-fetch-tools.js +329 -0
  365. package/dist/src/mcp-tools/index.d.ts +34 -0
  366. package/dist/src/mcp-tools/index.js +40 -0
  367. package/dist/src/mcp-tools/managed-agent-tools.d.ts +22 -0
  368. package/dist/src/mcp-tools/managed-agent-tools.js +357 -0
  369. package/dist/src/mcp-tools/memory-tools.d.ts +14 -0
  370. package/dist/src/mcp-tools/memory-tools.js +1330 -0
  371. package/dist/src/mcp-tools/metaharness-tools.d.ts +51 -0
  372. package/dist/src/mcp-tools/metaharness-tools.js +684 -0
  373. package/dist/src/mcp-tools/neural-tools.d.ts +54 -0
  374. package/dist/src/mcp-tools/neural-tools.js +1168 -0
  375. package/dist/src/mcp-tools/performance-tools.d.ts +16 -0
  376. package/dist/src/mcp-tools/performance-tools.js +675 -0
  377. package/dist/src/mcp-tools/progress-tools.d.ts +14 -0
  378. package/dist/src/mcp-tools/progress-tools.js +348 -0
  379. package/dist/src/mcp-tools/request-tracker.d.ts +17 -0
  380. package/dist/src/mcp-tools/request-tracker.js +27 -0
  381. package/dist/src/mcp-tools/ruvllm-tools.d.ts +9 -0
  382. package/dist/src/mcp-tools/ruvllm-tools.js +355 -0
  383. package/dist/src/mcp-tools/security-tools.d.ts +18 -0
  384. package/dist/src/mcp-tools/security-tools.js +556 -0
  385. package/dist/src/mcp-tools/session-tools.d.ts +8 -0
  386. package/dist/src/mcp-tools/session-tools.js +517 -0
  387. package/dist/src/mcp-tools/swarm-tools.d.ts +37 -0
  388. package/dist/src/mcp-tools/swarm-tools.js +390 -0
  389. package/dist/src/mcp-tools/system-tools.d.ts +13 -0
  390. package/dist/src/mcp-tools/system-tools.js +688 -0
  391. package/dist/src/mcp-tools/task-tools.d.ts +8 -0
  392. package/dist/src/mcp-tools/task-tools.js +487 -0
  393. package/dist/src/mcp-tools/terminal-tools.d.ts +8 -0
  394. package/dist/src/mcp-tools/terminal-tools.js +306 -0
  395. package/dist/src/mcp-tools/testgen-tools.d.ts +26 -0
  396. package/dist/src/mcp-tools/testgen-tools.js +168 -0
  397. package/dist/src/mcp-tools/tool-loop-guardrail.d.ts +31 -0
  398. package/dist/src/mcp-tools/tool-loop-guardrail.js +71 -0
  399. package/dist/src/mcp-tools/transfer-tools.d.ts +14 -0
  400. package/dist/src/mcp-tools/transfer-tools.js +447 -0
  401. package/dist/src/mcp-tools/types.d.ts +8 -0
  402. package/dist/src/mcp-tools/types.js +8 -0
  403. package/dist/src/mcp-tools/validate-input.d.ts +9 -0
  404. package/dist/src/mcp-tools/validate-input.js +9 -0
  405. package/dist/src/mcp-tools/wasm-agent-tools.d.ts +13 -0
  406. package/dist/src/mcp-tools/wasm-agent-tools.js +840 -0
  407. package/dist/src/mcp-tools/workflow-tools.d.ts +8 -0
  408. package/dist/src/mcp-tools/workflow-tools.js +884 -0
  409. package/dist/src/memory/bge-embedder.d.ts +25 -0
  410. package/dist/src/memory/bge-embedder.js +121 -0
  411. package/dist/src/memory/cross-encoder-rerank.d.ts +33 -0
  412. package/dist/src/memory/cross-encoder-rerank.js +123 -0
  413. package/dist/src/memory/embedding-policy.d.ts +21 -0
  414. package/dist/src/memory/embedding-policy.js +30 -0
  415. package/dist/src/memory/embedding-quantization.d.ts +62 -0
  416. package/dist/src/memory/embedding-quantization.js +156 -0
  417. package/dist/src/memory/ewc-consolidation.d.ts +305 -0
  418. package/dist/src/memory/ewc-consolidation.js +611 -0
  419. package/dist/src/memory/graph-edge-writer.d.ts +95 -0
  420. package/dist/src/memory/graph-edge-writer.js +217 -0
  421. package/dist/src/memory/hybrid-retrieval.d.ts +77 -0
  422. package/dist/src/memory/hybrid-retrieval.js +192 -0
  423. package/dist/src/memory/intelligence.d.ts +405 -0
  424. package/dist/src/memory/intelligence.js +1316 -0
  425. package/dist/src/memory/lucene-bm25.d.ts +19 -0
  426. package/dist/src/memory/lucene-bm25.js +308 -0
  427. package/dist/src/memory/memory-bridge.d.ts +537 -0
  428. package/dist/src/memory/memory-bridge.js +2460 -0
  429. package/dist/src/memory/memory-initializer.d.ts +556 -0
  430. package/dist/src/memory/memory-initializer.js +3021 -0
  431. package/dist/src/memory/neural-package-bridge.d.ts +48 -0
  432. package/dist/src/memory/neural-package-bridge.js +87 -0
  433. package/dist/src/memory/rabitq-index.d.ts +60 -0
  434. package/dist/src/memory/rabitq-index.js +242 -0
  435. package/dist/src/memory/sona-optimizer.d.ts +267 -0
  436. package/dist/src/memory/sona-optimizer.js +779 -0
  437. package/dist/src/memory/structured-distill.d.ts +48 -0
  438. package/dist/src/memory/structured-distill.js +125 -0
  439. package/dist/src/output.d.ts +9 -0
  440. package/dist/src/output.js +9 -0
  441. package/dist/src/parser.d.ts +89 -0
  442. package/dist/src/parser.js +516 -0
  443. package/dist/src/plugins/manager.d.ts +133 -0
  444. package/dist/src/plugins/manager.js +415 -0
  445. package/dist/src/plugins/store/discovery.d.ts +99 -0
  446. package/dist/src/plugins/store/discovery.js +1224 -0
  447. package/dist/src/plugins/store/index.d.ts +76 -0
  448. package/dist/src/plugins/store/index.js +141 -0
  449. package/dist/src/plugins/store/search.d.ts +46 -0
  450. package/dist/src/plugins/store/search.js +230 -0
  451. package/dist/src/plugins/store/types.d.ts +279 -0
  452. package/dist/src/plugins/store/types.js +7 -0
  453. package/dist/src/plugins/tests/demo-plugin-store.d.ts +7 -0
  454. package/dist/src/plugins/tests/demo-plugin-store.js +126 -0
  455. package/dist/src/plugins/tests/standalone-test.d.ts +12 -0
  456. package/dist/src/plugins/tests/standalone-test.js +188 -0
  457. package/dist/src/plugins/tests/test-plugin-store.d.ts +7 -0
  458. package/dist/src/plugins/tests/test-plugin-store.js +206 -0
  459. package/dist/src/production/circuit-breaker.d.ts +101 -0
  460. package/dist/src/production/circuit-breaker.js +241 -0
  461. package/dist/src/production/error-handler.d.ts +92 -0
  462. package/dist/src/production/error-handler.js +299 -0
  463. package/dist/src/production/index.d.ts +23 -0
  464. package/dist/src/production/index.js +18 -0
  465. package/dist/src/production/monitoring.d.ts +161 -0
  466. package/dist/src/production/monitoring.js +356 -0
  467. package/dist/src/production/rate-limiter.d.ts +80 -0
  468. package/dist/src/production/rate-limiter.js +201 -0
  469. package/dist/src/production/retry.d.ts +48 -0
  470. package/dist/src/production/retry.js +179 -0
  471. package/dist/src/prompt.d.ts +44 -0
  472. package/dist/src/prompt.js +501 -0
  473. package/dist/src/proxy/install.d.ts +29 -0
  474. package/dist/src/proxy/install.js +135 -0
  475. package/dist/src/proxy/lifecycle.d.ts +61 -0
  476. package/dist/src/proxy/lifecycle.js +249 -0
  477. package/dist/src/proxy/paths.d.ts +34 -0
  478. package/dist/src/proxy/paths.js +70 -0
  479. package/dist/src/proxy/release.d.ts +47 -0
  480. package/dist/src/proxy/release.js +138 -0
  481. package/dist/src/proxy/token-bridge.d.ts +5 -0
  482. package/dist/src/proxy/token-bridge.js +61 -0
  483. package/dist/src/proxy/verify.d.ts +44 -0
  484. package/dist/src/proxy/verify.js +68 -0
  485. package/dist/src/runtime/headless.d.ts +60 -0
  486. package/dist/src/runtime/headless.js +284 -0
  487. package/dist/src/runtime/parent-death-watchdog.d.ts +42 -0
  488. package/dist/src/runtime/parent-death-watchdog.js +70 -0
  489. package/dist/src/ruvector/agent-wasm.d.ts +228 -0
  490. package/dist/src/ruvector/agent-wasm.js +463 -0
  491. package/dist/src/ruvector/ast-analyzer.d.ts +67 -0
  492. package/dist/src/ruvector/ast-analyzer.js +277 -0
  493. package/dist/src/ruvector/codemods/engine.d.ts +45 -0
  494. package/dist/src/ruvector/codemods/engine.js +291 -0
  495. package/dist/src/ruvector/codemods/scope-analysis.d.ts +29 -0
  496. package/dist/src/ruvector/codemods/scope-analysis.js +162 -0
  497. package/dist/src/ruvector/coverage-router.d.ts +160 -0
  498. package/dist/src/ruvector/coverage-router.js +531 -0
  499. package/dist/src/ruvector/coverage-tools.d.ts +33 -0
  500. package/dist/src/ruvector/coverage-tools.js +157 -0
  501. package/dist/src/ruvector/diff-classifier.d.ts +175 -0
  502. package/dist/src/ruvector/diff-classifier.js +699 -0
  503. package/dist/src/ruvector/diskann-backend.d.ts +78 -0
  504. package/dist/src/ruvector/diskann-backend.js +310 -0
  505. package/dist/src/ruvector/enhanced-model-router.d.ts +172 -0
  506. package/dist/src/ruvector/enhanced-model-router.js +577 -0
  507. package/dist/src/ruvector/graph-analyzer.d.ts +187 -0
  508. package/dist/src/ruvector/graph-analyzer.js +929 -0
  509. package/dist/src/ruvector/graph-backend.d.ts +79 -0
  510. package/dist/src/ruvector/graph-backend.js +220 -0
  511. package/dist/src/ruvector/index.d.ts +38 -0
  512. package/dist/src/ruvector/index.js +86 -0
  513. package/dist/src/ruvector/lora-adapter.d.ts +292 -0
  514. package/dist/src/ruvector/lora-adapter.js +710 -0
  515. package/dist/src/ruvector/model-prices.d.ts +50 -0
  516. package/dist/src/ruvector/model-prices.js +72 -0
  517. package/dist/src/ruvector/model-router.d.ts +408 -0
  518. package/dist/src/ruvector/model-router.js +1162 -0
  519. package/dist/src/ruvector/neural-router.d.ts +182 -0
  520. package/dist/src/ruvector/neural-router.js +825 -0
  521. package/dist/src/ruvector/output-verifier.d.ts +83 -0
  522. package/dist/src/ruvector/output-verifier.js +277 -0
  523. package/dist/src/ruvector/q-learning-router.d.ts +227 -0
  524. package/dist/src/ruvector/q-learning-router.js +721 -0
  525. package/dist/src/ruvector/router-calibrator.d.ts +65 -0
  526. package/dist/src/ruvector/router-calibrator.js +120 -0
  527. package/dist/src/ruvector/router-parallel-recorder.d.ts +127 -0
  528. package/dist/src/ruvector/router-parallel-recorder.js +183 -0
  529. package/dist/src/ruvector/router-trajectory.d.ts +194 -0
  530. package/dist/src/ruvector/router-trajectory.js +281 -0
  531. package/dist/src/ruvector/run-transcript-recorder.d.ts +154 -0
  532. package/dist/src/ruvector/run-transcript-recorder.js +209 -0
  533. package/dist/src/ruvector/ruvllm-wasm.d.ts +179 -0
  534. package/dist/src/ruvector/ruvllm-wasm.js +379 -0
  535. package/dist/src/ruvector/semantic-router.d.ts +77 -0
  536. package/dist/src/ruvector/semantic-router.js +178 -0
  537. package/dist/src/ruvector/task-embedder.d.ts +56 -0
  538. package/dist/src/ruvector/task-embedder.js +237 -0
  539. package/dist/src/ruvector/trajectory-tree.d.ts +113 -0
  540. package/dist/src/ruvector/trajectory-tree.js +237 -0
  541. package/dist/src/ruvector/vector-db.d.ts +73 -0
  542. package/dist/src/ruvector/vector-db.js +301 -0
  543. package/dist/src/ruvector/wasm-embedder.d.ts +13 -0
  544. package/dist/src/ruvector/wasm-embedder.js +143 -0
  545. package/dist/src/security/builtin-aidefence.d.ts +34 -0
  546. package/dist/src/security/builtin-aidefence.js +86 -0
  547. package/dist/src/services/agentic-flow-bridge.d.ts +50 -0
  548. package/dist/src/services/agentic-flow-bridge.js +95 -0
  549. package/dist/src/services/ai-job-dedup.d.ts +61 -0
  550. package/dist/src/services/ai-job-dedup.js +136 -0
  551. package/dist/src/services/checkpoint-gate.d.ts +140 -0
  552. package/dist/src/services/checkpoint-gate.js +223 -0
  553. package/dist/src/services/claim-service.d.ts +204 -0
  554. package/dist/src/services/claim-service.js +818 -0
  555. package/dist/src/services/config-file-manager.d.ts +37 -0
  556. package/dist/src/services/config-file-manager.js +224 -0
  557. package/dist/src/services/container-worker-pool.d.ts +204 -0
  558. package/dist/src/services/container-worker-pool.js +589 -0
  559. package/dist/src/services/daemon-autostart.d.ts +17 -0
  560. package/dist/src/services/daemon-autostart.js +102 -0
  561. package/dist/src/services/distill-oracle.d.ts +190 -0
  562. package/dist/src/services/distill-oracle.js +349 -0
  563. package/dist/src/services/distill-tuning.d.ts +111 -0
  564. package/dist/src/services/distill-tuning.js +510 -0
  565. package/dist/src/services/evolve-proof.d.ts +253 -0
  566. package/dist/src/services/evolve-proof.js +343 -0
  567. package/dist/src/services/fable-harness.d.ts +208 -0
  568. package/dist/src/services/fable-harness.js +388 -0
  569. package/dist/src/services/git-workspace-identity.d.ts +42 -0
  570. package/dist/src/services/git-workspace-identity.js +99 -0
  571. package/dist/src/services/global-ai-budget.d.ts +135 -0
  572. package/dist/src/services/global-ai-budget.js +415 -0
  573. package/dist/src/services/harness-benchmark.d.ts +68 -0
  574. package/dist/src/services/harness-benchmark.js +94 -0
  575. package/dist/src/services/harness-canary.d.ts +60 -0
  576. package/dist/src/services/harness-canary.js +69 -0
  577. package/dist/src/services/harness-corpus-harvester.d.ts +51 -0
  578. package/dist/src/services/harness-corpus-harvester.js +74 -0
  579. package/dist/src/services/harness-flywheel-generations.d.ts +115 -0
  580. package/dist/src/services/harness-flywheel-generations.js +360 -0
  581. package/dist/src/services/harness-flywheel-runtime.d.ts +25 -0
  582. package/dist/src/services/harness-flywheel-runtime.js +92 -0
  583. package/dist/src/services/harness-flywheel.d.ts +48 -0
  584. package/dist/src/services/harness-flywheel.js +207 -0
  585. package/dist/src/services/harness-frozen-eval.d.ts +22 -0
  586. package/dist/src/services/harness-frozen-eval.js +66 -0
  587. package/dist/src/services/harness-hosts.d.ts +40 -0
  588. package/dist/src/services/harness-hosts.js +88 -0
  589. package/dist/src/services/harness-improvement-ledger.d.ts +63 -0
  590. package/dist/src/services/harness-improvement-ledger.js +101 -0
  591. package/dist/src/services/harness-loop.d.ts +53 -0
  592. package/dist/src/services/harness-loop.js +85 -0
  593. package/dist/src/services/harness-qualification.d.ts +66 -0
  594. package/dist/src/services/harness-qualification.js +143 -0
  595. package/dist/src/services/harness-replay.d.ts +37 -0
  596. package/dist/src/services/harness-replay.js +92 -0
  597. package/dist/src/services/harness-verify.d.ts +33 -0
  598. package/dist/src/services/harness-verify.js +26 -0
  599. package/dist/src/services/harness-worker.d.ts +23 -0
  600. package/dist/src/services/harness-worker.js +66 -0
  601. package/dist/src/services/headless-worker-executor.d.ts +358 -0
  602. package/dist/src/services/headless-worker-executor.js +1269 -0
  603. package/dist/src/services/index.d.ts +13 -0
  604. package/dist/src/services/index.js +11 -0
  605. package/dist/src/services/memory-backup.d.ts +53 -0
  606. package/dist/src/services/memory-backup.js +198 -0
  607. package/dist/src/services/memory-distillation.d.ts +41 -0
  608. package/dist/src/services/memory-distillation.js +277 -0
  609. package/dist/src/services/native-training.d.ts +68 -0
  610. package/dist/src/services/native-training.js +141 -0
  611. package/dist/src/services/registry-api.d.ts +58 -0
  612. package/dist/src/services/registry-api.js +146 -0
  613. package/dist/src/services/repo-supervisor.d.ts +70 -0
  614. package/dist/src/services/repo-supervisor.js +228 -0
  615. package/dist/src/services/ruvector-training.d.ts +222 -0
  616. package/dist/src/services/ruvector-training.js +693 -0
  617. package/dist/src/services/swarm-memory-branches.d.ts +135 -0
  618. package/dist/src/services/swarm-memory-branches.js +213 -0
  619. package/dist/src/services/weight-eft.d.ts +305 -0
  620. package/dist/src/services/weight-eft.js +296 -0
  621. package/dist/src/services/worker-daemon.d.ts +439 -0
  622. package/dist/src/services/worker-daemon.js +1865 -0
  623. package/dist/src/services/worker-queue.d.ts +194 -0
  624. package/dist/src/services/worker-queue.js +513 -0
  625. package/dist/src/services/workspace-lease.d.ts +55 -0
  626. package/dist/src/services/workspace-lease.js +191 -0
  627. package/dist/src/suggest.d.ts +53 -0
  628. package/dist/src/suggest.js +200 -0
  629. package/dist/src/transfer/anonymization/index.d.ts +25 -0
  630. package/dist/src/transfer/anonymization/index.js +175 -0
  631. package/dist/src/transfer/deploy-seraphine.d.ts +13 -0
  632. package/dist/src/transfer/deploy-seraphine.js +205 -0
  633. package/dist/src/transfer/export.d.ts +25 -0
  634. package/dist/src/transfer/export.js +113 -0
  635. package/dist/src/transfer/index.d.ts +12 -0
  636. package/dist/src/transfer/index.js +31 -0
  637. package/dist/src/transfer/ipfs/client.d.ts +109 -0
  638. package/dist/src/transfer/ipfs/client.js +307 -0
  639. package/dist/src/transfer/ipfs/upload.d.ts +95 -0
  640. package/dist/src/transfer/ipfs/upload.js +413 -0
  641. package/dist/src/transfer/models/seraphine.d.ts +72 -0
  642. package/dist/src/transfer/models/seraphine.js +373 -0
  643. package/dist/src/transfer/serialization/cfp.d.ts +49 -0
  644. package/dist/src/transfer/serialization/cfp.js +183 -0
  645. package/dist/src/transfer/storage/gcs.d.ts +82 -0
  646. package/dist/src/transfer/storage/gcs.js +272 -0
  647. package/dist/src/transfer/storage/index.d.ts +6 -0
  648. package/dist/src/transfer/storage/index.js +6 -0
  649. package/dist/src/transfer/store/discovery.d.ts +84 -0
  650. package/dist/src/transfer/store/discovery.js +382 -0
  651. package/dist/src/transfer/store/download.d.ts +70 -0
  652. package/dist/src/transfer/store/download.js +334 -0
  653. package/dist/src/transfer/store/index.d.ts +84 -0
  654. package/dist/src/transfer/store/index.js +153 -0
  655. package/dist/src/transfer/store/publish.d.ts +76 -0
  656. package/dist/src/transfer/store/publish.js +294 -0
  657. package/dist/src/transfer/store/registry.d.ts +58 -0
  658. package/dist/src/transfer/store/registry.js +285 -0
  659. package/dist/src/transfer/store/search.d.ts +54 -0
  660. package/dist/src/transfer/store/search.js +232 -0
  661. package/dist/src/transfer/store/tests/standalone-test.d.ts +12 -0
  662. package/dist/src/transfer/store/tests/standalone-test.js +190 -0
  663. package/dist/src/transfer/store/types.d.ts +193 -0
  664. package/dist/src/transfer/store/types.js +6 -0
  665. package/dist/src/transfer/test-seraphine.d.ts +6 -0
  666. package/dist/src/transfer/test-seraphine.js +105 -0
  667. package/dist/src/transfer/tests/test-store.d.ts +7 -0
  668. package/dist/src/transfer/tests/test-store.js +214 -0
  669. package/dist/src/transfer/types.d.ts +245 -0
  670. package/dist/src/transfer/types.js +6 -0
  671. package/dist/src/types.d.ts +13 -0
  672. package/dist/src/types.js +13 -0
  673. package/dist/src/update/checker.d.ts +34 -0
  674. package/dist/src/update/checker.js +191 -0
  675. package/dist/src/update/executor.d.ts +33 -0
  676. package/dist/src/update/executor.js +217 -0
  677. package/dist/src/update/index.d.ts +33 -0
  678. package/dist/src/update/index.js +64 -0
  679. package/dist/src/update/rate-limiter.d.ts +20 -0
  680. package/dist/src/update/rate-limiter.js +96 -0
  681. package/dist/src/update/validator.d.ts +17 -0
  682. package/dist/src/update/validator.js +123 -0
  683. package/package.json +1 -1
@@ -0,0 +1,1269 @@
1
+ /**
2
+ * Headless Worker Executor
3
+ * Enables workers to invoke Claude Code in headless mode with configurable sandbox profiles.
4
+ *
5
+ * ADR-020: Headless Worker Integration Architecture
6
+ * - Integrates with CLAUDE_CODE_HEADLESS and CLAUDE_CODE_SANDBOX_MODE environment variables
7
+ * - Provides process pool for concurrent execution
8
+ * - Builds context from file glob patterns
9
+ * - Supports prompt templates and output parsing
10
+ * - Implements timeout and graceful error handling
11
+ *
12
+ * Key Features:
13
+ * - Process pool with configurable maxConcurrent
14
+ * - Context building from file glob patterns with caching
15
+ * - Prompt template system with context injection
16
+ * - Output parsing (text, json, markdown)
17
+ * - Timeout handling with graceful termination
18
+ * - Execution logging for debugging
19
+ * - Event emission for monitoring
20
+ */
21
+ import { spawn, execSync } from 'child_process';
22
+ import { EventEmitter } from 'events';
23
+ import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync } from 'fs';
24
+ import { join } from 'path';
25
+ import { getGlobalAiBudget, isQuotaErrorText } from './global-ai-budget.js';
26
+ import { resolveGitWorkspaceIdentity } from './git-workspace-identity.js';
27
+ import { getAiJobDedupRegistry, computeAiJobKey, hashWorkerConfig } from './ai-job-dedup.js';
28
+ // ============================================
29
+ // Constants
30
+ // ============================================
31
+ /**
32
+ * Array of headless worker types for runtime checking
33
+ */
34
+ export const HEADLESS_WORKER_TYPES = [
35
+ 'audit',
36
+ 'optimize',
37
+ 'testgaps',
38
+ 'document',
39
+ 'ultralearn',
40
+ 'refactor',
41
+ 'deepdive',
42
+ 'predict',
43
+ ];
44
+ /**
45
+ * Array of local worker types
46
+ */
47
+ export const LOCAL_WORKER_TYPES = [
48
+ 'map',
49
+ 'consolidate',
50
+ 'benchmark',
51
+ 'preload',
52
+ ];
53
+ /**
54
+ * Model ID mapping
55
+ */
56
+ /**
57
+ * Model ID mapping — use short aliases so they auto-resolve to the latest
58
+ * snapshot. Hardcoded dated IDs (e.g. claude-sonnet-4-5-20250929) go stale
59
+ * when Anthropic retires them, causing 100% worker failure (#1431).
60
+ *
61
+ * Users can override per-worker via the `model` field in daemon-state.json
62
+ * or the ANTHROPIC_MODEL environment variable.
63
+ */
64
+ const MODEL_IDS = {
65
+ sonnet: 'sonnet',
66
+ opus: 'opus',
67
+ haiku: 'haiku',
68
+ };
69
+ /**
70
+ * Default headless worker configurations based on ADR-020
71
+ */
72
+ export const HEADLESS_WORKER_CONFIGS = {
73
+ audit: {
74
+ type: 'audit',
75
+ mode: 'headless',
76
+ intervalMs: 30 * 60 * 1000,
77
+ priority: 'critical',
78
+ description: 'AI-powered security analysis',
79
+ enabled: true,
80
+ headless: {
81
+ promptTemplate: `Analyze this codebase for security vulnerabilities:
82
+ - Check for hardcoded secrets (API keys, passwords)
83
+ - Identify SQL injection risks
84
+ - Find XSS vulnerabilities
85
+ - Check for insecure dependencies
86
+ - Identify authentication/authorization issues
87
+
88
+ Provide a JSON report with:
89
+ {
90
+ "vulnerabilities": [{ "severity": "high|medium|low", "file": "...", "line": N, "description": "..." }],
91
+ "riskScore": 0-100,
92
+ "recommendations": ["..."]
93
+ }`,
94
+ sandbox: 'strict',
95
+ model: 'haiku',
96
+ outputFormat: 'json',
97
+ contextPatterns: ['**/*.ts', '**/*.js', '**/.env*', '**/package.json'],
98
+ timeoutMs: 5 * 60 * 1000,
99
+ },
100
+ },
101
+ optimize: {
102
+ type: 'optimize',
103
+ mode: 'headless',
104
+ intervalMs: 60 * 60 * 1000,
105
+ priority: 'high',
106
+ description: 'AI optimization suggestions',
107
+ enabled: true,
108
+ headless: {
109
+ promptTemplate: `Analyze this codebase for performance optimizations:
110
+ - Identify N+1 query patterns
111
+ - Find unnecessary re-renders in React
112
+ - Suggest caching opportunities
113
+ - Identify memory leaks
114
+ - Find redundant computations
115
+
116
+ Provide actionable suggestions with code examples.`,
117
+ sandbox: 'permissive',
118
+ model: 'sonnet',
119
+ outputFormat: 'markdown',
120
+ contextPatterns: ['src/**/*.ts', 'src/**/*.tsx'],
121
+ timeoutMs: 10 * 60 * 1000,
122
+ },
123
+ },
124
+ testgaps: {
125
+ type: 'testgaps',
126
+ mode: 'headless',
127
+ intervalMs: 60 * 60 * 1000,
128
+ priority: 'normal',
129
+ description: 'AI test gap analysis',
130
+ enabled: true,
131
+ headless: {
132
+ promptTemplate: `Analyze test coverage and identify gaps:
133
+ - Find untested functions and classes
134
+ - Identify edge cases not covered
135
+ - Suggest new test scenarios
136
+ - Check for missing error handling tests
137
+ - Identify integration test gaps
138
+
139
+ For each gap, provide a test skeleton.`,
140
+ sandbox: 'permissive',
141
+ model: 'sonnet',
142
+ outputFormat: 'markdown',
143
+ contextPatterns: ['src/**/*.ts', 'tests/**/*.ts', '__tests__/**/*.ts'],
144
+ timeoutMs: 10 * 60 * 1000,
145
+ },
146
+ },
147
+ document: {
148
+ type: 'document',
149
+ mode: 'headless',
150
+ intervalMs: 120 * 60 * 1000,
151
+ priority: 'low',
152
+ description: 'AI documentation generation',
153
+ enabled: false,
154
+ headless: {
155
+ promptTemplate: `Generate documentation for undocumented code:
156
+ - Add JSDoc comments to functions
157
+ - Create README sections for modules
158
+ - Document API endpoints
159
+ - Add inline comments for complex logic
160
+ - Generate usage examples
161
+
162
+ Focus on public APIs and exported functions.`,
163
+ sandbox: 'permissive',
164
+ model: 'haiku',
165
+ outputFormat: 'markdown',
166
+ contextPatterns: ['src/**/*.ts'],
167
+ timeoutMs: 10 * 60 * 1000,
168
+ },
169
+ },
170
+ ultralearn: {
171
+ type: 'ultralearn',
172
+ mode: 'headless',
173
+ intervalMs: 0, // Manual trigger only
174
+ priority: 'normal',
175
+ description: 'Deep knowledge acquisition',
176
+ enabled: false,
177
+ headless: {
178
+ promptTemplate: `Deeply analyze this codebase to learn:
179
+ - Architectural patterns used
180
+ - Coding conventions
181
+ - Domain-specific terminology
182
+ - Common patterns and idioms
183
+ - Team preferences
184
+
185
+ Provide insights as JSON:
186
+ {
187
+ "architecture": { "patterns": [...], "style": "..." },
188
+ "conventions": { "naming": "...", "formatting": "..." },
189
+ "domains": ["..."],
190
+ "insights": ["..."]
191
+ }`,
192
+ sandbox: 'strict',
193
+ model: 'opus',
194
+ outputFormat: 'json',
195
+ contextPatterns: ['**/*.ts', '**/CLAUDE.md', '**/README.md'],
196
+ timeoutMs: 15 * 60 * 1000,
197
+ },
198
+ },
199
+ refactor: {
200
+ type: 'refactor',
201
+ mode: 'headless',
202
+ intervalMs: 0, // Manual trigger only
203
+ priority: 'normal',
204
+ description: 'AI refactoring suggestions',
205
+ enabled: false,
206
+ headless: {
207
+ promptTemplate: `Suggest refactoring opportunities:
208
+ - Identify code duplication
209
+ - Suggest better abstractions
210
+ - Find opportunities for design patterns
211
+ - Identify overly complex functions
212
+ - Suggest module reorganization
213
+
214
+ Provide before/after code examples.`,
215
+ sandbox: 'permissive',
216
+ model: 'sonnet',
217
+ outputFormat: 'markdown',
218
+ contextPatterns: ['src/**/*.ts'],
219
+ timeoutMs: 10 * 60 * 1000,
220
+ },
221
+ },
222
+ deepdive: {
223
+ type: 'deepdive',
224
+ mode: 'headless',
225
+ intervalMs: 0, // Manual trigger only
226
+ priority: 'normal',
227
+ description: 'Deep code analysis',
228
+ enabled: false,
229
+ headless: {
230
+ promptTemplate: `Perform deep analysis of this codebase:
231
+ - Understand data flow
232
+ - Map dependencies
233
+ - Identify architectural issues
234
+ - Find potential bugs
235
+ - Analyze error handling
236
+
237
+ Provide comprehensive report.`,
238
+ sandbox: 'strict',
239
+ model: 'opus',
240
+ outputFormat: 'markdown',
241
+ contextPatterns: ['src/**/*.ts'],
242
+ timeoutMs: 15 * 60 * 1000,
243
+ },
244
+ },
245
+ predict: {
246
+ type: 'predict',
247
+ mode: 'headless',
248
+ intervalMs: 10 * 60 * 1000,
249
+ priority: 'low',
250
+ description: 'Predictive preloading',
251
+ enabled: false,
252
+ headless: {
253
+ promptTemplate: `Based on recent activity, predict what the developer needs:
254
+ - Files likely to be edited next
255
+ - Tests that should be run
256
+ - Documentation to reference
257
+ - Dependencies to check
258
+
259
+ Provide preload suggestions as JSON:
260
+ {
261
+ "filesToPreload": ["..."],
262
+ "testsToRun": ["..."],
263
+ "docsToReference": ["..."],
264
+ "confidence": 0.0-1.0
265
+ }`,
266
+ sandbox: 'strict',
267
+ model: 'haiku',
268
+ outputFormat: 'json',
269
+ contextPatterns: ['.claude-flow/metrics/*.json'],
270
+ timeoutMs: 2 * 60 * 1000,
271
+ },
272
+ },
273
+ };
274
+ /**
275
+ * Local worker configurations
276
+ */
277
+ export const LOCAL_WORKER_CONFIGS = {
278
+ map: {
279
+ type: 'map',
280
+ mode: 'local',
281
+ intervalMs: 15 * 60 * 1000,
282
+ priority: 'normal',
283
+ description: 'Codebase mapping',
284
+ enabled: true,
285
+ },
286
+ consolidate: {
287
+ type: 'consolidate',
288
+ mode: 'local',
289
+ intervalMs: 30 * 60 * 1000,
290
+ priority: 'low',
291
+ description: 'Memory consolidation',
292
+ enabled: true,
293
+ },
294
+ benchmark: {
295
+ type: 'benchmark',
296
+ mode: 'local',
297
+ intervalMs: 60 * 60 * 1000,
298
+ priority: 'low',
299
+ description: 'Performance benchmarking',
300
+ enabled: false,
301
+ },
302
+ preload: {
303
+ type: 'preload',
304
+ mode: 'local',
305
+ intervalMs: 5 * 60 * 1000,
306
+ priority: 'low',
307
+ description: 'Resource preloading',
308
+ enabled: false,
309
+ },
310
+ };
311
+ /**
312
+ * Combined worker configurations
313
+ */
314
+ export const ALL_WORKER_CONFIGS = [
315
+ ...Object.values(HEADLESS_WORKER_CONFIGS),
316
+ ...Object.values(LOCAL_WORKER_CONFIGS),
317
+ ];
318
+ // ============================================
319
+ // Utility Functions
320
+ // ============================================
321
+ /**
322
+ * Check if a worker type is a headless worker
323
+ */
324
+ export function isHeadlessWorker(type) {
325
+ return HEADLESS_WORKER_TYPES.includes(type);
326
+ }
327
+ /**
328
+ * Check if a worker type is a local worker
329
+ */
330
+ export function isLocalWorker(type) {
331
+ return LOCAL_WORKER_TYPES.includes(type);
332
+ }
333
+ /**
334
+ * Get model ID from model type
335
+ */
336
+ export function getModelId(model) {
337
+ return MODEL_IDS[model];
338
+ }
339
+ /**
340
+ * #2661 root-fix — best-effort parse of `claude --print --output-format
341
+ * json`'s response envelope. Deliberately lenient: probes a couple of
342
+ * plausible field-name shapes (the CLI's JSON schema is not a versioned
343
+ * public contract) and returns null on anything unexpected rather than
344
+ * throwing, so a schema mismatch degrades to "no usage captured" — the
345
+ * caller then falls back to the raw stdout text, exactly today's behavior.
346
+ * Exported for direct unit testing without spawning a real process.
347
+ */
348
+ export function parseClaudePrintJsonEnvelope(raw) {
349
+ const trimmed = raw.trim();
350
+ if (!trimmed || trimmed[0] !== '{')
351
+ return null;
352
+ let parsed;
353
+ try {
354
+ parsed = JSON.parse(trimmed);
355
+ }
356
+ catch {
357
+ return null;
358
+ }
359
+ if (!parsed || typeof parsed !== 'object')
360
+ return null;
361
+ const obj = parsed;
362
+ const result = typeof obj.result === 'string' ? obj.result : undefined;
363
+ if (result === undefined)
364
+ return null; // not the envelope shape we expect
365
+ const usage = (obj.usage && typeof obj.usage === 'object') ? obj.usage : undefined;
366
+ const numOrUndef = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
367
+ return {
368
+ result,
369
+ inputTokens: numOrUndef(usage?.input_tokens ?? usage?.inputTokens),
370
+ outputTokens: numOrUndef(usage?.output_tokens ?? usage?.outputTokens),
371
+ costUsd: numOrUndef(obj.total_cost_usd ?? obj.cost_usd ?? obj.totalCostUsd),
372
+ durationMs: numOrUndef(obj.duration_ms ?? obj.durationMs),
373
+ };
374
+ }
375
+ /**
376
+ * Get worker configuration by type
377
+ */
378
+ export function getWorkerConfig(type) {
379
+ if (isHeadlessWorker(type)) {
380
+ return HEADLESS_WORKER_CONFIGS[type];
381
+ }
382
+ if (isLocalWorker(type)) {
383
+ return LOCAL_WORKER_CONFIGS[type];
384
+ }
385
+ return undefined;
386
+ }
387
+ // ============================================
388
+ // HeadlessWorkerExecutor Class
389
+ // ============================================
390
+ /**
391
+ * HeadlessWorkerExecutor - Executes workers using Claude Code in headless mode
392
+ *
393
+ * Features:
394
+ * - Process pool with configurable concurrency limit
395
+ * - Pending queue for overflow requests
396
+ * - Context caching with configurable TTL
397
+ * - Execution logging for debugging
398
+ * - Event emission for monitoring
399
+ * - Graceful termination
400
+ */
401
+ export class HeadlessWorkerExecutor extends EventEmitter {
402
+ projectRoot;
403
+ config;
404
+ processPool = new Map();
405
+ pendingQueue = [];
406
+ contextCache = new Map();
407
+ claudeCodeAvailable = null;
408
+ claudeCodeVersion = null;
409
+ constructor(projectRoot, options) {
410
+ super();
411
+ this.projectRoot = projectRoot;
412
+ // Merge with defaults
413
+ this.config = {
414
+ maxConcurrent: options?.maxConcurrent ?? 2,
415
+ defaultTimeoutMs: options?.defaultTimeoutMs ?? 5 * 60 * 1000,
416
+ maxContextFiles: options?.maxContextFiles ?? 20,
417
+ maxCharsPerFile: options?.maxCharsPerFile ?? 5000,
418
+ logDir: options?.logDir ?? join(projectRoot, '.claude-flow', 'logs', 'headless'),
419
+ cacheContext: options?.cacheContext ?? true,
420
+ cacheTtlMs: options?.cacheTtlMs ?? 60000, // 1 minute default
421
+ };
422
+ // Ensure log directory exists
423
+ this.ensureLogDir();
424
+ }
425
+ // ============================================
426
+ // Public API
427
+ // ============================================
428
+ /**
429
+ * Check if Claude Code CLI is available.
430
+ *
431
+ * #2110 fix — three issues addressed:
432
+ * 1. Cache only `true`, never `false`. A transient failure (WSL2 cold
433
+ * start, AV scanner, slow shell init) used to set
434
+ * `claudeCodeAvailable = false` for the rest of the daemon
435
+ * lifetime, so the daemon kept running local stubs even after the
436
+ * user fixed `claude auth login`. Now: false results re-probe on
437
+ * the next call.
438
+ * 2. Log the actual error from the catch block instead of silently
439
+ * swallowing it. Operators couldn't distinguish timeout / ENOENT /
440
+ * auth-failure / exit-code without this.
441
+ * 3. Honour `CLAUDE_CODE_AVAILABILITY_TIMEOUT_MS` for WSL2 / slow
442
+ * systems where `claude --version` can take >5s on first invoke.
443
+ */
444
+ async isAvailable() {
445
+ // Only the `true` result is cached — `false` is re-probed every call
446
+ // so a transient failure doesn't poison the rest of the daemon's life.
447
+ if (this.claudeCodeAvailable === true) {
448
+ return true;
449
+ }
450
+ const timeoutMs = Number.parseInt(process.env.CLAUDE_CODE_AVAILABILITY_TIMEOUT_MS || '', 10) || 5000;
451
+ try {
452
+ const output = execSync('claude --version', {
453
+ encoding: 'utf-8',
454
+ stdio: 'pipe',
455
+ timeout: timeoutMs,
456
+ windowsHide: true, // Prevent phantom console windows on Windows
457
+ });
458
+ this.claudeCodeAvailable = true;
459
+ this.claudeCodeVersion = output.trim();
460
+ this.emit('status', { available: true, version: this.claudeCodeVersion });
461
+ return true;
462
+ }
463
+ catch (err) {
464
+ // Don't cache false — let the next call retry. Surface the actual
465
+ // error via emit so operators can diagnose timeout / ENOENT / auth.
466
+ this.claudeCodeAvailable = null;
467
+ const reason = err instanceof Error
468
+ ? `${err.name}: ${err.message}`.slice(0, 200)
469
+ : String(err).slice(0, 200);
470
+ this.emit('status', { available: false, reason });
471
+ return false;
472
+ }
473
+ }
474
+ /**
475
+ * Get Claude Code version
476
+ */
477
+ async getVersion() {
478
+ await this.isAvailable();
479
+ return this.claudeCodeVersion;
480
+ }
481
+ /**
482
+ * Execute a headless worker
483
+ */
484
+ async execute(workerType, configOverrides) {
485
+ const baseConfig = HEADLESS_WORKER_CONFIGS[workerType];
486
+ if (!baseConfig) {
487
+ throw new Error(`Unknown headless worker type: ${workerType}`);
488
+ }
489
+ // Check availability
490
+ const available = await this.isAvailable();
491
+ if (!available) {
492
+ const result = this.createErrorResult(workerType, 'Claude Code CLI not available. Install with: npm install -g @anthropic-ai/claude-code');
493
+ this.emit('error', result);
494
+ return result;
495
+ }
496
+ // Check concurrent limit
497
+ if (this.processPool.size >= this.config.maxConcurrent) {
498
+ // Queue the request
499
+ return new Promise((resolve, reject) => {
500
+ const entry = {
501
+ workerType,
502
+ config: configOverrides,
503
+ resolve,
504
+ reject,
505
+ queuedAt: new Date(),
506
+ };
507
+ this.pendingQueue.push(entry);
508
+ this.emit('queued', {
509
+ workerType,
510
+ queuePosition: this.pendingQueue.length,
511
+ });
512
+ });
513
+ }
514
+ // Execute immediately
515
+ return this.executeInternal(workerType, configOverrides);
516
+ }
517
+ /**
518
+ * Get pool status
519
+ */
520
+ /**
521
+ * #1855: return the PIDs of all currently-running headless worker
522
+ * children. Used by `WorkerDaemon` to snapshot active child PIDs to
523
+ * disk so the next lifetime can reap orphans after a hard crash.
524
+ */
525
+ getActiveChildPids() {
526
+ const out = [];
527
+ for (const entry of this.processPool.values()) {
528
+ const pid = entry.process?.pid;
529
+ if (typeof pid === 'number' && pid > 0)
530
+ out.push(pid);
531
+ }
532
+ return out;
533
+ }
534
+ getPoolStatus() {
535
+ const now = Date.now();
536
+ return {
537
+ activeCount: this.processPool.size,
538
+ queueLength: this.pendingQueue.length,
539
+ maxConcurrent: this.config.maxConcurrent,
540
+ activeWorkers: Array.from(this.processPool.values()).map((entry) => ({
541
+ executionId: entry.executionId,
542
+ workerType: entry.workerType,
543
+ startTime: entry.startTime,
544
+ elapsedMs: now - entry.startTime.getTime(),
545
+ })),
546
+ queuedWorkers: this.pendingQueue.map((entry) => ({
547
+ workerType: entry.workerType,
548
+ queuedAt: entry.queuedAt,
549
+ waitingMs: now - entry.queuedAt.getTime(),
550
+ })),
551
+ };
552
+ }
553
+ /**
554
+ * Get number of active executions
555
+ */
556
+ getActiveCount() {
557
+ return this.processPool.size;
558
+ }
559
+ /**
560
+ * #2661 — signal a pool entry's whole process group, not just the head.
561
+ * Children are spawned `detached: true` on POSIX precisely so their MCP
562
+ * bridge grandchildren can be reaped with `kill(-pid)`; a head-only kill
563
+ * orphans them (#2098B).
564
+ */
565
+ killEntryTree(proc, signal) {
566
+ if (process.platform !== 'win32' && typeof proc.pid === 'number') {
567
+ try {
568
+ process.kill(-proc.pid, signal);
569
+ return;
570
+ }
571
+ catch { /* fall through */ }
572
+ }
573
+ try {
574
+ proc.kill(signal);
575
+ }
576
+ catch { /* already dead */ }
577
+ }
578
+ /**
579
+ * Cancel a running execution
580
+ */
581
+ cancel(executionId) {
582
+ const entry = this.processPool.get(executionId);
583
+ if (!entry) {
584
+ return false;
585
+ }
586
+ clearTimeout(entry.timeout);
587
+ this.killEntryTree(entry.process, 'SIGTERM');
588
+ this.processPool.delete(executionId);
589
+ this.emit('cancelled', { executionId });
590
+ // Process next in queue
591
+ this.processQueue();
592
+ return true;
593
+ }
594
+ /**
595
+ * Cancel all running executions
596
+ */
597
+ cancelAll() {
598
+ let cancelled = 0;
599
+ // Cancel active processes (convert to array to avoid iterator issues)
600
+ const entries = Array.from(this.processPool.entries());
601
+ for (const [executionId, entry] of entries) {
602
+ clearTimeout(entry.timeout);
603
+ this.killEntryTree(entry.process, 'SIGTERM');
604
+ // SIGKILL fallback after 5s to prevent orphan processes (#1395 Bug 6)
605
+ setTimeout(() => {
606
+ try {
607
+ if (!entry.process.killed)
608
+ this.killEntryTree(entry.process, 'SIGKILL');
609
+ }
610
+ catch { /* already dead */ }
611
+ }, 5000).unref();
612
+ this.emit('cancelled', { executionId });
613
+ cancelled++;
614
+ }
615
+ this.processPool.clear();
616
+ // Reject pending queue
617
+ for (const entry of this.pendingQueue) {
618
+ entry.reject(new Error('Executor cancelled all executions'));
619
+ }
620
+ this.pendingQueue = [];
621
+ this.emit('allCancelled', { count: cancelled });
622
+ return cancelled;
623
+ }
624
+ /**
625
+ * Clear context cache
626
+ */
627
+ clearContextCache() {
628
+ this.contextCache.clear();
629
+ this.emit('cacheClear', {});
630
+ }
631
+ /**
632
+ * Get worker configuration
633
+ */
634
+ getConfig(workerType) {
635
+ return HEADLESS_WORKER_CONFIGS[workerType];
636
+ }
637
+ /**
638
+ * Get all headless worker types
639
+ */
640
+ getHeadlessWorkerTypes() {
641
+ return [...HEADLESS_WORKER_TYPES];
642
+ }
643
+ /**
644
+ * Get all local worker types
645
+ */
646
+ getLocalWorkerTypes() {
647
+ return [...LOCAL_WORKER_TYPES];
648
+ }
649
+ // ============================================
650
+ // Private Methods
651
+ // ============================================
652
+ /**
653
+ * Ensure log directory exists
654
+ */
655
+ ensureLogDir() {
656
+ try {
657
+ if (!existsSync(this.config.logDir)) {
658
+ mkdirSync(this.config.logDir, { recursive: true });
659
+ }
660
+ }
661
+ catch (error) {
662
+ this.emit('warning', { message: 'Failed to create log directory', error });
663
+ }
664
+ }
665
+ /**
666
+ * Internal execution logic
667
+ */
668
+ async executeInternal(workerType, configOverrides) {
669
+ const baseConfig = HEADLESS_WORKER_CONFIGS[workerType];
670
+ const headless = { ...baseConfig.headless, ...configOverrides };
671
+ const startTime = Date.now();
672
+ const executionId = `${workerType}_${startTime}_${Math.random().toString(36).slice(2, 8)}`;
673
+ // #2661 invariant 5 — cross-worktree job dedup. Worktrees of one
674
+ // repository at the same HEAD would otherwise run identical analyses
675
+ // once per worktree. jobKey = sha256(repositoryId, HEAD, worker,
676
+ // configHash); a success within the freshness window (the worker's own
677
+ // interval, floor 10 min) skips the launch entirely — no budget spend,
678
+ // no process. HEAD moves → new key → the job runs again.
679
+ const identity = resolveGitWorkspaceIdentity(this.projectRoot);
680
+ const jobKey = computeAiJobKey({
681
+ repositoryId: identity.repositoryId,
682
+ head: identity.head,
683
+ workerType,
684
+ configHash: hashWorkerConfig(headless),
685
+ });
686
+ const dedup = getAiJobDedupRegistry();
687
+ const envWindowSecs = Number.parseInt(process.env.RUFLO_AI_DEDUP_WINDOW_SECS || '', 10);
688
+ const freshnessMs = Number.isFinite(envWindowSecs) && envWindowSecs >= 0
689
+ ? envWindowSecs * 1000
690
+ : Math.max(baseConfig.intervalMs || 0, 10 * 60 * 1000);
691
+ const freshness = dedup.isFresh(jobKey, freshnessMs);
692
+ if (freshness.fresh) {
693
+ const skipped = {
694
+ success: true,
695
+ dedupSkipped: true,
696
+ output: '',
697
+ parsedOutput: undefined,
698
+ durationMs: 0,
699
+ model: 'none',
700
+ sandboxMode: headless.sandbox,
701
+ workerType,
702
+ timestamp: new Date(),
703
+ executionId,
704
+ };
705
+ this.logExecution(executionId, 'result', `dedup-skip: job ${jobKey.slice(0, 12)} succeeded ${Math.round((Date.now() - (freshness.lastRunAt ?? Date.now())) / 1000)}s ago (repo ${identity.repositoryId.slice(0, 12)}, head ${identity.head.slice(0, 12) || 'n/a'})`);
706
+ this.emit('dedup:skipped', { executionId, workerType, jobKey, lastRunAt: freshness.lastRunAt });
707
+ this.processQueue();
708
+ return skipped;
709
+ }
710
+ // #2661 — every autonomous launch must reserve a slot in the USER-GLOBAL
711
+ // AI budget before any process is created. This is the hard invariant
712
+ // that bounds aggregate launches across all worktree daemons: per-daemon
713
+ // maxConcurrent limits multiply with worktree count, the global budget
714
+ // does not. Denials return an error result (with a receipted reason)
715
+ // instead of queueing, so denied work never piles up into a retry storm.
716
+ const budget = getGlobalAiBudget();
717
+ const model = headless.model || 'sonnet';
718
+ const permit = await budget.reserve({ workerType, model, workspace: this.projectRoot });
719
+ if (!permit.allowed) {
720
+ const denied = this.createErrorResult(workerType, `Denied by global AI budget: ${permit.reason}`);
721
+ denied.executionId = executionId;
722
+ this.logExecution(executionId, 'error', `budget-denied: ${permit.reason}`);
723
+ // NOTE: deliberately no `emit('error', ...)` here — Node treats
724
+ // unlistened 'error' events as throws, and callers consume the
725
+ // returned error result; `budget:denied` is the observable signal.
726
+ this.emit('budget:denied', { executionId, workerType, reason: permit.reason });
727
+ this.processQueue();
728
+ return denied;
729
+ }
730
+ this.emit('start', { executionId, workerType, config: headless });
731
+ try {
732
+ // Build context from file patterns
733
+ const context = await this.buildContext(headless.contextPatterns || []);
734
+ // Build the full prompt
735
+ const fullPrompt = this.buildPrompt(headless.promptTemplate, context);
736
+ // Log prompt for debugging
737
+ this.logExecution(executionId, 'prompt', fullPrompt);
738
+ // Execute Claude Code headlessly
739
+ const result = await this.executeClaudeCode(fullPrompt, {
740
+ sandbox: headless.sandbox,
741
+ model: headless.model || 'sonnet',
742
+ timeoutMs: headless.timeoutMs || this.config.defaultTimeoutMs,
743
+ executionId,
744
+ workerType,
745
+ });
746
+ // Parse output based on format
747
+ let parsedOutput;
748
+ if (headless.outputFormat === 'json' && result.output) {
749
+ parsedOutput = this.parseJsonOutput(result.output);
750
+ }
751
+ else if (headless.outputFormat === 'markdown' && result.output) {
752
+ parsedOutput = this.parseMarkdownOutput(result.output);
753
+ }
754
+ const executionResult = {
755
+ success: result.success,
756
+ output: result.output,
757
+ parsedOutput,
758
+ durationMs: Date.now() - startTime,
759
+ tokensUsed: result.tokensUsed,
760
+ inputTokens: result.inputTokens,
761
+ outputTokens: result.outputTokens,
762
+ costUsd: result.costUsd,
763
+ model: headless.model || 'sonnet',
764
+ sandboxMode: headless.sandbox,
765
+ workerType,
766
+ timestamp: new Date(),
767
+ executionId,
768
+ error: result.error,
769
+ };
770
+ // Log result
771
+ this.logExecution(executionId, 'result', JSON.stringify(executionResult, null, 2));
772
+ // #2661 root-fix — structured per-launch telemetry, receipted
773
+ // regardless of success/failure (a failed launch still spent
774
+ // whatever tokens it spent before erroring).
775
+ budget.recordUsage(permit.permitId, {
776
+ workerType,
777
+ model,
778
+ inputTokens: result.inputTokens,
779
+ outputTokens: result.outputTokens,
780
+ durationMs: result.apiDurationMs ?? executionResult.durationMs,
781
+ costUsd: result.costUsd,
782
+ });
783
+ // #2661 invariant 5 — record the success so sibling worktrees at the
784
+ // same HEAD skip this job for the rest of the freshness window.
785
+ if (result.success) {
786
+ dedup.recordSuccess(jobKey, {
787
+ workerType,
788
+ repositoryId: identity.repositoryId,
789
+ workspace: this.projectRoot,
790
+ });
791
+ }
792
+ // #2661 — a quota/429/usage-limit failure opens the user-global
793
+ // circuit breaker so EVERY daemon stops launching for the cooldown
794
+ // window instead of retrying into an exhausted quota. Only inspected
795
+ // on failure: successful analysis output may legitimately discuss
796
+ // rate limiting in the user's own code.
797
+ if (!result.success && isQuotaErrorText(result.error)) {
798
+ await budget.recordQuotaError(`${workerType}: ${(result.error ?? '').slice(0, 200)}`);
799
+ }
800
+ this.emit('complete', executionResult);
801
+ return executionResult;
802
+ }
803
+ catch (error) {
804
+ const errorMessage = error instanceof Error ? error.message : String(error);
805
+ const executionResult = this.createErrorResult(workerType, errorMessage);
806
+ executionResult.executionId = executionId;
807
+ executionResult.durationMs = Date.now() - startTime;
808
+ this.logExecution(executionId, 'error', errorMessage);
809
+ if (isQuotaErrorText(errorMessage)) {
810
+ await budget.recordQuotaError(`${workerType}: ${errorMessage.slice(0, 200)}`);
811
+ }
812
+ this.emit('error', executionResult);
813
+ return executionResult;
814
+ }
815
+ finally {
816
+ // #2661 — free the global concurrency slot (launch counts persist).
817
+ await budget.release(permit.permitId);
818
+ // Process next in queue
819
+ this.processQueue();
820
+ }
821
+ }
822
+ /**
823
+ * Process the pending queue
824
+ */
825
+ processQueue() {
826
+ while (this.pendingQueue.length > 0 &&
827
+ this.processPool.size < this.config.maxConcurrent) {
828
+ const next = this.pendingQueue.shift();
829
+ if (!next)
830
+ break;
831
+ this.executeInternal(next.workerType, next.config)
832
+ .then(next.resolve)
833
+ .catch(next.reject);
834
+ }
835
+ }
836
+ /**
837
+ * Build context from file patterns
838
+ */
839
+ async buildContext(patterns) {
840
+ if (patterns.length === 0)
841
+ return '';
842
+ // Check cache
843
+ const cacheKey = patterns.sort().join('|');
844
+ if (this.config.cacheContext) {
845
+ const cached = this.contextCache.get(cacheKey);
846
+ if (cached && Date.now() - cached.timestamp < this.config.cacheTtlMs) {
847
+ return cached.content;
848
+ }
849
+ }
850
+ // Collect files matching patterns
851
+ const files = [];
852
+ for (const pattern of patterns) {
853
+ const matches = this.simpleGlob(pattern);
854
+ files.push(...matches);
855
+ }
856
+ // Deduplicate and limit
857
+ const uniqueFiles = Array.from(new Set(files)).slice(0, this.config.maxContextFiles);
858
+ // Build context
859
+ const contextParts = [];
860
+ for (const file of uniqueFiles) {
861
+ try {
862
+ const fullPath = join(this.projectRoot, file);
863
+ if (!existsSync(fullPath))
864
+ continue;
865
+ const content = readFileSync(fullPath, 'utf-8');
866
+ const truncated = content.slice(0, this.config.maxCharsPerFile);
867
+ const wasTruncated = content.length > this.config.maxCharsPerFile;
868
+ contextParts.push(`--- ${file}${wasTruncated ? ' (truncated)' : ''} ---\n${truncated}`);
869
+ }
870
+ catch {
871
+ // Skip unreadable files
872
+ }
873
+ }
874
+ const contextContent = contextParts.join('\n\n');
875
+ // Cache the result
876
+ if (this.config.cacheContext) {
877
+ this.contextCache.set(cacheKey, {
878
+ content: contextContent,
879
+ timestamp: Date.now(),
880
+ patterns,
881
+ });
882
+ }
883
+ return contextContent;
884
+ }
885
+ /**
886
+ * Simple glob implementation for file matching
887
+ */
888
+ simpleGlob(pattern) {
889
+ const results = [];
890
+ // Handle simple patterns (no wildcards)
891
+ if (!pattern.includes('*')) {
892
+ const fullPath = join(this.projectRoot, pattern);
893
+ if (existsSync(fullPath)) {
894
+ results.push(pattern);
895
+ }
896
+ return results;
897
+ }
898
+ // Parse pattern parts
899
+ const parts = pattern.split('/');
900
+ const scanDir = (dir, remainingParts) => {
901
+ if (remainingParts.length === 0)
902
+ return;
903
+ if (results.length >= 100)
904
+ return; // Limit results
905
+ try {
906
+ const fullDir = join(this.projectRoot, dir);
907
+ if (!existsSync(fullDir))
908
+ return;
909
+ const entries = readdirSync(fullDir, { withFileTypes: true });
910
+ const currentPart = remainingParts[0];
911
+ const isLastPart = remainingParts.length === 1;
912
+ for (const entry of entries) {
913
+ // Skip common non-code directories
914
+ if (entry.name === 'node_modules' ||
915
+ entry.name === '.git' ||
916
+ entry.name === 'dist' ||
917
+ entry.name === 'build' ||
918
+ entry.name === 'coverage' ||
919
+ entry.name === '.next' ||
920
+ entry.name === '.cache') {
921
+ continue;
922
+ }
923
+ const entryPath = dir ? `${dir}/${entry.name}` : entry.name;
924
+ if (currentPart === '**') {
925
+ // Recursive glob
926
+ if (entry.isDirectory()) {
927
+ scanDir(entryPath, remainingParts); // Continue with **
928
+ scanDir(entryPath, remainingParts.slice(1)); // Try next part
929
+ }
930
+ else if (entry.isFile() && remainingParts.length > 1) {
931
+ // Check if file matches next pattern part
932
+ const nextPart = remainingParts[1];
933
+ if (this.matchesPattern(entry.name, nextPart)) {
934
+ results.push(entryPath);
935
+ }
936
+ }
937
+ }
938
+ else if (this.matchesPattern(entry.name, currentPart)) {
939
+ if (isLastPart && entry.isFile()) {
940
+ results.push(entryPath);
941
+ }
942
+ else if (!isLastPart && entry.isDirectory()) {
943
+ scanDir(entryPath, remainingParts.slice(1));
944
+ }
945
+ }
946
+ }
947
+ }
948
+ catch {
949
+ // Skip unreadable directories
950
+ }
951
+ };
952
+ scanDir('', parts);
953
+ return results;
954
+ }
955
+ /**
956
+ * Match filename against a simple pattern
957
+ */
958
+ matchesPattern(name, pattern) {
959
+ if (pattern === '*')
960
+ return true;
961
+ if (pattern === '**')
962
+ return true;
963
+ // Handle *.ext patterns
964
+ if (pattern.startsWith('*.')) {
965
+ return name.endsWith(pattern.slice(1));
966
+ }
967
+ // Handle prefix* patterns
968
+ if (pattern.endsWith('*')) {
969
+ return name.startsWith(pattern.slice(0, -1));
970
+ }
971
+ // Handle *suffix patterns
972
+ if (pattern.startsWith('*')) {
973
+ return name.endsWith(pattern.slice(1));
974
+ }
975
+ // Exact match
976
+ return name === pattern;
977
+ }
978
+ /**
979
+ * Build full prompt with context
980
+ */
981
+ buildPrompt(template, context) {
982
+ if (!context) {
983
+ return `${template}
984
+
985
+ ## Instructions
986
+
987
+ Analyze the codebase and provide your response following the format specified in the task.`;
988
+ }
989
+ return `${template}
990
+
991
+ ## Codebase Context
992
+
993
+ ${context}
994
+
995
+ ## Instructions
996
+
997
+ Analyze the above codebase context and provide your response following the format specified in the task.`;
998
+ }
999
+ /**
1000
+ * Execute Claude Code in headless mode
1001
+ */
1002
+ executeClaudeCode(prompt, options) {
1003
+ return new Promise((resolve) => {
1004
+ const env = {
1005
+ ...process.env,
1006
+ CLAUDE_CODE_HEADLESS: 'true',
1007
+ CLAUDE_CODE_SANDBOX_MODE: options.sandbox,
1008
+ // Fix #1395 Bug 2: Workers fail inside active Claude Code session.
1009
+ // Claude Code detects nested sessions and exits immediately.
1010
+ // Setting CLAUDE_ENTRYPOINT=worker bypasses the nested-session check,
1011
+ // and unsetting CLAUDE_SESSION_ID prevents parent session detection.
1012
+ CLAUDE_ENTRYPOINT: 'worker',
1013
+ };
1014
+ // Remove parent session markers so the child doesn't detect a "nested" session
1015
+ delete env.CLAUDE_SESSION_ID;
1016
+ delete env.CLAUDE_PARENT_SESSION_ID;
1017
+ // Set model
1018
+ // Resolve model: user env override > config override > default alias
1019
+ env.ANTHROPIC_MODEL = process.env.ANTHROPIC_MODEL || MODEL_IDS[options.model];
1020
+ // Spawn claude CLI process. #1852: previously the prompt was passed
1021
+ // as a positional CLI arg. On Windows `claude` resolves to
1022
+ // `claude.cmd`, which Node refuses to exec directly (CVE-2024-27980
1023
+ // mitigation) — it routes through `cmd.exe /d /s /c`, which then
1024
+ // re-tokenizes the entire command line including the prompt.
1025
+ // Source-code prompts contain `>` `<` `&` `|` (arrow functions,
1026
+ // comparisons, redirections) — cmd.exe parses those as redirects
1027
+ // and creates zero-byte files in cwd named after the next token
1028
+ // (`controller.abort()`, `{const`, `0`, `HTTP`, etc.).
1029
+ //
1030
+ // Fix: pipe the prompt via stdin instead. `child.stdin.end(prompt)`
1031
+ // writes the prompt and closes stdin atomically — the EOF still
1032
+ // unblocks `claude --print` (the original concern in #1395) but no
1033
+ // shell tokenization touches the prompt.
1034
+ // #2098B / #2093 — `claude --print` can spawn grandchildren (MCP
1035
+ // server stdio bridges, plugin tools). When the head times out a
1036
+ // plain `child.kill()` only signals the head; grandchildren get
1037
+ // reparented to init and survive — the symptom @maxstefanakis1114
1038
+ // diagnosed as a 5-second redispatch + subprocess-table growth.
1039
+ // `detached: true` puts the child in its own process group so we
1040
+ // can signal the whole tree with `process.kill(-pid, sig)`.
1041
+ // #2661 root-fix — structured usage telemetry. `--output-format json`
1042
+ // wraps the response in an envelope carrying `result` (the actual
1043
+ // text — what `output` must still contain, unchanged for every
1044
+ // existing downstream parser) alongside `usage`/cost/duration
1045
+ // metadata. Parsing is lenient (parseClaudePrintJsonEnvelope below)
1046
+ // and ALWAYS falls back to the raw text on any mismatch — a schema
1047
+ // surprise from an older/newer `claude` CLI must degrade to exactly
1048
+ // today's behavior (no usage captured), never break analysis output.
1049
+ const child = spawn('claude', ['--print', '--output-format', 'json'], {
1050
+ cwd: this.projectRoot,
1051
+ env,
1052
+ stdio: ['pipe', 'pipe', 'pipe'],
1053
+ windowsHide: true, // Prevent phantom console windows on Windows
1054
+ detached: process.platform !== 'win32',
1055
+ });
1056
+ try {
1057
+ child.stdin?.end(prompt);
1058
+ }
1059
+ catch {
1060
+ // stdin already closed (e.g. spawn failed) — `error` handler below
1061
+ // will surface the real cause.
1062
+ }
1063
+ // Kill the whole process group on POSIX, fall back to the child on
1064
+ // Windows (where setsid-style detach isn't available the same way).
1065
+ const killTree = (signal) => {
1066
+ if (process.platform !== 'win32' && typeof child.pid === 'number') {
1067
+ try {
1068
+ process.kill(-child.pid, signal);
1069
+ return;
1070
+ }
1071
+ catch { /* fall through */ }
1072
+ }
1073
+ try {
1074
+ child.kill(signal);
1075
+ }
1076
+ catch { /* already dead */ }
1077
+ };
1078
+ // Setup timeout
1079
+ const timeoutHandle = setTimeout(() => {
1080
+ if (this.processPool.has(options.executionId)) {
1081
+ killTree('SIGTERM');
1082
+ // Give it a moment to terminate gracefully
1083
+ setTimeout(() => {
1084
+ if (!child.killed) {
1085
+ killTree('SIGKILL');
1086
+ }
1087
+ }, 5000);
1088
+ }
1089
+ }, options.timeoutMs);
1090
+ // Track in process pool
1091
+ const poolEntry = {
1092
+ process: child,
1093
+ executionId: options.executionId,
1094
+ workerType: options.workerType,
1095
+ startTime: new Date(),
1096
+ timeout: timeoutHandle,
1097
+ };
1098
+ this.processPool.set(options.executionId, poolEntry);
1099
+ let stdout = '';
1100
+ let stderr = '';
1101
+ let resolved = false;
1102
+ const cleanup = () => {
1103
+ clearTimeout(timeoutHandle);
1104
+ this.processPool.delete(options.executionId);
1105
+ };
1106
+ child.stdout?.on('data', (data) => {
1107
+ const chunk = data.toString();
1108
+ stdout += chunk;
1109
+ this.emit('output', {
1110
+ executionId: options.executionId,
1111
+ type: 'stdout',
1112
+ data: chunk,
1113
+ });
1114
+ });
1115
+ child.stderr?.on('data', (data) => {
1116
+ const chunk = data.toString();
1117
+ stderr += chunk;
1118
+ this.emit('output', {
1119
+ executionId: options.executionId,
1120
+ type: 'stderr',
1121
+ data: chunk,
1122
+ });
1123
+ });
1124
+ child.on('close', (code) => {
1125
+ if (resolved)
1126
+ return;
1127
+ resolved = true;
1128
+ cleanup();
1129
+ const envelope = parseClaudePrintJsonEnvelope(stdout);
1130
+ resolve({
1131
+ success: code === 0,
1132
+ output: envelope?.result ?? stdout ?? stderr,
1133
+ inputTokens: envelope?.inputTokens,
1134
+ outputTokens: envelope?.outputTokens,
1135
+ tokensUsed: envelope
1136
+ ? (envelope.inputTokens ?? 0) + (envelope.outputTokens ?? 0)
1137
+ : undefined,
1138
+ costUsd: envelope?.costUsd,
1139
+ apiDurationMs: envelope?.durationMs,
1140
+ error: code !== 0 ? stderr || `Process exited with code ${code}` : undefined,
1141
+ });
1142
+ });
1143
+ child.on('error', (error) => {
1144
+ if (resolved)
1145
+ return;
1146
+ resolved = true;
1147
+ cleanup();
1148
+ resolve({
1149
+ success: false,
1150
+ output: '',
1151
+ error: error.message,
1152
+ });
1153
+ });
1154
+ // Handle timeout
1155
+ setTimeout(() => {
1156
+ if (resolved)
1157
+ return;
1158
+ if (!this.processPool.has(options.executionId))
1159
+ return;
1160
+ resolved = true;
1161
+ killTree('SIGTERM');
1162
+ cleanup();
1163
+ resolve({
1164
+ success: false,
1165
+ output: stdout || stderr,
1166
+ error: `Execution timed out after ${options.timeoutMs}ms`,
1167
+ });
1168
+ }, options.timeoutMs + 100); // Slightly after the kill timeout
1169
+ });
1170
+ }
1171
+ /**
1172
+ * Parse JSON output from Claude Code
1173
+ */
1174
+ parseJsonOutput(output) {
1175
+ try {
1176
+ // Try to find JSON in code blocks first
1177
+ const codeBlockMatch = output.match(/```(?:json)?\s*([\s\S]*?)```/);
1178
+ if (codeBlockMatch) {
1179
+ return JSON.parse(codeBlockMatch[1].trim());
1180
+ }
1181
+ // Try to find any JSON object
1182
+ const jsonMatch = output.match(/\{[\s\S]*\}/);
1183
+ if (jsonMatch) {
1184
+ return JSON.parse(jsonMatch[0]);
1185
+ }
1186
+ // Try direct parse
1187
+ return JSON.parse(output.trim());
1188
+ }
1189
+ catch {
1190
+ return {
1191
+ parseError: true,
1192
+ rawOutput: output,
1193
+ };
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Parse markdown output into sections
1198
+ */
1199
+ parseMarkdownOutput(output) {
1200
+ const sections = [];
1201
+ const codeBlocks = [];
1202
+ // Extract code blocks first
1203
+ const codeBlockRegex = /```(\w*)\n([\s\S]*?)```/g;
1204
+ let codeMatch;
1205
+ while ((codeMatch = codeBlockRegex.exec(output)) !== null) {
1206
+ codeBlocks.push({
1207
+ language: codeMatch[1] || 'text',
1208
+ code: codeMatch[2].trim(),
1209
+ });
1210
+ }
1211
+ // Parse sections
1212
+ const lines = output.split('\n');
1213
+ let currentSection = null;
1214
+ for (const line of lines) {
1215
+ const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
1216
+ if (headerMatch) {
1217
+ if (currentSection) {
1218
+ sections.push(currentSection);
1219
+ }
1220
+ currentSection = {
1221
+ title: headerMatch[2].trim(),
1222
+ content: '',
1223
+ level: headerMatch[1].length,
1224
+ };
1225
+ }
1226
+ else if (currentSection) {
1227
+ currentSection.content += line + '\n';
1228
+ }
1229
+ }
1230
+ if (currentSection) {
1231
+ currentSection.content = currentSection.content.trim();
1232
+ sections.push(currentSection);
1233
+ }
1234
+ return { sections, codeBlocks };
1235
+ }
1236
+ /**
1237
+ * Create an error result
1238
+ */
1239
+ createErrorResult(workerType, error) {
1240
+ return {
1241
+ success: false,
1242
+ output: '',
1243
+ durationMs: 0,
1244
+ model: 'unknown',
1245
+ sandboxMode: 'strict',
1246
+ workerType,
1247
+ timestamp: new Date(),
1248
+ executionId: `error_${Date.now()}`,
1249
+ error,
1250
+ };
1251
+ }
1252
+ /**
1253
+ * Log execution details for debugging
1254
+ */
1255
+ logExecution(executionId, type, content) {
1256
+ try {
1257
+ const timestamp = new Date().toISOString();
1258
+ const logFile = join(this.config.logDir, `${executionId}_${type}.log`);
1259
+ const logContent = `[${timestamp}] ${type.toUpperCase()}\n${'='.repeat(60)}\n${content}\n`;
1260
+ writeFileSync(logFile, logContent);
1261
+ }
1262
+ catch {
1263
+ // Ignore log write errors
1264
+ }
1265
+ }
1266
+ }
1267
+ // Export default
1268
+ export default HeadlessWorkerExecutor;
1269
+ //# sourceMappingURL=headless-worker-executor.js.map