claude-flow-novice 1.6.1 → 1.6.2

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 (244) hide show
  1. package/.claude/agents/cfn-loop/product-owner.md +54 -4
  2. package/.claude/commands/cfn-claude-sync.md +303 -0
  3. package/.claude/commands/cfn-loop-epic.md +290 -0
  4. package/.claude/commands/cfn-loop-single.md +168 -0
  5. package/.claude/commands/cfn-loop-sprints.md +384 -0
  6. package/.claude/commands/cfn-loop.md +180 -0
  7. package/.claude/commands/metrics-summary.md +58 -0
  8. package/.claude/commands/parse-epic.md +357 -0
  9. package/.claude/settings.json +4 -4
  10. package/.claude/settings.local.json +9 -2
  11. package/.claude-flow-novice/.claude/agents/cfn-loop/product-owner.md +792 -0
  12. package/.claude-flow-novice/dist/mcp/server.js +21 -2
  13. package/.claude-flow-novice/dist/src/api/claude-client.js +138 -3
  14. package/.claude-flow-novice/dist/src/api/claude-client.js.map +1 -1
  15. package/.claude-flow-novice/dist/src/cfn-loop/phase-orchestrator-example.js +1 -1
  16. package/.claude-flow-novice/dist/src/cfn-loop/scope-control.js +247 -0
  17. package/.claude-flow-novice/dist/src/cfn-loop/scope-control.js.map +1 -0
  18. package/.claude-flow-novice/dist/src/cli/commands/swarm.js +32 -15
  19. package/.claude-flow-novice/dist/src/cli/commands/swarm.js.map +1 -1
  20. package/.claude-flow-novice/dist/src/cli/commands/transparency.js +455 -0
  21. package/.claude-flow-novice/dist/src/cli/commands/transparency.js.map +1 -0
  22. package/.claude-flow-novice/dist/src/cli/simple-commands/init/templates/CLAUDE.md +129 -13
  23. package/.claude-flow-novice/dist/src/components/visualizations/index.js +9 -0
  24. package/.claude-flow-novice/dist/src/components/visualizations/index.js.map +1 -0
  25. package/.claude-flow-novice/dist/src/coordination/adapters/v1-coordinator-adapter.js +462 -0
  26. package/.claude-flow-novice/dist/src/coordination/adapters/v1-coordinator-adapter.js.map +1 -0
  27. package/.claude-flow-novice/dist/src/coordination/config-translator.js +248 -0
  28. package/.claude-flow-novice/dist/src/coordination/config-translator.js.map +1 -0
  29. package/.claude-flow-novice/dist/src/coordination/coordination-toggle.js +287 -0
  30. package/.claude-flow-novice/dist/src/coordination/coordination-toggle.js.map +1 -0
  31. package/.claude-flow-novice/dist/src/coordination/distributed-consensus.js +68 -9
  32. package/.claude-flow-novice/dist/src/coordination/distributed-consensus.js.map +1 -1
  33. package/.claude-flow-novice/dist/src/coordination/feature-flags.js +166 -0
  34. package/.claude-flow-novice/dist/src/coordination/feature-flags.js.map +1 -0
  35. package/.claude-flow-novice/dist/src/coordination/queen-agent.js +18 -4
  36. package/.claude-flow-novice/dist/src/coordination/queen-agent.js.map +1 -1
  37. package/.claude-flow-novice/dist/src/coordination/role-assignment.js +6 -110
  38. package/.claude-flow-novice/dist/src/coordination/role-assignment.js.map +1 -1
  39. package/.claude-flow-novice/dist/src/coordination/v2/cache/artifact-cache-optimizer.js +632 -0
  40. package/.claude-flow-novice/dist/src/coordination/v2/cache/artifact-cache-optimizer.js.map +1 -0
  41. package/.claude-flow-novice/dist/src/coordination/v2/cache/index.js +11 -0
  42. package/.claude-flow-novice/dist/src/coordination/v2/cache/index.js.map +1 -0
  43. package/.claude-flow-novice/dist/src/coordination/v2/checkpoints/checkpoint-compressor.js +318 -0
  44. package/.claude-flow-novice/dist/src/coordination/v2/checkpoints/checkpoint-compressor.js.map +1 -0
  45. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.example.js +364 -0
  46. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.example.js.map +1 -0
  47. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.js +492 -0
  48. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/cascading-shutdown.js.map +1 -0
  49. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/hierarchical-coordinator.js +786 -0
  50. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/hierarchical-coordinator.js.map +1 -0
  51. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/index.js +16 -0
  52. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/index.js.map +1 -0
  53. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/parent-child-manager.js +342 -0
  54. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/parent-child-manager.js.map +1 -0
  55. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/swarm-coordinator-v2.js +601 -0
  56. package/.claude-flow-novice/dist/src/coordination/v2/coordinators/swarm-coordinator-v2.js.map +1 -0
  57. package/.claude-flow-novice/dist/src/coordination/v2/core/help-request-metrics.js +211 -0
  58. package/.claude-flow-novice/dist/src/coordination/v2/core/help-request-metrics.js.map +1 -0
  59. package/.claude-flow-novice/dist/src/coordination/v2/core/index.js +1 -0
  60. package/.claude-flow-novice/dist/src/coordination/v2/core/index.js.map +1 -1
  61. package/.claude-flow-novice/dist/src/coordination/v2/core/message-broker.js +365 -6
  62. package/.claude-flow-novice/dist/src/coordination/v2/core/message-broker.js.map +1 -1
  63. package/.claude-flow-novice/dist/src/coordination/v2/core/resource-manager-safe.js +478 -0
  64. package/.claude-flow-novice/dist/src/coordination/v2/core/resource-manager-safe.js.map +1 -0
  65. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine-config.js +5 -2
  66. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine-config.js.map +1 -1
  67. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine.js +189 -0
  68. package/.claude-flow-novice/dist/src/coordination/v2/core/state-machine.js.map +1 -1
  69. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/deadlock-detector.js +424 -0
  70. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/deadlock-detector.js.map +1 -0
  71. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/index.js +9 -0
  72. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/index.js.map +1 -0
  73. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/resource-manager.js +669 -0
  74. package/.claude-flow-novice/dist/src/coordination/v2/deadlock/resource-manager.js.map +1 -0
  75. package/.claude-flow-novice/dist/src/coordination/v2/dependency/artifact-storage.js +451 -0
  76. package/.claude-flow-novice/dist/src/coordination/v2/dependency/artifact-storage.js.map +1 -0
  77. package/.claude-flow-novice/dist/src/coordination/v2/dependency/cycle-detector.js +271 -0
  78. package/.claude-flow-novice/dist/src/coordination/v2/dependency/cycle-detector.js.map +1 -0
  79. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-graph.js +335 -0
  80. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-graph.js.map +1 -0
  81. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-manager.js +439 -0
  82. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-manager.js.map +1 -0
  83. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-request.js +92 -0
  84. package/.claude-flow-novice/dist/src/coordination/v2/dependency/dependency-request.js.map +1 -0
  85. package/.claude-flow-novice/dist/src/coordination/v2/dependency/index.js +21 -0
  86. package/.claude-flow-novice/dist/src/coordination/v2/dependency/index.js.map +1 -0
  87. package/.claude-flow-novice/dist/src/coordination/v2/dependency/topological-sort.js +223 -0
  88. package/.claude-flow-novice/dist/src/coordination/v2/dependency/topological-sort.js.map +1 -0
  89. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-coordinator.js +436 -0
  90. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-coordinator.js.map +1 -0
  91. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-matcher.js +278 -0
  92. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-matcher.js.map +1 -0
  93. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request-handler.js +317 -0
  94. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request-handler.js.map +1 -0
  95. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request.js +273 -0
  96. package/.claude-flow-novice/dist/src/coordination/v2/help-system/help-request.js.map +1 -0
  97. package/.claude-flow-novice/dist/src/coordination/v2/help-system/index.js +15 -0
  98. package/.claude-flow-novice/dist/src/coordination/v2/help-system/index.js.map +1 -0
  99. package/.claude-flow-novice/dist/src/coordination/v2/help-system/waiting-agent-pool.js +512 -0
  100. package/.claude-flow-novice/dist/src/coordination/v2/help-system/waiting-agent-pool.js.map +1 -0
  101. package/.claude-flow-novice/dist/src/coordination/v2/index.js +6 -0
  102. package/.claude-flow-novice/dist/src/coordination/v2/index.js.map +1 -1
  103. package/.claude-flow-novice/dist/src/coordination/v2/integration/help-deadlock-integration.js +557 -0
  104. package/.claude-flow-novice/dist/src/coordination/v2/integration/help-deadlock-integration.js.map +1 -0
  105. package/.claude-flow-novice/dist/src/coordination/v2/integration/index.js +14 -0
  106. package/.claude-flow-novice/dist/src/coordination/v2/integration/index.js.map +1 -0
  107. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.example.js +212 -0
  108. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.example.js.map +1 -0
  109. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.js +552 -0
  110. package/.claude-flow-novice/dist/src/coordination/v2/integration/message-bus-completion-integration.js.map +1 -0
  111. package/.claude-flow-novice/dist/src/coordination/v2/memory/dependency-storage.js +367 -0
  112. package/.claude-flow-novice/dist/src/coordination/v2/memory/dependency-storage.js.map +1 -0
  113. package/.claude-flow-novice/dist/src/coordination/v2/memory/index.js +1 -0
  114. package/.claude-flow-novice/dist/src/coordination/v2/memory/index.js.map +1 -1
  115. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channel.js +371 -0
  116. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channel.js.map +1 -0
  117. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/dependency-channel.js +355 -0
  118. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/dependency-channel.js.map +1 -0
  119. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/help-channel.js +424 -0
  120. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/help-channel.js.map +1 -0
  121. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/index.js +16 -0
  122. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/index.js.map +1 -0
  123. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/state-channel.js +295 -0
  124. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/state-channel.js.map +1 -0
  125. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/task-channel.js +411 -0
  126. package/.claude-flow-novice/dist/src/coordination/v2/messaging/channels/task-channel.js.map +1 -0
  127. package/.claude-flow-novice/dist/src/coordination/v2/messaging/index.js +14 -0
  128. package/.claude-flow-novice/dist/src/coordination/v2/messaging/index.js.map +1 -0
  129. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-bus.js +387 -0
  130. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-bus.js.map +1 -0
  131. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-persistence.js +589 -0
  132. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-persistence.js.map +1 -0
  133. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-router.js +444 -0
  134. package/.claude-flow-novice/dist/src/coordination/v2/messaging/message-router.js.map +1 -0
  135. package/.claude-flow-novice/dist/src/coordination/v2/sdk/checkpoint-manager.js +29 -8
  136. package/.claude-flow-novice/dist/src/coordination/v2/sdk/checkpoint-manager.js.map +1 -1
  137. package/.claude-flow-novice/dist/src/coordination/v2/sdk/help-coordinator.js +470 -0
  138. package/.claude-flow-novice/dist/src/coordination/v2/sdk/help-coordinator.js.map +1 -0
  139. package/.claude-flow-novice/dist/src/coordination/v2/sdk/hierarchical-background-integration.js +450 -0
  140. package/.claude-flow-novice/dist/src/coordination/v2/sdk/hierarchical-background-integration.js.map +1 -0
  141. package/.claude-flow-novice/dist/src/coordination/v2/sdk/index.js +5 -0
  142. package/.claude-flow-novice/dist/src/coordination/v2/sdk/index.js.map +1 -1
  143. package/.claude-flow-novice/dist/src/coordination/v2/sdk/multi-level-control.js +545 -0
  144. package/.claude-flow-novice/dist/src/coordination/v2/sdk/multi-level-control.js.map +1 -0
  145. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-controller.js +44 -0
  146. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-controller.js.map +1 -1
  147. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-message-integration.js +415 -0
  148. package/.claude-flow-novice/dist/src/coordination/v2/sdk/query-message-integration.js.map +1 -0
  149. package/.claude-flow-novice/dist/src/coordination/v2/sdk/session-pool-optimizer.js +615 -0
  150. package/.claude-flow-novice/dist/src/coordination/v2/sdk/session-pool-optimizer.js.map +1 -0
  151. package/.claude-flow-novice/dist/src/coordination/v2/security/payload-validator.js +259 -0
  152. package/.claude-flow-novice/dist/src/coordination/v2/security/payload-validator.js.map +1 -0
  153. package/.claude-flow-novice/dist/src/coordination/v2/transparency/index.js +17 -0
  154. package/.claude-flow-novice/dist/src/coordination/v2/transparency/index.js.map +1 -0
  155. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-integration.js +357 -0
  156. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-integration.js.map +1 -0
  157. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-system.js +679 -0
  158. package/.claude-flow-novice/dist/src/coordination/v2/transparency/transparency-system.js.map +1 -0
  159. package/.claude-flow-novice/dist/src/core/agent-manager.js +30 -0
  160. package/.claude-flow-novice/dist/src/core/agent-manager.js.map +1 -1
  161. package/.claude-flow-novice/dist/src/mcp/server.js +21 -2
  162. package/.claude-flow-novice/dist/src/mcp/server.js.map +1 -1
  163. package/.claude-flow-novice/dist/src/observability/metrics-counter.js +268 -0
  164. package/.claude-flow-novice/dist/src/observability/metrics-counter.js.map +1 -0
  165. package/.claude-flow-novice/dist/src/observability/metrics-storage.js +265 -0
  166. package/.claude-flow-novice/dist/src/observability/metrics-storage.js.map +1 -0
  167. package/.claude-flow-novice/dist/src/observability/telemetry.js +26 -0
  168. package/.claude-flow-novice/dist/src/observability/telemetry.js.map +1 -1
  169. package/.claude-flow-novice/dist/src/providers/tiered-router.js +64 -10
  170. package/.claude-flow-novice/dist/src/providers/tiered-router.js.map +1 -1
  171. package/.claude-flow-novice/dist/src/providers/zai-provider.js +196 -97
  172. package/.claude-flow-novice/dist/src/providers/zai-provider.js.map +1 -1
  173. package/.claude-flow-novice/dist/src/slash-commands/cfn-claude-sync.js +533 -0
  174. package/.claude-flow-novice/dist/src/slash-commands/index.js +5 -0
  175. package/.claude-flow-novice/dist/src/slash-commands/metrics-summary-class.js +74 -0
  176. package/.claude-flow-novice/dist/src/slash-commands/metrics-summary.js +335 -0
  177. package/.claude-flow-novice/dist/src/slash-commands/register-all-commands.js +12 -0
  178. package/.claude-flow-novice/dist/src/verification/checkpoint-compression-demo.js +96 -0
  179. package/.claude-flow-novice/dist/src/verification/checkpoint-compression-demo.js.map +1 -0
  180. package/.claude-flow-novice/dist/src/verification/checkpoint-compression.js +406 -0
  181. package/.claude-flow-novice/dist/src/verification/checkpoint-compression.js.map +1 -0
  182. package/.claude-flow-novice/dist/src/verification/checkpoint-manager.js +35 -5
  183. package/.claude-flow-novice/dist/src/verification/checkpoint-manager.js.map +1 -1
  184. package/.claude-flow-novice/dist/src/web/api/config/api-config.js +186 -0
  185. package/.claude-flow-novice/dist/src/web/api/config/api-config.js.map +1 -0
  186. package/.claude-flow-novice/dist/src/web/api/middleware/auth.js +205 -0
  187. package/.claude-flow-novice/dist/src/web/api/middleware/auth.js.map +1 -0
  188. package/.claude-flow-novice/dist/src/web/api/middleware/cache.js +262 -0
  189. package/.claude-flow-novice/dist/src/web/api/middleware/cache.js.map +1 -0
  190. package/.claude-flow-novice/dist/src/web/api/middleware/error-handler.js +250 -0
  191. package/.claude-flow-novice/dist/src/web/api/middleware/error-handler.js.map +1 -0
  192. package/.claude-flow-novice/dist/src/web/api/middleware/request-logger.js +217 -0
  193. package/.claude-flow-novice/dist/src/web/api/middleware/request-logger.js.map +1 -0
  194. package/.claude-flow-novice/dist/src/web/api/middleware/validation.js +325 -0
  195. package/.claude-flow-novice/dist/src/web/api/middleware/validation.js.map +1 -0
  196. package/.claude-flow-novice/dist/src/web/api/routes/events.js +465 -0
  197. package/.claude-flow-novice/dist/src/web/api/routes/events.js.map +1 -0
  198. package/.claude-flow-novice/dist/src/web/api/routes/hierarchy.js +302 -0
  199. package/.claude-flow-novice/dist/src/web/api/routes/hierarchy.js.map +1 -0
  200. package/.claude-flow-novice/dist/src/web/api/routes/index.js +14 -0
  201. package/.claude-flow-novice/dist/src/web/api/routes/index.js.map +1 -0
  202. package/.claude-flow-novice/dist/src/web/api/routes/metrics.js +561 -0
  203. package/.claude-flow-novice/dist/src/web/api/routes/metrics.js.map +1 -0
  204. package/.claude-flow-novice/dist/src/web/api/routes/status.js +450 -0
  205. package/.claude-flow-novice/dist/src/web/api/routes/status.js.map +1 -0
  206. package/.claude-flow-novice/dist/src/web/api/server.js +451 -0
  207. package/.claude-flow-novice/dist/src/web/api/server.js.map +1 -0
  208. package/.claude-flow-novice/dist/src/web/dashboard/hooks/useWebSocket.js +385 -0
  209. package/.claude-flow-novice/dist/src/web/dashboard/hooks/useWebSocket.js.map +1 -0
  210. package/.claude-flow-novice/dist/src/web/dashboard/index.js +87 -0
  211. package/.claude-flow-novice/dist/src/web/dashboard/index.js.map +1 -0
  212. package/.claude-flow-novice/dist/src/web/dashboard/types.js +6 -0
  213. package/.claude-flow-novice/dist/src/web/dashboard/types.js.map +1 -0
  214. package/.claude-flow-novice/metrics.db +0 -0
  215. package/.claude-flow-novice/metrics.db-shm +0 -0
  216. package/.claude-flow-novice/metrics.db-wal +0 -0
  217. package/CLAUDE.md +29 -0
  218. package/README.md +27 -0
  219. package/config/hooks/post-edit-pipeline.js +36 -2
  220. package/examples/metrics-counter-demo.ts +106 -0
  221. package/examples/persistent-metrics-demo.ts +83 -0
  222. package/examples/phase-5-multi-level-control.ts +282 -0
  223. package/examples/session-pool-optimizer-example.ts +311 -0
  224. package/package.json +15 -3
  225. package/scripts/check-routing-stats.cjs +122 -0
  226. package/scripts/pre-publish-validation.cjs +212 -0
  227. package/scripts/test-provider-routing.cjs +228 -0
  228. package/scripts/test-routing-telemetry.cjs +147 -0
  229. package/scripts/test-zai-10k.cjs +81 -0
  230. package/scripts/test-zai-api.cjs +191 -0
  231. package/scripts/test-zai-diagnostic.cjs +151 -0
  232. package/scripts/test-zai-final.cjs +128 -0
  233. package/scripts/test-zai-with-env.cjs +85 -0
  234. package/scripts/validate-coordination-cli.js +69 -0
  235. package/scripts/validate-coordination-toggle-integration.cjs +501 -0
  236. package/src/cli/simple-commands/init/templates/CLAUDE.md +29 -0
  237. package/src/observability/metrics-counter.ts +347 -0
  238. package/src/observability/metrics-storage.ts +356 -0
  239. package/src/observability/telemetry.ts +658 -0
  240. package/src/slash-commands/cfn-claude-sync.js +533 -0
  241. package/src/slash-commands/index.js +5 -0
  242. package/src/slash-commands/metrics-summary-class.js +74 -0
  243. package/src/slash-commands/metrics-summary.js +335 -0
  244. package/src/slash-commands/register-all-commands.js +12 -0
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Metrics Counter Demo
3
+ *
4
+ * Demonstrates how to use the simple metrics counter API
5
+ */
6
+
7
+ import {
8
+ incrementMetric,
9
+ recordGauge,
10
+ recordTiming,
11
+ measureExecution,
12
+ trackProviderRouting,
13
+ trackAgentSpawn,
14
+ trackAPICall,
15
+ trackError,
16
+ getMetricValue,
17
+ getMetricBreakdown,
18
+ } from '../src/observability/metrics-counter.js';
19
+
20
+ async function demo() {
21
+ console.log('📊 Metrics Counter Demo\n');
22
+
23
+ // ===== EXAMPLE 1: Simple Counter =====
24
+ console.log('1️⃣ Simple Counters:');
25
+ incrementMetric('user.login');
26
+ incrementMetric('user.login');
27
+ incrementMetric('user.login');
28
+ console.log(' ✅ Tracked 3 user logins');
29
+
30
+ // ===== EXAMPLE 2: Counter with Tags =====
31
+ console.log('\n2️⃣ Counters with Tags:');
32
+ incrementMetric('api.requests', 1, { endpoint: '/users', method: 'GET' });
33
+ incrementMetric('api.requests', 1, { endpoint: '/users', method: 'POST' });
34
+ incrementMetric('api.requests', 1, { endpoint: '/posts', method: 'GET' });
35
+ console.log(' ✅ Tracked API requests with endpoint/method tags');
36
+
37
+ // ===== EXAMPLE 3: Gauge Values =====
38
+ console.log('\n3️⃣ Gauge Values:');
39
+ recordGauge('queue.size', 42);
40
+ recordGauge('active.connections', 15, { region: 'us-east-1' });
41
+ recordGauge('cpu.usage', 67.5, { unit: 'percent' });
42
+ console.log(' ✅ Recorded queue size, connections, CPU usage');
43
+
44
+ // ===== EXAMPLE 4: Timing Metrics =====
45
+ console.log('\n4️⃣ Timing Metrics:');
46
+ recordTiming('database.query', 45, { query: 'SELECT' });
47
+ recordTiming('database.query', 120, { query: 'INSERT' });
48
+ console.log(' ✅ Recorded database query timings');
49
+
50
+ // ===== EXAMPLE 5: Automatic Timing with measureExecution =====
51
+ console.log('\n5️⃣ Automatic Execution Timing:');
52
+ const result = await measureExecution('task.process', async () => {
53
+ await new Promise(resolve => setTimeout(resolve, 100)); // Simulate work
54
+ return { processed: 100 };
55
+ }, { taskType: 'data-import' });
56
+ console.log(` ✅ Measured execution: ${result.processed} items processed`);
57
+
58
+ // ===== EXAMPLE 6: Provider Routing Tracking =====
59
+ console.log('\n6️⃣ Provider Routing:');
60
+ trackProviderRouting('custom', 'Tier 2: Z.ai', 'coder', 'fallback');
61
+ trackProviderRouting('custom', 'Tier 2: Z.ai', 'researcher', 'fallback');
62
+ trackProviderRouting('anthropic', 'Tier 1: Subscription', 'coordinator', 'tier-config');
63
+ console.log(' ✅ Tracked 3 provider routing decisions');
64
+
65
+ // ===== EXAMPLE 7: Agent Lifecycle Tracking =====
66
+ console.log('\n7️⃣ Agent Lifecycle:');
67
+ trackAgentSpawn('coder', 'swarm-123', 'mesh');
68
+ trackAgentSpawn('tester', 'swarm-123', 'mesh');
69
+ console.log(' ✅ Tracked 2 agent spawns');
70
+
71
+ // ===== EXAMPLE 8: API Call Tracking =====
72
+ console.log('\n8️⃣ API Call Tracking:');
73
+ trackAPICall('/api/users', 'GET', 200, 45);
74
+ trackAPICall('/api/users', 'POST', 201, 120);
75
+ trackAPICall('/api/posts', 'GET', 200, 30);
76
+ console.log(' ✅ Tracked 3 API calls with status codes');
77
+
78
+ // ===== EXAMPLE 9: Error Tracking =====
79
+ console.log('\n9️⃣ Error Tracking:');
80
+ trackError('ValidationError', 'user-service', 'low');
81
+ trackError('DatabaseConnectionError', 'database', 'critical');
82
+ console.log(' ✅ Tracked 2 errors with severity levels');
83
+
84
+ // ===== EXAMPLE 10: Query Metrics =====
85
+ console.log('\n🔟 Query Metrics:');
86
+ const loginCount = getMetricValue('user.login');
87
+ console.log(` Login count: ${loginCount}`);
88
+
89
+ const apiBreakdown = getMetricBreakdown('api.requests', 'endpoint');
90
+ console.log(' API requests by endpoint:');
91
+ Object.entries(apiBreakdown).forEach(([endpoint, count]) => {
92
+ console.log(` ${endpoint}: ${count} requests`);
93
+ });
94
+
95
+ const providerBreakdown = getMetricBreakdown('provider.request', 'provider');
96
+ console.log(' Provider routing breakdown:');
97
+ Object.entries(providerBreakdown).forEach(([provider, count]) => {
98
+ const name = provider === 'custom' ? 'Z.ai' : provider;
99
+ console.log(` ${name}: ${count} requests`);
100
+ });
101
+
102
+ console.log('\n✅ Demo complete! All metrics tracked successfully.\n');
103
+ }
104
+
105
+ // Run demo
106
+ demo().catch(console.error);
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Persistent Metrics Demo
3
+ *
4
+ * Demonstrates:
5
+ * 1. Metrics persist across restarts (stored in SQLite)
6
+ * 2. Query historical metrics
7
+ * 3. Aggregate metrics from multiple runs
8
+ */
9
+
10
+ import { incrementMetric, trackProviderRouting } from '../src/observability/metrics-counter.js';
11
+ import { getGlobalMetricsStorage } from '../src/observability/metrics-storage.js';
12
+
13
+ async function demo() {
14
+ console.log('📊 Persistent Metrics Demo\n');
15
+ console.log('=' .repeat(60));
16
+
17
+ const storage = getGlobalMetricsStorage();
18
+
19
+ // Show database stats FIRST (to see if we have previous data)
20
+ const stats = storage.getStats();
21
+ console.log('\n📈 Database Stats (BEFORE adding new metrics):');
22
+ console.log(` Total metrics stored: ${stats.totalMetrics}`);
23
+ console.log(` Unique metric names: ${stats.uniqueNames}`);
24
+ console.log(` Oldest metric: ${stats.oldestMetric || 'N/A'}`);
25
+ console.log(` Newest metric: ${stats.newestMetric || 'N/A'}`);
26
+ console.log(` Database size: ${stats.dbSizeMB} MB`);
27
+
28
+ if (stats.totalMetrics > 0) {
29
+ console.log('\n✅ Found previous metrics! They persisted across restarts.');
30
+ } else {
31
+ console.log('\n🆕 No previous metrics found. This is a fresh database.');
32
+ }
33
+
34
+ // Add new metrics in THIS run
35
+ console.log('\n➕ Adding new metrics in THIS run...');
36
+
37
+ incrementMetric('demo.run.count');
38
+ incrementMetric('user.actions', 1, { action: 'click', page: 'home' });
39
+ incrementMetric('user.actions', 1, { action: 'submit', page: 'form' });
40
+
41
+ trackProviderRouting('custom', 'Tier 2: Z.ai', 'coder', 'fallback');
42
+ trackProviderRouting('anthropic', 'Tier 1: Subscription', 'coordinator', 'tier-config');
43
+
44
+ console.log(' ✅ Added 5 metrics');
45
+
46
+ // Query metrics from ALL time (including previous runs)
47
+ console.log('\n🔍 Querying ALL historical metrics...');
48
+
49
+ const totalRuns = storage.getCounterTotal('demo.run.count');
50
+ console.log(`\n Total demo runs (across ALL sessions): ${totalRuns}`);
51
+
52
+ const userActions = storage.getSummary('user.actions');
53
+ if (userActions) {
54
+ console.log(`\n User actions summary:`);
55
+ console.log(` Total actions: ${userActions.count}`);
56
+ console.log(` By action type:`);
57
+ Object.entries(userActions.tags.action || {}).forEach(([action, count]) => {
58
+ console.log(` ${action}: ${count}`);
59
+ });
60
+ }
61
+
62
+ const providerBreakdown = storage.getBreakdown('provider.request', 'provider');
63
+ console.log(`\n Provider routing breakdown (ALL time):`);
64
+ Object.entries(providerBreakdown).forEach(([provider, count]) => {
65
+ const name = provider === 'custom' ? 'Z.ai' : provider;
66
+ console.log(` ${name}: ${count} requests`);
67
+ });
68
+
69
+ // Show final stats
70
+ const finalStats = storage.getStats();
71
+ console.log('\n📊 Database Stats (AFTER adding new metrics):');
72
+ console.log(` Total metrics stored: ${finalStats.totalMetrics}`);
73
+ console.log(` Database size: ${finalStats.dbSizeMB} MB`);
74
+
75
+ console.log('\n' + '='.repeat(60));
76
+ console.log('✅ Demo complete!\n');
77
+ console.log('💡 TIP: Run this script multiple times to see metrics accumulate:');
78
+ console.log(' npx tsx examples/persistent-metrics-demo.ts\n');
79
+ console.log('📂 Database location: .claude-flow/metrics.db\n');
80
+ }
81
+
82
+ // Run demo
83
+ demo().catch(console.error);
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Phase 5 - Sprint 5.2: Multi-Level Agent Control Example
3
+ *
4
+ * Demonstrates pause/inject/resume from Level 0 to any child level
5
+ *
6
+ * @module examples/phase-5-multi-level-control
7
+ */
8
+
9
+ import { QueryController } from '../src/coordination/v2/sdk/query-controller.js';
10
+ import { HierarchicalCoordinator } from '../src/agents/hierarchical-coordinator.js';
11
+ import {
12
+ MultiLevelController,
13
+ InjectedCommandType,
14
+ createMultiLevelControllerWithHierarchy,
15
+ } from '../src/coordination/v2/sdk/multi-level-control.js';
16
+
17
+ /**
18
+ * Example: Multi-Level Agent Control
19
+ *
20
+ * Scenario:
21
+ * - Level 0: Supervisor (top-level coordinator)
22
+ * - Level 1: Team Leads (2 agents)
23
+ * - Level 2: Workers (3 agents under Team Lead A)
24
+ *
25
+ * Demonstrates:
26
+ * - Level 0 pauses any agent at any level
27
+ * - Level 0 injects commands to modify agent state/tasks
28
+ * - Level 0 resumes agents with commands applied
29
+ * - <100ms latency for all control operations
30
+ */
31
+ async function multiLevelControlExample() {
32
+ console.log('=== Phase 5 - Sprint 5.2: Multi-Level Agent Control Example ===\n');
33
+
34
+ // Step 1: Initialize QueryController (Phase 0)
35
+ console.log('Step 1: Initialize QueryController for pause/resume...');
36
+ const queryController = new QueryController({
37
+ maxConcurrentAgents: 20,
38
+ defaultTokenBudget: 10000,
39
+ enableDynamicAllocation: true,
40
+ });
41
+ await queryController.initialize();
42
+ console.log('✓ QueryController initialized\n');
43
+
44
+ // Step 2: Initialize HierarchicalCoordinator (Phase 5)
45
+ console.log('Step 2: Initialize HierarchicalCoordinator for hierarchy management...');
46
+ const hierarchicalCoordinator = new HierarchicalCoordinator({
47
+ maxDepth: 10,
48
+ maxChildrenPerNode: 10,
49
+ enableDependencyTracking: true,
50
+ });
51
+ await hierarchicalCoordinator.initialize();
52
+ console.log('✓ HierarchicalCoordinator initialized\n');
53
+
54
+ // Step 3: Create Multi-Level Controller (Sprint 5.2)
55
+ console.log('Step 3: Create MultiLevelController integration layer...');
56
+ const multiLevelController = createMultiLevelControllerWithHierarchy(
57
+ queryController,
58
+ hierarchicalCoordinator,
59
+ {
60
+ maxControlLatencyMs: 100, // <100ms target
61
+ enableCommandQueue: true,
62
+ maxQueuedCommands: 50,
63
+ }
64
+ );
65
+ console.log('✓ MultiLevelController created\n');
66
+
67
+ // Step 4: Build 3-Level Agent Hierarchy
68
+ console.log('Step 4: Build 3-level agent hierarchy...');
69
+
70
+ // Level 0: Supervisor
71
+ const supervisor = await queryController.spawnAgent({
72
+ agentId: 'supervisor',
73
+ type: 'coordinator',
74
+ priority: 10,
75
+ metadata: { role: 'Level 0 Supervisor' },
76
+ });
77
+ await hierarchicalCoordinator.registerAgent(
78
+ 'supervisor',
79
+ {
80
+ name: 'Supervisor',
81
+ type: 'coordinator',
82
+ level: 0,
83
+ status: 'ready',
84
+ capabilities: ['coordination', 'hierarchy-control'],
85
+ },
86
+ undefined // No parent (root)
87
+ );
88
+
89
+ // Level 1: Team Leads
90
+ const teamLeadA = await queryController.spawnAgent({
91
+ agentId: 'team-lead-a',
92
+ type: 'coordinator',
93
+ priority: 8,
94
+ metadata: { role: 'Team Lead A' },
95
+ });
96
+ await hierarchicalCoordinator.registerAgent(
97
+ 'team-lead-a',
98
+ {
99
+ name: 'Team Lead A',
100
+ type: 'coordinator',
101
+ level: 1,
102
+ status: 'ready',
103
+ capabilities: ['coordination', 'task-delegation'],
104
+ },
105
+ 'supervisor' // Parent: supervisor
106
+ );
107
+
108
+ const teamLeadB = await queryController.spawnAgent({
109
+ agentId: 'team-lead-b',
110
+ type: 'coordinator',
111
+ priority: 8,
112
+ metadata: { role: 'Team Lead B' },
113
+ });
114
+ await hierarchicalCoordinator.registerAgent(
115
+ 'team-lead-b',
116
+ {
117
+ name: 'Team Lead B',
118
+ type: 'coordinator',
119
+ level: 1,
120
+ status: 'ready',
121
+ capabilities: ['coordination', 'task-delegation'],
122
+ },
123
+ 'supervisor'
124
+ );
125
+
126
+ // Level 2: Workers (under Team Lead A)
127
+ const workerA1 = await queryController.spawnAgent({
128
+ agentId: 'worker-a1',
129
+ type: 'worker',
130
+ priority: 5,
131
+ metadata: { role: 'Worker A1' },
132
+ });
133
+ await hierarchicalCoordinator.registerAgent(
134
+ 'worker-a1',
135
+ {
136
+ name: 'Worker A1',
137
+ type: 'worker',
138
+ level: 2,
139
+ status: 'ready',
140
+ capabilities: ['code-generation', 'testing'],
141
+ },
142
+ 'team-lead-a'
143
+ );
144
+
145
+ const workerA2 = await queryController.spawnAgent({
146
+ agentId: 'worker-a2',
147
+ type: 'worker',
148
+ priority: 5,
149
+ metadata: { role: 'Worker A2' },
150
+ });
151
+ await hierarchicalCoordinator.registerAgent(
152
+ 'worker-a2',
153
+ {
154
+ name: 'Worker A2',
155
+ type: 'worker',
156
+ level: 2,
157
+ status: 'ready',
158
+ capabilities: ['documentation', 'review'],
159
+ },
160
+ 'team-lead-a'
161
+ );
162
+
163
+ console.log('✓ Hierarchy built:');
164
+ console.log(' - Level 0: Supervisor');
165
+ console.log(' - Level 1: Team Lead A, Team Lead B');
166
+ console.log(' - Level 2: Worker A1, Worker A2\n');
167
+
168
+ // Step 5: Demonstrate Multi-Level Control Operations
169
+ console.log('Step 5: Multi-Level Control Operations\n');
170
+
171
+ // Operation 1: Level 0 pauses Level 2 agent
172
+ console.log('Operation 1: Supervisor (L0) pauses Worker A1 (L2)...');
173
+ const pauseResult = await multiLevelController.pauseChildAgent(
174
+ 'supervisor',
175
+ 'worker-a1',
176
+ 'Supervisor directive: pause for configuration update'
177
+ );
178
+ console.log(`✓ Paused: ${pauseResult.success}`);
179
+ console.log(` - Agent: ${pauseResult.agentId} (Level ${pauseResult.level})`);
180
+ console.log(` - Latency: ${pauseResult.latencyMs.toFixed(2)}ms (<100ms target)\n`);
181
+
182
+ // Operation 2: Level 0 injects commands to paused agent
183
+ console.log('Operation 2: Supervisor (L0) injects commands to Worker A1 (L2)...');
184
+
185
+ const stateInjection = await multiLevelController.injectCommand(
186
+ 'supervisor',
187
+ 'worker-a1',
188
+ InjectedCommandType.STATE_UPDATE,
189
+ { state: 'working' },
190
+ false
191
+ );
192
+ console.log(`✓ Injected STATE_UPDATE: ${stateInjection.success} (${stateInjection.latencyMs.toFixed(2)}ms)`);
193
+
194
+ const taskInjection = await multiLevelController.injectCommand(
195
+ 'supervisor',
196
+ 'worker-a1',
197
+ InjectedCommandType.TASK_UPDATE,
198
+ {
199
+ task: 'Implement authentication module',
200
+ taskId: 'task-auth-001',
201
+ deadline: '2025-10-15',
202
+ },
203
+ false
204
+ );
205
+ console.log(`✓ Injected TASK_UPDATE: ${taskInjection.success} (${taskInjection.latencyMs.toFixed(2)}ms)`);
206
+
207
+ const priorityInjection = await multiLevelController.injectCommand(
208
+ 'supervisor',
209
+ 'worker-a1',
210
+ InjectedCommandType.PRIORITY_UPDATE,
211
+ { priority: 9 },
212
+ false
213
+ );
214
+ console.log(`✓ Injected PRIORITY_UPDATE: ${priorityInjection.success} (${priorityInjection.latencyMs.toFixed(2)}ms)`);
215
+
216
+ const queuedCount = multiLevelController.getQueuedCommandsCount('worker-a1');
217
+ console.log(` - Queued commands: ${queuedCount}\n`);
218
+
219
+ // Operation 3: Level 0 resumes agent with commands applied
220
+ console.log('Operation 3: Supervisor (L0) resumes Worker A1 (L2)...');
221
+ const resumeResult = await multiLevelController.resumeChildAgent('supervisor', 'worker-a1');
222
+ console.log(`✓ Resumed: ${resumeResult.success}`);
223
+ console.log(` - Commands applied: ${resumeResult.data?.appliedCommands}`);
224
+ console.log(` - Latency: ${resumeResult.latencyMs.toFixed(2)}ms\n`);
225
+
226
+ // Verify commands were applied
227
+ const workerSession = await queryController.getAgentSession('worker-a1');
228
+ console.log('✓ Verification:');
229
+ console.log(` - Worker A1 state: ${workerSession.state}`);
230
+ console.log(` - Worker A1 priority: ${workerSession.priority}`);
231
+ console.log(` - Injected commands: ${workerSession.metadata.injectedCommands?.length ?? 0}\n`);
232
+
233
+ // Operation 4: Cascade pause to all Team Lead A's children
234
+ console.log('Operation 4: Supervisor (L0) cascades pause to all Team Lead A children...');
235
+ const cascadeResults = await multiLevelController.cascadeControlOperation('team-lead-a', 'pause');
236
+ console.log(`✓ Cascade pause completed: ${cascadeResults.length} agents affected`);
237
+ for (const result of cascadeResults) {
238
+ console.log(
239
+ ` - ${result.agentId} (L${result.level}): ${result.success ? 'Paused' : 'Failed'} (${result.latencyMs.toFixed(2)}ms)`
240
+ );
241
+ }
242
+ console.log('');
243
+
244
+ // Operation 5: Cascade resume
245
+ console.log('Operation 5: Supervisor (L0) cascades resume to all Team Lead A children...');
246
+ const resumeCascade = await multiLevelController.cascadeControlOperation('team-lead-a', 'resume');
247
+ console.log(`✓ Cascade resume completed: ${resumeCascade.length} agents resumed\n`);
248
+
249
+ // Step 6: Show Final Metrics
250
+ console.log('Step 6: Control Operation Metrics');
251
+ const metrics = multiLevelController.getMetrics();
252
+ console.log(` - Total pauses: ${metrics.totalPauses}`);
253
+ console.log(` - Total injections: ${metrics.totalInjections}`);
254
+ console.log(` - Total resumes: ${metrics.totalResumes}`);
255
+ console.log(` - Average latency: ${metrics.averageControlLatencyMs.toFixed(2)}ms`);
256
+ console.log(` - Max latency: ${metrics.maxControlLatencyMs.toFixed(2)}ms`);
257
+ console.log(` - Within <100ms target: ${metrics.withinTarget ? 'YES ✓' : 'NO ✗'}\n`);
258
+
259
+ // Cleanup
260
+ console.log('Cleanup...');
261
+ await multiLevelController.cleanup();
262
+ await hierarchicalCoordinator.shutdown();
263
+ await queryController.cleanup();
264
+ console.log('✓ All components cleaned up\n');
265
+
266
+ console.log('=== Multi-Level Control Example Complete ===');
267
+ }
268
+
269
+ // Run example
270
+ if (import.meta.url === `file://${process.argv[1]}`) {
271
+ multiLevelControlExample()
272
+ .then(() => {
273
+ console.log('\n✓ Example completed successfully');
274
+ process.exit(0);
275
+ })
276
+ .catch((error) => {
277
+ console.error('\n✗ Example failed:', error);
278
+ process.exit(1);
279
+ });
280
+ }
281
+
282
+ export { multiLevelControlExample };