claude-flow-novice 2.0.3 → 2.0.4

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 (272) hide show
  1. package/dist/src/cli/commands/guidance.js +487 -668
  2. package/dist/src/cli/commands/index-validate.js +18 -29
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +230 -282
  4. package/dist/src/cli/commands/neural-goal-init.js +92 -125
  5. package/dist/src/cli/commands/swarm-exec.js +317 -393
  6. package/dist/src/cli/commands/swarm.js +1 -1
  7. package/dist/src/cli/commands/validate-framework.js +983 -1100
  8. package/dist/src/cli/commands/validate.js +144 -223
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +265 -277
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +6 -7
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +373 -356
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +6 -7
  13. package/dist/src/cli/simple-commands/agent.js +157 -193
  14. package/dist/src/cli/simple-commands/analysis.js +336 -446
  15. package/dist/src/cli/simple-commands/automation-executor.js +1095 -1339
  16. package/dist/src/cli/simple-commands/automation.js +481 -469
  17. package/dist/src/cli/simple-commands/batch-manager.js +261 -313
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +241 -267
  19. package/dist/src/cli/simple-commands/claude-track.js +68 -90
  20. package/dist/src/cli/simple-commands/concurrent-display.js +266 -320
  21. package/dist/src/cli/simple-commands/config.js +245 -290
  22. package/dist/src/cli/simple-commands/coordination.js +182 -234
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +812 -615
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +922 -981
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +274 -294
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +378 -457
  27. package/dist/src/cli/simple-commands/github/github-api.js +535 -574
  28. package/dist/src/cli/simple-commands/github/init.js +276 -303
  29. package/dist/src/cli/simple-commands/github.js +222 -247
  30. package/dist/src/cli/simple-commands/goal.js +51 -63
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +208 -278
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +601 -696
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +907 -979
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +406 -655
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1125 -1245
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +854 -1090
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +459 -574
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +263 -347
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +727 -768
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +745 -1049
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +227 -283
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +174 -217
  43. package/dist/src/cli/simple-commands/hive-mind.js +1842 -2283
  44. package/dist/src/cli/simple-commands/hive.js +90 -79
  45. package/dist/src/cli/simple-commands/hook-safety.js +431 -521
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +203 -254
  47. package/dist/src/cli/simple-commands/hooks.js +1064 -1204
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +294 -319
  49. package/dist/src/cli/simple-commands/init/batch-init.js +496 -562
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +13 -19
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +13 -19
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +61 -88
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +125 -150
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +42 -49
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +43 -61
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +141 -147
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +31 -44
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +64 -90
  59. package/dist/src/cli/simple-commands/init/help.js +104 -107
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +509 -528
  61. package/dist/src/cli/simple-commands/init/index.js +1510 -1759
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +234 -317
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +441 -504
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +289 -364
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +652 -728
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +416 -481
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +369 -448
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +1 -2
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +122 -99
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +32 -37
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +55 -62
  72. package/dist/src/cli/simple-commands/init/template-copier.js +421 -533
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +3 -6
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +344 -318
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +173 -218
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +65 -75
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +3 -6
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +2 -4
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +187 -230
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +53 -80
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +101 -85
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +283 -330
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +495 -561
  84. package/dist/src/cli/simple-commands/init/validation/index.js +302 -358
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +308 -359
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +389 -366
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +270 -268
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +427 -447
  89. package/dist/src/cli/simple-commands/init.js +1 -2
  90. package/dist/src/cli/simple-commands/mcp-health.js +131 -158
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +533 -634
  92. package/dist/src/cli/simple-commands/mcp.js +345 -400
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +426 -537
  94. package/dist/src/cli/simple-commands/memory.js +247 -311
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +39 -46
  96. package/dist/src/cli/simple-commands/monitor.js +294 -363
  97. package/dist/src/cli/simple-commands/neural.js +51 -65
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +538 -662
  99. package/dist/src/cli/simple-commands/pair-basic.js +528 -656
  100. package/dist/src/cli/simple-commands/pair-old.js +430 -543
  101. package/dist/src/cli/simple-commands/pair-working.js +615 -751
  102. package/dist/src/cli/simple-commands/pair.js +615 -751
  103. package/dist/src/cli/simple-commands/performance-hooks.js +83 -111
  104. package/dist/src/cli/simple-commands/performance-metrics.js +348 -433
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +708 -787
  106. package/dist/src/cli/simple-commands/process-ui.js +230 -254
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +525 -611
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1704 -1530
  109. package/dist/src/cli/simple-commands/sparc/commands.js +438 -516
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1224 -1481
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +913 -978
  112. package/dist/src/cli/simple-commands/sparc/index.js +241 -298
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +314 -390
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +965 -869
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +980 -1273
  116. package/dist/src/cli/simple-commands/sparc/specification.js +559 -645
  117. package/dist/src/cli/simple-commands/sparc-modes/architect.js +1 -1
  118. package/dist/src/cli/simple-commands/sparc-modes/ask.js +1 -1
  119. package/dist/src/cli/simple-commands/sparc-modes/code.js +1 -1
  120. package/dist/src/cli/simple-commands/sparc-modes/debug.js +1 -1
  121. package/dist/src/cli/simple-commands/sparc-modes/devops.js +1 -1
  122. package/dist/src/cli/simple-commands/sparc-modes/docs-writer.js +1 -1
  123. package/dist/src/cli/simple-commands/sparc-modes/generic.js +1 -1
  124. package/dist/src/cli/simple-commands/sparc-modes/index.js +47 -55
  125. package/dist/src/cli/simple-commands/sparc-modes/integration.js +1 -1
  126. package/dist/src/cli/simple-commands/sparc-modes/mcp.js +1 -1
  127. package/dist/src/cli/simple-commands/sparc-modes/monitoring.js +1 -1
  128. package/dist/src/cli/simple-commands/sparc-modes/optimization.js +1 -1
  129. package/dist/src/cli/simple-commands/sparc-modes/security-review.js +1 -1
  130. package/dist/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +1 -1
  131. package/dist/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +1 -1
  132. package/dist/src/cli/simple-commands/sparc-modes/supabase-admin.js +1 -1
  133. package/dist/src/cli/simple-commands/sparc-modes/swarm.js +101 -87
  134. package/dist/src/cli/simple-commands/sparc-modes/tdd.js +1 -1
  135. package/dist/src/cli/simple-commands/sparc-modes/tutorial.js +1 -1
  136. package/dist/src/cli/simple-commands/sparc.js +465 -493
  137. package/dist/src/cli/simple-commands/start-ui.js +108 -132
  138. package/dist/src/cli/simple-commands/start-wrapper.js +240 -268
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +254 -275
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +128 -171
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +61 -82
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +267 -331
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +211 -263
  145. package/dist/src/cli/simple-commands/stream-chain.js +260 -318
  146. package/dist/src/cli/simple-commands/stream-processor.js +290 -315
  147. package/dist/src/cli/simple-commands/swarm-executor.js +189 -222
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +208 -300
  149. package/dist/src/cli/simple-commands/swarm-ui.js +623 -703
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +258 -286
  151. package/dist/src/cli/simple-commands/swarm.js +887 -1082
  152. package/dist/src/cli/simple-commands/task.js +161 -206
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +59 -89
  154. package/dist/src/cli/simple-commands/token-tracker.js +258 -316
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +433 -519
  156. package/dist/src/cli/simple-commands/train-and-stream.js +275 -331
  157. package/dist/src/cli/simple-commands/training-pipeline.js +619 -725
  158. package/dist/src/cli/simple-commands/training.js +170 -227
  159. package/dist/src/cli/simple-commands/verification-hooks.js +261 -284
  160. package/dist/src/cli/simple-commands/verification-integration.js +389 -417
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +486 -606
  162. package/dist/src/cli/simple-commands/verification.js +493 -513
  163. package/dist/src/cli/simple-commands/web-server.js +766 -836
  164. package/dist/src/cli/simple-commands/webui-validator.js +106 -124
  165. package/dist/src/coordination/event-bus/demo-wasm-integration.js +212 -251
  166. package/dist/src/coordination/event-bus/qe-event-bus.js +608 -748
  167. package/dist/src/coordination/event-bus/qe-event-bus.test.js +379 -454
  168. package/dist/src/coordination/iteration-tracker.js +363 -454
  169. package/dist/src/enterprise/analytics-manager.js +1135 -0
  170. package/dist/src/enterprise/audit-manager.js +1115 -0
  171. package/dist/src/enterprise/cloud-manager.js +891 -0
  172. package/dist/src/enterprise/deployment-manager.js +966 -0
  173. package/dist/src/enterprise/index.js +6 -0
  174. package/dist/src/enterprise/project-manager.js +584 -0
  175. package/dist/src/enterprise/security-manager.js +991 -0
  176. package/dist/src/index.js +1 -1
  177. package/dist/src/mcp/DEPRECATED.js +46 -60
  178. package/dist/src/mcp/fixes/mcp-error-fixes.js +115 -134
  179. package/dist/src/mcp/implementations/agent-tracker.js +114 -128
  180. package/dist/src/mcp/implementations/daa-tools.js +292 -350
  181. package/dist/src/mcp/implementations/workflow-tools.js +329 -361
  182. package/dist/src/mcp/mcp-config-manager.js +1183 -1331
  183. package/dist/src/mcp/mcp-server-novice-simplified.js +11 -17
  184. package/dist/src/mcp/mcp-server-novice.js +11 -17
  185. package/dist/src/mcp/mcp-server-sdk.js +11 -17
  186. package/dist/src/mcp/mcp-server.js +1620 -1484
  187. package/dist/src/mcp/ruv-swarm-wrapper.js +209 -239
  188. package/dist/src/memory/advanced-serializer.js +609 -589
  189. package/dist/src/memory/enhanced-examples.js +220 -305
  190. package/dist/src/memory/enhanced-memory.js +295 -336
  191. package/dist/src/memory/enhanced-session-serializer.js +408 -492
  192. package/dist/src/memory/fallback-memory-system.js +900 -1021
  193. package/dist/src/memory/fallback-store.js +93 -131
  194. package/dist/src/memory/high-performance-serialization.js +592 -730
  195. package/dist/src/memory/in-memory-store.js +161 -213
  196. package/dist/src/memory/index.js +123 -157
  197. package/dist/src/memory/lock-free-structures.js +578 -764
  198. package/dist/src/memory/memory-mapped-persistence.js +585 -766
  199. package/dist/src/memory/memory-pressure-manager.js +569 -707
  200. package/dist/src/memory/migration.js +358 -445
  201. package/dist/src/memory/shared-memory.js +641 -768
  202. package/dist/src/memory/sqlite-store.js +245 -325
  203. package/dist/src/memory/sqlite-wrapper.js +122 -151
  204. package/dist/src/memory/swarm-memory.js +470 -603
  205. package/dist/src/memory/test-example.js +126 -134
  206. package/dist/src/memory/ultra-fast-memory-store.js +622 -821
  207. package/dist/src/memory/unified-memory-manager.js +356 -437
  208. package/dist/src/migration/index.js +92 -0
  209. package/dist/src/migration/logger.js +121 -0
  210. package/dist/src/migration/migration-analyzer.js +268 -0
  211. package/dist/src/migration/migration-runner.js +522 -0
  212. package/dist/src/migration/migration-validator.js +285 -0
  213. package/dist/src/migration/progress-reporter.js +150 -0
  214. package/dist/src/migration/rollback-manager.js +321 -0
  215. package/dist/src/migration/tests/migration-system.test.js +7 -0
  216. package/dist/src/migration/types.js +3 -0
  217. package/dist/src/swarm/CodeRefactoringSwarm.js +777 -952
  218. package/dist/src/swarm/__tests__/integration.test.js +227 -0
  219. package/dist/src/swarm/__tests__/prompt-copier.test.js +344 -0
  220. package/dist/src/swarm/advanced-orchestrator.js +1095 -0
  221. package/dist/src/swarm/claude-code-interface.js +961 -0
  222. package/dist/src/swarm/claude-flow-executor.js +229 -0
  223. package/dist/src/swarm/consensus-coordinator.js +475 -0
  224. package/dist/src/swarm/coordinator.js +2993 -0
  225. package/dist/src/swarm/direct-executor.js +1180 -0
  226. package/dist/src/swarm/error-recovery/advanced-error-detection.js +691 -0
  227. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +998 -0
  228. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +1197 -0
  229. package/dist/src/swarm/error-recovery/recovery-monitoring.js +772 -0
  230. package/dist/src/swarm/error-recovery/resilience-architecture.js +714 -0
  231. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +1319 -0
  232. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +808 -0
  233. package/dist/src/swarm/executor-v2.js +322 -0
  234. package/dist/src/swarm/executor.js +815 -0
  235. package/dist/src/swarm/hive-mind-integration.js +703 -0
  236. package/dist/src/swarm/index.js +41 -0
  237. package/dist/src/swarm/json-output-aggregator.js +267 -0
  238. package/dist/src/swarm/large-scale-coordinator.js +542 -0
  239. package/dist/src/swarm/mcp-integration-wrapper.js +628 -0
  240. package/dist/src/swarm/memory.js +1117 -0
  241. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +348 -0
  242. package/dist/src/swarm/optimizations/async-file-manager.js +285 -0
  243. package/dist/src/swarm/optimizations/circular-buffer.js +162 -0
  244. package/dist/src/swarm/optimizations/connection-pool.js +244 -0
  245. package/dist/src/swarm/optimizations/index.js +28 -0
  246. package/dist/src/swarm/optimizations/optimized-executor.js +320 -0
  247. package/dist/src/swarm/optimizations/ttl-map.js +234 -0
  248. package/dist/src/swarm/prompt-cli.js +200 -0
  249. package/dist/src/swarm/prompt-copier-enhanced.js +202 -0
  250. package/dist/src/swarm/prompt-copier.js +381 -0
  251. package/dist/src/swarm/prompt-manager.js +295 -0
  252. package/dist/src/swarm/prompt-utils.js +310 -0
  253. package/dist/src/swarm/result-aggregator.js +718 -0
  254. package/dist/src/swarm/sparc-executor.js +1568 -0
  255. package/dist/src/swarm/strategies/auto.js +758 -0
  256. package/dist/src/swarm/strategies/base.js +128 -0
  257. package/dist/src/swarm/strategies/research.js +914 -0
  258. package/dist/src/swarm/strategies/strategy-metrics-patch.js +2 -0
  259. package/dist/src/swarm/types.js +52 -0
  260. package/dist/src/swarm/workers/copy-worker.js +56 -0
  261. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +332 -400
  262. package/dist/src/utils/github-cli-safe.js +56 -64
  263. package/dist/src/utils/github-cli-safety-wrapper.js +451 -546
  264. package/dist/src/utils/npx-isolated-cache.js +104 -119
  265. package/dist/src/utils/preference-manager.js +622 -652
  266. package/dist/src/utils/timezone-utils.js +86 -105
  267. package/dist/src/validators/epic-config-schema.js +214 -0
  268. package/dist/src/validators/index.js +10 -0
  269. package/dist/src/validators/swarm-init-validator.js +259 -0
  270. package/dist/src/validators/todowrite-batching-validator.js +215 -0
  271. package/dist/src/validators/todowrite-integration.js +187 -0
  272. package/package.json +2 -2
@@ -1,1269 +1,1129 @@
1
- import {
2
- printSuccess,
3
- printError,
4
- printWarning,
5
- execRuvSwarmHook,
6
- checkRuvSwarmAvailable,
7
- } from '../utils.js';
8
- import { SqliteMemoryStore } from '../../memory/sqlite-store.js';
9
- import { executeSessionStartSoulHook, executeSessionEndSoulHook } from './hooks/session-start-soul.js';
10
- import { enhancedPostEditHook } from '../../hooks/enhanced-post-edit-pipeline.js';
11
-
1
+ import { printSuccess, printError, printWarning, execRuvSwarmHook, checkRuvSwarmAvailable } from "../utils.js";
2
+ import { SqliteMemoryStore } from "../../memory/sqlite-store.js";
3
+ import { executeSessionStartSoulHook, executeSessionEndSoulHook } from "./hooks/session-start-soul.js";
12
4
  // Initialize memory store
13
5
  let memoryStore = null;
14
-
15
6
  async function getMemoryStore() {
16
- if (!memoryStore) {
17
- memoryStore = new SqliteMemoryStore();
18
- await memoryStore.initialize();
19
- }
20
- return memoryStore;
7
+ if (!memoryStore) {
8
+ memoryStore = new SqliteMemoryStore();
9
+ await memoryStore.initialize();
10
+ }
11
+ return memoryStore;
21
12
  }
22
-
23
13
  // Simple ID generator
24
14
  function generateId(prefix = 'id') {
25
- return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
15
+ return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
26
16
  }
27
-
28
17
  export async function hooksAction(subArgs, flags) {
29
- const subcommand = subArgs[0];
30
- const options = flags;
31
-
32
- if (options.help || options.h || !subcommand) {
33
- showHooksHelp();
34
- return;
35
- }
36
-
37
- try {
38
- switch (subcommand) {
39
- // Pre-Operation Hooks
40
- case 'pre-task':
41
- await preTaskCommand(subArgs, flags);
42
- break;
43
- case 'pre-edit':
44
- await preEditCommand(subArgs, flags);
45
- break;
46
- case 'pre-bash':
47
- case 'pre-command': // Support both names for compatibility
48
- await preBashCommand(subArgs, flags);
49
- break;
50
-
51
- // Post-Operation Hooks
52
- case 'post-task':
53
- await postTaskCommand(subArgs, flags);
54
- break;
55
- case 'post-edit':
56
- await postEditCommand(subArgs, flags);
57
- break;
58
- case 'post-bash':
59
- case 'post-command': // Support both names for compatibility
60
- await postBashCommand(subArgs, flags);
61
- break;
62
- case 'post-search':
63
- await postSearchCommand(subArgs, flags);
64
- break;
65
-
66
- // MCP Integration Hooks
67
- case 'mcp-initialized':
68
- await mcpInitializedCommand(subArgs, flags);
69
- break;
70
- case 'agent-spawned':
71
- await agentSpawnedCommand(subArgs, flags);
72
- break;
73
- case 'task-orchestrated':
74
- await taskOrchestratedCommand(subArgs, flags);
75
- break;
76
- case 'neural-trained':
77
- await neuralTrainedCommand(subArgs, flags);
78
- break;
79
-
80
- // Session Hooks
81
- case 'session-start':
82
- await sessionStartCommand(subArgs, flags);
83
- break;
84
- case 'session-end':
85
- await sessionEndCommand(subArgs, flags);
86
- break;
87
- case 'session-restore':
88
- await sessionRestoreCommand(subArgs, flags);
89
- break;
90
- case 'notify':
91
- await notifyCommand(subArgs, flags);
92
- break;
93
-
94
- default:
95
- printError(`Unknown hooks command: ${subcommand}`);
18
+ const subcommand = subArgs[0];
19
+ const options = flags;
20
+ if (options.help || options.h || !subcommand) {
96
21
  showHooksHelp();
22
+ return;
23
+ }
24
+ try {
25
+ switch(subcommand){
26
+ // Pre-Operation Hooks
27
+ case 'pre-task':
28
+ await preTaskCommand(subArgs, flags);
29
+ break;
30
+ case 'pre-edit':
31
+ await preEditCommand(subArgs, flags);
32
+ break;
33
+ case 'pre-bash':
34
+ case 'pre-command':
35
+ await preBashCommand(subArgs, flags);
36
+ break;
37
+ // Post-Operation Hooks
38
+ case 'post-task':
39
+ await postTaskCommand(subArgs, flags);
40
+ break;
41
+ case 'post-edit':
42
+ await postEditCommand(subArgs, flags);
43
+ break;
44
+ case 'post-bash':
45
+ case 'post-command':
46
+ await postBashCommand(subArgs, flags);
47
+ break;
48
+ case 'post-search':
49
+ await postSearchCommand(subArgs, flags);
50
+ break;
51
+ // MCP Integration Hooks
52
+ case 'mcp-initialized':
53
+ await mcpInitializedCommand(subArgs, flags);
54
+ break;
55
+ case 'agent-spawned':
56
+ await agentSpawnedCommand(subArgs, flags);
57
+ break;
58
+ case 'task-orchestrated':
59
+ await taskOrchestratedCommand(subArgs, flags);
60
+ break;
61
+ case 'neural-trained':
62
+ await neuralTrainedCommand(subArgs, flags);
63
+ break;
64
+ // Session Hooks
65
+ case 'session-start':
66
+ await sessionStartCommand(subArgs, flags);
67
+ break;
68
+ case 'session-end':
69
+ await sessionEndCommand(subArgs, flags);
70
+ break;
71
+ case 'session-restore':
72
+ await sessionRestoreCommand(subArgs, flags);
73
+ break;
74
+ case 'notify':
75
+ await notifyCommand(subArgs, flags);
76
+ break;
77
+ default:
78
+ printError(`Unknown hooks command: ${subcommand}`);
79
+ showHooksHelp();
80
+ }
81
+ } catch (err) {
82
+ printError(`Hooks command failed: ${err.message}`);
97
83
  }
98
- } catch (err) {
99
- printError(`Hooks command failed: ${err.message}`);
100
- }
101
84
  }
102
-
103
85
  // ===== PRE-OPERATION HOOKS =====
104
-
105
86
  async function preTaskCommand(subArgs, flags) {
106
- const options = flags;
107
- const description = options.description || 'Unnamed task';
108
- const taskId = options['task-id'] || options.taskId || generateId('task');
109
- const agentId = options['agent-id'] || options.agentId;
110
- const autoSpawnAgents = options['auto-spawn-agents'] !== 'false';
111
-
112
- console.log(`🔄 Executing pre-task hook...`);
113
- console.log(`📋 Task: ${description}`);
114
- console.log(`🆔 Task ID: ${taskId}`);
115
- if (agentId) console.log(`🤖 Agent: ${agentId}`);
116
-
117
- try {
118
- const store = await getMemoryStore();
119
- const taskData = {
120
- taskId,
121
- description,
122
- agentId,
123
- autoSpawnAgents,
124
- status: 'started',
125
- startedAt: new Date().toISOString(),
126
- };
127
-
128
- await store.store(`task:${taskId}`, taskData, {
129
- namespace: 'hooks:pre-task',
130
- metadata: { hookType: 'pre-task', agentId },
131
- });
132
-
133
- await store.store(
134
- `task-index:${Date.now()}`,
135
- {
136
- taskId,
137
- description,
138
- timestamp: new Date().toISOString(),
139
- },
140
- { namespace: 'task-index' },
141
- );
142
-
143
- console.log(` 💾 Saved to .swarm/memory.db`);
144
-
145
- // Execute ruv-swarm hook if available (with timeout for npx scenarios)
87
+ const options = flags;
88
+ const description = options.description || 'Unnamed task';
89
+ const taskId = options['task-id'] || options.taskId || generateId('task');
90
+ const agentId = options['agent-id'] || options.agentId;
91
+ const autoSpawnAgents = options['auto-spawn-agents'] !== 'false';
92
+ console.log(`🔄 Executing pre-task hook...`);
93
+ console.log(`📋 Task: ${description}`);
94
+ console.log(`🆔 Task ID: ${taskId}`);
95
+ if (agentId) console.log(`🤖 Agent: ${agentId}`);
146
96
  try {
147
- const checkPromise = checkRuvSwarmAvailable();
148
- const timeoutPromise = new Promise((_, reject) =>
149
- setTimeout(() => reject(new Error('Timeout')), 3000),
150
- );
151
-
152
- const isAvailable = await Promise.race([checkPromise, timeoutPromise]);
153
-
154
- if (isAvailable) {
155
- console.log(`\n🔄 Executing ruv-swarm pre-task hook...`);
156
- const hookResult = await execRuvSwarmHook('pre-task', {
157
- description,
158
- 'task-id': taskId,
159
- 'auto-spawn-agents': autoSpawnAgents,
160
- ...(agentId ? { 'agent-id': agentId } : {}),
97
+ const store = await getMemoryStore();
98
+ const taskData = {
99
+ taskId,
100
+ description,
101
+ agentId,
102
+ autoSpawnAgents,
103
+ status: 'started',
104
+ startedAt: new Date().toISOString()
105
+ };
106
+ await store.store(`task:${taskId}`, taskData, {
107
+ namespace: 'hooks:pre-task',
108
+ metadata: {
109
+ hookType: 'pre-task',
110
+ agentId
111
+ }
112
+ });
113
+ await store.store(`task-index:${Date.now()}`, {
114
+ taskId,
115
+ description,
116
+ timestamp: new Date().toISOString()
117
+ }, {
118
+ namespace: 'task-index'
161
119
  });
162
-
163
- if (hookResult.success) {
164
- await store.store(
165
- `task:${taskId}:ruv-output`,
166
- {
167
- output: hookResult.output,
168
- timestamp: new Date().toISOString(),
169
- },
170
- { namespace: 'hooks:ruv-swarm' },
171
- );
172
-
173
- printSuccess(`✅ Pre-task hook completed successfully`);
120
+ console.log(` 💾 Saved to .swarm/memory.db`);
121
+ // Execute ruv-swarm hook if available (with timeout for npx scenarios)
122
+ try {
123
+ const checkPromise = checkRuvSwarmAvailable();
124
+ const timeoutPromise = new Promise((_, reject)=>setTimeout(()=>reject(new Error('Timeout')), 3000));
125
+ const isAvailable = await Promise.race([
126
+ checkPromise,
127
+ timeoutPromise
128
+ ]);
129
+ if (isAvailable) {
130
+ console.log(`\n🔄 Executing ruv-swarm pre-task hook...`);
131
+ const hookResult = await execRuvSwarmHook('pre-task', {
132
+ description,
133
+ 'task-id': taskId,
134
+ 'auto-spawn-agents': autoSpawnAgents,
135
+ ...agentId ? {
136
+ 'agent-id': agentId
137
+ } : {}
138
+ });
139
+ if (hookResult.success) {
140
+ await store.store(`task:${taskId}:ruv-output`, {
141
+ output: hookResult.output,
142
+ timestamp: new Date().toISOString()
143
+ }, {
144
+ namespace: 'hooks:ruv-swarm'
145
+ });
146
+ printSuccess(`✅ Pre-task hook completed successfully`);
147
+ }
148
+ }
149
+ } catch (err) {
150
+ // Skip ruv-swarm hook if it times out or fails
151
+ console.log(`\n⚠️ Skipping ruv-swarm hook (${err.message})`);
174
152
  }
175
- }
153
+ console.log(`\n🎯 TASK PREPARATION COMPLETE`);
154
+ // Close the memory store to prevent hanging
155
+ if (memoryStore && memoryStore.close) {
156
+ memoryStore.close();
157
+ }
158
+ // Force exit after a short delay to ensure cleanup
159
+ setTimeout(()=>{
160
+ process.exit(0);
161
+ }, 100);
176
162
  } catch (err) {
177
- // Skip ruv-swarm hook if it times out or fails
178
- console.log(`\n⚠️ Skipping ruv-swarm hook (${err.message})`);
179
- }
180
-
181
- console.log(`\n🎯 TASK PREPARATION COMPLETE`);
182
-
183
- // Close the memory store to prevent hanging
184
- if (memoryStore && memoryStore.close) {
185
- memoryStore.close();
186
- }
187
-
188
- // Force exit after a short delay to ensure cleanup
189
- setTimeout(() => {
190
- process.exit(0);
191
- }, 100);
192
- } catch (err) {
193
- printError(`Pre-task hook failed: ${err.message}`);
194
-
195
- // Close the memory store on error too
196
- if (memoryStore && memoryStore.close) {
197
- memoryStore.close();
163
+ printError(`Pre-task hook failed: ${err.message}`);
164
+ // Close the memory store on error too
165
+ if (memoryStore && memoryStore.close) {
166
+ memoryStore.close();
167
+ }
168
+ // Force exit after a short delay to ensure cleanup
169
+ setTimeout(()=>{
170
+ process.exit(1);
171
+ }, 100);
198
172
  }
199
-
200
- // Force exit after a short delay to ensure cleanup
201
- setTimeout(() => {
202
- process.exit(1);
203
- }, 100);
204
- }
205
173
  }
206
-
207
174
  async function preEditCommand(subArgs, flags) {
208
- const options = flags;
209
- const file = options.file || 'unknown-file';
210
- const operation = options.operation || 'edit';
211
- const autoAssignAgents = options['auto-assign-agents'] || false;
212
- const loadContext = options['load-context'] || false;
213
-
214
- console.log(`📝 Executing pre-edit hook...`);
215
- console.log(`📄 File: ${file}`);
216
- console.log(`⚙️ Operation: ${operation}`);
217
- if (autoAssignAgents) console.log(`🤖 Auto-assign agents: ENABLED`);
218
- if (loadContext) console.log(`🔄 Load context: ENABLED`);
219
-
220
- try {
221
- const store = await getMemoryStore();
222
-
223
- // Auto-assign agents based on file type
224
- let assignedAgentType = 'general';
225
- let recommendedAgent = null;
226
-
227
- if (autoAssignAgents) {
228
- const path = await import('path');
229
- const ext = path.extname(file).toLowerCase();
230
-
231
- const agentMapping = {
232
- '.js': 'javascript-developer',
233
- '.ts': 'typescript-developer',
234
- '.py': 'python-developer',
235
- '.go': 'golang-developer',
236
- '.rs': 'rust-developer',
237
- '.java': 'java-developer',
238
- '.cpp': 'cpp-developer',
239
- '.c': 'c-developer',
240
- '.css': 'frontend-developer',
241
- '.html': 'frontend-developer',
242
- '.vue': 'frontend-developer',
243
- '.react': 'frontend-developer',
244
- '.md': 'technical-writer',
245
- '.yml': 'devops-engineer',
246
- '.yaml': 'devops-engineer',
247
- '.json': 'config-specialist',
248
- '.sql': 'database-expert',
249
- '.sh': 'system-admin',
250
- '.dockerfile': 'devops-engineer',
251
- };
252
-
253
- assignedAgentType = agentMapping[ext] || 'general-developer';
254
- recommendedAgent = {
255
- type: assignedAgentType,
256
- file: file,
257
- extension: ext,
258
- recommended: true,
259
- };
260
-
261
- console.log(` 🤖 Recommended agent: ${assignedAgentType}`);
262
- }
263
-
264
- // Load context if requested
265
- let contextData = null;
266
- if (loadContext) {
267
- try {
268
- // Check if file exists and get basic info
269
- const fs = await import('fs');
270
- const path = await import('path');
271
-
272
- if (fs.existsSync(file)) {
273
- const stats = fs.statSync(file);
274
- const dirname = path.dirname(file);
275
- const basename = path.basename(file);
276
-
277
- contextData = {
278
- fileExists: true,
279
- size: stats.size,
280
- modified: stats.mtime,
281
- directory: dirname,
282
- filename: basename,
283
- isDirectory: stats.isDirectory(),
284
- };
285
-
286
- console.log(` 📁 Context loaded: ${basename} (${stats.size} bytes)`);
287
- } else {
288
- contextData = {
289
- fileExists: false,
290
- willCreate: true,
291
- directory: path.dirname(file),
292
- filename: path.basename(file),
293
- };
294
- console.log(` 📁 Context: New file will be created`);
175
+ const options = flags;
176
+ const file = options.file || 'unknown-file';
177
+ const operation = options.operation || 'edit';
178
+ const autoAssignAgents = options['auto-assign-agents'] || false;
179
+ const loadContext = options['load-context'] || false;
180
+ console.log(`📝 Executing pre-edit hook...`);
181
+ console.log(`📄 File: ${file}`);
182
+ console.log(`⚙️ Operation: ${operation}`);
183
+ if (autoAssignAgents) console.log(`🤖 Auto-assign agents: ENABLED`);
184
+ if (loadContext) console.log(`🔄 Load context: ENABLED`);
185
+ try {
186
+ const store = await getMemoryStore();
187
+ // Auto-assign agents based on file type
188
+ let assignedAgentType = 'general';
189
+ let recommendedAgent = null;
190
+ if (autoAssignAgents) {
191
+ const path = await import("path");
192
+ const ext = path.extname(file).toLowerCase();
193
+ const agentMapping = {
194
+ '.js': 'javascript-developer',
195
+ '.ts': 'typescript-developer',
196
+ '.py': 'python-developer',
197
+ '.go': 'golang-developer',
198
+ '.rs': 'rust-developer',
199
+ '.java': 'java-developer',
200
+ '.cpp': 'cpp-developer',
201
+ '.c': 'c-developer',
202
+ '.css': 'frontend-developer',
203
+ '.html': 'frontend-developer',
204
+ '.vue': 'frontend-developer',
205
+ '.react': 'frontend-developer',
206
+ '.md': 'technical-writer',
207
+ '.yml': 'devops-engineer',
208
+ '.yaml': 'devops-engineer',
209
+ '.json': 'config-specialist',
210
+ '.sql': 'database-expert',
211
+ '.sh': 'system-admin',
212
+ '.dockerfile': 'devops-engineer'
213
+ };
214
+ assignedAgentType = agentMapping[ext] || 'general-developer';
215
+ recommendedAgent = {
216
+ type: assignedAgentType,
217
+ file: file,
218
+ extension: ext,
219
+ recommended: true
220
+ };
221
+ console.log(` 🤖 Recommended agent: ${assignedAgentType}`);
295
222
  }
296
- } catch (err) {
297
- console.log(` ⚠️ Warning: Could not load context for ${file}`);
298
- contextData = { error: err.message };
299
- }
300
- }
301
-
302
- const editData = {
303
- file,
304
- operation,
305
- timestamp: new Date().toISOString(),
306
- editId: generateId('edit'),
307
- autoAssignAgents,
308
- loadContext,
309
- assignedAgentType,
310
- recommendedAgent,
311
- contextData,
312
- };
313
-
314
- await store.store(`edit:${editData.editId}:pre`, editData, {
315
- namespace: 'hooks:pre-edit',
316
- metadata: { hookType: 'pre-edit', file, agentType: assignedAgentType },
317
- });
318
-
319
- // Store agent recommendation if enabled
320
- if (autoAssignAgents && recommendedAgent) {
321
- await store.store(`agent-recommendation:${file}`, recommendedAgent, {
322
- namespace: 'agent-assignments',
323
- ttl: 3600, // 1 hour
324
- });
223
+ // Load context if requested
224
+ let contextData = null;
225
+ if (loadContext) {
226
+ try {
227
+ // Check if file exists and get basic info
228
+ const fs = await import("fs");
229
+ const path = await import("path");
230
+ if (fs.existsSync(file)) {
231
+ const stats = fs.statSync(file);
232
+ const dirname = path.dirname(file);
233
+ const basename = path.basename(file);
234
+ contextData = {
235
+ fileExists: true,
236
+ size: stats.size,
237
+ modified: stats.mtime,
238
+ directory: dirname,
239
+ filename: basename,
240
+ isDirectory: stats.isDirectory()
241
+ };
242
+ console.log(` 📁 Context loaded: ${basename} (${stats.size} bytes)`);
243
+ } else {
244
+ contextData = {
245
+ fileExists: false,
246
+ willCreate: true,
247
+ directory: path.dirname(file),
248
+ filename: path.basename(file)
249
+ };
250
+ console.log(` 📁 Context: New file will be created`);
251
+ }
252
+ } catch (err) {
253
+ console.log(` ⚠️ Warning: Could not load context for ${file}`);
254
+ contextData = {
255
+ error: err.message
256
+ };
257
+ }
258
+ }
259
+ const editData = {
260
+ file,
261
+ operation,
262
+ timestamp: new Date().toISOString(),
263
+ editId: generateId('edit'),
264
+ autoAssignAgents,
265
+ loadContext,
266
+ assignedAgentType,
267
+ recommendedAgent,
268
+ contextData
269
+ };
270
+ await store.store(`edit:${editData.editId}:pre`, editData, {
271
+ namespace: 'hooks:pre-edit',
272
+ metadata: {
273
+ hookType: 'pre-edit',
274
+ file,
275
+ agentType: assignedAgentType
276
+ }
277
+ });
278
+ // Store agent recommendation if enabled
279
+ if (autoAssignAgents && recommendedAgent) {
280
+ await store.store(`agent-recommendation:${file}`, recommendedAgent, {
281
+ namespace: 'agent-assignments',
282
+ ttl: 3600
283
+ });
284
+ }
285
+ console.log(` 💾 Pre-edit state saved to .swarm/memory.db`);
286
+ printSuccess(`✅ Pre-edit hook completed`);
287
+ } catch (err) {
288
+ printError(`Pre-edit hook failed: ${err.message}`);
325
289
  }
326
-
327
- console.log(` 💾 Pre-edit state saved to .swarm/memory.db`);
328
- printSuccess(`✅ Pre-edit hook completed`);
329
- } catch (err) {
330
- printError(`Pre-edit hook failed: ${err.message}`);
331
- }
332
290
  }
333
-
334
291
  async function preBashCommand(subArgs, flags) {
335
- const options = flags;
336
- const command = options.command || subArgs.slice(1).join(' ') || '';
337
- const workingDir = options.cwd || process.cwd();
338
- const validateSafety =
339
- options['validate-safety'] === true ||
340
- options['validate-safety'] === 'true' ||
341
- options.validate === true ||
342
- options.validate === 'true' ||
343
- false;
344
- const prepareResources =
345
- options['prepare-resources'] === true || options['prepare-resources'] === 'true' || false;
346
-
347
- console.log(`🔧 Executing pre-bash hook...`);
348
- console.log(`📜 Command: ${command}`);
349
- console.log(`📁 Working dir: ${workingDir}`);
350
- if (validateSafety) console.log(`🔒 Safety validation: ENABLED`);
351
- if (prepareResources) console.log(`🛠️ Resource preparation: ENABLED`);
352
-
353
- try {
354
- const store = await getMemoryStore();
355
- let safetyResult = 'skipped';
356
-
357
- if (validateSafety) {
358
- // Basic safety validation
359
- const dangerousCommands = [
360
- 'rm -rf /',
361
- 'rm -rf .',
362
- 'rm -rf *',
363
- 'format',
364
- 'fdisk',
365
- 'mkfs',
366
- 'curl * | bash',
367
- 'wget * | sh',
368
- 'eval',
369
- 'exec',
370
- 'chmod 777',
371
- ];
372
-
373
- const isDangerous =
374
- command && typeof command === 'string' && command.length > 0
375
- ? dangerousCommands.some((dangerous) =>
376
- command.toLowerCase().includes(dangerous.toLowerCase()),
377
- )
378
- : false;
379
-
380
- safetyResult = isDangerous ? 'dangerous' : 'safe';
381
-
382
- if (isDangerous) {
383
- console.log(` ⚠️ Safety check: DANGEROUS COMMAND DETECTED`);
384
- console.log(` 🚫 Command blocked for safety`);
385
- printError(`Command blocked due to safety validation: ${command}`);
386
- return;
387
- }
388
- }
389
-
390
- if (prepareResources) {
391
- // Resource preparation - create working directory if needed
392
- const fs = await import('fs');
393
- const path = await import('path');
394
-
395
- if (!fs.existsSync(workingDir)) {
396
- fs.mkdirSync(workingDir, { recursive: true });
397
- console.log(` 📁 Created working directory: ${workingDir}`);
398
- }
399
-
400
- // Check available disk space
401
- try {
402
- const stats = fs.statSync(workingDir);
403
- console.log(` 💾 Working directory prepared`);
404
- } catch (err) {
405
- console.log(` ⚠️ Warning: Could not check working directory`);
406
- }
292
+ const options = flags;
293
+ const command = options.command || subArgs.slice(1).join(' ') || '';
294
+ const workingDir = options.cwd || process.cwd();
295
+ const validateSafety = options['validate-safety'] === true || options['validate-safety'] === 'true' || options.validate === true || options.validate === 'true' || false;
296
+ const prepareResources = options['prepare-resources'] === true || options['prepare-resources'] === 'true' || false;
297
+ console.log(`🔧 Executing pre-bash hook...`);
298
+ console.log(`📜 Command: ${command}`);
299
+ console.log(`📁 Working dir: ${workingDir}`);
300
+ if (validateSafety) console.log(`🔒 Safety validation: ENABLED`);
301
+ if (prepareResources) console.log(`🛠️ Resource preparation: ENABLED`);
302
+ try {
303
+ const store = await getMemoryStore();
304
+ let safetyResult = 'skipped';
305
+ if (validateSafety) {
306
+ // Basic safety validation
307
+ const dangerousCommands = [
308
+ 'rm -rf /',
309
+ 'rm -rf .',
310
+ 'rm -rf *',
311
+ 'format',
312
+ 'fdisk',
313
+ 'mkfs',
314
+ 'curl * | bash',
315
+ 'wget * | sh',
316
+ 'eval',
317
+ 'exec',
318
+ 'chmod 777'
319
+ ];
320
+ const isDangerous = command && typeof command === 'string' && command.length > 0 ? dangerousCommands.some((dangerous)=>command.toLowerCase().includes(dangerous.toLowerCase())) : false;
321
+ safetyResult = isDangerous ? 'dangerous' : 'safe';
322
+ if (isDangerous) {
323
+ console.log(` ⚠️ Safety check: DANGEROUS COMMAND DETECTED`);
324
+ console.log(` 🚫 Command blocked for safety`);
325
+ printError(`Command blocked due to safety validation: ${command}`);
326
+ return;
327
+ }
328
+ }
329
+ if (prepareResources) {
330
+ // Resource preparation - create working directory if needed
331
+ const fs = await import("fs");
332
+ const path = await import("path");
333
+ if (!fs.existsSync(workingDir)) {
334
+ fs.mkdirSync(workingDir, {
335
+ recursive: true
336
+ });
337
+ console.log(` 📁 Created working directory: ${workingDir}`);
338
+ }
339
+ // Check available disk space
340
+ try {
341
+ const stats = fs.statSync(workingDir);
342
+ console.log(` 💾 Working directory prepared`);
343
+ } catch (err) {
344
+ console.log(` ⚠️ Warning: Could not check working directory`);
345
+ }
346
+ }
347
+ const bashData = {
348
+ command,
349
+ workingDir,
350
+ timestamp: new Date().toISOString(),
351
+ bashId: generateId('bash'),
352
+ safety: safetyResult,
353
+ validationEnabled: validateSafety,
354
+ resourcesPrepped: prepareResources
355
+ };
356
+ await store.store(`bash:${bashData.bashId}:pre`, bashData, {
357
+ namespace: 'hooks:pre-bash',
358
+ metadata: {
359
+ hookType: 'pre-bash',
360
+ command,
361
+ safety: safetyResult
362
+ }
363
+ });
364
+ console.log(` 💾 Command logged to .swarm/memory.db`);
365
+ console.log(` 🔒 Safety check: ${safetyResult.toUpperCase()}`);
366
+ printSuccess(`✅ Pre-bash hook completed`);
367
+ } catch (err) {
368
+ printError(`Pre-bash hook failed: ${err.message}`);
407
369
  }
408
-
409
- const bashData = {
410
- command,
411
- workingDir,
412
- timestamp: new Date().toISOString(),
413
- bashId: generateId('bash'),
414
- safety: safetyResult,
415
- validationEnabled: validateSafety,
416
- resourcesPrepped: prepareResources,
417
- };
418
-
419
- await store.store(`bash:${bashData.bashId}:pre`, bashData, {
420
- namespace: 'hooks:pre-bash',
421
- metadata: { hookType: 'pre-bash', command, safety: safetyResult },
422
- });
423
-
424
- console.log(` 💾 Command logged to .swarm/memory.db`);
425
- console.log(` 🔒 Safety check: ${safetyResult.toUpperCase()}`);
426
- printSuccess(`✅ Pre-bash hook completed`);
427
- } catch (err) {
428
- printError(`Pre-bash hook failed: ${err.message}`);
429
- }
430
370
  }
431
-
432
371
  // ===== POST-OPERATION HOOKS =====
433
-
434
372
  async function postTaskCommand(subArgs, flags) {
435
- const options = flags;
436
- const taskId = options['task-id'] || options.taskId || generateId('task');
437
- const analyzePerformance = options['analyze-performance'] !== 'false';
438
-
439
- console.log(`🏁 Executing post-task hook...`);
440
- console.log(`🆔 Task ID: ${taskId}`);
441
-
442
- try {
443
- const store = await getMemoryStore();
444
- const taskData = await store.retrieve(`task:${taskId}`, {
445
- namespace: 'hooks:pre-task',
446
- });
447
-
448
- const completedData = {
449
- ...(taskData || {}),
450
- status: 'completed',
451
- completedAt: new Date().toISOString(),
452
- duration: taskData ? Date.now() - new Date(taskData.startedAt).getTime() : null,
453
- };
454
-
455
- await store.store(`task:${taskId}:completed`, completedData, {
456
- namespace: 'hooks:post-task',
457
- metadata: { hookType: 'post-task' },
458
- });
459
-
460
- if (analyzePerformance && completedData.duration) {
461
- const metrics = {
462
- taskId,
463
- duration: completedData.duration,
464
- durationHuman: `${(completedData.duration / 1000).toFixed(2)}s`,
465
- timestamp: new Date().toISOString(),
466
- };
467
-
468
- await store.store(`metrics:${taskId}`, metrics, {
469
- namespace: 'performance',
470
- });
471
- console.log(` 📊 Performance: ${metrics.durationHuman}`);
373
+ const options = flags;
374
+ const taskId = options['task-id'] || options.taskId || generateId('task');
375
+ const analyzePerformance = options['analyze-performance'] !== 'false';
376
+ console.log(`🏁 Executing post-task hook...`);
377
+ console.log(`🆔 Task ID: ${taskId}`);
378
+ try {
379
+ const store = await getMemoryStore();
380
+ const taskData = await store.retrieve(`task:${taskId}`, {
381
+ namespace: 'hooks:pre-task'
382
+ });
383
+ const completedData = {
384
+ ...taskData || {},
385
+ status: 'completed',
386
+ completedAt: new Date().toISOString(),
387
+ duration: taskData ? Date.now() - new Date(taskData.startedAt).getTime() : null
388
+ };
389
+ await store.store(`task:${taskId}:completed`, completedData, {
390
+ namespace: 'hooks:post-task',
391
+ metadata: {
392
+ hookType: 'post-task'
393
+ }
394
+ });
395
+ if (analyzePerformance && completedData.duration) {
396
+ const metrics = {
397
+ taskId,
398
+ duration: completedData.duration,
399
+ durationHuman: `${(completedData.duration / 1000).toFixed(2)}s`,
400
+ timestamp: new Date().toISOString()
401
+ };
402
+ await store.store(`metrics:${taskId}`, metrics, {
403
+ namespace: 'performance'
404
+ });
405
+ console.log(` 📊 Performance: ${metrics.durationHuman}`);
406
+ }
407
+ console.log(` 💾 Task completion saved to .swarm/memory.db`);
408
+ printSuccess(`✅ Post-task hook completed`);
409
+ } catch (err) {
410
+ printError(`Post-task hook failed: ${err.message}`);
472
411
  }
473
-
474
- console.log(` 💾 Task completion saved to .swarm/memory.db`);
475
- printSuccess(`✅ Post-task hook completed`);
476
- } catch (err) {
477
- printError(`Post-task hook failed: ${err.message}`);
478
- }
479
412
  }
480
-
481
413
  async function postEditCommand(subArgs, flags) {
482
- const options = flags;
483
- const file = options.file || 'unknown-file';
484
- let memoryKey = options['memory-key'] || options.memoryKey;
485
-
486
- // Handle case where memory-key is passed as a boolean flag without value
487
- if (memoryKey === true) {
488
- // Generate a default memory key based on the file path and timestamp
489
- const path = await import('path');
490
- const basename = path.basename(file);
491
- memoryKey = `edit:${basename}:${Date.now()}`;
492
- }
493
-
494
- const format = options.format || false;
495
- const updateMemory = options['update-memory'] || false;
496
- const trainNeural = options['train-neural'] || false;
497
-
498
- console.log(`📝 Executing post-edit hook...`);
499
- console.log(`📄 File: ${file}`);
500
- if (memoryKey) console.log(`💾 Memory key: ${memoryKey}`);
501
- if (format) console.log(`🎨 Auto-format: ENABLED`);
502
- if (updateMemory) console.log(`🧠 Memory update: ENABLED`);
503
- if (trainNeural) console.log(`🤖 Neural training: ENABLED`);
504
-
505
- try {
506
- const store = await getMemoryStore();
507
- const path = await import('path');
508
- const fs = await import('fs');
509
-
510
- // Auto-format file if requested
511
- let formatResult = null;
512
- if (format && fs.existsSync(file)) {
513
- const ext = path.extname(file).toLowerCase();
514
- const formatters = {
515
- '.js': 'prettier',
516
- '.ts': 'prettier',
517
- '.json': 'prettier',
518
- '.css': 'prettier',
519
- '.html': 'prettier',
520
- '.py': 'black',
521
- '.go': 'gofmt',
522
- '.rs': 'rustfmt',
523
- '.java': 'google-java-format',
524
- '.cpp': 'clang-format',
525
- '.c': 'clang-format',
526
- };
527
-
528
- const formatter = formatters[ext];
529
- if (formatter) {
530
- console.log(` 🎨 Auto-formatting with ${formatter}...`);
531
- formatResult = {
532
- formatter,
533
- extension: ext,
534
- attempted: true,
535
- timestamp: new Date().toISOString(),
536
- };
537
- } else {
538
- console.log(` ⚠️ No formatter available for ${ext}`);
539
- formatResult = {
540
- extension: ext,
541
- attempted: false,
542
- reason: 'No formatter available',
543
- };
544
- }
545
- }
546
-
547
- // Update memory with edit context
548
- let memoryUpdate = null;
549
- if (updateMemory) {
550
- const editContext = {
551
- file,
552
- editedAt: new Date().toISOString(),
553
- editId: generateId('edit'),
554
- formatted: formatResult?.attempted || false,
555
- fileSize: fs.existsSync(file) ? fs.statSync(file).size : 0,
556
- directory: path.dirname(file),
557
- basename: path.basename(file),
558
- };
559
-
560
- memoryUpdate = editContext;
561
-
562
- // Store in coordination namespace
563
- await store.store(`edit-context:${editContext.editId}`, editContext, {
564
- namespace: 'coordination',
565
- metadata: { type: 'edit-context', file },
566
- });
567
-
568
- console.log(` 🧠 Edit context stored in memory`);
414
+ const options = flags;
415
+ const file = options.file || 'unknown-file';
416
+ let memoryKey = options['memory-key'] || options.memoryKey;
417
+ // Handle case where memory-key is passed as a boolean flag without value
418
+ if (memoryKey === true) {
419
+ // Generate a default memory key based on the file path and timestamp
420
+ const path = await import("path");
421
+ const basename = path.basename(file);
422
+ memoryKey = `edit:${basename}:${Date.now()}`;
569
423
  }
570
-
571
- // Train neural patterns if requested
572
- let neuralTraining = null;
573
- if (trainNeural) {
574
- // Simulate neural training with file patterns
575
- const ext = path.extname(file).toLowerCase();
576
- const basename = path.basename(file);
577
- const editTime = new Date().toISOString();
578
-
579
- const patterns = {
580
- fileType: ext,
581
- fileName: basename,
582
- editTime,
583
- confidence: Math.random() * 0.5 + 0.5, // 50-100% confidence
584
- patterns: [
585
- `${ext}_edit_pattern`,
586
- `${basename}_modification`,
587
- `edit_${Date.now()}_sequence`,
588
- ],
589
- };
590
-
591
- neuralTraining = patterns;
592
-
593
- await store.store(`neural-pattern:${generateId('pattern')}`, patterns, {
594
- namespace: 'neural-training',
595
- metadata: { type: 'edit-pattern', file, extension: ext },
596
- });
597
-
598
- console.log(
599
- ` 🤖 Neural patterns trained (${(patterns.confidence * 100).toFixed(1)}% confidence)`,
600
- );
601
- }
602
-
603
- const editData = {
604
- file,
605
- memoryKey,
606
- timestamp: new Date().toISOString(),
607
- editId: generateId('edit'),
608
- format,
609
- updateMemory,
610
- trainNeural,
611
- formatResult,
612
- memoryUpdate,
613
- neuralTraining,
614
- };
615
-
616
- await store.store(`edit:${editData.editId}:post`, editData, {
617
- namespace: 'hooks:post-edit',
618
- metadata: { hookType: 'post-edit', file, formatted: formatResult?.attempted || false },
619
- });
620
-
621
- if (memoryKey && typeof memoryKey === 'string') {
622
- await store.store(
623
- memoryKey,
624
- {
625
- file,
626
- editedAt: new Date().toISOString(),
627
- editId: editData.editId,
628
- enhanced: true,
629
- formatResult,
630
- memoryUpdate,
631
- neuralTraining,
632
- },
633
- { namespace: 'coordination' },
634
- );
424
+ const format = options.format || false;
425
+ const updateMemory = options['update-memory'] || false;
426
+ const trainNeural = options['train-neural'] || false;
427
+ console.log(`📝 Executing post-edit hook...`);
428
+ console.log(`📄 File: ${file}`);
429
+ if (memoryKey) console.log(`💾 Memory key: ${memoryKey}`);
430
+ if (format) console.log(`🎨 Auto-format: ENABLED`);
431
+ if (updateMemory) console.log(`🧠 Memory update: ENABLED`);
432
+ if (trainNeural) console.log(`🤖 Neural training: ENABLED`);
433
+ try {
434
+ const store = await getMemoryStore();
435
+ const path = await import("path");
436
+ const fs = await import("fs");
437
+ // Auto-format file if requested
438
+ let formatResult = null;
439
+ if (format && fs.existsSync(file)) {
440
+ const ext = path.extname(file).toLowerCase();
441
+ const formatters = {
442
+ '.js': 'prettier',
443
+ '.ts': 'prettier',
444
+ '.json': 'prettier',
445
+ '.css': 'prettier',
446
+ '.html': 'prettier',
447
+ '.py': 'black',
448
+ '.go': 'gofmt',
449
+ '.rs': 'rustfmt',
450
+ '.java': 'google-java-format',
451
+ '.cpp': 'clang-format',
452
+ '.c': 'clang-format'
453
+ };
454
+ const formatter = formatters[ext];
455
+ if (formatter) {
456
+ console.log(` 🎨 Auto-formatting with ${formatter}...`);
457
+ formatResult = {
458
+ formatter,
459
+ extension: ext,
460
+ attempted: true,
461
+ timestamp: new Date().toISOString()
462
+ };
463
+ } else {
464
+ console.log(` ⚠️ No formatter available for ${ext}`);
465
+ formatResult = {
466
+ extension: ext,
467
+ attempted: false,
468
+ reason: 'No formatter available'
469
+ };
470
+ }
471
+ }
472
+ // Update memory with edit context
473
+ let memoryUpdate = null;
474
+ if (updateMemory) {
475
+ const editContext = {
476
+ file,
477
+ editedAt: new Date().toISOString(),
478
+ editId: generateId('edit'),
479
+ formatted: formatResult?.attempted || false,
480
+ fileSize: fs.existsSync(file) ? fs.statSync(file).size : 0,
481
+ directory: path.dirname(file),
482
+ basename: path.basename(file)
483
+ };
484
+ memoryUpdate = editContext;
485
+ // Store in coordination namespace
486
+ await store.store(`edit-context:${editContext.editId}`, editContext, {
487
+ namespace: 'coordination',
488
+ metadata: {
489
+ type: 'edit-context',
490
+ file
491
+ }
492
+ });
493
+ console.log(` 🧠 Edit context stored in memory`);
494
+ }
495
+ // Train neural patterns if requested
496
+ let neuralTraining = null;
497
+ if (trainNeural) {
498
+ // Simulate neural training with file patterns
499
+ const ext = path.extname(file).toLowerCase();
500
+ const basename = path.basename(file);
501
+ const editTime = new Date().toISOString();
502
+ const patterns = {
503
+ fileType: ext,
504
+ fileName: basename,
505
+ editTime,
506
+ confidence: Math.random() * 0.5 + 0.5,
507
+ patterns: [
508
+ `${ext}_edit_pattern`,
509
+ `${basename}_modification`,
510
+ `edit_${Date.now()}_sequence`
511
+ ]
512
+ };
513
+ neuralTraining = patterns;
514
+ await store.store(`neural-pattern:${generateId('pattern')}`, patterns, {
515
+ namespace: 'neural-training',
516
+ metadata: {
517
+ type: 'edit-pattern',
518
+ file,
519
+ extension: ext
520
+ }
521
+ });
522
+ console.log(` 🤖 Neural patterns trained (${(patterns.confidence * 100).toFixed(1)}% confidence)`);
523
+ }
524
+ const editData = {
525
+ file,
526
+ memoryKey,
527
+ timestamp: new Date().toISOString(),
528
+ editId: generateId('edit'),
529
+ format,
530
+ updateMemory,
531
+ trainNeural,
532
+ formatResult,
533
+ memoryUpdate,
534
+ neuralTraining
535
+ };
536
+ await store.store(`edit:${editData.editId}:post`, editData, {
537
+ namespace: 'hooks:post-edit',
538
+ metadata: {
539
+ hookType: 'post-edit',
540
+ file,
541
+ formatted: formatResult?.attempted || false
542
+ }
543
+ });
544
+ if (memoryKey && typeof memoryKey === 'string') {
545
+ await store.store(memoryKey, {
546
+ file,
547
+ editedAt: new Date().toISOString(),
548
+ editId: editData.editId,
549
+ enhanced: true,
550
+ formatResult,
551
+ memoryUpdate,
552
+ neuralTraining
553
+ }, {
554
+ namespace: 'coordination'
555
+ });
556
+ }
557
+ const historyKey = `file-history:${file.replace(/\//g, '_')}:${Date.now()}`;
558
+ await store.store(historyKey, {
559
+ file,
560
+ editId: editData.editId,
561
+ timestamp: new Date().toISOString(),
562
+ enhanced: true,
563
+ features: {
564
+ format,
565
+ updateMemory,
566
+ trainNeural
567
+ }
568
+ }, {
569
+ namespace: 'file-history'
570
+ });
571
+ console.log(` 💾 Post-edit data saved to .swarm/memory.db`);
572
+ printSuccess(`✅ Post-edit hook completed`);
573
+ } catch (err) {
574
+ printError(`Post-edit hook failed: ${err.message}`);
635
575
  }
636
-
637
- const historyKey = `file-history:${file.replace(/\//g, '_')}:${Date.now()}`;
638
- await store.store(
639
- historyKey,
640
- {
641
- file,
642
- editId: editData.editId,
643
- timestamp: new Date().toISOString(),
644
- enhanced: true,
645
- features: {
646
- format,
647
- updateMemory,
648
- trainNeural,
649
- },
650
- },
651
- { namespace: 'file-history' },
652
- );
653
-
654
- console.log(` 💾 Post-edit data saved to .swarm/memory.db`);
655
- printSuccess(`✅ Post-edit hook completed`);
656
- } catch (err) {
657
- printError(`Post-edit hook failed: ${err.message}`);
658
- }
659
576
  }
660
-
661
577
  async function postBashCommand(subArgs, flags) {
662
- const options = flags;
663
- const command = options.command || subArgs.slice(1).join(' ');
664
- const exitCode = options['exit-code'] || '0';
665
- const output = options.output || '';
666
- const trackMetrics = options['track-metrics'] || false;
667
- const storeResults = options['store-results'] || false;
668
- const duration = options.duration || 0;
669
-
670
- console.log(`🔧 Executing post-bash hook...`);
671
- console.log(`📜 Command: ${command}`);
672
- console.log(`📊 Exit code: ${exitCode}`);
673
- if (trackMetrics) console.log(`📊 Metrics tracking: ENABLED`);
674
- if (storeResults) console.log(`💾 Results storage: ENABLED`);
675
-
676
- try {
677
- const store = await getMemoryStore();
678
- const startTime = Date.now();
679
-
680
- // Calculate performance metrics if enabled
681
- let metrics = null;
682
- if (trackMetrics) {
683
- const commandLength = command.length;
684
- const outputLength = output.length;
685
- const success = parseInt(exitCode) === 0;
686
-
687
- metrics = {
688
- commandLength,
689
- outputLength,
690
- success,
691
- duration: parseInt(duration) || 0,
692
- exitCode: parseInt(exitCode),
693
- timestamp: new Date().toISOString(),
694
- complexity: commandLength > 100 ? 'high' : commandLength > 50 ? 'medium' : 'low',
695
- };
696
-
697
- console.log(
698
- ` 📊 Command metrics: ${commandLength} chars, ${outputLength} output, ${success ? 'SUCCESS' : 'FAILED'}`,
699
- );
700
- }
701
-
702
- const bashData = {
703
- command,
704
- exitCode,
705
- output: storeResults ? output.substring(0, 5000) : output.substring(0, 1000), // Store more if requested
706
- timestamp: new Date().toISOString(),
707
- bashId: generateId('bash'),
708
- trackMetrics,
709
- storeResults,
710
- metrics,
711
- };
712
-
713
- await store.store(`bash:${bashData.bashId}:post`, bashData, {
714
- namespace: 'hooks:post-bash',
715
- metadata: { hookType: 'post-bash', command, exitCode, success: parseInt(exitCode) === 0 },
716
- });
717
-
718
- // Store detailed results if enabled
719
- if (storeResults) {
720
- await store.store(
721
- `command-results:${bashData.bashId}`,
722
- {
723
- command,
724
- exitCode,
725
- output,
726
- timestamp: new Date().toISOString(),
727
- fullOutput: true,
728
- },
729
- { namespace: 'command-results' },
730
- );
731
-
732
- console.log(` 💾 Full command results stored`);
733
- }
734
-
735
- // Store metrics if enabled
736
- if (trackMetrics && metrics) {
737
- await store.store(`command-metrics:${bashData.bashId}`, metrics, {
738
- namespace: 'performance-metrics',
739
- });
740
-
741
- // Update running metrics
742
- const existingMetrics = (await store.retrieve('command-metrics-summary', {
743
- namespace: 'performance-metrics',
744
- })) || { totalCommands: 0, successRate: 0, avgDuration: 0 };
745
-
746
- existingMetrics.totalCommands += 1;
747
- existingMetrics.successRate =
748
- (existingMetrics.successRate * (existingMetrics.totalCommands - 1) +
749
- (metrics.success ? 1 : 0)) /
750
- existingMetrics.totalCommands;
751
- existingMetrics.avgDuration =
752
- (existingMetrics.avgDuration * (existingMetrics.totalCommands - 1) + metrics.duration) /
753
- existingMetrics.totalCommands;
754
- existingMetrics.lastUpdated = new Date().toISOString();
755
-
756
- await store.store('command-metrics-summary', existingMetrics, {
757
- namespace: 'performance-metrics',
758
- });
578
+ const options = flags;
579
+ const command = options.command || subArgs.slice(1).join(' ');
580
+ const exitCode = options['exit-code'] || '0';
581
+ const output = options.output || '';
582
+ const trackMetrics = options['track-metrics'] || false;
583
+ const storeResults = options['store-results'] || false;
584
+ const duration = options.duration || 0;
585
+ console.log(`🔧 Executing post-bash hook...`);
586
+ console.log(`📜 Command: ${command}`);
587
+ console.log(`📊 Exit code: ${exitCode}`);
588
+ if (trackMetrics) console.log(`📊 Metrics tracking: ENABLED`);
589
+ if (storeResults) console.log(`💾 Results storage: ENABLED`);
590
+ try {
591
+ const store = await getMemoryStore();
592
+ const startTime = Date.now();
593
+ // Calculate performance metrics if enabled
594
+ let metrics = null;
595
+ if (trackMetrics) {
596
+ const commandLength = command.length;
597
+ const outputLength = output.length;
598
+ const success = parseInt(exitCode) === 0;
599
+ metrics = {
600
+ commandLength,
601
+ outputLength,
602
+ success,
603
+ duration: parseInt(duration) || 0,
604
+ exitCode: parseInt(exitCode),
605
+ timestamp: new Date().toISOString(),
606
+ complexity: commandLength > 100 ? 'high' : commandLength > 50 ? 'medium' : 'low'
607
+ };
608
+ console.log(` 📊 Command metrics: ${commandLength} chars, ${outputLength} output, ${success ? 'SUCCESS' : 'FAILED'}`);
609
+ }
610
+ const bashData = {
611
+ command,
612
+ exitCode,
613
+ output: storeResults ? output.substring(0, 5000) : output.substring(0, 1000),
614
+ timestamp: new Date().toISOString(),
615
+ bashId: generateId('bash'),
616
+ trackMetrics,
617
+ storeResults,
618
+ metrics
619
+ };
620
+ await store.store(`bash:${bashData.bashId}:post`, bashData, {
621
+ namespace: 'hooks:post-bash',
622
+ metadata: {
623
+ hookType: 'post-bash',
624
+ command,
625
+ exitCode,
626
+ success: parseInt(exitCode) === 0
627
+ }
628
+ });
629
+ // Store detailed results if enabled
630
+ if (storeResults) {
631
+ await store.store(`command-results:${bashData.bashId}`, {
632
+ command,
633
+ exitCode,
634
+ output,
635
+ timestamp: new Date().toISOString(),
636
+ fullOutput: true
637
+ }, {
638
+ namespace: 'command-results'
639
+ });
640
+ console.log(` 💾 Full command results stored`);
641
+ }
642
+ // Store metrics if enabled
643
+ if (trackMetrics && metrics) {
644
+ await store.store(`command-metrics:${bashData.bashId}`, metrics, {
645
+ namespace: 'performance-metrics'
646
+ });
647
+ // Update running metrics
648
+ const existingMetrics = await store.retrieve('command-metrics-summary', {
649
+ namespace: 'performance-metrics'
650
+ }) || {
651
+ totalCommands: 0,
652
+ successRate: 0,
653
+ avgDuration: 0
654
+ };
655
+ existingMetrics.totalCommands += 1;
656
+ existingMetrics.successRate = (existingMetrics.successRate * (existingMetrics.totalCommands - 1) + (metrics.success ? 1 : 0)) / existingMetrics.totalCommands;
657
+ existingMetrics.avgDuration = (existingMetrics.avgDuration * (existingMetrics.totalCommands - 1) + metrics.duration) / existingMetrics.totalCommands;
658
+ existingMetrics.lastUpdated = new Date().toISOString();
659
+ await store.store('command-metrics-summary', existingMetrics, {
660
+ namespace: 'performance-metrics'
661
+ });
662
+ }
663
+ // Update command history
664
+ await store.store(`command-history:${Date.now()}`, {
665
+ command,
666
+ exitCode,
667
+ timestamp: new Date().toISOString(),
668
+ success: parseInt(exitCode) === 0,
669
+ hasMetrics: trackMetrics,
670
+ hasResults: storeResults
671
+ }, {
672
+ namespace: 'command-history'
673
+ });
674
+ console.log(` 💾 Command execution logged to .swarm/memory.db`);
675
+ printSuccess(`✅ Post-bash hook completed`);
676
+ } catch (err) {
677
+ printError(`Post-bash hook failed: ${err.message}`);
759
678
  }
760
-
761
- // Update command history
762
- await store.store(
763
- `command-history:${Date.now()}`,
764
- {
765
- command,
766
- exitCode,
767
- timestamp: new Date().toISOString(),
768
- success: parseInt(exitCode) === 0,
769
- hasMetrics: trackMetrics,
770
- hasResults: storeResults,
771
- },
772
- { namespace: 'command-history' },
773
- );
774
-
775
- console.log(` 💾 Command execution logged to .swarm/memory.db`);
776
- printSuccess(`✅ Post-bash hook completed`);
777
- } catch (err) {
778
- printError(`Post-bash hook failed: ${err.message}`);
779
- }
780
679
  }
781
-
782
680
  async function postSearchCommand(subArgs, flags) {
783
- const options = flags;
784
- const query = options.query || subArgs.slice(1).join(' ');
785
- const resultCount = options['result-count'] || '0';
786
- const searchType = options.type || 'general';
787
-
788
- console.log(`🔍 Executing post-search hook...`);
789
- console.log(`🔎 Query: ${query}`);
790
- console.log(`📊 Results: ${resultCount}`);
791
-
792
- try {
793
- const store = await getMemoryStore();
794
- const searchData = {
795
- query,
796
- resultCount: parseInt(resultCount),
797
- searchType,
798
- timestamp: new Date().toISOString(),
799
- searchId: generateId('search'),
800
- };
801
-
802
- await store.store(`search:${searchData.searchId}`, searchData, {
803
- namespace: 'hooks:post-search',
804
- metadata: { hookType: 'post-search', query },
805
- });
806
-
807
- // Cache search for future use
808
- await store.store(
809
- `search-cache:${query}`,
810
- {
811
- resultCount: searchData.resultCount,
812
- cachedAt: new Date().toISOString(),
813
- },
814
- { namespace: 'search-cache', ttl: 3600 },
815
- ); // 1 hour TTL
816
-
817
- console.log(` 💾 Search results cached to .swarm/memory.db`);
818
- printSuccess(`✅ Post-search hook completed`);
819
- } catch (err) {
820
- printError(`Post-search hook failed: ${err.message}`);
821
- }
681
+ const options = flags;
682
+ const query = options.query || subArgs.slice(1).join(' ');
683
+ const resultCount = options['result-count'] || '0';
684
+ const searchType = options.type || 'general';
685
+ console.log(`🔍 Executing post-search hook...`);
686
+ console.log(`🔎 Query: ${query}`);
687
+ console.log(`📊 Results: ${resultCount}`);
688
+ try {
689
+ const store = await getMemoryStore();
690
+ const searchData = {
691
+ query,
692
+ resultCount: parseInt(resultCount),
693
+ searchType,
694
+ timestamp: new Date().toISOString(),
695
+ searchId: generateId('search')
696
+ };
697
+ await store.store(`search:${searchData.searchId}`, searchData, {
698
+ namespace: 'hooks:post-search',
699
+ metadata: {
700
+ hookType: 'post-search',
701
+ query
702
+ }
703
+ });
704
+ // Cache search for future use
705
+ await store.store(`search-cache:${query}`, {
706
+ resultCount: searchData.resultCount,
707
+ cachedAt: new Date().toISOString()
708
+ }, {
709
+ namespace: 'search-cache',
710
+ ttl: 3600
711
+ }); // 1 hour TTL
712
+ console.log(` 💾 Search results cached to .swarm/memory.db`);
713
+ printSuccess(`✅ Post-search hook completed`);
714
+ } catch (err) {
715
+ printError(`Post-search hook failed: ${err.message}`);
716
+ }
822
717
  }
823
-
824
718
  // ===== MCP INTEGRATION HOOKS =====
825
-
826
719
  async function mcpInitializedCommand(subArgs, flags) {
827
- const options = flags;
828
- const serverName = options.server || 'claude-flow';
829
- const sessionId = options['session-id'] || generateId('mcp-session');
830
-
831
- console.log(`🔌 Executing mcp-initialized hook...`);
832
- console.log(`💻 Server: ${serverName}`);
833
- console.log(`🆔 Session: ${sessionId}`);
834
-
835
- try {
836
- const store = await getMemoryStore();
837
- const mcpData = {
838
- serverName,
839
- sessionId,
840
- initializedAt: new Date().toISOString(),
841
- status: 'active',
842
- };
843
-
844
- await store.store(`mcp:${sessionId}`, mcpData, {
845
- namespace: 'hooks:mcp-initialized',
846
- metadata: { hookType: 'mcp-initialized', server: serverName },
847
- });
848
-
849
- console.log(` 💾 MCP session saved to .swarm/memory.db`);
850
- printSuccess(`✅ MCP initialized hook completed`);
851
- } catch (err) {
852
- printError(`MCP initialized hook failed: ${err.message}`);
853
- }
720
+ const options = flags;
721
+ const serverName = options.server || 'claude-flow';
722
+ const sessionId = options['session-id'] || generateId('mcp-session');
723
+ console.log(`🔌 Executing mcp-initialized hook...`);
724
+ console.log(`💻 Server: ${serverName}`);
725
+ console.log(`🆔 Session: ${sessionId}`);
726
+ try {
727
+ const store = await getMemoryStore();
728
+ const mcpData = {
729
+ serverName,
730
+ sessionId,
731
+ initializedAt: new Date().toISOString(),
732
+ status: 'active'
733
+ };
734
+ await store.store(`mcp:${sessionId}`, mcpData, {
735
+ namespace: 'hooks:mcp-initialized',
736
+ metadata: {
737
+ hookType: 'mcp-initialized',
738
+ server: serverName
739
+ }
740
+ });
741
+ console.log(` 💾 MCP session saved to .swarm/memory.db`);
742
+ printSuccess(`✅ MCP initialized hook completed`);
743
+ } catch (err) {
744
+ printError(`MCP initialized hook failed: ${err.message}`);
745
+ }
854
746
  }
855
-
856
747
  async function agentSpawnedCommand(subArgs, flags) {
857
- const options = flags;
858
- const agentType = options.type || 'generic';
859
- const agentName = options.name || generateId('agent');
860
- const swarmId = options['swarm-id'] || 'default';
861
-
862
- console.log(`🤖 Executing agent-spawned hook...`);
863
- console.log(`📛 Agent: ${agentName}`);
864
- console.log(`🏷️ Type: ${agentType}`);
865
-
866
- try {
867
- const store = await getMemoryStore();
868
- const agentData = {
869
- agentName,
870
- agentType,
871
- swarmId,
872
- spawnedAt: new Date().toISOString(),
873
- status: 'active',
874
- };
875
-
876
- await store.store(`agent:${agentName}`, agentData, {
877
- namespace: 'hooks:agent-spawned',
878
- metadata: { hookType: 'agent-spawned', type: agentType },
879
- });
880
-
881
- // Update agent roster
882
- await store.store(
883
- `agent-roster:${Date.now()}`,
884
- {
885
- agentName,
886
- action: 'spawned',
887
- timestamp: new Date().toISOString(),
888
- },
889
- { namespace: 'agent-roster' },
890
- );
891
-
892
- console.log(` 💾 Agent registered to .swarm/memory.db`);
893
- printSuccess(`✅ Agent spawned hook completed`);
894
- } catch (err) {
895
- printError(`Agent spawned hook failed: ${err.message}`);
896
- }
748
+ const options = flags;
749
+ const agentType = options.type || 'generic';
750
+ const agentName = options.name || generateId('agent');
751
+ const swarmId = options['swarm-id'] || 'default';
752
+ console.log(`🤖 Executing agent-spawned hook...`);
753
+ console.log(`📛 Agent: ${agentName}`);
754
+ console.log(`🏷️ Type: ${agentType}`);
755
+ try {
756
+ const store = await getMemoryStore();
757
+ const agentData = {
758
+ agentName,
759
+ agentType,
760
+ swarmId,
761
+ spawnedAt: new Date().toISOString(),
762
+ status: 'active'
763
+ };
764
+ await store.store(`agent:${agentName}`, agentData, {
765
+ namespace: 'hooks:agent-spawned',
766
+ metadata: {
767
+ hookType: 'agent-spawned',
768
+ type: agentType
769
+ }
770
+ });
771
+ // Update agent roster
772
+ await store.store(`agent-roster:${Date.now()}`, {
773
+ agentName,
774
+ action: 'spawned',
775
+ timestamp: new Date().toISOString()
776
+ }, {
777
+ namespace: 'agent-roster'
778
+ });
779
+ console.log(` 💾 Agent registered to .swarm/memory.db`);
780
+ printSuccess(`✅ Agent spawned hook completed`);
781
+ } catch (err) {
782
+ printError(`Agent spawned hook failed: ${err.message}`);
783
+ }
897
784
  }
898
-
899
785
  async function taskOrchestratedCommand(subArgs, flags) {
900
- const options = flags;
901
- const taskId = options['task-id'] || generateId('orchestrated-task');
902
- const strategy = options.strategy || 'balanced';
903
- const priority = options.priority || 'medium';
904
-
905
- console.log(`🎭 Executing task-orchestrated hook...`);
906
- console.log(`🆔 Task: ${taskId}`);
907
- console.log(`📊 Strategy: ${strategy}`);
908
-
909
- try {
910
- const store = await getMemoryStore();
911
- const orchestrationData = {
912
- taskId,
913
- strategy,
914
- priority,
915
- orchestratedAt: new Date().toISOString(),
916
- status: 'orchestrated',
917
- };
918
-
919
- await store.store(`orchestration:${taskId}`, orchestrationData, {
920
- namespace: 'hooks:task-orchestrated',
921
- metadata: { hookType: 'task-orchestrated', strategy },
922
- });
923
-
924
- console.log(` 💾 Orchestration saved to .swarm/memory.db`);
925
- printSuccess(`✅ Task orchestrated hook completed`);
926
- } catch (err) {
927
- printError(`Task orchestrated hook failed: ${err.message}`);
928
- }
786
+ const options = flags;
787
+ const taskId = options['task-id'] || generateId('orchestrated-task');
788
+ const strategy = options.strategy || 'balanced';
789
+ const priority = options.priority || 'medium';
790
+ console.log(`🎭 Executing task-orchestrated hook...`);
791
+ console.log(`🆔 Task: ${taskId}`);
792
+ console.log(`📊 Strategy: ${strategy}`);
793
+ try {
794
+ const store = await getMemoryStore();
795
+ const orchestrationData = {
796
+ taskId,
797
+ strategy,
798
+ priority,
799
+ orchestratedAt: new Date().toISOString(),
800
+ status: 'orchestrated'
801
+ };
802
+ await store.store(`orchestration:${taskId}`, orchestrationData, {
803
+ namespace: 'hooks:task-orchestrated',
804
+ metadata: {
805
+ hookType: 'task-orchestrated',
806
+ strategy
807
+ }
808
+ });
809
+ console.log(` 💾 Orchestration saved to .swarm/memory.db`);
810
+ printSuccess(`✅ Task orchestrated hook completed`);
811
+ } catch (err) {
812
+ printError(`Task orchestrated hook failed: ${err.message}`);
813
+ }
929
814
  }
930
-
931
815
  async function neuralTrainedCommand(subArgs, flags) {
932
- const options = flags;
933
- const modelName = options.model || 'default-neural';
934
- const accuracy = options.accuracy || '0.0';
935
- const patterns = options.patterns || '0';
936
-
937
- console.log(`🧠 Executing neural-trained hook...`);
938
- console.log(`🤖 Model: ${modelName}`);
939
- console.log(`📊 Accuracy: ${accuracy}%`);
940
-
941
- try {
942
- const store = await getMemoryStore();
943
- const trainingData = {
944
- modelName,
945
- accuracy: parseFloat(accuracy),
946
- patternsLearned: parseInt(patterns),
947
- trainedAt: new Date().toISOString(),
948
- };
949
-
950
- await store.store(`neural:${modelName}:${Date.now()}`, trainingData, {
951
- namespace: 'hooks:neural-trained',
952
- metadata: { hookType: 'neural-trained', model: modelName },
953
- });
954
-
955
- console.log(` 💾 Training results saved to .swarm/memory.db`);
956
- printSuccess(`✅ Neural trained hook completed`);
957
- } catch (err) {
958
- printError(`Neural trained hook failed: ${err.message}`);
959
- }
816
+ const options = flags;
817
+ const modelName = options.model || 'default-neural';
818
+ const accuracy = options.accuracy || '0.0';
819
+ const patterns = options.patterns || '0';
820
+ console.log(`🧠 Executing neural-trained hook...`);
821
+ console.log(`🤖 Model: ${modelName}`);
822
+ console.log(`📊 Accuracy: ${accuracy}%`);
823
+ try {
824
+ const store = await getMemoryStore();
825
+ const trainingData = {
826
+ modelName,
827
+ accuracy: parseFloat(accuracy),
828
+ patternsLearned: parseInt(patterns),
829
+ trainedAt: new Date().toISOString()
830
+ };
831
+ await store.store(`neural:${modelName}:${Date.now()}`, trainingData, {
832
+ namespace: 'hooks:neural-trained',
833
+ metadata: {
834
+ hookType: 'neural-trained',
835
+ model: modelName
836
+ }
837
+ });
838
+ console.log(` 💾 Training results saved to .swarm/memory.db`);
839
+ printSuccess(`✅ Neural trained hook completed`);
840
+ } catch (err) {
841
+ printError(`Neural trained hook failed: ${err.message}`);
842
+ }
960
843
  }
961
-
962
844
  // ===== SESSION HOOKS =====
963
-
964
845
  async function sessionStartCommand(subArgs, flags) {
965
- const options = flags;
966
- const silent = options.silent || false;
967
- const generateMissing = options['generate-missing'] !== 'false';
968
- const fallbackToDefault = options['fallback-to-default'] !== 'false';
969
-
970
- console.log(`🚀 Executing session-start hook...`);
971
- if (generateMissing) console.log(`🔄 Auto-generate missing soul: ENABLED`);
972
- if (fallbackToDefault) console.log(`📄 Fallback to default: ENABLED`);
973
-
974
- try {
975
- const result = await executeSessionStartSoulHook({
976
- silent,
977
- generateMissing,
978
- fallbackToDefault
979
- });
980
-
981
- if (result.success) {
982
- console.log(` 💾 Soul integration: ${result.action.toUpperCase()}`);
983
- if (result.contentLength) {
984
- console.log(` 📊 Content loaded: ${result.contentLength} characters`);
985
- }
986
- printSuccess(`✅ Session-start hook completed`);
987
- } else {
988
- printError(`Session-start hook failed: ${result.error}`);
846
+ const options = flags;
847
+ const silent = options.silent || false;
848
+ const generateMissing = options['generate-missing'] !== 'false';
849
+ const fallbackToDefault = options['fallback-to-default'] !== 'false';
850
+ console.log(`🚀 Executing session-start hook...`);
851
+ if (generateMissing) console.log(`🔄 Auto-generate missing soul: ENABLED`);
852
+ if (fallbackToDefault) console.log(`📄 Fallback to default: ENABLED`);
853
+ try {
854
+ const result = await executeSessionStartSoulHook({
855
+ silent,
856
+ generateMissing,
857
+ fallbackToDefault
858
+ });
859
+ if (result.success) {
860
+ console.log(` 💾 Soul integration: ${result.action.toUpperCase()}`);
861
+ if (result.contentLength) {
862
+ console.log(` 📊 Content loaded: ${result.contentLength} characters`);
863
+ }
864
+ printSuccess(`✅ Session-start hook completed`);
865
+ } else {
866
+ printError(`Session-start hook failed: ${result.error}`);
867
+ }
868
+ } catch (err) {
869
+ printError(`Session-start hook failed: ${err.message}`);
989
870
  }
990
- } catch (err) {
991
- printError(`Session-start hook failed: ${err.message}`);
992
- }
993
871
  }
994
-
995
872
  async function sessionEndCommand(subArgs, flags) {
996
- const options = flags;
997
- const generateSummary = options['generate-summary'] !== 'false';
998
- const persistState = options['persist-state'] !== 'false';
999
- const exportMetrics = options['export-metrics'] || false;
1000
-
1001
- console.log(`🔚 Executing session-end hook...`);
1002
- if (generateSummary) console.log(`📊 Summary generation: ENABLED`);
1003
- if (persistState) console.log(`💾 State persistence: ENABLED`);
1004
- if (exportMetrics) console.log(`📈 Metrics export: ENABLED`);
1005
-
1006
- try {
1007
- const store = await getMemoryStore();
1008
- const tasks = await store.list({ namespace: 'task-index', limit: 1000 });
1009
- const edits = await store.list({ namespace: 'file-history', limit: 1000 });
1010
- const commands = await store.list({ namespace: 'command-history', limit: 1000 });
1011
- const agents = await store.list({ namespace: 'agent-roster', limit: 1000 });
1012
-
1013
- // Calculate session metrics
1014
- let metrics = null;
1015
- if (exportMetrics) {
1016
- const now = new Date();
1017
- const sessionStart = Math.min(
1018
- ...tasks.map((t) => new Date(t.value.timestamp || now).getTime()),
1019
- ...edits.map((e) => new Date(e.value.timestamp || now).getTime()),
1020
- ...commands.map((c) => new Date(c.value.timestamp || now).getTime()),
1021
- );
1022
-
1023
- const duration = now.getTime() - sessionStart;
1024
- const successfulCommands = commands.filter((c) => c.value.success !== false).length;
1025
- const commandSuccessRate = commands.length > 0 ? successfulCommands / commands.length : 1;
1026
-
1027
- metrics = {
1028
- sessionDuration: duration,
1029
- sessionDurationHuman: `${Math.round(duration / 1000 / 60)} minutes`,
1030
- totalTasks: tasks.length,
1031
- totalEdits: edits.length,
1032
- totalCommands: commands.length,
1033
- uniqueAgents: agents.length,
1034
- commandSuccessRate: Math.round(commandSuccessRate * 100),
1035
- avgTasksPerMinute: Math.round((tasks.length / (duration / 1000 / 60)) * 100) / 100,
1036
- avgEditsPerMinute: Math.round((edits.length / (duration / 1000 / 60)) * 100) / 100,
1037
- timestamp: now.toISOString(),
1038
- };
1039
- }
1040
-
1041
- const sessionData = {
1042
- endedAt: new Date().toISOString(),
1043
- totalTasks: tasks.length,
1044
- totalEdits: edits.length,
1045
- totalCommands: commands.length,
1046
- uniqueAgents: agents.length,
1047
- sessionId: generateId('session'),
1048
- generateSummary,
1049
- persistState,
1050
- exportMetrics,
1051
- metrics,
1052
- };
1053
-
1054
- await store.store(`session:${sessionData.sessionId}`, sessionData, {
1055
- namespace: 'sessions',
1056
- metadata: { hookType: 'session-end' },
1057
- });
1058
-
1059
- // Persist detailed state if requested
1060
- if (persistState) {
1061
- const detailedState = {
1062
- sessionId: sessionData.sessionId,
1063
- tasks: tasks.slice(0, 100), // Limit to prevent memory issues
1064
- edits: edits.slice(0, 100),
1065
- commands: commands.slice(0, 100),
1066
- agents: agents.slice(0, 50),
1067
- persistedAt: new Date().toISOString(),
1068
- fullState: true,
1069
- };
1070
-
1071
- await store.store(`session-state:${sessionData.sessionId}`, detailedState, {
1072
- namespace: 'session-states',
1073
- metadata: { type: 'full-state', sessionId: sessionData.sessionId },
1074
- });
1075
-
1076
- console.log(` 💾 Full session state persisted`);
1077
- }
1078
-
1079
- // Export metrics if requested
1080
- if (exportMetrics && metrics) {
1081
- await store.store(`session-metrics:${sessionData.sessionId}`, metrics, {
1082
- namespace: 'session-metrics',
1083
- metadata: { type: 'performance-metrics', sessionId: sessionData.sessionId },
1084
- });
1085
-
1086
- console.log(` 📈 Session metrics exported`);
1087
- }
1088
-
1089
- if (generateSummary) {
1090
- console.log(`\n📊 SESSION SUMMARY:`);
1091
- console.log(` 📋 Tasks: ${sessionData.totalTasks}`);
1092
- console.log(` ✏️ Edits: ${sessionData.totalEdits}`);
1093
- console.log(` 🔧 Commands: ${sessionData.totalCommands}`);
1094
- console.log(` 🤖 Agents: ${sessionData.uniqueAgents}`);
1095
-
1096
- if (metrics) {
1097
- console.log(` ⏱️ Duration: ${metrics.sessionDurationHuman}`);
1098
- console.log(` 📈 Success Rate: ${metrics.commandSuccessRate}%`);
1099
- console.log(` 🏃 Tasks/min: ${metrics.avgTasksPerMinute}`);
1100
- console.log(` ✏️ Edits/min: ${metrics.avgEditsPerMinute}`);
1101
- }
1102
- }
1103
-
1104
- console.log(` 💾 Session saved to .swarm/memory.db`);
1105
-
1106
- // Clean up soul context files
873
+ const options = flags;
874
+ const generateSummary = options['generate-summary'] !== 'false';
875
+ const persistState = options['persist-state'] !== 'false';
876
+ const exportMetrics = options['export-metrics'] || false;
877
+ console.log(`🔚 Executing session-end hook...`);
878
+ if (generateSummary) console.log(`📊 Summary generation: ENABLED`);
879
+ if (persistState) console.log(`💾 State persistence: ENABLED`);
880
+ if (exportMetrics) console.log(`📈 Metrics export: ENABLED`);
1107
881
  try {
1108
- await executeSessionEndSoulHook();
1109
- console.log(` 🧹 Soul context cleanup completed`);
882
+ const store = await getMemoryStore();
883
+ const tasks = await store.list({
884
+ namespace: 'task-index',
885
+ limit: 1000
886
+ });
887
+ const edits = await store.list({
888
+ namespace: 'file-history',
889
+ limit: 1000
890
+ });
891
+ const commands = await store.list({
892
+ namespace: 'command-history',
893
+ limit: 1000
894
+ });
895
+ const agents = await store.list({
896
+ namespace: 'agent-roster',
897
+ limit: 1000
898
+ });
899
+ // Calculate session metrics
900
+ let metrics = null;
901
+ if (exportMetrics) {
902
+ const now = new Date();
903
+ const sessionStart = Math.min(...tasks.map((t)=>new Date(t.value.timestamp || now).getTime()), ...edits.map((e)=>new Date(e.value.timestamp || now).getTime()), ...commands.map((c)=>new Date(c.value.timestamp || now).getTime()));
904
+ const duration = now.getTime() - sessionStart;
905
+ const successfulCommands = commands.filter((c)=>c.value.success !== false).length;
906
+ const commandSuccessRate = commands.length > 0 ? successfulCommands / commands.length : 1;
907
+ metrics = {
908
+ sessionDuration: duration,
909
+ sessionDurationHuman: `${Math.round(duration / 1000 / 60)} minutes`,
910
+ totalTasks: tasks.length,
911
+ totalEdits: edits.length,
912
+ totalCommands: commands.length,
913
+ uniqueAgents: agents.length,
914
+ commandSuccessRate: Math.round(commandSuccessRate * 100),
915
+ avgTasksPerMinute: Math.round(tasks.length / (duration / 1000 / 60) * 100) / 100,
916
+ avgEditsPerMinute: Math.round(edits.length / (duration / 1000 / 60) * 100) / 100,
917
+ timestamp: now.toISOString()
918
+ };
919
+ }
920
+ const sessionData = {
921
+ endedAt: new Date().toISOString(),
922
+ totalTasks: tasks.length,
923
+ totalEdits: edits.length,
924
+ totalCommands: commands.length,
925
+ uniqueAgents: agents.length,
926
+ sessionId: generateId('session'),
927
+ generateSummary,
928
+ persistState,
929
+ exportMetrics,
930
+ metrics
931
+ };
932
+ await store.store(`session:${sessionData.sessionId}`, sessionData, {
933
+ namespace: 'sessions',
934
+ metadata: {
935
+ hookType: 'session-end'
936
+ }
937
+ });
938
+ // Persist detailed state if requested
939
+ if (persistState) {
940
+ const detailedState = {
941
+ sessionId: sessionData.sessionId,
942
+ tasks: tasks.slice(0, 100),
943
+ edits: edits.slice(0, 100),
944
+ commands: commands.slice(0, 100),
945
+ agents: agents.slice(0, 50),
946
+ persistedAt: new Date().toISOString(),
947
+ fullState: true
948
+ };
949
+ await store.store(`session-state:${sessionData.sessionId}`, detailedState, {
950
+ namespace: 'session-states',
951
+ metadata: {
952
+ type: 'full-state',
953
+ sessionId: sessionData.sessionId
954
+ }
955
+ });
956
+ console.log(` 💾 Full session state persisted`);
957
+ }
958
+ // Export metrics if requested
959
+ if (exportMetrics && metrics) {
960
+ await store.store(`session-metrics:${sessionData.sessionId}`, metrics, {
961
+ namespace: 'session-metrics',
962
+ metadata: {
963
+ type: 'performance-metrics',
964
+ sessionId: sessionData.sessionId
965
+ }
966
+ });
967
+ console.log(` 📈 Session metrics exported`);
968
+ }
969
+ if (generateSummary) {
970
+ console.log(`\n📊 SESSION SUMMARY:`);
971
+ console.log(` 📋 Tasks: ${sessionData.totalTasks}`);
972
+ console.log(` ✏️ Edits: ${sessionData.totalEdits}`);
973
+ console.log(` 🔧 Commands: ${sessionData.totalCommands}`);
974
+ console.log(` 🤖 Agents: ${sessionData.uniqueAgents}`);
975
+ if (metrics) {
976
+ console.log(` ⏱️ Duration: ${metrics.sessionDurationHuman}`);
977
+ console.log(` 📈 Success Rate: ${metrics.commandSuccessRate}%`);
978
+ console.log(` 🏃 Tasks/min: ${metrics.avgTasksPerMinute}`);
979
+ console.log(` ✏️ Edits/min: ${metrics.avgEditsPerMinute}`);
980
+ }
981
+ }
982
+ console.log(` 💾 Session saved to .swarm/memory.db`);
983
+ // Clean up soul context files
984
+ try {
985
+ await executeSessionEndSoulHook();
986
+ console.log(` 🧹 Soul context cleanup completed`);
987
+ } catch (err) {
988
+ console.log(` ⚠️ Soul cleanup warning: ${err.message}`);
989
+ }
990
+ if (memoryStore) {
991
+ memoryStore.close();
992
+ memoryStore = null;
993
+ }
994
+ printSuccess(`✅ Session-end hook completed`);
1110
995
  } catch (err) {
1111
- console.log(` ⚠️ Soul cleanup warning: ${err.message}`);
1112
- }
1113
-
1114
- if (memoryStore) {
1115
- memoryStore.close();
1116
- memoryStore = null;
996
+ printError(`Session-end hook failed: ${err.message}`);
1117
997
  }
1118
-
1119
- printSuccess(`✅ Session-end hook completed`);
1120
- } catch (err) {
1121
- printError(`Session-end hook failed: ${err.message}`);
1122
- }
1123
998
  }
1124
-
1125
999
  async function sessionRestoreCommand(subArgs, flags) {
1126
- const options = flags;
1127
- const sessionId = options['session-id'] || 'latest';
1128
-
1129
- console.log(`🔄 Executing session-restore hook...`);
1130
- console.log(`🆔 Session: ${sessionId}`);
1131
-
1132
- try {
1133
- const store = await getMemoryStore();
1134
-
1135
- // Find session to restore
1136
- let sessionData;
1137
- if (sessionId === 'latest') {
1138
- const sessions = await store.list({ namespace: 'sessions', limit: 1 });
1139
- sessionData = sessions[0]?.value;
1140
- } else {
1141
- sessionData = await store.retrieve(`session:${sessionId}`, { namespace: 'sessions' });
1142
- }
1143
-
1144
- if (sessionData) {
1145
- console.log(`\n📊 RESTORED SESSION:`);
1146
- console.log(` 🆔 ID: ${sessionData.sessionId || 'unknown'}`);
1147
- console.log(` 📋 Tasks: ${sessionData.totalTasks || 0}`);
1148
- console.log(` ✏️ Edits: ${sessionData.totalEdits || 0}`);
1149
- console.log(` ⏰ Ended: ${sessionData.endedAt || 'unknown'}`);
1150
-
1151
- // Store restoration event
1152
- await store.store(
1153
- `session-restore:${Date.now()}`,
1154
- {
1155
- restoredSessionId: sessionData.sessionId || sessionId,
1156
- restoredAt: new Date().toISOString(),
1157
- },
1158
- { namespace: 'session-events' },
1159
- );
1160
-
1161
- console.log(` 💾 Session restored from .swarm/memory.db`);
1162
- printSuccess(`✅ Session restore completed`);
1163
- } else {
1164
- printWarning(`No session found with ID: ${sessionId}`);
1000
+ const options = flags;
1001
+ const sessionId = options['session-id'] || 'latest';
1002
+ console.log(`🔄 Executing session-restore hook...`);
1003
+ console.log(`🆔 Session: ${sessionId}`);
1004
+ try {
1005
+ const store = await getMemoryStore();
1006
+ // Find session to restore
1007
+ let sessionData;
1008
+ if (sessionId === 'latest') {
1009
+ const sessions = await store.list({
1010
+ namespace: 'sessions',
1011
+ limit: 1
1012
+ });
1013
+ sessionData = sessions[0]?.value;
1014
+ } else {
1015
+ sessionData = await store.retrieve(`session:${sessionId}`, {
1016
+ namespace: 'sessions'
1017
+ });
1018
+ }
1019
+ if (sessionData) {
1020
+ console.log(`\n📊 RESTORED SESSION:`);
1021
+ console.log(` 🆔 ID: ${sessionData.sessionId || 'unknown'}`);
1022
+ console.log(` 📋 Tasks: ${sessionData.totalTasks || 0}`);
1023
+ console.log(` ✏️ Edits: ${sessionData.totalEdits || 0}`);
1024
+ console.log(` ⏰ Ended: ${sessionData.endedAt || 'unknown'}`);
1025
+ // Store restoration event
1026
+ await store.store(`session-restore:${Date.now()}`, {
1027
+ restoredSessionId: sessionData.sessionId || sessionId,
1028
+ restoredAt: new Date().toISOString()
1029
+ }, {
1030
+ namespace: 'session-events'
1031
+ });
1032
+ console.log(` 💾 Session restored from .swarm/memory.db`);
1033
+ printSuccess(`✅ Session restore completed`);
1034
+ } else {
1035
+ printWarning(`No session found with ID: ${sessionId}`);
1036
+ }
1037
+ } catch (err) {
1038
+ printError(`Session restore hook failed: ${err.message}`);
1165
1039
  }
1166
- } catch (err) {
1167
- printError(`Session restore hook failed: ${err.message}`);
1168
- }
1169
1040
  }
1170
-
1171
1041
  async function notifyCommand(subArgs, flags) {
1172
- const options = flags;
1173
- const message = options.message || subArgs.slice(1).join(' ');
1174
- const level = options.level || 'info';
1175
- const swarmStatus = options['swarm-status'] || 'active';
1176
-
1177
- console.log(`📢 Executing notify hook...`);
1178
- console.log(`💬 Message: ${message}`);
1179
- console.log(`📊 Level: ${level}`);
1180
-
1181
- try {
1182
- const store = await getMemoryStore();
1183
- const notificationData = {
1184
- message,
1185
- level,
1186
- swarmStatus,
1187
- timestamp: new Date().toISOString(),
1188
- notifyId: generateId('notify'),
1189
- };
1190
-
1191
- await store.store(`notification:${notificationData.notifyId}`, notificationData, {
1192
- namespace: 'hooks:notify',
1193
- metadata: { hookType: 'notify', level },
1194
- });
1195
-
1196
- // Display notification
1197
- const icon = level === 'error' ? '❌' : level === 'warning' ? '⚠️' : '✅';
1198
- console.log(`\n${icon} NOTIFICATION:`);
1199
- console.log(` ${message}`);
1200
- console.log(` 🐝 Swarm: ${swarmStatus}`);
1201
-
1202
- console.log(`\n 💾 Notification saved to .swarm/memory.db`);
1203
- printSuccess(`✅ Notify hook completed`);
1204
- } catch (err) {
1205
- printError(`Notify hook failed: ${err.message}`);
1206
- }
1042
+ const options = flags;
1043
+ const message = options.message || subArgs.slice(1).join(' ');
1044
+ const level = options.level || 'info';
1045
+ const swarmStatus = options['swarm-status'] || 'active';
1046
+ console.log(`📢 Executing notify hook...`);
1047
+ console.log(`💬 Message: ${message}`);
1048
+ console.log(`📊 Level: ${level}`);
1049
+ try {
1050
+ const store = await getMemoryStore();
1051
+ const notificationData = {
1052
+ message,
1053
+ level,
1054
+ swarmStatus,
1055
+ timestamp: new Date().toISOString(),
1056
+ notifyId: generateId('notify')
1057
+ };
1058
+ await store.store(`notification:${notificationData.notifyId}`, notificationData, {
1059
+ namespace: 'hooks:notify',
1060
+ metadata: {
1061
+ hookType: 'notify',
1062
+ level
1063
+ }
1064
+ });
1065
+ // Display notification
1066
+ const icon = level === 'error' ? '❌' : level === 'warning' ? '⚠️' : '✅';
1067
+ console.log(`\n${icon} NOTIFICATION:`);
1068
+ console.log(` ${message}`);
1069
+ console.log(` 🐝 Swarm: ${swarmStatus}`);
1070
+ console.log(`\n 💾 Notification saved to .swarm/memory.db`);
1071
+ printSuccess(`✅ Notify hook completed`);
1072
+ } catch (err) {
1073
+ printError(`Notify hook failed: ${err.message}`);
1074
+ }
1207
1075
  }
1208
-
1209
1076
  function showHooksHelp() {
1210
- console.log('Claude Flow Hooks (with .swarm/memory.db persistence):\n');
1211
-
1212
- console.log('Pre-Operation Hooks:');
1213
- console.log(' pre-task Execute before starting a task');
1214
- console.log(' pre-edit Validate before file modifications');
1215
- console.log(' --auto-assign-agents Auto-assign agents based on file type');
1216
- console.log(' --load-context Load file context');
1217
- console.log(' pre-bash Check command safety (alias: pre-command)');
1218
- console.log(' pre-command Same as pre-bash');
1219
- console.log(' --validate-safety Enable safety validation');
1220
- console.log(' --prepare-resources Prepare execution resources');
1221
-
1222
- console.log('\nPost-Operation Hooks:');
1223
- console.log(' post-task Execute after completing a task');
1224
- console.log(' post-edit Auto-format and log edits');
1225
- console.log(' --format Auto-format code');
1226
- console.log(' --update-memory Update agent memory');
1227
- console.log(' --train-neural Train neural patterns');
1228
- console.log(' post-bash Log command execution (alias: post-command)');
1229
- console.log(' post-command Same as post-bash');
1230
- console.log(' --track-metrics Track performance metrics');
1231
- console.log(' --store-results Store detailed results');
1232
- console.log(' post-search Cache search results');
1233
-
1234
- console.log('\nMCP Integration Hooks:');
1235
- console.log(' mcp-initialized Persist MCP configuration');
1236
- console.log(' agent-spawned Update agent roster');
1237
- console.log(' task-orchestrated Monitor task progress');
1238
- console.log(' neural-trained Save pattern improvements');
1239
-
1240
- console.log('\nSession Hooks:');
1241
- console.log(' session-start Load project soul into Claude Code session');
1242
- console.log(' --generate-missing Auto-generate missing claude-soul.md');
1243
- console.log(' --fallback-to-default Use minimal soul if generation fails');
1244
- console.log(' --silent Run without output');
1245
- console.log(' session-end Generate summary and save state');
1246
- console.log(' --generate-summary Generate session summary');
1247
- console.log(' --persist-state Persist session state');
1248
- console.log(' --export-metrics Export performance metrics');
1249
- console.log(' session-restore Load previous session state');
1250
- console.log(' notify Custom notifications');
1251
-
1252
- console.log('\nExamples:');
1253
- console.log(' hooks session-start --generate-missing true --silent false');
1254
- console.log(' hooks pre-command --command "npm test" --validate-safety true');
1255
- console.log(' hooks pre-edit --file "src/app.js" --auto-assign-agents true');
1256
- console.log(' hooks post-command --command "build" --track-metrics true');
1257
- console.log(' hooks post-edit --file "src/app.js" --format true --train-neural true');
1258
- console.log(' hooks session-end --generate-summary true --export-metrics true');
1259
- console.log(' hooks agent-spawned --name "CodeReviewer" --type "reviewer"');
1260
- console.log(' hooks notify --message "Build completed" --level "success"');
1261
-
1262
- console.log('\nCompatibility:');
1263
- console.log(' • pre-command and pre-bash are aliases');
1264
- console.log(' • post-command and post-bash are aliases');
1265
- console.log(' • Both --dash-case and camelCase parameters supported');
1266
- console.log(' • All parameters from settings.json template supported');
1077
+ console.log('Claude Flow Hooks (with .swarm/memory.db persistence):\n');
1078
+ console.log('Pre-Operation Hooks:');
1079
+ console.log(' pre-task Execute before starting a task');
1080
+ console.log(' pre-edit Validate before file modifications');
1081
+ console.log(' --auto-assign-agents Auto-assign agents based on file type');
1082
+ console.log(' --load-context Load file context');
1083
+ console.log(' pre-bash Check command safety (alias: pre-command)');
1084
+ console.log(' pre-command Same as pre-bash');
1085
+ console.log(' --validate-safety Enable safety validation');
1086
+ console.log(' --prepare-resources Prepare execution resources');
1087
+ console.log('\nPost-Operation Hooks:');
1088
+ console.log(' post-task Execute after completing a task');
1089
+ console.log(' post-edit Auto-format and log edits');
1090
+ console.log(' --format Auto-format code');
1091
+ console.log(' --update-memory Update agent memory');
1092
+ console.log(' --train-neural Train neural patterns');
1093
+ console.log(' post-bash Log command execution (alias: post-command)');
1094
+ console.log(' post-command Same as post-bash');
1095
+ console.log(' --track-metrics Track performance metrics');
1096
+ console.log(' --store-results Store detailed results');
1097
+ console.log(' post-search Cache search results');
1098
+ console.log('\nMCP Integration Hooks:');
1099
+ console.log(' mcp-initialized Persist MCP configuration');
1100
+ console.log(' agent-spawned Update agent roster');
1101
+ console.log(' task-orchestrated Monitor task progress');
1102
+ console.log(' neural-trained Save pattern improvements');
1103
+ console.log('\nSession Hooks:');
1104
+ console.log(' session-start Load project soul into Claude Code session');
1105
+ console.log(' --generate-missing Auto-generate missing claude-soul.md');
1106
+ console.log(' --fallback-to-default Use minimal soul if generation fails');
1107
+ console.log(' --silent Run without output');
1108
+ console.log(' session-end Generate summary and save state');
1109
+ console.log(' --generate-summary Generate session summary');
1110
+ console.log(' --persist-state Persist session state');
1111
+ console.log(' --export-metrics Export performance metrics');
1112
+ console.log(' session-restore Load previous session state');
1113
+ console.log(' notify Custom notifications');
1114
+ console.log('\nExamples:');
1115
+ console.log(' hooks session-start --generate-missing true --silent false');
1116
+ console.log(' hooks pre-command --command "npm test" --validate-safety true');
1117
+ console.log(' hooks pre-edit --file "src/app.js" --auto-assign-agents true');
1118
+ console.log(' hooks post-command --command "build" --track-metrics true');
1119
+ console.log(' hooks post-edit --file "src/app.js" --format true --train-neural true');
1120
+ console.log(' hooks session-end --generate-summary true --export-metrics true');
1121
+ console.log(' hooks agent-spawned --name "CodeReviewer" --type "reviewer"');
1122
+ console.log(' hooks notify --message "Build completed" --level "success"');
1123
+ console.log('\nCompatibility:');
1124
+ console.log(' pre-command and pre-bash are aliases');
1125
+ console.log(' post-command and post-bash are aliases');
1126
+ console.log(' Both --dash-case and camelCase parameters supported');
1127
+ console.log(' All parameters from settings.json template supported');
1267
1128
  }
1268
-
1269
1129
  export default hooksAction;