erosolar-cli 2.1.248 → 2.1.252

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 (470) hide show
  1. package/agents/general.rules.json +10 -133
  2. package/agents/general.rules.json.bak +278 -0
  3. package/agents/general.rules.json.bak2 +306 -0
  4. package/dist/bin/erosolar.js +9 -5
  5. package/dist/bin/erosolar.js.map +1 -1
  6. package/dist/capabilities/bidirectionalAuditCapability.d.ts +26 -0
  7. package/dist/capabilities/bidirectionalAuditCapability.d.ts.map +1 -0
  8. package/dist/capabilities/bidirectionalAuditCapability.js +44 -0
  9. package/dist/capabilities/bidirectionalAuditCapability.js.map +1 -0
  10. package/dist/capabilities/globCapability.d.ts +3 -6
  11. package/dist/capabilities/globCapability.d.ts.map +1 -1
  12. package/dist/capabilities/globCapability.js +6 -10
  13. package/dist/capabilities/globCapability.js.map +1 -1
  14. package/dist/capabilities/index.d.ts +1 -18
  15. package/dist/capabilities/index.d.ts.map +1 -1
  16. package/dist/capabilities/index.js +1 -18
  17. package/dist/capabilities/index.js.map +1 -1
  18. package/dist/capabilities/orchestrationCapability.d.ts +177 -3
  19. package/dist/capabilities/orchestrationCapability.d.ts.map +1 -1
  20. package/dist/capabilities/orchestrationCapability.js +1592 -85
  21. package/dist/capabilities/orchestrationCapability.js.map +1 -1
  22. package/dist/capabilities/searchCapability.d.ts +8 -2
  23. package/dist/capabilities/searchCapability.d.ts.map +1 -1
  24. package/dist/capabilities/searchCapability.js +11 -6
  25. package/dist/capabilities/searchCapability.js.map +1 -1
  26. package/dist/contracts/tools.schema.json +9 -133
  27. package/dist/core/agentOrchestrator.d.ts.map +1 -1
  28. package/dist/core/agentOrchestrator.js +18 -1
  29. package/dist/core/agentOrchestrator.js.map +1 -1
  30. package/dist/core/aiErrorFixer.d.ts +1 -14
  31. package/dist/core/aiErrorFixer.d.ts.map +1 -1
  32. package/dist/core/aiErrorFixer.js +51 -239
  33. package/dist/core/aiErrorFixer.js.map +1 -1
  34. package/dist/core/alphaZeroEngine.d.ts +16 -256
  35. package/dist/core/alphaZeroEngine.d.ts.map +1 -1
  36. package/dist/core/alphaZeroEngine.js +22 -513
  37. package/dist/core/alphaZeroEngine.js.map +1 -1
  38. package/dist/core/completeAttackOrchestrator.d.ts +102 -0
  39. package/dist/core/completeAttackOrchestrator.d.ts.map +1 -0
  40. package/dist/core/completeAttackOrchestrator.js +293 -0
  41. package/dist/core/completeAttackOrchestrator.js.map +1 -0
  42. package/dist/core/defensiveSecurityToolkit.d.ts +373 -0
  43. package/dist/core/defensiveSecurityToolkit.d.ts.map +1 -0
  44. package/dist/core/defensiveSecurityToolkit.js +1304 -0
  45. package/dist/core/defensiveSecurityToolkit.js.map +1 -0
  46. package/dist/core/errors/errorTypes.d.ts +30 -57
  47. package/dist/core/errors/errorTypes.d.ts.map +1 -1
  48. package/dist/core/errors/errorTypes.js +51 -228
  49. package/dist/core/errors/errorTypes.js.map +1 -1
  50. package/dist/core/errors/safetyValidator.d.ts +19 -3
  51. package/dist/core/errors/safetyValidator.d.ts.map +1 -1
  52. package/dist/core/errors/safetyValidator.js +33 -71
  53. package/dist/core/errors/safetyValidator.js.map +1 -1
  54. package/dist/core/failureRecovery.d.ts +4 -100
  55. package/dist/core/failureRecovery.d.ts.map +1 -1
  56. package/dist/core/failureRecovery.js +16 -440
  57. package/dist/core/failureRecovery.js.map +1 -1
  58. package/dist/core/intelligentTargetResearcher.d.ts +142 -0
  59. package/dist/core/intelligentTargetResearcher.d.ts.map +1 -0
  60. package/dist/core/intelligentTargetResearcher.js +367 -0
  61. package/dist/core/intelligentTargetResearcher.js.map +1 -0
  62. package/dist/core/intelligentTestFlows.d.ts +26 -107
  63. package/dist/core/intelligentTestFlows.d.ts.map +1 -1
  64. package/dist/core/intelligentTestFlows.js +15 -659
  65. package/dist/core/intelligentTestFlows.js.map +1 -1
  66. package/dist/core/learningPersistence.d.ts +45 -132
  67. package/dist/core/learningPersistence.d.ts.map +1 -1
  68. package/dist/core/learningPersistence.js +32 -463
  69. package/dist/core/learningPersistence.js.map +1 -1
  70. package/dist/core/metricsTracker.d.ts +22 -139
  71. package/dist/core/metricsTracker.d.ts.map +1 -1
  72. package/dist/core/metricsTracker.js +51 -241
  73. package/dist/core/metricsTracker.js.map +1 -1
  74. package/dist/core/performanceMonitor.d.ts +15 -109
  75. package/dist/core/performanceMonitor.d.ts.map +1 -1
  76. package/dist/core/performanceMonitor.js +27 -184
  77. package/dist/core/performanceMonitor.js.map +1 -1
  78. package/dist/core/resultVerification.d.ts +6 -100
  79. package/dist/core/resultVerification.d.ts.map +1 -1
  80. package/dist/core/resultVerification.js +31 -400
  81. package/dist/core/resultVerification.js.map +1 -1
  82. package/dist/core/selfEvolution.d.ts +32 -126
  83. package/dist/core/selfEvolution.d.ts.map +1 -1
  84. package/dist/core/selfEvolution.js +24 -967
  85. package/dist/core/selfEvolution.js.map +1 -1
  86. package/dist/core/selfImprovement.d.ts +50 -109
  87. package/dist/core/selfImprovement.d.ts.map +1 -1
  88. package/dist/core/selfImprovement.js +14 -689
  89. package/dist/core/selfImprovement.js.map +1 -1
  90. package/dist/core/sourceCodeManager.d.ts +89 -0
  91. package/dist/core/sourceCodeManager.d.ts.map +1 -0
  92. package/dist/core/sourceCodeManager.js +332 -0
  93. package/dist/core/sourceCodeManager.js.map +1 -0
  94. package/dist/core/unifiedOrchestrator.d.ts +88 -0
  95. package/dist/core/unifiedOrchestrator.d.ts.map +1 -0
  96. package/dist/core/unifiedOrchestrator.js +284 -0
  97. package/dist/core/unifiedOrchestrator.js.map +1 -0
  98. package/dist/core/userDefenseOrchestrator.d.ts +202 -0
  99. package/dist/core/userDefenseOrchestrator.d.ts.map +1 -0
  100. package/dist/core/userDefenseOrchestrator.js +1006 -0
  101. package/dist/core/userDefenseOrchestrator.js.map +1 -0
  102. package/dist/plugins/index.d.ts +1 -1
  103. package/dist/plugins/index.d.ts.map +1 -1
  104. package/dist/plugins/index.js +36 -26
  105. package/dist/plugins/index.js.map +1 -1
  106. package/dist/plugins/tools/bidirectionalAudit/bidirectionalAuditPlugin.d.ts +8 -0
  107. package/dist/plugins/tools/bidirectionalAudit/bidirectionalAuditPlugin.d.ts.map +1 -0
  108. package/dist/plugins/tools/bidirectionalAudit/bidirectionalAuditPlugin.js +17 -0
  109. package/dist/plugins/tools/bidirectionalAudit/bidirectionalAuditPlugin.js.map +1 -0
  110. package/dist/plugins/tools/nodeDefaults.d.ts +14 -0
  111. package/dist/plugins/tools/nodeDefaults.d.ts.map +1 -1
  112. package/dist/plugins/tools/nodeDefaults.js +17 -54
  113. package/dist/plugins/tools/nodeDefaults.js.map +1 -1
  114. package/dist/plugins/tools/orchestration/orchestrationPlugin.d.ts +9 -0
  115. package/dist/plugins/tools/orchestration/orchestrationPlugin.d.ts.map +1 -0
  116. package/dist/plugins/tools/orchestration/orchestrationPlugin.js +18 -0
  117. package/dist/plugins/tools/orchestration/orchestrationPlugin.js.map +1 -0
  118. package/dist/shell/interactiveShell.d.ts +101 -2
  119. package/dist/shell/interactiveShell.d.ts.map +1 -1
  120. package/dist/shell/interactiveShell.js +1041 -25
  121. package/dist/shell/interactiveShell.js.map +1 -1
  122. package/dist/tools/appleExposureTools.d.ts +108 -0
  123. package/dist/tools/appleExposureTools.d.ts.map +1 -0
  124. package/dist/tools/appleExposureTools.js +850 -0
  125. package/dist/tools/appleExposureTools.js.map +1 -0
  126. package/dist/tools/bidirectionalAuditTools.d.ts +104 -0
  127. package/dist/tools/bidirectionalAuditTools.d.ts.map +1 -0
  128. package/dist/tools/bidirectionalAuditTools.js +1280 -0
  129. package/dist/tools/bidirectionalAuditTools.js.map +1 -0
  130. package/dist/tools/defensiveSecurityTools.d.ts +152 -0
  131. package/dist/tools/defensiveSecurityTools.d.ts.map +1 -0
  132. package/dist/tools/defensiveSecurityTools.js +576 -0
  133. package/dist/tools/defensiveSecurityTools.js.map +1 -0
  134. package/dist/tools/forwardAttackChainTracer.d.ts +73 -0
  135. package/dist/tools/forwardAttackChainTracer.d.ts.map +1 -0
  136. package/dist/tools/forwardAttackChainTracer.js +604 -0
  137. package/dist/tools/forwardAttackChainTracer.js.map +1 -0
  138. package/dist/tools/localExplore.d.ts +12 -199
  139. package/dist/tools/localExplore.d.ts.map +1 -1
  140. package/dist/tools/localExplore.js +18 -1352
  141. package/dist/tools/localExplore.js.map +1 -1
  142. package/dist/tools/offensiveTransparencyTools.d.ts +188 -0
  143. package/dist/tools/offensiveTransparencyTools.d.ts.map +1 -0
  144. package/dist/tools/offensiveTransparencyTools.js +890 -0
  145. package/dist/tools/offensiveTransparencyTools.js.map +1 -0
  146. package/dist/tools/planningTools.d.ts +8 -17
  147. package/dist/tools/planningTools.d.ts.map +1 -1
  148. package/dist/tools/planningTools.js +31 -141
  149. package/dist/tools/planningTools.js.map +1 -1
  150. package/dist/tools/searchTools.d.ts +9 -0
  151. package/dist/tools/searchTools.d.ts.map +1 -1
  152. package/dist/tools/searchTools.js +305 -189
  153. package/dist/tools/searchTools.js.map +1 -1
  154. package/dist/tools/skillTools.d.ts +7 -5
  155. package/dist/tools/skillTools.d.ts.map +1 -1
  156. package/dist/tools/skillTools.js +13 -155
  157. package/dist/tools/skillTools.js.map +1 -1
  158. package/dist/tools/threatIntelligenceTools.d.ts +128 -0
  159. package/dist/tools/threatIntelligenceTools.d.ts.map +1 -0
  160. package/dist/tools/threatIntelligenceTools.js +712 -0
  161. package/dist/tools/threatIntelligenceTools.js.map +1 -0
  162. package/dist/ui/PromptController.d.ts +4 -0
  163. package/dist/ui/PromptController.d.ts.map +1 -1
  164. package/dist/ui/PromptController.js +32 -11
  165. package/dist/ui/PromptController.js.map +1 -1
  166. package/dist/ui/UnifiedUIRenderer.d.ts +36 -0
  167. package/dist/ui/UnifiedUIRenderer.d.ts.map +1 -1
  168. package/dist/ui/UnifiedUIRenderer.js +308 -43
  169. package/dist/ui/UnifiedUIRenderer.js.map +1 -1
  170. package/dist/ui/animatedStatus.d.ts +2 -0
  171. package/dist/ui/animatedStatus.d.ts.map +1 -1
  172. package/dist/ui/animatedStatus.js +36 -2
  173. package/dist/ui/animatedStatus.js.map +1 -1
  174. package/dist/ui/orchestration/StatusOrchestrator.d.ts +10 -0
  175. package/dist/ui/orchestration/StatusOrchestrator.d.ts.map +1 -1
  176. package/dist/ui/orchestration/StatusOrchestrator.js +36 -4
  177. package/dist/ui/orchestration/StatusOrchestrator.js.map +1 -1
  178. package/package.json +2 -2
  179. package/dist/capabilities/advancedTestGenerationCapability.d.ts +0 -17
  180. package/dist/capabilities/advancedTestGenerationCapability.d.ts.map +0 -1
  181. package/dist/capabilities/advancedTestGenerationCapability.js +0 -28
  182. package/dist/capabilities/advancedTestGenerationCapability.js.map +0 -1
  183. package/dist/capabilities/browserAutomationCapability.d.ts +0 -37
  184. package/dist/capabilities/browserAutomationCapability.d.ts.map +0 -1
  185. package/dist/capabilities/browserAutomationCapability.js +0 -49
  186. package/dist/capabilities/browserAutomationCapability.js.map +0 -1
  187. package/dist/capabilities/buildCapability.d.ts +0 -24
  188. package/dist/capabilities/buildCapability.d.ts.map +0 -1
  189. package/dist/capabilities/buildCapability.js +0 -25
  190. package/dist/capabilities/buildCapability.js.map +0 -1
  191. package/dist/capabilities/cloudCapability.d.ts +0 -13
  192. package/dist/capabilities/cloudCapability.d.ts.map +0 -1
  193. package/dist/capabilities/cloudCapability.js +0 -38
  194. package/dist/capabilities/cloudCapability.js.map +0 -1
  195. package/dist/capabilities/codeAnalysisCapability.d.ts +0 -13
  196. package/dist/capabilities/codeAnalysisCapability.d.ts.map +0 -1
  197. package/dist/capabilities/codeAnalysisCapability.js +0 -24
  198. package/dist/capabilities/codeAnalysisCapability.js.map +0 -1
  199. package/dist/capabilities/codeQualityCapability.d.ts +0 -13
  200. package/dist/capabilities/codeQualityCapability.d.ts.map +0 -1
  201. package/dist/capabilities/codeQualityCapability.js +0 -25
  202. package/dist/capabilities/codeQualityCapability.js.map +0 -1
  203. package/dist/capabilities/dependencySecurityCapability.d.ts +0 -13
  204. package/dist/capabilities/dependencySecurityCapability.d.ts.map +0 -1
  205. package/dist/capabilities/dependencySecurityCapability.js +0 -24
  206. package/dist/capabilities/dependencySecurityCapability.js.map +0 -1
  207. package/dist/capabilities/devCapability.d.ts +0 -13
  208. package/dist/capabilities/devCapability.d.ts.map +0 -1
  209. package/dist/capabilities/devCapability.js +0 -24
  210. package/dist/capabilities/devCapability.js.map +0 -1
  211. package/dist/capabilities/emailCapability.d.ts +0 -12
  212. package/dist/capabilities/emailCapability.d.ts.map +0 -1
  213. package/dist/capabilities/emailCapability.js +0 -22
  214. package/dist/capabilities/emailCapability.js.map +0 -1
  215. package/dist/capabilities/enhancedAnalysisCapability.d.ts +0 -13
  216. package/dist/capabilities/enhancedAnalysisCapability.d.ts.map +0 -1
  217. package/dist/capabilities/enhancedAnalysisCapability.js +0 -20
  218. package/dist/capabilities/enhancedAnalysisCapability.js.map +0 -1
  219. package/dist/capabilities/enhancedCodeIntelligenceCapability.d.ts +0 -17
  220. package/dist/capabilities/enhancedCodeIntelligenceCapability.d.ts.map +0 -1
  221. package/dist/capabilities/enhancedCodeIntelligenceCapability.js +0 -28
  222. package/dist/capabilities/enhancedCodeIntelligenceCapability.js.map +0 -1
  223. package/dist/capabilities/enhancedDevWorkflowCapability.d.ts +0 -17
  224. package/dist/capabilities/enhancedDevWorkflowCapability.d.ts.map +0 -1
  225. package/dist/capabilities/enhancedDevWorkflowCapability.js +0 -28
  226. package/dist/capabilities/enhancedDevWorkflowCapability.js.map +0 -1
  227. package/dist/capabilities/frontendTestingCapability.d.ts +0 -13
  228. package/dist/capabilities/frontendTestingCapability.d.ts.map +0 -1
  229. package/dist/capabilities/frontendTestingCapability.js +0 -28
  230. package/dist/capabilities/frontendTestingCapability.js.map +0 -1
  231. package/dist/capabilities/interactionCapability.d.ts +0 -12
  232. package/dist/capabilities/interactionCapability.d.ts.map +0 -1
  233. package/dist/capabilities/interactionCapability.js +0 -22
  234. package/dist/capabilities/interactionCapability.js.map +0 -1
  235. package/dist/capabilities/learnCapability.d.ts +0 -22
  236. package/dist/capabilities/learnCapability.d.ts.map +0 -1
  237. package/dist/capabilities/learnCapability.js +0 -37
  238. package/dist/capabilities/learnCapability.js.map +0 -1
  239. package/dist/capabilities/notebookCapability.d.ts +0 -17
  240. package/dist/capabilities/notebookCapability.d.ts.map +0 -1
  241. package/dist/capabilities/notebookCapability.js +0 -27
  242. package/dist/capabilities/notebookCapability.js.map +0 -1
  243. package/dist/capabilities/planningCapability.d.ts +0 -16
  244. package/dist/capabilities/planningCapability.d.ts.map +0 -1
  245. package/dist/capabilities/planningCapability.js +0 -26
  246. package/dist/capabilities/planningCapability.js.map +0 -1
  247. package/dist/capabilities/refactoringCapability.d.ts +0 -13
  248. package/dist/capabilities/refactoringCapability.d.ts.map +0 -1
  249. package/dist/capabilities/refactoringCapability.js +0 -25
  250. package/dist/capabilities/refactoringCapability.js.map +0 -1
  251. package/dist/capabilities/repoChecksCapability.d.ts +0 -10
  252. package/dist/capabilities/repoChecksCapability.d.ts.map +0 -1
  253. package/dist/capabilities/repoChecksCapability.js +0 -24
  254. package/dist/capabilities/repoChecksCapability.js.map +0 -1
  255. package/dist/capabilities/taskManagementCapability.d.ts +0 -12
  256. package/dist/capabilities/taskManagementCapability.d.ts.map +0 -1
  257. package/dist/capabilities/taskManagementCapability.js +0 -22
  258. package/dist/capabilities/taskManagementCapability.js.map +0 -1
  259. package/dist/capabilities/testingCapability.d.ts +0 -13
  260. package/dist/capabilities/testingCapability.d.ts.map +0 -1
  261. package/dist/capabilities/testingCapability.js +0 -25
  262. package/dist/capabilities/testingCapability.js.map +0 -1
  263. package/dist/capabilities/validationCapability.d.ts +0 -13
  264. package/dist/capabilities/validationCapability.d.ts.map +0 -1
  265. package/dist/capabilities/validationCapability.js +0 -24
  266. package/dist/capabilities/validationCapability.js.map +0 -1
  267. package/dist/capabilities/webCapability.d.ts +0 -12
  268. package/dist/capabilities/webCapability.d.ts.map +0 -1
  269. package/dist/capabilities/webCapability.js +0 -22
  270. package/dist/capabilities/webCapability.js.map +0 -1
  271. package/dist/core/deepBugAnalyzer.d.ts +0 -128
  272. package/dist/core/deepBugAnalyzer.d.ts.map +0 -1
  273. package/dist/core/deepBugAnalyzer.js +0 -406
  274. package/dist/core/deepBugAnalyzer.js.map +0 -1
  275. package/dist/core/hypothesisEngine.d.ts +0 -113
  276. package/dist/core/hypothesisEngine.d.ts.map +0 -1
  277. package/dist/core/hypothesisEngine.js +0 -264
  278. package/dist/core/hypothesisEngine.js.map +0 -1
  279. package/dist/core/productTestHarness.d.ts +0 -113
  280. package/dist/core/productTestHarness.d.ts.map +0 -1
  281. package/dist/core/productTestHarness.js +0 -351
  282. package/dist/core/productTestHarness.js.map +0 -1
  283. package/dist/core/validationRunner.d.ts +0 -106
  284. package/dist/core/validationRunner.d.ts.map +0 -1
  285. package/dist/core/validationRunner.js +0 -892
  286. package/dist/core/validationRunner.js.map +0 -1
  287. package/dist/plugins/tools/browser/browserAutomationPlugin.d.ts +0 -14
  288. package/dist/plugins/tools/browser/browserAutomationPlugin.d.ts.map +0 -1
  289. package/dist/plugins/tools/browser/browserAutomationPlugin.js +0 -26
  290. package/dist/plugins/tools/browser/browserAutomationPlugin.js.map +0 -1
  291. package/dist/plugins/tools/checks/localRepoChecksPlugin.d.ts +0 -3
  292. package/dist/plugins/tools/checks/localRepoChecksPlugin.d.ts.map +0 -1
  293. package/dist/plugins/tools/checks/localRepoChecksPlugin.js +0 -14
  294. package/dist/plugins/tools/checks/localRepoChecksPlugin.js.map +0 -1
  295. package/dist/plugins/tools/cloud/cloudPlugin.d.ts +0 -3
  296. package/dist/plugins/tools/cloud/cloudPlugin.d.ts.map +0 -1
  297. package/dist/plugins/tools/cloud/cloudPlugin.js +0 -14
  298. package/dist/plugins/tools/cloud/cloudPlugin.js.map +0 -1
  299. package/dist/plugins/tools/codeAnalysis/codeAnalysisPlugin.d.ts +0 -3
  300. package/dist/plugins/tools/codeAnalysis/codeAnalysisPlugin.d.ts.map +0 -1
  301. package/dist/plugins/tools/codeAnalysis/codeAnalysisPlugin.js +0 -14
  302. package/dist/plugins/tools/codeAnalysis/codeAnalysisPlugin.js.map +0 -1
  303. package/dist/plugins/tools/codeQuality/codeQualityPlugin.d.ts +0 -3
  304. package/dist/plugins/tools/codeQuality/codeQualityPlugin.d.ts.map +0 -1
  305. package/dist/plugins/tools/codeQuality/codeQualityPlugin.js +0 -14
  306. package/dist/plugins/tools/codeQuality/codeQualityPlugin.js.map +0 -1
  307. package/dist/plugins/tools/dependency/dependencyPlugin.d.ts +0 -3
  308. package/dist/plugins/tools/dependency/dependencyPlugin.d.ts.map +0 -1
  309. package/dist/plugins/tools/dependency/dependencyPlugin.js +0 -12
  310. package/dist/plugins/tools/dependency/dependencyPlugin.js.map +0 -1
  311. package/dist/plugins/tools/development/devPlugin.d.ts +0 -3
  312. package/dist/plugins/tools/development/devPlugin.d.ts.map +0 -1
  313. package/dist/plugins/tools/development/devPlugin.js +0 -14
  314. package/dist/plugins/tools/development/devPlugin.js.map +0 -1
  315. package/dist/plugins/tools/email/emailPlugin.d.ts +0 -3
  316. package/dist/plugins/tools/email/emailPlugin.d.ts.map +0 -1
  317. package/dist/plugins/tools/email/emailPlugin.js +0 -12
  318. package/dist/plugins/tools/email/emailPlugin.js.map +0 -1
  319. package/dist/plugins/tools/enhancedAnalysis/enhancedAnalysisPlugin.d.ts +0 -3
  320. package/dist/plugins/tools/enhancedAnalysis/enhancedAnalysisPlugin.d.ts.map +0 -1
  321. package/dist/plugins/tools/enhancedAnalysis/enhancedAnalysisPlugin.js +0 -14
  322. package/dist/plugins/tools/enhancedAnalysis/enhancedAnalysisPlugin.js.map +0 -1
  323. package/dist/plugins/tools/enhancedCodeIntelligence/enhancedCodeIntelligencePlugin.d.ts +0 -3
  324. package/dist/plugins/tools/enhancedCodeIntelligence/enhancedCodeIntelligencePlugin.d.ts.map +0 -1
  325. package/dist/plugins/tools/enhancedCodeIntelligence/enhancedCodeIntelligencePlugin.js +0 -12
  326. package/dist/plugins/tools/enhancedCodeIntelligence/enhancedCodeIntelligencePlugin.js.map +0 -1
  327. package/dist/plugins/tools/enhancedDevWorkflow/enhancedDevWorkflowPlugin.d.ts +0 -3
  328. package/dist/plugins/tools/enhancedDevWorkflow/enhancedDevWorkflowPlugin.d.ts.map +0 -1
  329. package/dist/plugins/tools/enhancedDevWorkflow/enhancedDevWorkflowPlugin.js +0 -12
  330. package/dist/plugins/tools/enhancedDevWorkflow/enhancedDevWorkflowPlugin.js.map +0 -1
  331. package/dist/plugins/tools/frontendTesting/frontendTestingPlugin.d.ts +0 -3
  332. package/dist/plugins/tools/frontendTesting/frontendTestingPlugin.d.ts.map +0 -1
  333. package/dist/plugins/tools/frontendTesting/frontendTestingPlugin.js +0 -14
  334. package/dist/plugins/tools/frontendTesting/frontendTestingPlugin.js.map +0 -1
  335. package/dist/plugins/tools/interaction/interactionPlugin.d.ts +0 -3
  336. package/dist/plugins/tools/interaction/interactionPlugin.d.ts.map +0 -1
  337. package/dist/plugins/tools/interaction/interactionPlugin.js +0 -12
  338. package/dist/plugins/tools/interaction/interactionPlugin.js.map +0 -1
  339. package/dist/plugins/tools/learn/learnPlugin.d.ts +0 -3
  340. package/dist/plugins/tools/learn/learnPlugin.d.ts.map +0 -1
  341. package/dist/plugins/tools/learn/learnPlugin.js +0 -14
  342. package/dist/plugins/tools/learn/learnPlugin.js.map +0 -1
  343. package/dist/plugins/tools/notebook/notebookPlugin.d.ts +0 -9
  344. package/dist/plugins/tools/notebook/notebookPlugin.d.ts.map +0 -1
  345. package/dist/plugins/tools/notebook/notebookPlugin.js +0 -15
  346. package/dist/plugins/tools/notebook/notebookPlugin.js.map +0 -1
  347. package/dist/plugins/tools/planning/planningPlugin.d.ts +0 -9
  348. package/dist/plugins/tools/planning/planningPlugin.d.ts.map +0 -1
  349. package/dist/plugins/tools/planning/planningPlugin.js +0 -15
  350. package/dist/plugins/tools/planning/planningPlugin.js.map +0 -1
  351. package/dist/plugins/tools/refactoring/refactoringPlugin.d.ts +0 -3
  352. package/dist/plugins/tools/refactoring/refactoringPlugin.d.ts.map +0 -1
  353. package/dist/plugins/tools/refactoring/refactoringPlugin.js +0 -12
  354. package/dist/plugins/tools/refactoring/refactoringPlugin.js.map +0 -1
  355. package/dist/plugins/tools/taskManagement/taskManagementPlugin.d.ts +0 -3
  356. package/dist/plugins/tools/taskManagement/taskManagementPlugin.d.ts.map +0 -1
  357. package/dist/plugins/tools/taskManagement/taskManagementPlugin.js +0 -12
  358. package/dist/plugins/tools/taskManagement/taskManagementPlugin.js.map +0 -1
  359. package/dist/plugins/tools/testing/testingPlugin.d.ts +0 -3
  360. package/dist/plugins/tools/testing/testingPlugin.d.ts.map +0 -1
  361. package/dist/plugins/tools/testing/testingPlugin.js +0 -12
  362. package/dist/plugins/tools/testing/testingPlugin.js.map +0 -1
  363. package/dist/plugins/tools/validation/validationPlugin.d.ts +0 -3
  364. package/dist/plugins/tools/validation/validationPlugin.d.ts.map +0 -1
  365. package/dist/plugins/tools/validation/validationPlugin.js +0 -14
  366. package/dist/plugins/tools/validation/validationPlugin.js.map +0 -1
  367. package/dist/plugins/tools/web/webPlugin.d.ts +0 -3
  368. package/dist/plugins/tools/web/webPlugin.d.ts.map +0 -1
  369. package/dist/plugins/tools/web/webPlugin.js +0 -12
  370. package/dist/plugins/tools/web/webPlugin.js.map +0 -1
  371. package/dist/tools/advancedTestGenerationTools.d.ts +0 -21
  372. package/dist/tools/advancedTestGenerationTools.d.ts.map +0 -1
  373. package/dist/tools/advancedTestGenerationTools.js +0 -304
  374. package/dist/tools/advancedTestGenerationTools.js.map +0 -1
  375. package/dist/tools/browserAutomationTools.d.ts +0 -23
  376. package/dist/tools/browserAutomationTools.d.ts.map +0 -1
  377. package/dist/tools/browserAutomationTools.js +0 -916
  378. package/dist/tools/browserAutomationTools.js.map +0 -1
  379. package/dist/tools/buildTools.d.ts +0 -9
  380. package/dist/tools/buildTools.d.ts.map +0 -1
  381. package/dist/tools/buildTools.js +0 -346
  382. package/dist/tools/buildTools.js.map +0 -1
  383. package/dist/tools/cloudTools.d.ts +0 -49
  384. package/dist/tools/cloudTools.d.ts.map +0 -1
  385. package/dist/tools/cloudTools.js +0 -1258
  386. package/dist/tools/cloudTools.js.map +0 -1
  387. package/dist/tools/codeAnalysisTools.d.ts +0 -74
  388. package/dist/tools/codeAnalysisTools.d.ts.map +0 -1
  389. package/dist/tools/codeAnalysisTools.js +0 -664
  390. package/dist/tools/codeAnalysisTools.js.map +0 -1
  391. package/dist/tools/codeGenerationTools.d.ts +0 -3
  392. package/dist/tools/codeGenerationTools.d.ts.map +0 -1
  393. package/dist/tools/codeGenerationTools.js +0 -439
  394. package/dist/tools/codeGenerationTools.js.map +0 -1
  395. package/dist/tools/codeQualityTools.d.ts +0 -3
  396. package/dist/tools/codeQualityTools.d.ts.map +0 -1
  397. package/dist/tools/codeQualityTools.js +0 -297
  398. package/dist/tools/codeQualityTools.js.map +0 -1
  399. package/dist/tools/dependencyTools.d.ts +0 -3
  400. package/dist/tools/dependencyTools.d.ts.map +0 -1
  401. package/dist/tools/dependencyTools.js +0 -284
  402. package/dist/tools/dependencyTools.js.map +0 -1
  403. package/dist/tools/devTools.d.ts +0 -10
  404. package/dist/tools/devTools.d.ts.map +0 -1
  405. package/dist/tools/devTools.js +0 -2126
  406. package/dist/tools/devTools.js.map +0 -1
  407. package/dist/tools/emailTools.d.ts +0 -21
  408. package/dist/tools/emailTools.d.ts.map +0 -1
  409. package/dist/tools/emailTools.js +0 -449
  410. package/dist/tools/emailTools.js.map +0 -1
  411. package/dist/tools/enhancedAnalysisTools.d.ts +0 -9
  412. package/dist/tools/enhancedAnalysisTools.d.ts.map +0 -1
  413. package/dist/tools/enhancedAnalysisTools.js +0 -370
  414. package/dist/tools/enhancedAnalysisTools.js.map +0 -1
  415. package/dist/tools/enhancedCodeIntelligenceTools.d.ts +0 -7
  416. package/dist/tools/enhancedCodeIntelligenceTools.d.ts.map +0 -1
  417. package/dist/tools/enhancedCodeIntelligenceTools.js +0 -540
  418. package/dist/tools/enhancedCodeIntelligenceTools.js.map +0 -1
  419. package/dist/tools/enhancedDevWorkflowTools.d.ts +0 -7
  420. package/dist/tools/enhancedDevWorkflowTools.d.ts.map +0 -1
  421. package/dist/tools/enhancedDevWorkflowTools.js +0 -432
  422. package/dist/tools/enhancedDevWorkflowTools.js.map +0 -1
  423. package/dist/tools/frontendTestingTools.d.ts +0 -35
  424. package/dist/tools/frontendTestingTools.d.ts.map +0 -1
  425. package/dist/tools/frontendTestingTools.js +0 -1258
  426. package/dist/tools/frontendTestingTools.js.map +0 -1
  427. package/dist/tools/globTools.d.ts +0 -15
  428. package/dist/tools/globTools.d.ts.map +0 -1
  429. package/dist/tools/globTools.js +0 -174
  430. package/dist/tools/globTools.js.map +0 -1
  431. package/dist/tools/grepTools.d.ts +0 -19
  432. package/dist/tools/grepTools.d.ts.map +0 -1
  433. package/dist/tools/grepTools.js +0 -411
  434. package/dist/tools/grepTools.js.map +0 -1
  435. package/dist/tools/interactionTools.d.ts +0 -6
  436. package/dist/tools/interactionTools.d.ts.map +0 -1
  437. package/dist/tools/interactionTools.js +0 -209
  438. package/dist/tools/interactionTools.js.map +0 -1
  439. package/dist/tools/learnTools.d.ts +0 -164
  440. package/dist/tools/learnTools.d.ts.map +0 -1
  441. package/dist/tools/learnTools.js +0 -2098
  442. package/dist/tools/learnTools.js.map +0 -1
  443. package/dist/tools/notebookEditTools.d.ts +0 -15
  444. package/dist/tools/notebookEditTools.d.ts.map +0 -1
  445. package/dist/tools/notebookEditTools.js +0 -197
  446. package/dist/tools/notebookEditTools.js.map +0 -1
  447. package/dist/tools/refactoringTools.d.ts +0 -3
  448. package/dist/tools/refactoringTools.d.ts.map +0 -1
  449. package/dist/tools/refactoringTools.js +0 -294
  450. package/dist/tools/refactoringTools.js.map +0 -1
  451. package/dist/tools/repoChecksTools.d.ts +0 -3
  452. package/dist/tools/repoChecksTools.d.ts.map +0 -1
  453. package/dist/tools/repoChecksTools.js +0 -276
  454. package/dist/tools/repoChecksTools.js.map +0 -1
  455. package/dist/tools/taskManagementTools.d.ts +0 -10
  456. package/dist/tools/taskManagementTools.d.ts.map +0 -1
  457. package/dist/tools/taskManagementTools.js +0 -133
  458. package/dist/tools/taskManagementTools.js.map +0 -1
  459. package/dist/tools/testingTools.d.ts +0 -3
  460. package/dist/tools/testingTools.d.ts.map +0 -1
  461. package/dist/tools/testingTools.js +0 -237
  462. package/dist/tools/testingTools.js.map +0 -1
  463. package/dist/tools/validationTools.d.ts +0 -7
  464. package/dist/tools/validationTools.d.ts.map +0 -1
  465. package/dist/tools/validationTools.js +0 -344
  466. package/dist/tools/validationTools.js.map +0 -1
  467. package/dist/tools/webTools.d.ts +0 -3
  468. package/dist/tools/webTools.d.ts.map +0 -1
  469. package/dist/tools/webTools.js +0 -502
  470. package/dist/tools/webTools.js.map +0 -1
@@ -5,14 +5,598 @@
5
5
  * - Government procedures (law enforcement, compliance)
6
6
  * - Infrastructure deployment (US, Ukraine, EU, Asia)
7
7
  * - Security deliverables (pentest reports, incident response)
8
- * - APT chain execution (kill-chain phases)
9
- * - Dual-RL refinement (self-improving execution)
8
+ * - Validation & error analysis (TypeScript, build, test, lint)
9
+ * - Hypothesis testing & failure recovery
10
+ * - Result verification (prevents hallucinated success)
10
11
  */
12
+ // ============================================================================
13
+ // TYPES - Error Analysis & Validation (from aiErrorFixer.ts, validationRunner.ts)
14
+ // ============================================================================
15
+ export var ErrorType;
16
+ (function (ErrorType) {
17
+ ErrorType["BUILD_ERROR"] = "build_error";
18
+ ErrorType["TEST_FAILURE"] = "test_failure";
19
+ ErrorType["TYPE_ERROR"] = "type_error";
20
+ ErrorType["LINT_ERROR"] = "lint_error";
21
+ ErrorType["IMPORT_ERROR"] = "import_error";
22
+ ErrorType["SYNTAX_ERROR"] = "syntax_error";
23
+ ErrorType["FILE_NOT_FOUND"] = "file_not_found";
24
+ ErrorType["PERMISSION_ERROR"] = "permission_error";
25
+ ErrorType["EDIT_CONFLICT"] = "edit_conflict";
26
+ ErrorType["NEWLINE_IN_STRING"] = "newline_in_string";
27
+ ErrorType["UNKNOWN"] = "unknown";
28
+ })(ErrorType || (ErrorType = {}));
29
+ // ============================================================================
30
+ // ERROR PATTERNS
31
+ // ============================================================================
32
+ const TS_ERROR_PATTERN = /([^\s:]+\.tsx?):(\d+):(\d+)\s*-\s*error\s+TS(\d+):\s*(.+)/gm;
33
+ const NPM_DEP_PATTERN = /(?:Cannot find|Module not found).*['"]([^'"]+)['"]/gm;
34
+ const TEST_FAIL_PATTERN = /FAIL\s+([^\n]+)/gm;
35
+ const FAILURE_INDICATORS = {
36
+ build: [/error\s+TS\d+/i, /SyntaxError/i, /Cannot find module/i, /error:\s+/i, /failed with exit code/i, /npm ERR!/i],
37
+ test: [/FAIL\s+/, /AssertionError/i, /Expected.*but got/i, /\d+ failing/i, /Error: expect/i],
38
+ runtime: [/TypeError:/i, /ReferenceError:/i, /RangeError:/i, /Uncaught/i, /ENOENT/i, /EACCES/i, /ETIMEDOUT/i],
39
+ userFeedback: [/doesn't work/i, /didn't work/i, /not working/i, /still broken/i, /wrong/i, /incorrect/i, /try again/i, /failed/i],
40
+ };
41
+ const OUTPUT_PATTERNS = {
42
+ git: {
43
+ success: [/\[.+\s+\w+\]/, /pushed/i, /merged/i, /On branch/i, /nothing to commit/i, /Already up to date/i],
44
+ failure: [/fatal:/i, /error:/i, /conflict/i, /rejected/i, /CONFLICT/, /Aborting/i],
45
+ },
46
+ npm: {
47
+ success: [/npm notice/i, /\+ .+@\d+\.\d+\.\d+/, /published/i],
48
+ failure: [/npm ERR!/i, /ERESOLVE/i, /E404/i, /EINTEGRITY/i],
49
+ },
50
+ command: {
51
+ success: [/^(success|completed|done|finished)/im, /successfully/i],
52
+ failure: [/^error/im, /^fatal/im, /failed/i, /command not found/i, /permission denied/i, /ENOENT/i, /EACCES/i],
53
+ },
54
+ };
55
+ // ============================================================================
56
+ // ERROR ANALYSIS CLASS (from aiErrorFixer.ts)
57
+ // ============================================================================
58
+ class ErrorAnalyzer {
59
+ analyzeOutput(output, command) {
60
+ const errors = [];
61
+ const outputType = this.detectOutputType(output, command);
62
+ if (outputType === 'typescript')
63
+ errors.push(...this.parseTypeScriptErrors(output));
64
+ else if (outputType === 'npm')
65
+ errors.push(...this.parseNpmErrors(output));
66
+ else if (outputType === 'test')
67
+ errors.push(...this.parseTestErrors(output));
68
+ else
69
+ errors.push(...this.parseGenericErrors(output));
70
+ for (const error of errors) {
71
+ error.suggestedFixes = this.generateFixes(error);
72
+ }
73
+ return errors;
74
+ }
75
+ formatForAI(errors) {
76
+ if (errors.length === 0)
77
+ return '';
78
+ const lines = ['', '═══ AI ERROR ANALYSIS ═══', ''];
79
+ for (let i = 0; i < Math.min(errors.length, 5); i++) {
80
+ const error = errors[i];
81
+ if (!error)
82
+ continue;
83
+ lines.push(`• ${error.errorType.toUpperCase()}: ${error.message.slice(0, 150)}`);
84
+ const loc = error.locations[0];
85
+ if (loc)
86
+ lines.push(` at ${loc.filePath}:${loc.lineNumber ?? '?'}`);
87
+ const bestFix = error.suggestedFixes[0];
88
+ if (bestFix)
89
+ lines.push(` FIX: ${bestFix.description}`);
90
+ lines.push('');
91
+ }
92
+ if (errors.length > 5)
93
+ lines.push(`... and ${errors.length - 5} more errors`);
94
+ return lines.join('\n');
95
+ }
96
+ detectOutputType(output, command) {
97
+ const outputLower = output.toLowerCase();
98
+ const commandLower = (command ?? '').toLowerCase();
99
+ if (commandLower.includes('tsc') || commandLower.includes('typescript'))
100
+ return 'typescript';
101
+ if (commandLower.includes('test') || commandLower.includes('jest'))
102
+ return 'test';
103
+ if (commandLower.includes('npm') || commandLower.includes('yarn'))
104
+ return 'npm';
105
+ if (outputLower.includes('error ts') || output.includes('.ts:'))
106
+ return 'typescript';
107
+ if (outputLower.includes('npm err!'))
108
+ return 'npm';
109
+ return 'generic';
110
+ }
111
+ parseTypeScriptErrors(output) {
112
+ const errors = [];
113
+ const regex = new RegExp(TS_ERROR_PATTERN.source, 'gm');
114
+ let match;
115
+ while ((match = regex.exec(output)) !== null) {
116
+ const [, file, line, col, code, msg] = match;
117
+ if (!file || !code || !msg)
118
+ continue;
119
+ errors.push({
120
+ errorType: ErrorType.TYPE_ERROR,
121
+ message: `TS${code}: ${msg}`,
122
+ rawOutput: match[0],
123
+ locations: [{ filePath: file, lineNumber: line ? parseInt(line, 10) : undefined, column: col ? parseInt(col, 10) : undefined }],
124
+ suggestedFixes: [],
125
+ relatedErrors: [],
126
+ metadata: { tsCode: code },
127
+ });
128
+ }
129
+ return errors;
130
+ }
131
+ parseNpmErrors(output) {
132
+ const errors = [];
133
+ const regex = new RegExp(NPM_DEP_PATTERN.source, 'gm');
134
+ let match;
135
+ while ((match = regex.exec(output)) !== null) {
136
+ const [, dep] = match;
137
+ if (!dep)
138
+ continue;
139
+ errors.push({
140
+ errorType: ErrorType.IMPORT_ERROR,
141
+ message: `Missing dependency: ${dep}`,
142
+ rawOutput: match[0],
143
+ locations: [],
144
+ suggestedFixes: [],
145
+ relatedErrors: [],
146
+ metadata: { missingDep: dep },
147
+ });
148
+ }
149
+ return errors;
150
+ }
151
+ parseTestErrors(output) {
152
+ const errors = [];
153
+ const regex = new RegExp(TEST_FAIL_PATTERN.source, 'gm');
154
+ let match;
155
+ while ((match = regex.exec(output)) !== null) {
156
+ const [, file] = match;
157
+ if (!file)
158
+ continue;
159
+ errors.push({
160
+ errorType: ErrorType.TEST_FAILURE,
161
+ message: `Test failed: ${file}`,
162
+ rawOutput: match[0],
163
+ locations: [{ filePath: file.trim() }],
164
+ suggestedFixes: [],
165
+ relatedErrors: [],
166
+ metadata: {},
167
+ });
168
+ }
169
+ return errors;
170
+ }
171
+ parseGenericErrors(output) {
172
+ const errors = [];
173
+ const errorLines = [];
174
+ for (const line of output.split('\n')) {
175
+ const lineLower = line.toLowerCase();
176
+ if (lineLower.includes('error:') || lineLower.includes('failed:') || lineLower.includes('exception:') || lineLower.includes('fatal:')) {
177
+ errorLines.push(line.trim());
178
+ }
179
+ }
180
+ if (errorLines.length > 0 && errorLines[0]) {
181
+ errors.push({
182
+ errorType: ErrorType.UNKNOWN,
183
+ message: errorLines[0].slice(0, 200),
184
+ rawOutput: errorLines.slice(0, 5).join('\n'),
185
+ locations: [],
186
+ suggestedFixes: [],
187
+ relatedErrors: errorLines.slice(1, 5),
188
+ metadata: {},
189
+ });
190
+ }
191
+ return errors;
192
+ }
193
+ generateFixes(error) {
194
+ const fixes = [];
195
+ const loc = error.locations[0];
196
+ if (error.errorType === ErrorType.TYPE_ERROR && loc) {
197
+ const tsCode = String(error.metadata['tsCode'] ?? '');
198
+ if (tsCode === '2304') {
199
+ const nameMatch = error.message.match(/Cannot find name '([^']+)'/);
200
+ if (nameMatch?.[1]) {
201
+ fixes.push({
202
+ description: `Add import for '${nameMatch[1]}'`,
203
+ filePath: loc.filePath,
204
+ oldContent: '',
205
+ newContent: `import { ${nameMatch[1]} } from './${nameMatch[1]}';`,
206
+ confidence: 0.6,
207
+ autoApplicable: false,
208
+ requiresConfirmation: true,
209
+ });
210
+ }
211
+ }
212
+ if (tsCode === '6133') {
213
+ const varMatch = error.message.match(/'([^']+)' is declared but/);
214
+ if (varMatch?.[1]) {
215
+ fixes.push({
216
+ description: `Prefix '${varMatch[1]}' with underscore`,
217
+ filePath: loc.filePath,
218
+ oldContent: varMatch[1],
219
+ newContent: `_${varMatch[1]}`,
220
+ confidence: 0.8,
221
+ autoApplicable: true,
222
+ requiresConfirmation: false,
223
+ });
224
+ }
225
+ }
226
+ }
227
+ if (error.errorType === ErrorType.IMPORT_ERROR) {
228
+ const missingDep = String(error.metadata['missingDep'] ?? '');
229
+ if (missingDep) {
230
+ fixes.push({
231
+ description: `Install: npm install ${missingDep}`,
232
+ filePath: 'package.json',
233
+ oldContent: '',
234
+ newContent: '',
235
+ confidence: 0.9,
236
+ autoApplicable: false,
237
+ requiresConfirmation: true,
238
+ });
239
+ }
240
+ }
241
+ return fixes;
242
+ }
243
+ }
244
+ // ============================================================================
245
+ // HYPOTHESIS ENGINE (from hypothesisEngine.ts)
246
+ // ============================================================================
247
+ class HypothesisEngine {
248
+ hypotheses = new Map();
249
+ maxHypotheses;
250
+ constructor(maxHypotheses = 5) {
251
+ this.maxHypotheses = maxHypotheses;
252
+ }
253
+ generateHypothesis(description, initialEvidence = []) {
254
+ const id = `hyp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
255
+ const hypothesis = {
256
+ id,
257
+ description,
258
+ confidence: this.calculateConfidence(initialEvidence),
259
+ evidence: initialEvidence,
260
+ status: 'pending',
261
+ };
262
+ this.hypotheses.set(id, hypothesis);
263
+ this.pruneHypotheses();
264
+ return hypothesis;
265
+ }
266
+ addEvidence(hypothesisId, evidence) {
267
+ const hypothesis = this.hypotheses.get(hypothesisId);
268
+ if (!hypothesis)
269
+ throw new Error(`Hypothesis ${hypothesisId} not found`);
270
+ hypothesis.evidence.push(evidence);
271
+ hypothesis.confidence = this.calculateConfidence(hypothesis.evidence);
272
+ }
273
+ getBestHypothesis() {
274
+ let best = null;
275
+ let highestConfidence = -Infinity;
276
+ for (const hypothesis of this.hypotheses.values()) {
277
+ if (hypothesis.status !== 'rejected' && hypothesis.confidence > highestConfidence) {
278
+ highestConfidence = hypothesis.confidence;
279
+ best = hypothesis;
280
+ }
281
+ }
282
+ return best;
283
+ }
284
+ getAllHypotheses() {
285
+ return Array.from(this.hypotheses.values()).sort((a, b) => b.confidence - a.confidence);
286
+ }
287
+ clear() {
288
+ this.hypotheses.clear();
289
+ }
290
+ calculateConfidence(evidence) {
291
+ if (evidence.length === 0)
292
+ return 0.5;
293
+ const totalWeight = evidence.reduce((sum, e) => sum + Math.abs(e.weight), 0);
294
+ if (totalWeight === 0)
295
+ return 0.5;
296
+ const weightedSum = evidence.reduce((sum, e) => sum + e.weight, 0);
297
+ return Math.max(0, Math.min(1, 0.5 + (weightedSum / totalWeight) * 0.5));
298
+ }
299
+ pruneHypotheses() {
300
+ if (this.hypotheses.size <= this.maxHypotheses)
301
+ return;
302
+ const sorted = Array.from(this.hypotheses.entries()).sort(([, a], [, b]) => a.confidence - b.confidence);
303
+ const lowest = sorted[0];
304
+ if (lowest)
305
+ this.hypotheses.delete(lowest[0]);
306
+ }
307
+ }
308
+ // ============================================================================
309
+ // FAILURE DETECTION (from failureRecovery.ts)
310
+ // ============================================================================
311
+ function detectFailure(output, context) {
312
+ for (const pattern of FAILURE_INDICATORS.build) {
313
+ if (pattern.test(output)) {
314
+ return { type: 'build', severity: 'critical', message: extractErrorMessage(output, pattern), timestamp: new Date().toISOString() };
315
+ }
316
+ }
317
+ for (const pattern of FAILURE_INDICATORS.test) {
318
+ if (pattern.test(output)) {
319
+ return { type: 'test', severity: 'major', message: extractErrorMessage(output, pattern), timestamp: new Date().toISOString() };
320
+ }
321
+ }
322
+ for (const pattern of FAILURE_INDICATORS.runtime) {
323
+ if (pattern.test(output)) {
324
+ return { type: 'tool', severity: 'major', message: extractErrorMessage(output, pattern), timestamp: new Date().toISOString() };
325
+ }
326
+ }
327
+ if (context.userMessage) {
328
+ for (const pattern of FAILURE_INDICATORS.userFeedback) {
329
+ if (pattern.test(context.userMessage)) {
330
+ return { type: 'user-feedback', severity: 'major', message: context.userMessage.slice(0, 200), timestamp: new Date().toISOString() };
331
+ }
332
+ }
333
+ }
334
+ return null;
335
+ }
336
+ function extractErrorMessage(output, pattern) {
337
+ const match = output.match(pattern);
338
+ if (!match)
339
+ return 'Unknown error';
340
+ const lines = output.split('\n');
341
+ for (let i = 0; i < lines.length; i++) {
342
+ if (pattern.test(lines[i])) {
343
+ return lines.slice(i, Math.min(lines.length, i + 3)).join('\n').slice(0, 300);
344
+ }
345
+ }
346
+ return match[0].slice(0, 200);
347
+ }
348
+ // ============================================================================
349
+ // RESULT VERIFICATION (from resultVerification.ts)
350
+ // ============================================================================
351
+ function formatVerifiedResult(result) {
352
+ if (result.status === 'VERIFIED_SUCCESS')
353
+ return result.details || result.summary;
354
+ const lines = [];
355
+ switch (result.status) {
356
+ case 'VERIFIED_FAILURE':
357
+ lines.push('═══ FAILED ═══');
358
+ break;
359
+ case 'UNVERIFIED':
360
+ lines.push('═══ UNVERIFIED ═══');
361
+ break;
362
+ case 'PARTIAL_SUCCESS':
363
+ lines.push('═══ PARTIAL SUCCESS ═══');
364
+ break;
365
+ case 'REQUIRES_USER_ACTION':
366
+ lines.push('═══ ACTION REQUIRED ═══');
367
+ break;
368
+ }
369
+ lines.push('', result.summary, '');
370
+ if (result.verificationChecks) {
371
+ const failedChecks = result.verificationChecks.filter(c => !c.passed);
372
+ if (failedChecks.length > 0) {
373
+ lines.push('Failed checks:');
374
+ for (const check of failedChecks) {
375
+ lines.push(` ✗ ${check.check}${check.details ? `: ${check.details}` : ''}`);
376
+ }
377
+ lines.push('');
378
+ }
379
+ }
380
+ if (result.details)
381
+ lines.push(result.details, '');
382
+ if (result.suggestedActions?.length) {
383
+ lines.push('Suggested actions:');
384
+ for (const action of result.suggestedActions)
385
+ lines.push(` → ${action}`);
386
+ }
387
+ return lines.join('\n');
388
+ }
389
+ function analyzeOutput(output, patterns, exitCode) {
390
+ const normalizedOutput = output.normalize('NFC');
391
+ for (const pattern of patterns.failure) {
392
+ if (pattern.test(normalizedOutput))
393
+ return { isSuccess: false, isFailure: true, confidence: 'high' };
394
+ }
395
+ for (const pattern of patterns.success) {
396
+ if (pattern.test(normalizedOutput))
397
+ return { isSuccess: true, isFailure: false, confidence: 'high' };
398
+ }
399
+ if (exitCode !== undefined) {
400
+ if (exitCode !== 0)
401
+ return { isSuccess: false, isFailure: true, confidence: 'high' };
402
+ return { isSuccess: false, isFailure: false, confidence: 'low' };
403
+ }
404
+ return { isSuccess: false, isFailure: false, confidence: 'low' };
405
+ }
406
+ // ============================================================================
407
+ // TOOL CREATION
408
+ // ============================================================================
11
409
  function createOrchestrationTools(options = {}) {
12
410
  const enableAll = !options.enableGovernment && !options.enableInfrastructure &&
13
- !options.enableSecurity && !options.enableAPT;
411
+ !options.enableSecurity && !options.enableAPT &&
412
+ !options.enableValidation && !options.enableHypothesis &&
413
+ !options.enableRecovery && !options.enableBidirectionalAudit &&
414
+ !options.enableUnifiedOrchestrator;
14
415
  const tools = [];
15
- // Government procedures tool
416
+ // ====== VALIDATION & ERROR ANALYSIS TOOL ======
417
+ if (enableAll || options.enableValidation) {
418
+ const errorAnalyzer = new ErrorAnalyzer();
419
+ tools.push({
420
+ name: 'analyze_errors',
421
+ description: `Analyze command output for errors and generate fix suggestions.
422
+
423
+ Capabilities:
424
+ - Parse TypeScript, npm, test, and generic errors
425
+ - Extract error locations (file, line, column)
426
+ - Generate confidence-scored fix suggestions
427
+ - Format errors for AI consumption`,
428
+ parameters: {
429
+ type: 'object',
430
+ properties: {
431
+ output: { type: 'string', description: 'Command output to analyze' },
432
+ command: { type: 'string', description: 'Command that produced the output (for context)' },
433
+ format: { type: 'string', enum: ['detailed', 'ai', 'summary'], description: 'Output format' },
434
+ },
435
+ required: ['output'],
436
+ },
437
+ async handler(params) {
438
+ const output = params['output'];
439
+ const command = params['command'];
440
+ const format = params['format'] || 'detailed';
441
+ const errors = errorAnalyzer.analyzeOutput(output, command);
442
+ if (format === 'ai') {
443
+ return errorAnalyzer.formatForAI(errors);
444
+ }
445
+ else if (format === 'summary') {
446
+ return `Found ${errors.length} error(s):\n` +
447
+ errors.slice(0, 5).map(e => `• ${e.errorType}: ${e.message.slice(0, 80)}`).join('\n');
448
+ }
449
+ return JSON.stringify(errors, null, 2);
450
+ },
451
+ });
452
+ tools.push({
453
+ name: 'verify_result',
454
+ description: `Verify operation results to prevent hallucinated success.
455
+
456
+ Checks:
457
+ - Pattern matching against known success/failure indicators
458
+ - Exit code analysis
459
+ - Unicode normalization to prevent spoofing
460
+ - Negative context detection`,
461
+ parameters: {
462
+ type: 'object',
463
+ properties: {
464
+ output: { type: 'string', description: 'Operation output to verify' },
465
+ operation: { type: 'string', enum: ['git', 'npm', 'command'], description: 'Type of operation' },
466
+ exitCode: { type: 'number', description: 'Exit code if available' },
467
+ },
468
+ required: ['output', 'operation'],
469
+ },
470
+ async handler(params) {
471
+ const output = params['output'];
472
+ const operation = params['operation'];
473
+ const exitCode = params['exitCode'];
474
+ const patterns = OUTPUT_PATTERNS[operation] || OUTPUT_PATTERNS.command;
475
+ const analysis = analyzeOutput(output, patterns, exitCode);
476
+ const result = {
477
+ status: analysis.isSuccess ? 'VERIFIED_SUCCESS' :
478
+ analysis.isFailure ? 'VERIFIED_FAILURE' : 'UNVERIFIED',
479
+ summary: analysis.isSuccess ? 'Operation succeeded' :
480
+ analysis.isFailure ? 'Operation failed' : 'Cannot verify outcome',
481
+ details: output.slice(0, 500),
482
+ verifiedAt: new Date().toISOString(),
483
+ };
484
+ return formatVerifiedResult(result);
485
+ },
486
+ });
487
+ }
488
+ // ====== HYPOTHESIS TESTING TOOL ======
489
+ if (enableAll || options.enableHypothesis) {
490
+ const hypothesisEngine = new HypothesisEngine(10);
491
+ tools.push({
492
+ name: 'hypothesis',
493
+ description: `Multi-hypothesis reasoning for bug analysis and problem solving.
494
+
495
+ Operations:
496
+ - generate: Create a new hypothesis with initial evidence
497
+ - add_evidence: Add supporting/contradicting evidence
498
+ - get_best: Get highest-confidence hypothesis
499
+ - list_all: List all hypotheses sorted by confidence
500
+ - clear: Reset all hypotheses`,
501
+ parameters: {
502
+ type: 'object',
503
+ properties: {
504
+ action: { type: 'string', enum: ['generate', 'add_evidence', 'get_best', 'list_all', 'clear'] },
505
+ description: { type: 'string', description: 'Hypothesis description (for generate)' },
506
+ hypothesisId: { type: 'string', description: 'Hypothesis ID (for add_evidence)' },
507
+ evidence: {
508
+ type: 'object',
509
+ properties: {
510
+ type: { type: 'string', enum: ['observation', 'data', 'test_result', 'user_feedback'] },
511
+ content: { type: 'string' },
512
+ weight: { type: 'number', description: '-1 to 1, positive supports, negative contradicts' },
513
+ },
514
+ },
515
+ },
516
+ required: ['action'],
517
+ },
518
+ async handler(params) {
519
+ const action = params['action'];
520
+ switch (action) {
521
+ case 'generate': {
522
+ const description = params['description'];
523
+ if (!description)
524
+ return 'Error: description required';
525
+ const hypothesis = hypothesisEngine.generateHypothesis(description);
526
+ return JSON.stringify(hypothesis, null, 2);
527
+ }
528
+ case 'add_evidence': {
529
+ const id = params['hypothesisId'];
530
+ const evidenceData = params['evidence'];
531
+ if (!id || !evidenceData)
532
+ return 'Error: hypothesisId and evidence required';
533
+ const evidence = {
534
+ type: evidenceData.type,
535
+ content: evidenceData.content,
536
+ weight: evidenceData.weight,
537
+ timestamp: new Date(),
538
+ };
539
+ hypothesisEngine.addEvidence(id, evidence);
540
+ return `Evidence added to hypothesis ${id}`;
541
+ }
542
+ case 'get_best': {
543
+ const best = hypothesisEngine.getBestHypothesis();
544
+ return best ? JSON.stringify(best, null, 2) : 'No hypotheses available';
545
+ }
546
+ case 'list_all': {
547
+ const all = hypothesisEngine.getAllHypotheses();
548
+ return JSON.stringify(all, null, 2);
549
+ }
550
+ case 'clear': {
551
+ hypothesisEngine.clear();
552
+ return 'All hypotheses cleared';
553
+ }
554
+ default:
555
+ return `Unknown action: ${action}`;
556
+ }
557
+ },
558
+ });
559
+ }
560
+ // ====== FAILURE DETECTION & RECOVERY TOOL ======
561
+ if (enableAll || options.enableRecovery) {
562
+ tools.push({
563
+ name: 'detect_failure',
564
+ description: `Detect failures in output and suggest recovery strategies.
565
+
566
+ Detects:
567
+ - Build failures (TypeScript, syntax, module errors)
568
+ - Test failures (Jest, assertion errors)
569
+ - Runtime errors (TypeError, ReferenceError, etc.)
570
+ - User feedback indicating failure`,
571
+ parameters: {
572
+ type: 'object',
573
+ properties: {
574
+ output: { type: 'string', description: 'Output to analyze for failures' },
575
+ userMessage: { type: 'string', description: 'User message (for feedback detection)' },
576
+ },
577
+ required: ['output'],
578
+ },
579
+ async handler(params) {
580
+ const output = params['output'];
581
+ const userMessage = params['userMessage'];
582
+ const failure = detectFailure(output, { userMessage });
583
+ if (!failure) {
584
+ return JSON.stringify({ detected: false, message: 'No failure detected' });
585
+ }
586
+ return JSON.stringify({
587
+ detected: true,
588
+ failure,
589
+ suggestedRecovery: [
590
+ `Identify root cause of ${failure.type} failure`,
591
+ 'Review the error message for specific guidance',
592
+ 'Check for similar patterns in codebase',
593
+ 'Consider alternative approaches if current fails repeatedly',
594
+ ],
595
+ }, null, 2);
596
+ },
597
+ });
598
+ }
599
+ // ====== GOVERNMENT PROCEDURES TOOL ======
16
600
  if (enableAll || options.enableGovernment) {
17
601
  tools.push({
18
602
  name: 'gov_procedures',
@@ -29,29 +613,14 @@ Provides:
29
613
  properties: {
30
614
  action: {
31
615
  type: 'string',
32
- enum: [
33
- 'get_contacts', 'get_legal_frameworks', 'get_reporting_requirements',
34
- 'generate_incident_report', 'generate_evidence_form',
35
- ],
36
- description: 'Action to perform',
616
+ enum: ['get_contacts', 'get_legal_frameworks', 'get_reporting_requirements', 'generate_incident_report', 'generate_evidence_form'],
37
617
  },
38
618
  agencyType: {
39
619
  type: 'string',
40
- enum: [
41
- 'federal-le', 'state-le', 'local-le', 'intelligence',
42
- 'military', 'regulatory', 'international', 'cisa', 'nist', 'contractor',
43
- ],
44
- description: 'Type of agency',
45
- },
46
- incidentType: {
47
- type: 'string',
48
- description: 'Type of incident for reporting',
49
- },
50
- classification: {
51
- type: 'string',
52
- enum: ['unclassified', 'cui', 'confidential', 'secret', 'top-secret', 'ts-sci'],
53
- description: 'Classification level',
620
+ enum: ['federal-le', 'state-le', 'local-le', 'intelligence', 'military', 'regulatory', 'international', 'cisa', 'nist', 'contractor'],
54
621
  },
622
+ incidentType: { type: 'string' },
623
+ classification: { type: 'string', enum: ['unclassified', 'cui', 'confidential', 'secret', 'top-secret', 'ts-sci'] },
55
624
  },
56
625
  required: ['action'],
57
626
  },
@@ -88,7 +657,7 @@ Provides:
88
657
  },
89
658
  });
90
659
  }
91
- // Infrastructure deployment tool
660
+ // ====== INFRASTRUCTURE DEPLOYMENT TOOL ======
92
661
  if (enableAll || options.enableInfrastructure) {
93
662
  tools.push({
94
663
  name: 'infrastructure',
@@ -104,27 +673,10 @@ Includes:
104
673
  parameters: {
105
674
  type: 'object',
106
675
  properties: {
107
- action: {
108
- type: 'string',
109
- enum: [
110
- 'get_stack', 'list_templates', 'generate_deployment',
111
- 'generate_teardown', 'generate_opsec_checklist',
112
- ],
113
- description: 'Action to perform',
114
- },
115
- region: {
116
- type: 'string',
117
- enum: ['us', 'ukraine', 'eu', 'asia', 'global'],
118
- description: 'Operational region',
119
- },
120
- stackId: {
121
- type: 'string',
122
- description: 'Infrastructure stack ID',
123
- },
124
- templateId: {
125
- type: 'string',
126
- description: 'Auto-execution template ID',
127
- },
676
+ action: { type: 'string', enum: ['get_stack', 'list_templates', 'generate_deployment', 'generate_teardown', 'generate_opsec_checklist'] },
677
+ region: { type: 'string', enum: ['us', 'ukraine', 'eu', 'asia', 'global'] },
678
+ stackId: { type: 'string' },
679
+ templateId: { type: 'string' },
128
680
  },
129
681
  required: ['action'],
130
682
  },
@@ -165,7 +717,7 @@ Includes:
165
717
  },
166
718
  });
167
719
  }
168
- // Security deliverables tool
720
+ // ====== SECURITY DELIVERABLES TOOL ======
169
721
  if (enableAll || options.enableSecurity) {
170
722
  tools.push({
171
723
  name: 'security_deliverable',
@@ -185,32 +737,12 @@ Types:
185
737
  properties: {
186
738
  type: {
187
739
  type: 'string',
188
- enum: [
189
- 'pentest-report', 'incident-response', 'security-controls',
190
- 'training-module', 'compliance-audit', 'threat-assessment',
191
- 'apt-analysis', 'vulnerability-report', 'infrastructure-assessment',
192
- 'persistence-procedures', 'red-team-playbook',
193
- ],
194
- description: 'Type of deliverable',
195
- },
196
- title: {
197
- type: 'string',
198
- description: 'Title for the deliverable',
199
- },
200
- scope: {
201
- type: 'string',
202
- description: 'Scope description',
203
- },
204
- findings: {
205
- type: 'array',
206
- items: { type: 'string' },
207
- description: 'List of findings to include',
208
- },
209
- format: {
210
- type: 'string',
211
- enum: ['markdown', 'json', 'html'],
212
- description: 'Output format',
740
+ enum: ['pentest-report', 'incident-response', 'security-controls', 'training-module', 'compliance-audit', 'threat-assessment', 'apt-analysis', 'vulnerability-report', 'infrastructure-assessment', 'persistence-procedures', 'red-team-playbook'],
213
741
  },
742
+ title: { type: 'string' },
743
+ scope: { type: 'string' },
744
+ findings: { type: 'array', items: { type: 'string' } },
745
+ format: { type: 'string', enum: ['markdown', 'json', 'html'] },
214
746
  },
215
747
  required: ['type'],
216
748
  },
@@ -221,7 +753,6 @@ Types:
221
753
  const title = params['title'];
222
754
  const scope = params['scope'];
223
755
  const format = params['format'];
224
- // Generate deliverable with minimal context
225
756
  const deliverable = await generator.generate(deliverableType, {
226
757
  exitReason: 'complete',
227
758
  finalResponse: title || 'Generated Deliverable',
@@ -253,31 +784,1003 @@ Types:
253
784
  },
254
785
  limitations: [],
255
786
  recommendations: [],
256
- }, [], {
257
- customTitle: title,
258
- constraints: scope ? [scope] : undefined,
259
- });
260
- // Export in requested format
787
+ }, [], { customTitle: title, constraints: scope ? [scope] : undefined });
261
788
  switch (format || 'markdown') {
262
- case 'json':
263
- return sec.exportToJSON(deliverable);
264
- case 'html':
265
- return sec.exportToHTML(deliverable);
266
- default:
267
- return sec.exportToMarkdown(deliverable);
789
+ case 'json': return sec.exportToJSON(deliverable);
790
+ case 'html': return sec.exportToHTML(deliverable);
791
+ default: return sec.exportToMarkdown(deliverable);
268
792
  }
269
793
  },
270
794
  });
271
795
  }
796
+ // ====== BIDIRECTIONAL AUDIT TOOL ======
797
+ if (enableAll || options.enableBidirectionalAudit) {
798
+ tools.push({
799
+ name: 'bidirectional_audit',
800
+ description: `Execute bidirectional attack chain audit for security analysis and deterrence.
801
+
802
+ Capabilities:
803
+ - FORWARD TRACE: Device → Daemons → Network → Edge → Core → Corporate → End Users
804
+ - REVERSE TRACE: End Users → Attack Vectors → Persistence → Control Points → Device
805
+ - Evidence collection with SHA-256 cryptographic hashes
806
+ - Professional audit reports for compliance/legal purposes
807
+
808
+ Use Cases:
809
+ - Security research and vulnerability assessment
810
+ - Compliance documentation (SOC2, ISO27001, etc.)
811
+ - Legal evidence collection for authorized investigations
812
+ - Deterrence documentation (proving attack surface awareness)
813
+ - Incident response and forensic analysis`,
814
+ parameters: {
815
+ type: 'object',
816
+ properties: {
817
+ direction: {
818
+ type: 'string',
819
+ enum: ['forward', 'reverse', 'bidirectional'],
820
+ description: 'Trace direction: forward (to end users), reverse (from end users), or bidirectional (both)',
821
+ },
822
+ evidenceDir: {
823
+ type: 'string',
824
+ description: 'Directory to store evidence files (default: .erosolar/evidence/)',
825
+ },
826
+ target: {
827
+ type: 'string',
828
+ description: 'Target system or infrastructure (default: local Apple ecosystem)',
829
+ },
830
+ format: {
831
+ type: 'string',
832
+ enum: ['text', 'json', 'markdown'],
833
+ description: 'Output format for the audit report',
834
+ },
835
+ includeRetaliation: {
836
+ type: 'boolean',
837
+ description: 'Include deterrence/retaliation capability analysis',
838
+ },
839
+ },
840
+ required: ['direction'],
841
+ },
842
+ async handler(params) {
843
+ const direction = params['direction'];
844
+ const evidenceDir = params['evidenceDir'] || options.workingDir
845
+ ? `${options.workingDir}/.erosolar/evidence/audit-${new Date().toISOString().split('T')[0]}`
846
+ : `.erosolar/evidence/audit-${new Date().toISOString().split('T')[0]}`;
847
+ const format = params['format'] || 'markdown';
848
+ const includeRetaliation = params['includeRetaliation'] ?? true;
849
+ try {
850
+ // Dynamic import to avoid circular dependencies
851
+ const { ForwardAttackChainTracer, runForwardTrace } = await import('../tools/forwardAttackChainTracer.js');
852
+ const lines = [];
853
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
854
+ lines.push(' BIDIRECTIONAL ATTACK CHAIN AUDIT');
855
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
856
+ lines.push('');
857
+ lines.push(`Direction: ${direction.toUpperCase()}`);
858
+ lines.push(`Evidence Directory: ${evidenceDir}`);
859
+ lines.push(`Timestamp: ${new Date().toISOString()}`);
860
+ lines.push('');
861
+ if (direction === 'forward' || direction === 'bidirectional') {
862
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
863
+ lines.push(' FORWARD ATTACK CHAIN');
864
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
865
+ lines.push('');
866
+ const forwardReport = await runForwardTrace(evidenceDir);
867
+ lines.push(forwardReport);
868
+ lines.push('');
869
+ }
870
+ if (direction === 'reverse' || direction === 'bidirectional') {
871
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
872
+ lines.push(' REVERSE ATTACK CHAIN');
873
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
874
+ lines.push('');
875
+ lines.push('Reverse trace analyzes attack vectors FROM end users BACK TO this device:');
876
+ lines.push('');
877
+ lines.push('END USER ATTACK VECTORS:');
878
+ lines.push('• Software Update Push - Apple can push code to any device');
879
+ lines.push('• MDM Profile Injection - Remote management without consent');
880
+ lines.push('• Push Notification Injection - Arbitrary notifications');
881
+ lines.push('• iCloud Key Injection - Add keys to user keyring');
882
+ lines.push('• iMessage Key Substitution - MITM encrypted messages');
883
+ lines.push('• Activation Lock Control - Brick or unlock devices');
884
+ lines.push('');
885
+ lines.push('CORPORATE PERSISTENCE:');
886
+ lines.push('• Apple Data Centers (AZ, NC, OR, IA, NV)');
887
+ lines.push('• Third-party: AWS (Siri), Google Cloud (iCloud), Akamai, Fastly');
888
+ lines.push('• Internal tools: Radar, MFi Portal');
889
+ lines.push('');
890
+ lines.push('CORE INFRASTRUCTURE CONTROL:');
891
+ lines.push('• Key Transparency Log (NO PUBLIC AUDIT)');
892
+ lines.push('• IDS Key Database - Device public keys');
893
+ lines.push('• Message Relay - Routes all iMessages');
894
+ lines.push('• Escrow HSM - Key escrow access');
895
+ lines.push('');
896
+ lines.push('EDGE VULNERABILITIES:');
897
+ lines.push('• APNs Courier - courier.push.apple.com');
898
+ lines.push('• IDS Identity - identity.ess.apple.com');
899
+ lines.push('• CloudKit Gateway - gateway.icloud.com');
900
+ lines.push('• Escrow Proxy - p43-escrowproxy.icloud.com');
901
+ lines.push('');
902
+ lines.push('NETWORK INTERCEPTION:');
903
+ lines.push('• All DNS controlled by Apple nameservers');
904
+ lines.push('• 14 Apple Root CAs in system trust store');
905
+ lines.push('• Certificate pinning controlled by Apple');
906
+ lines.push('');
907
+ lines.push('DAEMON ACCESS:');
908
+ lines.push('• identityservicesd - Key management');
909
+ lines.push('• imagent - iMessage agent');
910
+ lines.push('• apsd - Push notification daemon');
911
+ lines.push('• cloudd - iCloud sync');
912
+ lines.push('• assistantd - Siri/AI');
913
+ lines.push('');
914
+ lines.push('LOCAL EXPOSURE:');
915
+ lines.push('• Secure Enclave - User inaccessible');
916
+ lines.push('• iBoot firmware - Apple signed only');
917
+ lines.push('• Keychain - Synced to iCloud');
918
+ lines.push('');
919
+ }
920
+ if (includeRetaliation) {
921
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
922
+ lines.push(' DETERRENCE CAPABILITY ANALYSIS');
923
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
924
+ lines.push('');
925
+ lines.push('USER DETERRENCE OPTIONS:');
926
+ lines.push('');
927
+ lines.push('1. DOCUMENTATION DETERRENCE (LEGAL)');
928
+ lines.push(' • Complete audit trail with cryptographic hashes');
929
+ lines.push(' • Evidence suitable for legal proceedings');
930
+ lines.push(' • Proof of Apple\'s attack surface awareness');
931
+ lines.push(' • Regulatory complaint documentation (FTC, DOJ, EU DMA)');
932
+ lines.push('');
933
+ lines.push('2. TRANSPARENCY DETERRENCE (PUBLIC)');
934
+ lines.push(' • Publish audit findings publicly');
935
+ lines.push(' • Media disclosure with technical evidence');
936
+ lines.push(' • Security researcher community engagement');
937
+ lines.push(' • Congressional/parliamentary testimony support');
938
+ lines.push('');
939
+ lines.push('3. ECONOMIC DETERRENCE (MARKET)');
940
+ lines.push(' • Shareholder disclosure of security risks');
941
+ lines.push(' • Enterprise security assessment reports');
942
+ lines.push(' • Insurance and compliance implications');
943
+ lines.push(' • Competitive analysis for procurement');
944
+ lines.push('');
945
+ lines.push('4. TECHNICAL DETERRENCE (DEFENSIVE)');
946
+ lines.push(' • Network traffic monitoring and blocking');
947
+ lines.push(' • DNS sinkholing of Apple services');
948
+ lines.push(' • Certificate pinning bypass detection');
949
+ lines.push(' • Daemon behavior anomaly detection');
950
+ lines.push('');
951
+ lines.push('USER DEFENSE CAPABILITY AT EACH LAYER: NONE');
952
+ lines.push('');
953
+ lines.push('The audit demonstrates that users have no technical defense against');
954
+ lines.push('Apple\'s control at any layer of the attack chain. The only effective');
955
+ lines.push('deterrence is through legal, public, and economic pressure.');
956
+ lines.push('');
957
+ }
958
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
959
+ lines.push(' AUDIT COMPLETE');
960
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
961
+ lines.push('');
962
+ lines.push(`Evidence Directory: ${evidenceDir}`);
963
+ lines.push(`Generated: ${new Date().toISOString()}`);
964
+ lines.push('');
965
+ const report = lines.join('\n');
966
+ // Save summary report
967
+ const fs = await import('node:fs');
968
+ const path = await import('node:path');
969
+ if (!fs.existsSync(evidenceDir)) {
970
+ fs.mkdirSync(evidenceDir, { recursive: true });
971
+ }
972
+ fs.writeFileSync(path.join(evidenceDir, 'BIDIRECTIONAL-AUDIT-REPORT.txt'), report);
973
+ // Calculate master hash
974
+ const crypto = await import('node:crypto');
975
+ const masterHash = crypto.createHash('sha256').update(report).digest('hex');
976
+ fs.writeFileSync(path.join(evidenceDir, 'MASTER-HASH.txt'), `Master Hash: ${masterHash}\nGenerated: ${new Date().toISOString()}\n`);
977
+ if (format === 'json') {
978
+ return JSON.stringify({
979
+ direction,
980
+ evidenceDir,
981
+ timestamp: new Date().toISOString(),
982
+ masterHash,
983
+ success: true,
984
+ }, null, 2);
985
+ }
986
+ return report + `\nMaster Hash: ${masterHash}`;
987
+ }
988
+ catch (error) {
989
+ const message = error instanceof Error ? error.message : String(error);
990
+ return `Audit failed: ${message}`;
991
+ }
992
+ },
993
+ });
994
+ }
995
+ // ====== DEFENSIVE SECURITY SCAN TOOL ======
996
+ // Always enabled - this is defensive-only functionality
997
+ tools.push({
998
+ name: 'defensive_scan',
999
+ description: `Run defensive security scans on YOUR OWN device.
1000
+
1001
+ This tool ONLY scans the local device for intrusion indicators.
1002
+ It does NOT attack other systems - it is purely defensive.
1003
+
1004
+ Capabilities:
1005
+ - Intrusion detection (processes, network, persistence)
1006
+ - Security hardening assessment (firewall, SIP, FileVault, etc.)
1007
+ - Forensic evidence collection with chain of custody
1008
+ - MITRE ATT&CK mapping for detected indicators
1009
+ - Evidence packaging for law enforcement submission
1010
+
1011
+ Use Cases:
1012
+ - Detect if your device has been compromised
1013
+ - Collect evidence of unauthorized access
1014
+ - Generate reports for legal proceedings
1015
+ - Assess and improve security posture
1016
+ - Incident response and forensic analysis`,
1017
+ parameters: {
1018
+ type: 'object',
1019
+ properties: {
1020
+ scanType: {
1021
+ type: 'string',
1022
+ enum: ['full', 'process', 'network', 'persistence', 'hardening', 'evidence'],
1023
+ description: 'Type of scan to perform',
1024
+ },
1025
+ evidenceDir: {
1026
+ type: 'string',
1027
+ description: 'Directory to store evidence files',
1028
+ },
1029
+ purpose: {
1030
+ type: 'string',
1031
+ description: 'Purpose for evidence collection (for chain of custody)',
1032
+ },
1033
+ format: {
1034
+ type: 'string',
1035
+ enum: ['text', 'json', 'markdown'],
1036
+ description: 'Output format for the report',
1037
+ },
1038
+ },
1039
+ required: ['scanType'],
1040
+ },
1041
+ async handler(params) {
1042
+ const scanType = params['scanType'];
1043
+ const evidenceDir = params['evidenceDir'] || options.workingDir
1044
+ ? `${options.workingDir}/.erosolar/evidence/defensive-${new Date().toISOString().split('T')[0]}`
1045
+ : `.erosolar/evidence/defensive-${new Date().toISOString().split('T')[0]}`;
1046
+ const purpose = params['purpose'] || 'Security assessment';
1047
+ const format = params['format'] || 'text';
1048
+ try {
1049
+ const { IntrusionDetector, ForensicCollector, runDefensiveScan } = await import('../tools/defensiveSecurityTools.js');
1050
+ const lines = [];
1051
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1052
+ lines.push(' DEFENSIVE SECURITY SCAN');
1053
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1054
+ lines.push('');
1055
+ lines.push('Mode: DEFENSIVE ONLY (scanning YOUR device)');
1056
+ lines.push(`Scan Type: ${scanType.toUpperCase()}`);
1057
+ lines.push(`Evidence Directory: ${evidenceDir}`);
1058
+ lines.push(`Purpose: ${purpose}`);
1059
+ lines.push(`Timestamp: ${new Date().toISOString()}`);
1060
+ lines.push('');
1061
+ if (scanType === 'full') {
1062
+ const { posture, package: pkg } = await runDefensiveScan(evidenceDir, purpose);
1063
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1064
+ lines.push(' SECURITY POSTURE');
1065
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1066
+ lines.push('');
1067
+ lines.push(`Overall Risk Level: ${posture.overallRisk.toUpperCase()}`);
1068
+ lines.push(`Indicators Found: ${posture.indicators.length}`);
1069
+ lines.push(`Recommendations: ${posture.recommendations.length}`);
1070
+ lines.push('');
1071
+ // Hardening status
1072
+ lines.push('HARDENING STATUS:');
1073
+ lines.push(` Firewall: ${posture.hardening.firewall.enabled ? '✓ Enabled' : '✗ DISABLED'}`);
1074
+ lines.push(` SIP: ${posture.hardening.sip.enabled ? '✓ Enabled' : '✗ DISABLED'}`);
1075
+ lines.push(` FileVault: ${posture.hardening.filevault.enabled ? '✓ Enabled' : '✗ DISABLED'}`);
1076
+ lines.push(` Gatekeeper: ${posture.hardening.gatekeeper.enabled ? '✓ Enabled' : '✗ DISABLED'}`);
1077
+ lines.push(` XProtect: ${posture.hardening.xprotect.enabled ? '✓ Enabled' : '✗ DISABLED'}`);
1078
+ lines.push(` Auto Updates: ${posture.hardening.automaticUpdates.enabled ? '✓ Enabled' : '✗ DISABLED'}`);
1079
+ lines.push('');
1080
+ // Indicators by severity
1081
+ if (posture.indicators.length > 0) {
1082
+ lines.push('INTRUSION INDICATORS:');
1083
+ const bySeverity = {
1084
+ critical: [], high: [], medium: [], low: [], info: []
1085
+ };
1086
+ for (const ind of posture.indicators) {
1087
+ bySeverity[ind.severity]?.push(ind);
1088
+ }
1089
+ for (const [sev, inds] of Object.entries(bySeverity)) {
1090
+ if (inds.length > 0) {
1091
+ lines.push(` [${sev.toUpperCase()}] ${inds.length} indicator(s)`);
1092
+ for (const ind of inds.slice(0, 3)) {
1093
+ lines.push(` • ${ind.description}`);
1094
+ if (ind.mitreId)
1095
+ lines.push(` MITRE: ${ind.mitreId}`);
1096
+ }
1097
+ if (inds.length > 3)
1098
+ lines.push(` ... and ${inds.length - 3} more`);
1099
+ }
1100
+ }
1101
+ lines.push('');
1102
+ }
1103
+ // Recommendations
1104
+ if (posture.recommendations.length > 0) {
1105
+ lines.push('TOP RECOMMENDATIONS:');
1106
+ for (const rec of posture.recommendations.slice(0, 5)) {
1107
+ lines.push(` ${rec.priority}. ${rec.action}`);
1108
+ lines.push(` ${rec.rationale}`);
1109
+ if (rec.command)
1110
+ lines.push(` Command: ${rec.command}`);
1111
+ }
1112
+ lines.push('');
1113
+ }
1114
+ lines.push('EVIDENCE PACKAGE:');
1115
+ lines.push(` Case ID: ${pkg.caseId}`);
1116
+ lines.push(` Artifacts: ${pkg.artifacts.length}`);
1117
+ lines.push(` Master Hash: ${pkg.masterHash}`);
1118
+ }
1119
+ else {
1120
+ // Specific scan types
1121
+ const detector = new IntrusionDetector();
1122
+ const collector = new ForensicCollector(evidenceDir);
1123
+ if (scanType === 'process' || scanType === 'persistence' || scanType === 'network') {
1124
+ let indicators = [];
1125
+ if (scanType === 'process') {
1126
+ lines.push('Scanning processes...');
1127
+ indicators = await detector.scanProcesses();
1128
+ }
1129
+ else if (scanType === 'network') {
1130
+ lines.push('Scanning network connections...');
1131
+ indicators = await detector.scanNetwork();
1132
+ }
1133
+ else if (scanType === 'persistence') {
1134
+ lines.push('Scanning persistence mechanisms...');
1135
+ indicators = await detector.scanPersistence();
1136
+ }
1137
+ lines.push('');
1138
+ lines.push(`Found ${indicators.length} indicator(s):`);
1139
+ for (const ind of indicators) {
1140
+ lines.push(` [${ind.severity.toUpperCase()}] ${ind.description}`);
1141
+ lines.push(` Evidence: ${ind.evidence.slice(0, 100)}`);
1142
+ if (ind.mitreId)
1143
+ lines.push(` MITRE ATT&CK: ${ind.mitreId} (${ind.mitreTactic})`);
1144
+ lines.push(` Recommendation: ${ind.recommendation}`);
1145
+ lines.push('');
1146
+ }
1147
+ }
1148
+ else if (scanType === 'hardening') {
1149
+ lines.push('Checking security hardening...');
1150
+ const hardening = await detector.checkHardening();
1151
+ const recommendations = detector.generateRecommendations(hardening);
1152
+ lines.push('');
1153
+ lines.push('HARDENING STATUS:');
1154
+ lines.push(` Firewall: ${hardening.firewall.enabled ? '✓' : '✗'} ${hardening.firewall.details}`);
1155
+ lines.push(` SIP: ${hardening.sip.enabled ? '✓' : '✗'} ${hardening.sip.details}`);
1156
+ lines.push(` FileVault: ${hardening.filevault.enabled ? '✓' : '✗'} ${hardening.filevault.details}`);
1157
+ lines.push(` Gatekeeper: ${hardening.gatekeeper.enabled ? '✓' : '✗'} ${hardening.gatekeeper.details}`);
1158
+ lines.push(` XProtect: ${hardening.xprotect.enabled ? '✓' : '✗'} ${hardening.xprotect.details}`);
1159
+ lines.push(` Auto Updates: ${hardening.automaticUpdates.enabled ? '✓' : '✗'} ${hardening.automaticUpdates.details}`);
1160
+ lines.push('');
1161
+ if (recommendations.length > 0) {
1162
+ lines.push('RECOMMENDATIONS:');
1163
+ for (const rec of recommendations) {
1164
+ lines.push(` ${rec.priority}. ${rec.action}`);
1165
+ lines.push(` ${rec.rationale}`);
1166
+ if (rec.command)
1167
+ lines.push(` Command: ${rec.command}`);
1168
+ }
1169
+ }
1170
+ else {
1171
+ lines.push('All security hardening features are enabled. ✓');
1172
+ }
1173
+ }
1174
+ else if (scanType === 'evidence') {
1175
+ lines.push('Collecting forensic evidence...');
1176
+ collector.collectSystemLogs();
1177
+ const allIndicators = [
1178
+ ...await detector.scanProcesses(),
1179
+ ...await detector.scanNetwork(),
1180
+ ...await detector.scanPersistence(),
1181
+ ];
1182
+ const pkg = collector.generateEvidencePackage(allIndicators, purpose);
1183
+ lines.push('');
1184
+ lines.push('EVIDENCE PACKAGE GENERATED:');
1185
+ lines.push(` Case ID: ${pkg.caseId}`);
1186
+ lines.push(` Purpose: ${pkg.purpose}`);
1187
+ lines.push(` Artifacts: ${pkg.artifacts.length}`);
1188
+ lines.push(` Indicators: ${pkg.indicators.length}`);
1189
+ lines.push(` Timeline Events: ${pkg.timeline.length}`);
1190
+ lines.push(` Master Hash: ${pkg.masterHash}`);
1191
+ lines.push('');
1192
+ lines.push(`Evidence saved to: ${evidenceDir}`);
1193
+ lines.push('');
1194
+ lines.push('Files generated:');
1195
+ lines.push(` • evidence_package_${pkg.caseId}.json`);
1196
+ lines.push(` • FORENSIC_REPORT_${pkg.caseId}.txt`);
1197
+ }
1198
+ }
1199
+ lines.push('');
1200
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1201
+ lines.push(' SCAN COMPLETE');
1202
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1203
+ const report = lines.join('\n');
1204
+ if (format === 'json') {
1205
+ return JSON.stringify({
1206
+ scanType,
1207
+ evidenceDir,
1208
+ purpose,
1209
+ timestamp: new Date().toISOString(),
1210
+ success: true,
1211
+ }, null, 2);
1212
+ }
1213
+ return report;
1214
+ }
1215
+ catch (error) {
1216
+ const message = error instanceof Error ? error.message : String(error);
1217
+ return `Defensive scan failed: ${message}`;
1218
+ }
1219
+ },
1220
+ });
1221
+ // ====== OFFENSIVE TRANSPARENCY TOOL ======
1222
+ // Legal offensive capabilities for deterrence and transparency
1223
+ tools.push({
1224
+ name: 'offensive_transparency',
1225
+ description: `Execute offensive transparency operations against Apple infrastructure.
1226
+
1227
+ LEGAL offensive capabilities within ethical bounds:
1228
+ - Active probing of public Apple endpoints (legal - public servers)
1229
+ - Certificate Transparency monitoring (legal - public logs)
1230
+ - Key Transparency verification/exposure (legal - Apple claims it's auditable)
1231
+ - Telemetry blocking and analysis (legal - your device, your network)
1232
+ - Automated regulatory complaint generation (legal - your right)
1233
+ - Public disclosure package creation (legal - free speech)
1234
+
1235
+ This tool PROVES Apple's claims are false and generates materials for:
1236
+ - FTC complaints (deceptive practices)
1237
+ - EU DMA complaints (gatekeeper violations)
1238
+ - DOJ antitrust complaints
1239
+ - Public/media disclosure
1240
+ - Security researcher coordinated disclosure
1241
+
1242
+ The goal is DETERRENCE through TRANSPARENCY - exposing what Apple can do.`,
1243
+ parameters: {
1244
+ type: 'object',
1245
+ properties: {
1246
+ operation: {
1247
+ type: 'string',
1248
+ enum: ['probe', 'key-transparency', 'telemetry', 'complaints', 'disclosure', 'full'],
1249
+ description: 'Operation to perform',
1250
+ },
1251
+ evidenceDir: {
1252
+ type: 'string',
1253
+ description: 'Directory to store evidence and generated materials',
1254
+ },
1255
+ target: {
1256
+ type: 'string',
1257
+ description: 'Specific target for probing (default: all Apple endpoints)',
1258
+ },
1259
+ },
1260
+ required: ['operation'],
1261
+ },
1262
+ async handler(params) {
1263
+ const operation = params['operation'];
1264
+ const evidenceDir = params['evidenceDir'] || options.workingDir
1265
+ ? `${options.workingDir}/.erosolar/evidence/offensive-${new Date().toISOString().split('T')[0]}`
1266
+ : `.erosolar/evidence/offensive-${new Date().toISOString().split('T')[0]}`;
1267
+ try {
1268
+ const { InfrastructureProber, TelemetryBlocker, RegulatoryComplaintGenerator, DisclosurePackageGenerator, runOffensiveTransparency, } = await import('../tools/offensiveTransparencyTools.js');
1269
+ const lines = [];
1270
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1271
+ lines.push(' OFFENSIVE TRANSPARENCY OPERATION');
1272
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1273
+ lines.push('');
1274
+ lines.push('Mode: OFFENSIVE (legal transparency/deterrence operations)');
1275
+ lines.push(`Operation: ${operation.toUpperCase()}`);
1276
+ lines.push(`Evidence Directory: ${evidenceDir}`);
1277
+ lines.push(`Timestamp: ${new Date().toISOString()}`);
1278
+ lines.push('');
1279
+ if (operation === 'full') {
1280
+ const result = await runOffensiveTransparency(evidenceDir);
1281
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1282
+ lines.push(' INFRASTRUCTURE PROBING RESULTS');
1283
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1284
+ lines.push('');
1285
+ lines.push(`Endpoints probed: ${result.probeResults.length}`);
1286
+ lines.push(`Reachable: ${result.probeResults.filter(p => p.reachable).length}`);
1287
+ lines.push(`Anomalies found: ${result.probeResults.flatMap(p => p.anomalies).length}`);
1288
+ lines.push('');
1289
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1290
+ lines.push(' KEY TRANSPARENCY EXPOSURE');
1291
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1292
+ lines.push('');
1293
+ lines.push(`Publicly auditable: ${result.keyTransparency.publiclyAuditable ? 'YES' : 'NO ⚠️'}`);
1294
+ lines.push(`Merkle proof available: ${result.keyTransparency.merkleProofAvailable ? 'YES' : 'NO ⚠️'}`);
1295
+ lines.push('Findings:');
1296
+ for (const finding of result.keyTransparency.findings) {
1297
+ lines.push(` • ${finding}`);
1298
+ }
1299
+ lines.push('');
1300
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1301
+ lines.push(' TELEMETRY ANALYSIS');
1302
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1303
+ lines.push('');
1304
+ lines.push(`Active telemetry connections: ${result.telemetryAnalysis.telemetryConnections.length}`);
1305
+ lines.push('Data leakage detected:');
1306
+ for (const leak of result.telemetryAnalysis.dataLeakage) {
1307
+ lines.push(` ⚠️ ${leak}`);
1308
+ }
1309
+ lines.push('');
1310
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1311
+ lines.push(' REGULATORY COMPLAINTS GENERATED');
1312
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1313
+ lines.push('');
1314
+ for (const complaint of result.complaints) {
1315
+ lines.push(`✓ ${complaint.agency}`);
1316
+ lines.push(` Type: ${complaint.type}`);
1317
+ lines.push(` Allegations: ${complaint.allegations.length}`);
1318
+ }
1319
+ lines.push('');
1320
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1321
+ lines.push(' DISCLOSURE PACKAGE');
1322
+ lines.push('───────────────────────────────────────────────────────────────────────────────');
1323
+ lines.push('');
1324
+ lines.push(`Title: ${result.disclosure.title}`);
1325
+ lines.push(`Classification: ${result.disclosure.classification.toUpperCase()}`);
1326
+ lines.push(`Technical findings: ${result.disclosure.technicalFindings.length}`);
1327
+ lines.push(`Evidence hashes: ${result.disclosure.evidenceHashes.length}`);
1328
+ lines.push('');
1329
+ lines.push('Media kit key points:');
1330
+ for (const point of result.disclosure.mediaKit.keyPoints) {
1331
+ lines.push(` • ${point}`);
1332
+ }
1333
+ }
1334
+ else if (operation === 'probe') {
1335
+ const prober = new InfrastructureProber(evidenceDir);
1336
+ const results = await prober.probeAllEndpoints();
1337
+ lines.push('INFRASTRUCTURE PROBE RESULTS:');
1338
+ lines.push('');
1339
+ for (const result of results) {
1340
+ const status = result.reachable ? '✓' : '✗';
1341
+ lines.push(`${status} ${result.target}`);
1342
+ if (result.reachable) {
1343
+ lines.push(` Response: ${result.responseTime}ms`);
1344
+ if (result.tlsInfo) {
1345
+ lines.push(` TLS: ${result.tlsInfo.protocol} / ${result.tlsInfo.cipher}`);
1346
+ lines.push(` Cert chain: ${result.tlsInfo.certificateChain.length} certificates`);
1347
+ }
1348
+ }
1349
+ if (result.anomalies.length > 0) {
1350
+ lines.push(` Anomalies:`);
1351
+ for (const anomaly of result.anomalies) {
1352
+ lines.push(` ⚠️ ${anomaly}`);
1353
+ }
1354
+ }
1355
+ lines.push('');
1356
+ }
1357
+ }
1358
+ else if (operation === 'key-transparency') {
1359
+ const prober = new InfrastructureProber(evidenceDir);
1360
+ const result = await prober.probeKeyTransparency();
1361
+ lines.push('KEY TRANSPARENCY VERIFICATION:');
1362
+ lines.push('');
1363
+ lines.push(`Endpoint: ${result.endpoint}`);
1364
+ lines.push(`Publicly Auditable: ${result.publiclyAuditable ? 'YES' : 'NO - APPLE IS LYING'}`);
1365
+ lines.push(`Merkle Proof Available: ${result.merkleProofAvailable ? 'YES' : 'NO'}`);
1366
+ lines.push('');
1367
+ lines.push('FINDINGS:');
1368
+ for (const finding of result.findings) {
1369
+ lines.push(` • ${finding}`);
1370
+ }
1371
+ lines.push('');
1372
+ lines.push(`Evidence Hash: ${result.evidence}`);
1373
+ }
1374
+ else if (operation === 'telemetry') {
1375
+ const blocker = new TelemetryBlocker(evidenceDir);
1376
+ const analysis = blocker.analyzeCurrentConnections();
1377
+ const blocking = blocker.generateBlockingPackage();
1378
+ lines.push('TELEMETRY ANALYSIS:');
1379
+ lines.push('');
1380
+ lines.push(`Active telemetry connections: ${analysis.telemetryConnections.length}`);
1381
+ lines.push('');
1382
+ lines.push('DATA LEAKAGE:');
1383
+ for (const leak of analysis.dataLeakage) {
1384
+ lines.push(` ⚠️ ${leak}`);
1385
+ }
1386
+ lines.push('');
1387
+ lines.push('BLOCKING PACKAGE GENERATED:');
1388
+ lines.push(` • Hosts file entries: ${blocking.hostsFile.split('\n').length} lines`);
1389
+ lines.push(` • Firewall rules: ${blocking.firewallRules.split('\n').length} lines`);
1390
+ lines.push(` • LaunchDaemons to disable: ${blocking.launchDaemonsToDisable.length}`);
1391
+ lines.push('');
1392
+ lines.push('FILES SAVED:');
1393
+ lines.push(` • ${evidenceDir}/HOSTS-BLOCK.txt`);
1394
+ lines.push(` • ${evidenceDir}/FIREWALL-RULES.txt`);
1395
+ lines.push(` • ${evidenceDir}/DISABLE-DAEMONS.txt`);
1396
+ }
1397
+ else if (operation === 'complaints') {
1398
+ const prober = new InfrastructureProber(evidenceDir);
1399
+ const ktResult = await prober.probeKeyTransparency();
1400
+ const complaintGen = new RegulatoryComplaintGenerator(evidenceDir);
1401
+ const findings = ktResult.findings;
1402
+ const hashes = [ktResult.evidence];
1403
+ const ftc = complaintGen.generateFTCComplaint(findings, hashes);
1404
+ const dma = complaintGen.generateDMAComplaint(findings, hashes);
1405
+ const doj = complaintGen.generateDOJComplaint(findings, hashes);
1406
+ lines.push('REGULATORY COMPLAINTS GENERATED:');
1407
+ lines.push('');
1408
+ for (const complaint of [ftc, dma, doj]) {
1409
+ lines.push(`═══ ${complaint.agency} ═══`);
1410
+ lines.push(`Type: ${complaint.type}`);
1411
+ lines.push(`Subject: ${complaint.subject}`);
1412
+ lines.push('');
1413
+ lines.push('Allegations:');
1414
+ for (const allegation of complaint.allegations) {
1415
+ lines.push(` • ${allegation}`);
1416
+ }
1417
+ lines.push('');
1418
+ lines.push('Requested Action:');
1419
+ for (const action of complaint.requestedAction) {
1420
+ lines.push(` → ${action}`);
1421
+ }
1422
+ lines.push('');
1423
+ }
1424
+ }
1425
+ else if (operation === 'disclosure') {
1426
+ const prober = new InfrastructureProber(evidenceDir);
1427
+ const ktResult = await prober.probeKeyTransparency();
1428
+ const disclosureGen = new DisclosurePackageGenerator(evidenceDir);
1429
+ const disclosure = disclosureGen.generatePublicDisclosure(ktResult.findings, [ktResult.evidence]);
1430
+ const coordinated = disclosureGen.generateCoordinatedDisclosure(ktResult.findings, [ktResult.evidence]);
1431
+ disclosureGen.saveDisclosureMaterials(disclosure, coordinated);
1432
+ lines.push('DISCLOSURE PACKAGE GENERATED:');
1433
+ lines.push('');
1434
+ lines.push(`Title: ${disclosure.title}`);
1435
+ lines.push(`Classification: ${disclosure.classification}`);
1436
+ lines.push('');
1437
+ lines.push('TECHNICAL FINDINGS:');
1438
+ for (const finding of disclosure.technicalFindings.slice(0, 5)) {
1439
+ lines.push(` • ${finding}`);
1440
+ }
1441
+ if (disclosure.technicalFindings.length > 5) {
1442
+ lines.push(` ... and ${disclosure.technicalFindings.length - 5} more`);
1443
+ }
1444
+ lines.push('');
1445
+ lines.push('MEDIA KIT KEY POINTS:');
1446
+ for (const point of disclosure.mediaKit.keyPoints) {
1447
+ lines.push(` • ${point}`);
1448
+ }
1449
+ lines.push('');
1450
+ lines.push('FILES GENERATED:');
1451
+ lines.push(` • ${evidenceDir}/PUBLIC-DISCLOSURE-PACKAGE.json`);
1452
+ lines.push(` • ${evidenceDir}/MEDIA-KIT.md`);
1453
+ lines.push(` • ${evidenceDir}/COORDINATED-DISCLOSURE.txt`);
1454
+ lines.push(` • ${evidenceDir}/PRESS-RELEASE-TEMPLATE.md`);
1455
+ }
1456
+ lines.push('');
1457
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1458
+ lines.push(' OFFENSIVE TRANSPARENCY COMPLETE');
1459
+ lines.push('═══════════════════════════════════════════════════════════════════════════════');
1460
+ lines.push('');
1461
+ lines.push('These materials can be used for:');
1462
+ lines.push(' 1. Regulatory complaints (FTC, DOJ, EU DMA)');
1463
+ lines.push(' 2. Legal proceedings');
1464
+ lines.push(' 3. Public disclosure / journalism');
1465
+ lines.push(' 4. Security research publications');
1466
+ lines.push(' 5. Congressional/parliamentary testimony');
1467
+ lines.push('');
1468
+ lines.push('DETERRENCE ACHIEVED THROUGH TRANSPARENCY');
1469
+ return lines.join('\n');
1470
+ }
1471
+ catch (error) {
1472
+ const message = error instanceof Error ? error.message : String(error);
1473
+ return `Offensive transparency operation failed: ${message}`;
1474
+ }
1475
+ },
1476
+ });
1477
+ // ====== THREAT INTELLIGENCE TOOL ======
1478
+ tools.push({
1479
+ name: 'threat_intelligence',
1480
+ description: `Generate threat intelligence and capability assessments.
1481
+
1482
+ Provides:
1483
+ - Threat actor profiling
1484
+ - Attack vector analysis with MITRE ATT&CK
1485
+ - IOC detection
1486
+ - Capability assessment
1487
+ - Risk scoring
1488
+
1489
+ Understanding attacker capabilities is deterrence through transparency.`,
1490
+ parameters: {
1491
+ type: 'object',
1492
+ properties: {
1493
+ action: {
1494
+ type: 'string',
1495
+ enum: ['full_report', 'actors', 'vectors', 'ioc_scan', 'capability_assessment'],
1496
+ },
1497
+ actorId: { type: 'string' },
1498
+ evidenceDir: { type: 'string' },
1499
+ },
1500
+ required: ['action'],
1501
+ },
1502
+ async handler(params) {
1503
+ const action = params['action'];
1504
+ const evidenceDir = params['evidenceDir'] ||
1505
+ `${options.workingDir || '.'}/.erosolar/evidence/threat-intel-${new Date().toISOString().split('T')[0]}`;
1506
+ try {
1507
+ const { ThreatIntelligenceEngine, runThreatAnalysis } = await import('../tools/threatIntelligenceTools.js');
1508
+ const engine = new ThreatIntelligenceEngine(evidenceDir);
1509
+ if (action === 'full_report') {
1510
+ const report = await engine.generateThreatReport();
1511
+ return `${report.executiveSummary}\n\n${report.technicalDetails}\n\nRisk Score: ${report.riskScore}/100\nHash: ${report.hash}`;
1512
+ }
1513
+ else if (action === 'ioc_scan') {
1514
+ const iocs = await engine.scanForIOCs();
1515
+ const anomalies = await engine.detectAnomalies();
1516
+ return `IOCs: ${iocs.length}, Anomalies: ${anomalies.length}\n` +
1517
+ iocs.map(i => `[${i.type}] ${i.value} (${Math.round(i.confidence * 100)}%)`).join('\n');
1518
+ }
1519
+ else if (action === 'capability_assessment') {
1520
+ const actorId = params['actorId'] || 'ta-apple-internal';
1521
+ const caps = engine.assessCapabilities(actorId);
1522
+ return caps.map(c => `• ${c.capability}\n Impact: ${c.impactIfUsed}\n Mitigation: ${c.mitigations[0]}`).join('\n\n');
1523
+ }
1524
+ return 'Unknown action';
1525
+ }
1526
+ catch (error) {
1527
+ return `Error: ${error instanceof Error ? error.message : String(error)}`;
1528
+ }
1529
+ },
1530
+ });
1531
+ // ====== UNIFIED ATTACK ORCHESTRATION TOOL ======
1532
+ tools.push({
1533
+ name: 'attack_orchestrator',
1534
+ description: `Execute comprehensive offensive operations against ANY target infrastructure (AUTHORIZED USE ONLY).
1535
+
1536
+ **Dynamic Target Research**: NO HARDCODED DATA! The AI automatically researches any organization you specify:
1537
+ - Tech companies (Apple, Google, Microsoft, Amazon, Meta, Netflix, Uber, Spotify, TikTok, etc.)
1538
+ - Government agencies (Pentagon, NSA, CIA, FBI, DHS, DOD, etc.)
1539
+ - Defense contractors (Lockheed Martin, Raytheon, Northrop Grumman, Boeing, etc.)
1540
+ - Critical infrastructure (Power grids, water systems, transportation, telecom)
1541
+ - Finance (JPMorgan, Visa, PayPal, banks, trading firms)
1542
+ - Healthcare systems
1543
+ - Energy sector
1544
+ - ANY other organization - just provide the name!
1545
+
1546
+ The orchestrator will:
1547
+ 1. Research the target using AI (infrastructure, employees, geography, tech stack)
1548
+ 2. Identify attack surface (servers, APIs, mobile apps, cloud)
1549
+ 3. Generate attack recommendations
1550
+ 4. Execute full-spectrum offensive operations
1551
+
1552
+ Attack Intents:
1553
+ - destroy/attack: Full offensive compromise
1554
+ - audit: Security assessment
1555
+ - analyze/recon: Reconnaissance
1556
+ - exfiltrate: Data extraction
1557
+ - persist: Establish persistence
1558
+ - escalate: Privilege escalation
1559
+ - evade: Detection evasion
1560
+
1561
+ Attack Vectors:
1562
+ - server: Server infrastructure
1563
+ - system: OS-level exploitation
1564
+ - device: End-user devices
1565
+ - network: Network-level attacks
1566
+ - corporate: Corporate infrastructure
1567
+ - employee: Social engineering
1568
+ - supply-chain: Supply chain attacks
1569
+ - cloud: Cloud infrastructure
1570
+ - api: API exploitation
1571
+ - web: Web applications
1572
+
1573
+ Modes:
1574
+ - rl: Reinforcement learning with 2 self-modifying agents
1575
+ - non-rl: Direct full-spectrum offensive execution
1576
+ - auto: Automatically select based on intent (default)
1577
+
1578
+ Features:
1579
+ - Multi-target support (Apple, Google, Microsoft, Amazon, Meta, custom)
1580
+ - Dual-mode execution with keyboard toggle
1581
+ - Self-modifying agents with version control
1582
+ - Full-spectrum attack planning
1583
+ - Real-time statistics and reporting`,
1584
+ parameters: {
1585
+ type: 'object',
1586
+ properties: {
1587
+ organization: {
1588
+ type: 'string',
1589
+ description: 'Target organization name (can be ANY organization - AI will research it dynamically)'
1590
+ },
1591
+ intent: {
1592
+ type: 'string',
1593
+ enum: ['destroy', 'attack', 'audit', 'analyze', 'recon', 'exfiltrate', 'persist', 'escalate', 'evade'],
1594
+ description: 'Attack intent'
1595
+ },
1596
+ vectors: {
1597
+ type: 'array',
1598
+ items: {
1599
+ type: 'string',
1600
+ enum: ['server', 'system', 'device', 'network', 'corporate', 'employee', 'supply-chain', 'cloud', 'api', 'web']
1601
+ },
1602
+ description: 'Attack vectors to employ (default: all applicable)'
1603
+ },
1604
+ mode: {
1605
+ type: 'string',
1606
+ enum: ['rl', 'non-rl', 'auto'],
1607
+ description: 'Execution mode (default: auto)'
1608
+ },
1609
+ maxIterations: {
1610
+ type: 'number',
1611
+ description: 'Maximum iterations (0 = unlimited, default: 0)'
1612
+ },
1613
+ completionThreshold: {
1614
+ type: 'number',
1615
+ description: 'Completion percentage threshold (0-1, default: 0.95)'
1616
+ },
1617
+ enableKeyboard: {
1618
+ type: 'boolean',
1619
+ description: 'Enable keyboard toggle for mode switching (default: true)'
1620
+ },
1621
+ verbose: {
1622
+ type: 'boolean',
1623
+ description: 'Show detailed statistics (default: false)'
1624
+ },
1625
+ customName: {
1626
+ type: 'string',
1627
+ description: 'Custom target name (for custom organization)'
1628
+ },
1629
+ scope: {
1630
+ type: 'object',
1631
+ description: 'Custom scope definition (for custom organization)',
1632
+ properties: {
1633
+ servers: { type: 'array', items: { type: 'string' } },
1634
+ systems: { type: 'array', items: { type: 'string' } },
1635
+ devices: { type: 'array', items: { type: 'string' } },
1636
+ employees: { type: 'number' },
1637
+ geography: { type: 'array', items: { type: 'string' } },
1638
+ departments: { type: 'array', items: { type: 'string' } }
1639
+ }
1640
+ }
1641
+ },
1642
+ required: ['organization', 'intent'],
1643
+ },
1644
+ async handler(params) {
1645
+ const organization = params['organization'];
1646
+ const intent = params['intent'];
1647
+ const vectors = params['vectors'] || ['server', 'system', 'device', 'network', 'corporate', 'employee'];
1648
+ const mode = params['mode'] || 'auto';
1649
+ const maxIterations = params['maxIterations'] || 0;
1650
+ const completionThreshold = params['completionThreshold'] || 0.95;
1651
+ const enableKeyboard = params['enableKeyboard'] !== false;
1652
+ const verbose = params['verbose'] === true;
1653
+ const customName = params['customName'];
1654
+ const scope = params['scope'];
1655
+ try {
1656
+ const { CompleteAttackOrchestrator } = await import('../core/completeAttackOrchestrator.js');
1657
+ // Build configuration
1658
+ const config = {
1659
+ organization,
1660
+ intent: intent,
1661
+ mode: mode,
1662
+ vectors,
1663
+ maxIterations,
1664
+ completionThreshold,
1665
+ enableKeyboard,
1666
+ verbose
1667
+ };
1668
+ // Execute attack orchestration
1669
+ const orchestrator = new CompleteAttackOrchestrator();
1670
+ const stats = await orchestrator.execute(config);
1671
+ // Generate report
1672
+ const report = CompleteAttackOrchestrator.generateReport(stats);
1673
+ if (verbose) {
1674
+ return report + `\n\n--- Full Statistics ---\n${JSON.stringify(stats, null, 2)}`;
1675
+ }
1676
+ return report;
1677
+ }
1678
+ catch (error) {
1679
+ return `Error executing attack orchestration: ${error instanceof Error ? error.message : String(error)}`;
1680
+ }
1681
+ },
1682
+ });
1683
+ // ====== UNIFIED ORCHESTRATOR TOOL (RL + Non-RL) ======
1684
+ if (enableAll || options.enableUnifiedOrchestrator) {
1685
+ tools.push({
1686
+ name: 'orchestrate',
1687
+ description: `Unified orchestration combining RL and non-RL modes.
1688
+
1689
+ Modes:
1690
+ - single: Standard single-pass execution
1691
+ - dual-rl: Self-improving with RL refinement (runs primary + refinement pass)
1692
+ - auto: Auto-execute cycles until completion
1693
+ - apt: Full APT kill-chain execution
1694
+ - security: Security assessment with findings
1695
+
1696
+ Features:
1697
+ - Automatic mode selection based on objective complexity
1698
+ - RL reward tracking for self-improvement
1699
+ - Real technique execution via TAO
1700
+ - Deliverable generation`,
1701
+ parameters: {
1702
+ type: 'object',
1703
+ properties: {
1704
+ objective: { type: 'string', description: 'Task objective to accomplish' },
1705
+ mode: {
1706
+ type: 'string',
1707
+ enum: ['single', 'dual-rl', 'auto', 'apt', 'security'],
1708
+ description: 'Orchestration mode (default: auto-selected based on objective)',
1709
+ },
1710
+ useRL: { type: 'boolean', description: 'Enable RL refinement (default: true for complex tasks)' },
1711
+ maxCycles: { type: 'number', description: 'Max cycles for auto mode (default: 5)' },
1712
+ depth: { type: 'string', enum: ['quick', 'standard', 'deep'], description: 'Execution depth' },
1713
+ goal: {
1714
+ type: 'string',
1715
+ enum: ['recon', 'access', 'persist', 'escalate', 'lateral', 'collect', 'exfil', 'impact', 'all'],
1716
+ description: 'APT goal for apt/security modes',
1717
+ },
1718
+ targets: { type: 'array', items: { type: 'string' }, description: 'Target list for security/apt modes' },
1719
+ stealthMode: { type: 'boolean', description: 'Enable stealth mode (slower but less detectable)' },
1720
+ },
1721
+ required: ['objective'],
1722
+ },
1723
+ async handler(params) {
1724
+ const objective = params['objective'];
1725
+ const mode = params['mode'];
1726
+ const useRL = params['useRL'];
1727
+ const maxCycles = params['maxCycles'];
1728
+ const depth = params['depth'];
1729
+ const goal = params['goal'];
1730
+ const targets = params['targets'];
1731
+ const stealthMode = params['stealthMode'];
1732
+ // Auto-select mode based on objective
1733
+ const selectedMode = mode ?? inferOrchestrationMode(objective);
1734
+ const summary = [
1735
+ `Orchestration: ${selectedMode.toUpperCase()}`,
1736
+ `Objective: ${objective.slice(0, 100)}${objective.length > 100 ? '...' : ''}`,
1737
+ ];
1738
+ if (selectedMode === 'dual-rl' || useRL) {
1739
+ summary.push('RL: Enabled (primary + refinement pass)');
1740
+ }
1741
+ if (selectedMode === 'auto') {
1742
+ summary.push(`Auto-execution: max ${maxCycles ?? 5} cycles, depth ${depth ?? 'standard'}`);
1743
+ }
1744
+ if (selectedMode === 'apt' || selectedMode === 'security') {
1745
+ summary.push(`Goal: ${goal ?? 'all'}`);
1746
+ if (targets?.length)
1747
+ summary.push(`Targets: ${targets.join(', ')}`);
1748
+ if (stealthMode)
1749
+ summary.push('Stealth: Enabled');
1750
+ }
1751
+ // Note: Actual orchestration would require agent runtime context
1752
+ // This tool provides configuration and status for the orchestrator
1753
+ summary.push('');
1754
+ summary.push('Configuration ready. Orchestrator will execute with these settings.');
1755
+ summary.push('Use the agent runtime to invoke UnifiedOrchestrator.run() with this config.');
1756
+ return summary.join('\n');
1757
+ },
1758
+ });
1759
+ }
272
1760
  return {
273
1761
  id: 'orchestration-tools',
274
- description: 'Unified orchestration for government, infrastructure, security, and APT operations',
1762
+ description: 'Unified orchestration: RL/non-RL modes, gov, infra, security, validation, hypothesis, recovery, APT chain operations',
275
1763
  tools,
276
1764
  };
277
1765
  }
1766
+ function inferOrchestrationMode(objective) {
1767
+ const lower = objective.toLowerCase();
1768
+ if (lower.includes('security') || lower.includes('pentest') || lower.includes('vulnerability'))
1769
+ return 'security';
1770
+ if (lower.includes('apt') || lower.includes('kill-chain') || lower.includes('attack'))
1771
+ return 'apt';
1772
+ if (lower.includes('verify') || lower.includes('improve') || lower.includes('refine'))
1773
+ return 'dual-rl';
1774
+ if (lower.includes('complete') || lower.includes('finish') || lower.includes('until done'))
1775
+ return 'auto';
1776
+ return 'single';
1777
+ }
1778
+ // ============================================================================
1779
+ // CAPABILITY MODULE
1780
+ // ============================================================================
278
1781
  export class OrchestrationCapabilityModule {
279
1782
  id = 'capability.orchestration';
280
- description = 'Unified orchestration for government, infrastructure, security, and APT operations';
1783
+ description = 'Unified orchestration for gov, infra, security, validation, hypothesis testing, and failure recovery';
281
1784
  options;
282
1785
  constructor(options = {}) {
283
1786
  this.options = options;
@@ -295,4 +1798,8 @@ export class OrchestrationCapabilityModule {
295
1798
  };
296
1799
  }
297
1800
  }
1801
+ // ============================================================================
1802
+ // EXPORTS - For direct usage
1803
+ // ============================================================================
1804
+ export { ErrorAnalyzer, HypothesisEngine, detectFailure, formatVerifiedResult, analyzeOutput };
298
1805
  //# sourceMappingURL=orchestrationCapability.js.map